palbase 0.37.0 → 0.37.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{KC64EJP4.js → 4Y47I6LA.js} +2 -2
- package/dist/chunks/{WBBBK7KR.js → 5HYKOPCW.js} +2 -2
- package/dist/chunks/{IVZQOIXW.js → 72CHRRHY.js} +1 -1
- package/dist/chunks/{PJP7TT3V.js → A6LIFQOQ.js} +3 -3
- package/dist/chunks/{ML2FPPCL.js → AF3XUGHY.js} +2 -2
- package/dist/chunks/{EIGFU7MO.js → C4ENQSIX.js} +1 -1
- package/dist/chunks/{VK6ALHIT.js → CHXCVOON.js} +1 -1
- package/dist/chunks/{BWQXLDGG.js → GEZH3OTX.js} +2 -2
- package/dist/chunks/{ZSJDQ34E.js → HMDMAILZ.js} +1 -1
- package/dist/chunks/{SRFAWNOD.js → IOVYIATC.js} +1 -1
- package/dist/chunks/{JHRMDLGF.js → JCHW52YV.js} +2 -2
- package/dist/chunks/{5IDPIZGR.js → L3S7O5FQ.js} +2 -2
- package/dist/chunks/{PBYDJFD3.js → LANEQ73A.js} +2 -2
- package/dist/chunks/{FVWB6QLP.js → NFFQO2UC.js} +2 -2
- package/dist/chunks/{TPHZCHLV.js → P5EW3DTQ.js} +2 -2
- package/dist/chunks/{RQBRUINN.js → QK2S67K3.js} +2 -2
- package/dist/chunks/{T64GKIOS.js → RVRPBQ4W.js} +2 -2
- package/dist/chunks/{SNCOLU4O.js → SEECU52P.js} +2 -2
- package/dist/chunks/{BJB4ODEW.js → UBQK5O7J.js} +1 -1
- package/dist/chunks/{3NCYWZCH.js → VAPNSTWC.js} +2 -2
- package/dist/chunks/{YIHRINWP.js → YLLZC52Q.js} +1 -1
- package/dist/chunks/{22UYQWHM.js → YQQHL67Y.js} +2 -2
- package/dist/chunks/{2HWKGNH2.js → ZDENVL2U.js} +2 -2
- package/dist/cli.js +15 -15
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/internal/src/messaging/store.d.ts +2 -0
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
/*! palbase 0.37.
|
|
2
|
+
/*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
|
|
3
3
|
var Ub=Object.defineProperty;var We=(e,t)=>{for(var n in t)Ub(e,n,{get:t[n],enumerable:!0})};import{parseArgs as Pw}from"node:util";var zb=Symbol.for("palbase.data"),Bb=globalThis,sp=Bb[zb]??=new WeakSet;function Fb(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function Oa(e){let t=[e];for(;t.length>0;){let n=t.pop();if(!(typeof n!="object"||n===null||sp.has(n)||Fb(n))){sp.add(n);for(let s of Array.isArray(n)?n:Object.values(n))t.push(s)}}return e}var Jb="X-PoW-Challenge-ID",Wb="X-PoW-Nonce";function ap(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:s,difficulty:a}=t.challenge;return typeof n!="string"||typeof s!="string"||typeof a!="number"||!Number.isInteger(a)||a<0?null:{id:n,prefix:s,difficulty:a}}function Vb(e){return 8*2**e}var Wn;async function Hb(){if(Wn)return Wn;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let s=(await import("node:crypto")).createHash;if(typeof s=="function")return Wn=a=>new Uint8Array(s("sha256").update(a).digest()),Wn}catch{}let t=new TextEncoder;return Wn=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),Wn}function Yb(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var Xb=4096,Zb=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function rp(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await Hb(),s=Vb(e.difficulty),a=Date.now()+(t.timeLimitMs??12e4);for(let r=0;r<s;r++){if(r%Xb===0&&r>0){if(await Zb(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>a)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${r} attempts`)}let i=n(e.prefix+r),o=i instanceof Uint8Array?i:await i;if(Yb(o)>=e.difficulty)return{[Jb]:e.id,[Wb]:String(r)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${s} attempts`)}var j=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="PalbaseError",this.op=t.op,this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.retryAfter=t.retryAfter,this.body=t.body}};function c(e,t,n){let s=String(n);if(s===""||s==="."||s==="..")throw new j({op:e,status:0,code:"invalid_path_parameter",message:`${e}: ${t} cannot be ${s===""?"empty":JSON.stringify(s)}`});return encodeURIComponent(s)}var Qb=new Set(["apikey","authorization"]),ew=64*1024;function vi(e){let t=Ma(e.baseUrl),n=e.fetch??globalThis.fetch,s=e.solveProofOfWork??!0,a=async(r,i)=>{let o=sw(t,r),l=new Headers;for(let[b,w]of Object.entries(r.headers??{}))w!=null&&!Qb.has(b.toLowerCase())&&l.set(b,String(w));for(let[b,w]of Object.entries(i))l.set(b,w);await aw(r,e.credentials,l),l.has("accept")||l.set("accept","application/json");let d={method:r.method,headers:l,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(l.set("content-type",r.body.contentType),d.body=rw(r.body.kind,r.body.value),Vn(d.body)||(d.duplex="half"));let p;try{p=r.onUploadProgress&&e.xmlHttpRequest?await tw(e.xmlHttpRequest,r.op,o,d,r.onUploadProgress):await n(o,d)}catch(b){throw r.signal?.aborted||b instanceof j?b:new j({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${t.origin}`,cause:b})}let u=r.answers[p.status]??(r.ownResponse&&p.status>=200&&p.status<300?"raw":void 0);if(u===void 0)throw p.status>=200&&p.status<300?(await p.body?.cancel(),new j({op:r.op,status:p.status,code:"undeclared_answer",message:`${r.op}: the server answered ${p.status}, which its contract does not declare; the request may have taken effect`})):await ow(r.op,p);let m;switch(u){case"json":try{m=Oa(await p.json())}catch(b){throw new j({op:r.op,status:p.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:b})}break;case"raw":m=p;break;default:await p.body?.cancel(),m=void 0}return{status:p.status,data:m,headers:p.headers}};return{async send(r){try{return await a(r,{})}catch(i){let o=s&&i instanceof j&&i.status===403?ap(i.body):null,l=r.body?.value;if(!o||r.body?.kind==="raw"&&!Vn(l))throw i;let d=i,p;try{p=await rp(o,{signal:r.signal})}catch(u){throw r.signal?.aborted?u:new j({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${u instanceof Error?u.message:String(u)}`,requestId:d.requestId,body:d.body,cause:u})}return a(r,p)}}}}function tw(e,t,n,s,a){return new Promise((r,i)=>{let o=s.signal;if(o?.aborted)return i(o.reason);let l=new e,d=()=>l.abort();o?.addEventListener("abort",d,{once:!0});let p=u=>{o?.removeEventListener("abort",d),u()};l.open(s.method??"GET",n.href),l.responseType="arraybuffer",new Headers(s.headers).forEach((u,m)=>l.setRequestHeader(m,u)),l.upload&&(l.upload.onprogress=u=>{u.lengthComputable&&a(u.loaded,u.total)}),l.onload=()=>p(()=>{if(l.responseURL!==""&&l.responseURL!==n.href){i(new j({op:t,status:0,code:"undeclared_redirect",message:`${t}: the server redirected; the answer is another address's, and was not read`}));return}if(l.status<200||l.status>599)return i(new TypeError(`${t}: answered ${l.status}`));let u=l.status===204||l.status===205||l.status===304;r(new Response(u?null:l.response,{status:l.status,statusText:l.statusText,headers:nw(l.getAllResponseHeaders())}))}),l.onerror=()=>p(()=>i(new TypeError(`${t}: the request failed`))),l.onabort=()=>p(()=>i(o?.reason??new DOMException("The request was aborted","AbortError"))),l.send(s.body)})}function nw(e){let t=new Headers;for(let n of e.split(/\r?\n/)){let s=n.indexOf(":");if(!(s<=0))try{t.append(n.slice(0,s).trim(),n.slice(s+1).trim())}catch{}}return t}function Ma(e){let t;try{t=new URL(e)}catch{throw new TypeError(`baseUrl ${JSON.stringify(e)} is not an absolute URL`)}let n=t.hostname==="localhost"||t.hostname.endsWith(".localhost")||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${t.origin}`);if(t.username||t.password||t.search||t.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(t.pathname!=="/"&&t.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return t}function sw(e,t){if(!t.path.startsWith("/")||t.path.startsWith("//"))throw new j({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path ${JSON.stringify(t.path)} is not absolute`});let n=new URL(t.path+iw(t.query),e);if(n.origin!==e.origin)throw new j({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path leaves the project's origin`});return n}async function aw(e,t,n){if(e.auth.length===0)return;let s=e.auth.some(i=>i.includes("userJWT"))?await t.accessToken?.():void 0,a=i=>{switch(i){case"ApiKeyAuth":return!!(t.publishableKey??t.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(t.secretKey??t.token);case"PalbaseBearer":return!!t.token;case"userJWT":return!!s&&!t.token;default:return!1}},r=e.auth.filter(i=>i.every(a)).reduce((i,o)=>i===void 0||o.length>i.length?o:i,void 0);if(!r)throw new j({op:e.op,status:0,code:"missing_credential",message:`${e.op} needs one of: ${e.auth.map(i=>i.length===0?"nothing":i.join(" + ")).join(" | ")}`});for(let i of r)i==="ApiKeyAuth"?n.set("apikey",t.publishableKey??t.secretKey):(i==="SecretKeyAuth"||i==="AdminAuth"||i==="PalbaseBearer")&&t.token?n.set("authorization",`Bearer ${t.token}`):i==="SecretKeyAuth"||i==="AdminAuth"?n.set("apikey",t.secretKey):i==="userJWT"&&n.set("authorization",`Bearer ${s}`)}function rw(e,t){switch(e){case"json":return JSON.stringify(t);case"form":{let n=new URLSearchParams;for(let[s,a]of Object.entries(t))_i(n,s,a);return n}case"raw":return t}}function Vn(e){return!!(e==null||typeof e=="string"||e instanceof URLSearchParams||e instanceof Blob||e instanceof FormData||e instanceof ArrayBuffer||ArrayBuffer.isView(e))}function iw(e){if(!e)return"";let t=new URLSearchParams;for(let[s,a]of Object.entries(e))_i(t,s,a);let n=t.toString();return n===""?"":`?${n}`}function _i(e,t,n){if(n!=null){if(Array.isArray(n)){for(let s of n)_i(e,t,s);return}if(n instanceof Date){e.append(t,n.toISOString());return}e.append(t,typeof n=="object"?JSON.stringify(n):String(n))}}async function ow(e,t){let n=await lw(t,ew).catch(()=>""),s;try{s=n===""?void 0:JSON.parse(n)}catch{s=n}let a=pw(s)?s:void 0,r=Number(t.headers.get("retry-after")),i=t.status>=300&&t.status<400;return new j({op:e,status:t.status,code:a?.error??(i?"undeclared_redirect":`http_${t.status}`),message:a?.error_description??(i?`${e}: the server redirected (${t.status}); the request was not followed, its credentials stay here`:`${e}: ${t.status} ${t.statusText}`.trim()),requestId:a?.request_id??t.headers.get("x-request-id")??void 0,retryAfter:a?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:s})}async function lw(e,t){if(!e.body)return"";let n=e.body.getReader(),s=[],a=0;for(;a<t;){let{done:o,value:l}=await n.read();if(o)break;s.push(l),a+=l.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(a,t)),i=0;for(let o of s){let l=Math.min(o.byteLength,r.byteLength-i);if(r.set(o.subarray(0,l),i),i+=l,i>=r.byteLength)break}return new TextDecoder().decode(r)}function pw(e){return typeof e=="object"&&e!==null&&typeof e.error=="string"}var xa={project:{type:"string",short:"P",value:"project",description:"the project (name or id; org/project when the name is in two organizations)"},env:{type:"string",short:"E",value:"env",description:"the project's environment (slug or ref)"},json:{type:"boolean",description:"print the answer as JSON"},"non-interactive":{type:"boolean",description:"never ask: refuse what would need a question"},yes:{type:"boolean",short:"y",description:"confirm a change to a production environment without asking"},debug:{type:"boolean",description:"print each request the command sends"},help:{type:"boolean",short:"h",description:"show help"}};var y=class extends Error{exitCode;hint;code;reported;constructor(t,n,s={}){super(n),this.name="CliError",this.code=t,this.hint=s.hint,this.exitCode=s.exitCode??1,this.reported=s.reported??!1}};function g(e,t){return new y("usage",e,{hint:t,exitCode:2})}var Ia=class{io;json;constructor(t,n){this.io=t,this.json=n}result(t,n){this.json?this.io.stdout(`${JSON.stringify(t,null,2)}
|
|
4
4
|
`):n()}line(t=""){this.io.stdout(`${K(t)}
|
|
5
5
|
`)}note(t){this.io.stderr(`${K(t)}
|
|
@@ -9,7 +9,7 @@ var Ub=Object.defineProperty;var We=(e,t)=>{for(var n in t)Ub(e,n,{get:t[n],enum
|
|
|
9
9
|
`);let i;try{i=await this.io.fetch(t,{method:n.method,headers:{...n.headers,...a},body:n.body,signal:n.signal,...s?{}:{duplex:"half"},redirect:"manual"})}catch(l){throw n.signal?.aborted?l:new y("network_error",`${new URL(t).origin} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(this.debug&&this.io.stderr(`< ${i.status} ${i.headers.get("x-request-id")??""}
|
|
10
10
|
`),i.status!==503||!s||r>=kw||!_w.has(await $i(i)??""))return i;await i.body?.cancel();let o=Number(i.headers.get("retry-after")??"");await this.io.sleep((Number.isFinite(o)&&o>0?Math.min(o,30):1)*1e3)}}async exchange(t,n,s){let a=await this.token(),r=await this.send(t,n,s,a.value);if(r.status===401&&a.renewable){let i=await this.renew(await this.currentSession());r=await this.send(t,n,s,i.access_token)}return{res:r,renewable:a.renewable}}async answered(t,n,s,a){if(s.status===204)return;let r=await s.text(),i=r===""?void 0:Sw(r);if(s.ok)return i;let o=i??{};throw s.status===401?o.error==="token_not_for_machines"?_p(new URL(this.cloud.studioApi).host):a?Hn():this.tokenRefused("Studio"):new j({op:`${t} ${n}`,status:s.status,code:o.error??`http_${s.status}`,message:o.error_description??`Studio answered ${s.status}`,requestId:o.request_id??s.headers.get("x-request-id")??void 0,body:i})}tokenRefused(t){return(this.io.env.PALBASE_TOKEN??"").startsWith("pbe_")?new y("token_refused",`${t} refused PALBASE_TOKEN, an environment's token: it ended (a few hours at most), it was revoked, or what minted it no longer holds`,{hint:"mint another: palbase env:tokens:create --scope <scope> (an admin), or with the environment's secret key (Studio's POST /environments/{ref}/tokens)"}):(this.io.env.PALBASE_TOKEN??"").startsWith("pbu_")?new y("token_refused",`${t} refused PALBASE_TOKEN, an account token: it was revoked, it ended, or, in this organization, the one who made it left it`,{hint:"its maker makes a new one: palbase account:tokens:create <name>"}):new y("token_refused",`${t} refused PALBASE_TOKEN: it was revoked, it ended, or the one who made it no longer holds its role`,{hint:"an admin makes a new one: palbase tokens:create <name>"})}async token(){let t=this.io.env.PALBASE_TOKEN;return t&&t!==""?{value:t,renewable:!1}:{value:(await this.currentSession()).access_token,renewable:!0}}async renew(t){let n=await yp(this.io,this.cloud,t);return await this.state.writeSession(n),this.session=n,n}async send(t,n,s,a){let r=`${this.cloud.studioApi}${vw}${n}`;this.debug&&this.io.stderr(`> ${t} ${r}
|
|
11
11
|
`);try{let i=await this.io.fetch(r,{method:t,headers:{...a===void 0?{}:{authorization:`Bearer ${a}`},accept:"application/json",...s===void 0?{}:{"content-type":"application/json"}},body:s===void 0?void 0:JSON.stringify(s),redirect:"manual"});return this.debug&&this.io.stderr(`< ${i.status} ${i.headers.get("x-request-id")??""}
|
|
12
|
-
`),i}catch(i){throw new y("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${i instanceof Error?i.message:String(i)}`)}}};function _p(e){return new y("token_not_for_machines",`the platform's edge refused PALBASE_TOKEN at ${e}, taking it for a machine's address (token_not_for_machines): the token itself was not refused`,{hint:"nothing is wrong with the token: run this again in a few minutes, and tell Palbase if it lasts"})}async function $i(e){let t=await e.clone().json().catch(()=>null),n=t&&typeof t=="object"?t.error:void 0;return typeof n=="string"&&/^(console|token|edge)_/.test(n)?n:void 0}function Sw(e){try{return JSON.parse(e)}catch{return e}}var kp={version:"0.37.
|
|
12
|
+
`),i}catch(i){throw new y("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${i instanceof Error?i.message:String(i)}`)}}};function _p(e){return new y("token_not_for_machines",`the platform's edge refused PALBASE_TOKEN at ${e}, taking it for a machine's address (token_not_for_machines): the token itself was not refused`,{hint:"nothing is wrong with the token: run this again in a few minutes, and tell Palbase if it lasts"})}async function $i(e){let t=await e.clone().json().catch(()=>null),n=t&&typeof t=="object"?t.error:void 0;return typeof n=="string"&&/^(console|token|edge)_/.test(n)?n:void 0}function Sw(e){try{return JSON.parse(e)}catch{return e}}var kp={version:"0.37.2"};var Ka=kp.version;async function Rp(e,t,n){let s=new Map(n.map(i=>[i.name,i])),a=e.includes("--json"),r=e.includes("--debug");try{let{name:i,at:o}=Aw(e);if(i===void 0)return e.includes("--version")?(t.stdout(`palbase ${Ka}
|
|
13
13
|
`),0):(t.stdout(Ap(n)),e.length===0||e.includes("--help")||e.includes("-h")?0:2);if(i==="help"){let S=e[o+1],$=S===void 0?void 0:s.get(S);if(S!==void 0&&!$)throw Sp(S,n);return t.stdout($?Pp($):Ap(n)),0}let l=s.get(i);if(!l)throw Sp(i,n);let d=[...e.slice(0,o),...e.slice(o+1)];if(d.includes("--help")||d.includes("-h"))return t.stdout(Pp(l)),0;let{flags:p,positionals:u}=Rw(l,d),m=l.args??{min:0,max:0};if(u.length<m.min)throw g(`${l.name} needs ${m.min===1?"an argument":`${m.min} arguments`}`,Ai(l));if(u.length>m.max)throw g(`${l.name} takes ${m.max===0?"no argument":`at most ${m.max}`}: ${JSON.stringify(u.slice(m.max))} is left over`,Ai(l));let b={project:p.project,env:p.env,json:p.json===!0,nonInteractive:p["non-interactive"]===!0,yes:p.yes===!0,debug:p.debug===!0},w=up(t.env),_=new La(mp(t.configDir,w)),T={io:t,state:_,out:new Ia(t,b.json),global:b,args:u,flags:p,interactive:t.interactive&&!b.nonInteractive,cloud:w,studio:new Na(t,w,_,b.debug)};return await l.run(T)??0}catch(i){return Tw(i,t,a,r)}}function Aw(e){let t=new Set;for(let[n,s]of Object.entries(xa))s.type==="string"&&(t.add(`--${n}`),s.short&&t.add(`-${s.short}`));for(let n=0;n<e.length;n++){let s=e[n];if(s==="--")return{at:-1};if(t.has(s)){n++;continue}if(!s.startsWith("-"))return{name:s,at:n}}return{at:-1}}function Rw(e,t){let n={...xa,...e.flags??{}},s={};for(let[a,r]of Object.entries(n))s[a]={type:r.type,...r.short?{short:r.short}:{},...r.multiple?{multiple:!0}:{}};try{let{values:a,positionals:r}=Pw({args:t,options:s,strict:!0,allowPositionals:!0});return{flags:a,positionals:r}}catch(a){throw g(a instanceof Error?a.message.replace(/^.*?: /,""):String(a),`palbase help ${e.name}`)}}function Tw(e,t,n,s){let a="error",r,i,o=1,l;return e instanceof y?(a=e.code,r=e.message,i=e.hint,o=e.exitCode):e instanceof j?(a=e.code,r=e.message,l=e.requestId,e.code==="token_out_of_scope"&&t.env.PALBASE_TOKEN&&(r=`${e.op} refused PALBASE_TOKEN: ${e.message}`,i="this is the token's reach, fixed when it was minted: a person's yes does not change it \u2014 mint a token whose scopes name this call, or have a person run it signed in")):r=e instanceof Error?e.message:String(e),n&&e instanceof y&&e.reported||(n&&t.stdout(`${JSON.stringify({error:a,message:r,...i?{hint:i}:{},...l?{request_id:l}:{}},null,2)}
|
|
14
14
|
`),t.stderr(`error: ${K(r)}${l?` (request ${K(l)})`:""}
|
|
15
15
|
`),i&&t.stderr(` ${K(i)}
|
|
@@ -18,7 +18,7 @@ var Ub=Object.defineProperty;var We=(e,t)=>{for(var n in t)Ub(e,n,{get:t[n],enum
|
|
|
18
18
|
`)}
|
|
19
19
|
`}function Ap(e){let t=new Map;for(let a of e){let r=a.name.includes(":")?a.name.slice(0,a.name.indexOf(":")):"";t.set(r,[...t.get(r)??[],a])}let n=Math.max(...e.map(a=>a.name.length)),s=["palbase \u2014 your Palbase organizations, projects and environments from the terminal","","usage: palbase <command> [flags]",""];for(let[a,r]of t){s.push(a===""?"Commands:":`${a}:`);for(let i of r)s.push(` ${i.name.padEnd(n)} ${i.summary}`);s.push("")}return s.push("palbase help <command> shows a command in full."),`${s.join(`
|
|
20
20
|
`)}
|
|
21
|
-
`}import{createHash as gM,randomBytes as fM,timingSafeEqual as yM}from"node:crypto";import{createServer as wM}from"node:http";var Ri="owner.json";var kM=300*1e3;function D(e,t){try{return c("palbase",e,t)}catch(n){throw n instanceof j&&n.code==="invalid_path_parameter"?new y("unsafe_path",`${e} cannot be ${t===""?"empty":JSON.stringify(t)}: a request's path cannot carry it`):n}}var Tp={name:"login",summary:"sign in with your Studio account",details:["Shows a one-time code and opens Studio, where you approve it while signed in there.","The CLI then holds a session of yours: Studio lists it with your others, and ending it there signs the CLI out.","On a machine with no browser (a server, an agent), open the address it prints on any device."],flags:{"no-browser":{type:"boolean",description:"print the address instead of opening a browser"}},scope:"none",async run(e){if(e.io.env.PALBASE_TOKEN)throw new y("token_in_use","PALBASE_TOKEN is set: the CLI acts with that token, and a sign-in would not be used",{hint:"unset PALBASE_TOKEN to sign in as yourself"});let t=await gp(e.io,e.cloud),n=`${e.cloud.studioWeb}/device`;e.out.note(""),e.out.note(` Enter this code in your browser: ${t.user_code}`),e.out.note("");let s=e.flags["no-browser"]!==!0&&e.interactive&&await e.io.openBrowser(n);e.out.note(s?`Opened ${n} \u2014 sign in there if asked, then enter the code.`:`Open ${n} on any device, sign in, and enter the code.`),e.out.note("Waiting for the approval\u2026");let a=await fp(e.io,e.cloud,t);await e.state.writeSession(a),e.out.result({user:a.user},()=>e.out.line(`Signed in as ${a.user.email??a.user.id}.`))}},Ep={name:"logout",summary:"sign out: the session is ended at Palbase and forgotten on this computer",scope:"none",async run(e){if(e.io.env.PALBASE_TOKEN)throw new y("token_in_use","PALBASE_TOKEN is set: logout ends your own sign-in, and the CLI acts with the token",{hint:"unset PALBASE_TOKEN to sign out"});let t=await e.state.readSession();if(!t){e.out.result({signed_out:!0},()=>e.out.line("You were not signed in."));return}for(let[n,s]of Object.entries(await e.state.personalKeys()))try{await e.studio.request("DELETE",`/environments/${D("the environment's ref",n)}/personal-key/${D("the personal key's id",s.id)}`)}catch(a){a instanceof Error&&"status"in a&&a.status===404||e.out.warn(`your key at ${n} (${s.label}) could not be revoked: ${a instanceof Error?a.message:String(a)} \u2014 revoke it in Studio, or it ends ${s.expires_at}`)}await e.state.forgetPersonalKeys(),await e.state.forget(Ri);try{await bp(e.io,e.cloud,t)}catch(n){e.out.warn(`${n instanceof Error?n.message:String(n)} \u2014 end the session in Studio (Account \u203A Sessions)`)}await e.state.clearSession(),e.out.result({signed_out:!0},()=>e.out.line(`Signed out ${t.user.email??t.user.id}.`))}},Cp={name:"whoami",summary:"the account the CLI acts as, and the environment chosen for this directory",scope:"account",async run(e){let t=e.io.env.PALBASE_TOKEN,n;if(t?.startsWith("pbu_")){let{organizations:a}=await e.studio.get("/orgs");n={id:`account token \u2026${t.slice(-4)}`,via:"token",organizations:a.length}}else if(t?.startsWith("pbo_")){let{organizations:a}=await e.studio.get("/orgs"),r=a[0];n={id:`token \u2026${t.slice(-4)}`,via:"token",...r&&{organization:{id:r.id,name:r.name,role:r.role}}}}else if(t){let a=Da(t);n={id:String(a.sub??""),...typeof a.email=="string"?{email:a.email}:{},via:"token"}}else n={...(await e.studio.currentSession()).user,via:"session"};let s=await e.state.targetFor(e.io.cwd);e.out.result({user:n,target:s?.target??null,target_dir:s?.dir??null},()=>{e.out.line(n.organization?`an access token of ${K(n.organization.name)} (${n.organization.role}), ${n.id} (PALBASE_TOKEN)`:n.organizations!==void 0?`an ${n.id} (PALBASE_TOKEN): an admin of the ${n.organizations} organization${n.organizations===1?"":"s"} it opened`:`${n.email??n.id}${n.via==="token"?" (PALBASE_TOKEN)":""}`),s&&e.out.line(`${s.target.org_name} \u203A ${s.target.project_name} \u203A ${s.target.env_name} (${s.target.env_slug}) \u2014 chosen for ${s.dir}`)})}};var Cw={name:"account:tokens:list",summary:"your account tokens (for a program that opens organizations): name, how many organizations they reach, when they end and were last used \u2014 never their values",scope:"account",async run(e){let{tokens:t}=await e.studio.get("/account/tokens");e.out.result({tokens:t},()=>{t.length===0?e.out.line("You have no account token yet: palbase account:tokens:create <name> makes one."):e.out.table(t,[{header:"name",value:n=>K(n.name)},{header:"token",value:n=>`pbu_\u2026${n.hint}`},{header:"organizations",value:n=>String(n.organizations)},{header:"ends",value:n=>n.expires_at.slice(0,10)},{header:"last used",value:n=>n.last_used_at?.slice(0,16).replace("T"," ")??"never"},{header:"id",value:n=>n.id}])})}},jw={name:"account:tokens:create",summary:"make an account token for a program that opens organizations; its value is shown this once",usage:"<name> [--days <n>]",details:["Give it to the program as its secret (PALBASE_TOKEN, or palbase/cloud's token): it opens organizations \u2014 you their owner, the token their admin \u2014 and builds projects and environments there.","It reaches only the organizations it opened, never your others; it makes no token or key and changes no one's place. It ends after --days (default 90, at most 365), when it is revoked, and, in an organization, when you leave it."],args:{min:1,max:1},flags:{days:{type:"string",value:"n",description:"how many days it is good for (default 90)"}},scope:"account",async run(e){let t=e.flags.days===void 0?90:Number(e.flags.days);if(!Number.isInteger(t)||t<1||t>365)throw g("--days is a whole number from 1 to 365");let n=await e.studio.post("/account/tokens",{name:e.args[0],expires_in_days:t});e.out.result(n,()=>{e.out.line(`Made the account token ${K(n.name)} (until ${n.expires_at.slice(0,10)}).`),e.out.line(`token (shown this once \u2014 keep it as the program's secret PALBASE_TOKEN): ${n.token}`)})}},Ow={name:"account:tokens:revoke",summary:"revoke one of your account tokens (by its name or id): refused from its next request on; the organizations it opened stay yours",usage:"<name|id>",args:{min:1,max:1},scope:"account",async run(e){let{tokens:t}=await e.studio.get("/account/tokens"),n=t.filter(s=>s.id===e.args[0]||s.name===e.args[0]);if(n.length===0)throw new y("no_such_token",`you have no account token ${JSON.stringify(e.args[0])}`,{hint:"palbase account:tokens:list shows them"});if(n.length>1)throw new y("ambiguous_token",`${JSON.stringify(e.args[0])} names more than one token`,{hint:"pass its id"});await e.studio.request("DELETE",`/account/tokens/${D("the token's id",n[0].id)}`),e.out.result({revoked:n[0].id},()=>e.out.line(`Revoked the account token ${K(n[0].name)}.`))}},jp=[Cw,jw,Ow];var Ga={};We(Ga,{client:()=>Mw});function Mw(e){return{async draftAgent(t){return e.send({op:"DraftAgent",method:"POST",path:"/ai/agent-drafts",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listAgents(t){return e.send({op:"ListAgents",method:"GET",path:"/ai/agents",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getAgent(t){return e.send({op:"GetAgent",method:"GET",path:"/ai/agents/"+c("GetAgent","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putAgent(t){return e.send({op:"PutAgent",method:"PUT",path:"/ai/agents/"+c("PutAgent","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteAgent(t){return e.send({op:"DeleteAgent",method:"DELETE",path:"/ai/agents/"+c("DeleteAgent","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async publishAgent(t){return e.send({op:"PublishAgent",method:"POST",path:"/ai/agents/"+c("PublishAgent","name",t.path.name)+"/publish",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async rollbackAgent(t){return e.send({op:"RollbackAgent",method:"POST",path:"/ai/agents/"+c("RollbackAgent","name",t.path.name)+"/rollback",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listAgentVersions(t){return e.send({op:"ListAgentVersions",method:"GET",path:"/ai/agents/"+c("ListAgentVersions","name",t.path.name)+"/versions",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async listChats(t){return e.send({op:"ListChats",method:"GET",path:"/ai/chats",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createChat(t){return e.send({op:"CreateChat",method:"POST",path:"/ai/chats",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getChat(t){return e.send({op:"GetChat",method:"GET",path:"/ai/chats/"+c("GetChat","chat_id",t.path.chat_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deleteChat(t){return e.send({op:"DeleteChat",method:"DELETE",path:"/ai/chats/"+c("DeleteChat","chat_id",t.path.chat_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async decideChatApproval(t){return e.send({op:"DecideChatApproval",method:"POST",path:"/ai/chats/"+c("DecideChatApproval","chat_id",t.path.chat_id)+"/approvals/"+c("DecideChatApproval","approval_id",t.path.approval_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async forkChat(t){return e.send({op:"ForkChat",method:"POST",path:"/ai/chats/"+c("ForkChat","chat_id",t.path.chat_id)+"/fork",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getChatGoal(t){return e.send({op:"GetChatGoal",method:"GET",path:"/ai/chats/"+c("GetChatGoal","chat_id",t.path.chat_id)+"/goal",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async setChatGoal(t){return e.send({op:"SetChatGoal",method:"PUT",path:"/ai/chats/"+c("SetChatGoal","chat_id",t.path.chat_id)+"/goal",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async clearChatGoal(t){return e.send({op:"ClearChatGoal",method:"DELETE",path:"/ai/chats/"+c("ClearChatGoal","chat_id",t.path.chat_id)+"/goal",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},query:t.query,signal:t.signal})},async updateChatGoal(t){return e.send({op:"UpdateChatGoal",method:"PATCH",path:"/ai/chats/"+c("UpdateChatGoal","chat_id",t.path.chat_id)+"/goal",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async putChatMember(t){return e.send({op:"PutChatMember",method:"PUT",path:"/ai/chats/"+c("PutChatMember","chat_id",t.path.chat_id)+"/members/"+c("PutChatMember","user_id",t.path.user_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteChatMember(t){return e.send({op:"DeleteChatMember",method:"DELETE",path:"/ai/chats/"+c("DeleteChatMember","chat_id",t.path.chat_id)+"/members/"+c("DeleteChatMember","user_id",t.path.user_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listChatMessages(t){return e.send({op:"ListChatMessages",method:"GET",path:"/ai/chats/"+c("ListChatMessages","chat_id",t.path.chat_id)+"/messages",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async sendChatMessage(t){return e.send({op:"SendChatMessage",method:"POST",path:"/ai/chats/"+c("SendChatMessage","chat_id",t.path.chat_id)+"/messages",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json",202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getChatMessageAttachment(t){return e.send({op:"GetChatMessageAttachment",method:"GET",path:"/ai/chats/"+c("GetChatMessageAttachment","chat_id",t.path.chat_id)+"/messages/"+c("GetChatMessageAttachment","message_id",t.path.message_id)+"/attachments/"+c("GetChatMessageAttachment","position",t.path.position),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"raw"},signal:t.signal})},async listChatParts(t){return e.send({op:"ListChatParts",method:"GET",path:"/ai/chats/"+c("ListChatParts","chat_id",t.path.chat_id)+"/parts",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async putChatPipe(t){return e.send({op:"PutChatPipe",method:"PUT",path:"/ai/chats/"+c("PutChatPipe","chat_id",t.path.chat_id)+"/pipe",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteChatPipe(t){return e.send({op:"DeleteChatPipe",method:"DELETE",path:"/ai/chats/"+c("DeleteChatPipe","chat_id",t.path.chat_id)+"/pipe",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async sendSubagentMessage(t){return e.send({op:"SendSubagentMessage",method:"POST",path:"/ai/chats/"+c("SendSubagentMessage","chat_id",t.path.chat_id)+"/runs/"+c("SendSubagentMessage","run_id",t.path.run_id)+"/messages",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async stopSubagent(t){return e.send({op:"StopSubagent",method:"POST",path:"/ai/chats/"+c("StopSubagent","chat_id",t.path.chat_id)+"/runs/"+c("StopSubagent","run_id",t.path.run_id)+"/stop",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async stopChat(t){return e.send({op:"StopChat",method:"POST",path:"/ai/chats/"+c("StopChat","chat_id",t.path.chat_id)+"/stop",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listTurnToolCalls(t){return e.send({op:"ListTurnToolCalls",method:"GET",path:"/ai/chats/"+c("ListTurnToolCalls","chat_id",t.path.chat_id)+"/tool-calls",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getChatToolCall(t){return e.send({op:"GetChatToolCall",method:"GET",path:"/ai/chats/"+c("GetChatToolCall","chat_id",t.path.chat_id)+"/tool-calls/"+c("GetChatToolCall","call_id",t.path.call_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async answerChatToolCall(t){return e.send({op:"AnswerChatToolCall",method:"POST",path:"/ai/chats/"+c("AnswerChatToolCall","chat_id",t.path.chat_id)+"/tool-outputs/"+c("AnswerChatToolCall","call_id",t.path.call_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listChatTurnArtifacts(t){return e.send({op:"ListChatTurnArtifacts",method:"GET",path:"/ai/chats/"+c("ListChatTurnArtifacts","chat_id",t.path.chat_id)+"/turns/"+c("ListChatTurnArtifacts","response_id",t.path.response_id)+"/artifacts",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getChatTurnArtifact(t){return e.send({op:"GetChatTurnArtifact",method:"GET",path:"/ai/chats/"+c("GetChatTurnArtifact","chat_id",t.path.chat_id)+"/turns/"+c("GetChatTurnArtifact","response_id",t.path.response_id)+"/artifacts/"+c("GetChatTurnArtifact","artifact_id",t.path.artifact_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"raw"},signal:t.signal})},async getChatTurnCost(t){return e.send({op:"GetChatTurnCost",method:"GET",path:"/ai/chats/"+c("GetChatTurnCost","chat_id",t.path.chat_id)+"/turns/"+c("GetChatTurnCost","response_id",t.path.response_id)+"/cost",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async startChatVoice(t){return e.send({op:"StartChatVoice",method:"POST",path:"/ai/chats/"+c("StartChatVoice","chat_id",t.path.chat_id)+"/voice",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getChatVoice(t){return e.send({op:"GetChatVoice",method:"GET",path:"/ai/chats/"+c("GetChatVoice","chat_id",t.path.chat_id)+"/voice/"+c("GetChatVoice","voice_id",t.path.voice_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async closeChatVoice(t){return e.send({op:"CloseChatVoice",method:"DELETE",path:"/ai/chats/"+c("CloseChatVoice","chat_id",t.path.chat_id)+"/voice/"+c("CloseChatVoice","voice_id",t.path.voice_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async commandChatVoice(t){return e.send({op:"CommandChatVoice",method:"POST",path:"/ai/chats/"+c("CommandChatVoice","chat_id",t.path.chat_id)+"/voice/"+c("CommandChatVoice","voice_id",t.path.voice_id)+"/commands",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getChatWorkspaceFile(t){return e.send({op:"GetChatWorkspaceFile",method:"GET",path:"/ai/chats/"+c("GetChatWorkspaceFile","chat_id",t.path.chat_id)+"/workspace/files",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"raw"},query:t.query,signal:t.signal})},async addChatWorkspaceRepo(t){return e.send({op:"AddChatWorkspaceRepo",method:"POST",path:"/ai/chats/"+c("AddChatWorkspaceRepo","chat_id",t.path.chat_id)+"/workspace/repos",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createEmbeddings(t){return e.send({op:"CreateEmbeddings",method:"POST",path:"/ai/embeddings",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listEndpoints(t){return e.send({op:"ListEndpoints",method:"GET",path:"/ai/endpoints",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putEndpoint(t){return e.send({op:"PutEndpoint",method:"PUT",path:"/ai/endpoints/"+c("PutEndpoint","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteEndpoint(t){return e.send({op:"DeleteEndpoint",method:"DELETE",path:"/ai/endpoints/"+c("DeleteEndpoint","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async createImage(t){return e.send({op:"CreateImage",method:"POST",path:"/ai/images",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getImage(t){return e.send({op:"GetImage",method:"GET",path:"/ai/images/"+c("GetImage","image_id",t.path.image_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getImageFile(t){return e.send({op:"GetImageFile",method:"GET",path:"/ai/images/"+c("GetImageFile","image_id",t.path.image_id)+"/files/"+c("GetImageFile","position",t.path.position),auth:[["SecretKeyAuth"]],answers:{200:"raw"},signal:t.signal})},async listModels(t){return e.send({op:"ListModels",method:"GET",path:"/ai/models",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listProviders(t){return e.send({op:"ListProviders",method:"GET",path:"/ai/providers",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async connectProvider(t){return e.send({op:"ConnectProvider",method:"PUT",path:"/ai/providers/"+c("ConnectProvider","provider",t.path.provider),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async disconnectProvider(t){return e.send({op:"DisconnectProvider",method:"DELETE",path:"/ai/providers/"+c("DisconnectProvider","provider",t.path.provider),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listRepos(t){return e.send({op:"ListRepos",method:"GET",path:"/ai/repos",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async putRepo(t){return e.send({op:"PutRepo",method:"PUT",path:"/ai/repos/"+c("PutRepo","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteRepo(t){return e.send({op:"DeleteRepo",method:"DELETE",path:"/ai/repos/"+c("DeleteRepo","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async createResponse(t){return e.send({op:"CreateResponse",method:"POST",path:"/ai/responses",auth:[["SecretKeyAuth"]],answers:{200:"raw",202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getResponse(t){return e.send({op:"GetResponse",method:"GET",path:"/ai/responses/"+c("GetResponse","response_id",t.path.response_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async cancelResponse(t){return e.send({op:"CancelResponse",method:"POST",path:"/ai/responses/"+c("CancelResponse","response_id",t.path.response_id)+"/cancel",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async followResponse(t){return e.send({op:"FollowResponse",method:"GET",path:"/ai/responses/"+c("FollowResponse","response_id",t.path.response_id)+"/live",auth:[["SecretKeyAuth"]],answers:{200:"raw"},query:t.query,signal:t.signal})},async getSettings(t){return e.send({op:"GetSettings",method:"GET",path:"/ai/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putSettings(t){return e.send({op:"PutSettings",method:"PUT",path:"/ai/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSpend(t){return e.send({op:"GetSpend",method:"GET",path:"/ai/spend",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async askSupport(t){return e.send({op:"AskSupport",method:"POST",path:"/ai/support-questions",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listTools(t){return e.send({op:"ListTools",method:"GET",path:"/ai/tools",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listUsage(t){return e.send({op:"ListUsage",method:"GET",path:"/ai/usage",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})}}}var Os={};We(Os,{client:()=>xw});function xw(e){return{async listAudiences(t){return e.send({op:"ListAudiences",method:"GET",path:"/analytics/audiences",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async createAudience(t){return e.send({op:"CreateAudience",method:"POST",path:"/analytics/audiences",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async previewAudience(t){return e.send({op:"PreviewAudience",method:"POST",path:"/analytics/audiences/preview",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getAudience(t){return e.send({op:"GetAudience",method:"GET",path:"/analytics/audiences/"+c("GetAudience","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deleteAudience(t){return e.send({op:"DeleteAudience",method:"DELETE",path:"/analytics/audiences/"+c("DeleteAudience","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async updateAudience(t){return e.send({op:"UpdateAudience",method:"PATCH",path:"/analytics/audiences/"+c("UpdateAudience","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listAudienceMembers(t){return e.send({op:"ListAudienceMembers",method:"GET",path:"/analytics/audiences/"+c("ListAudienceMembers","id",t.path.id)+"/members",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async alias(t){return e.send({op:"Alias",method:"POST",path:"/analytics/alias",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async batch(t){return e.send({op:"Batch",method:"POST",path:"/analytics/batch",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"json",207:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getEventBreakdown(t){return e.send({op:"GetEventBreakdown",method:"GET",path:"/analytics/breakdown",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async capture(t){return e.send({op:"Capture",method:"POST",path:"/analytics/capture",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async sendConsoleHistory(t){return e.send({op:"SendConsoleHistory",method:"POST",path:"/analytics/console-breadcrumbs",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getConsoleConfig(t){return e.send({op:"GetConsoleConfig",method:"GET",path:"/analytics/console-breadcrumbs/config",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listConsoleRecords(t){return e.send({op:"ListConsoleRecords",method:"GET",path:"/analytics/console-records",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listEventNames(t){return e.send({op:"ListEventNames",method:"GET",path:"/analytics/event-names",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listEvents(t){return e.send({op:"ListEvents",method:"GET",path:"/analytics/events",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getEventTimeline(t){return e.send({op:"GetEventTimeline",method:"GET",path:"/analytics/events/timeline",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async runFunnel(t){return e.send({op:"RunFunnel",method:"POST",path:"/analytics/funnel",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async identify(t){return e.send({op:"Identify",method:"POST",path:"/analytics/identify",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async page(t){return e.send({op:"Page",method:"POST",path:"/analytics/page",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async sendPerf(t){return e.send({op:"SendPerf",method:"POST",path:"/analytics/perf",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listPerfGroups(t){return e.send({op:"ListPerfGroups",method:"GET",path:"/analytics/perf/client",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getPerfConfig(t){return e.send({op:"GetPerfConfig",method:"GET",path:"/analytics/perf/config",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json",304:"empty"},headers:t?.headers,signal:t?.signal})},async getPerfTimeline(t){return e.send({op:"GetPerfTimeline",method:"GET",path:"/analytics/perf/timeline",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async listRequestLines(t){return e.send({op:"ListRequestLines",method:"GET",path:"/analytics/requests",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getMachineTraffic(t){return e.send({op:"GetMachineTraffic",method:"GET",path:"/analytics/machines/"+c("GetMachineTraffic","name",t.path.name)+"/traffic",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async runRetention(t){return e.send({op:"RunRetention",method:"POST",path:"/analytics/retention",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async screen(t){return e.send({op:"Screen",method:"POST",path:"/analytics/screen",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSettings(t){return e.send({op:"GetSettings",method:"GET",path:"/analytics/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putSettings(t){return e.send({op:"PutSettings",method:"PUT",path:"/analytics/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSummary(t){return e.send({op:"GetSummary",method:"GET",path:"/analytics/summary",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listTraces(t){return e.send({op:"ListTraces",method:"GET",path:"/analytics/traces",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async sendTrace(t){return e.send({op:"SendTrace",method:"POST",path:"/analytics/traces",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async sendTraceBatch(t){return e.send({op:"SendTraceBatch",method:"POST",path:"/analytics/traces/batch",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"json",207:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getTraceHops(t){return e.send({op:"GetTraceHops",method:"GET",path:"/analytics/traces/by-trace",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async listSessionTraces(t){return e.send({op:"ListSessionTraces",method:"GET",path:"/analytics/traces/session",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getTraceSummary(t){return e.send({op:"GetTraceSummary",method:"GET",path:"/analytics/traces/summary",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getTraceTimeline(t){return e.send({op:"GetTraceTimeline",method:"GET",path:"/analytics/traces/timeline",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async searchPeople(t){return e.send({op:"SearchPeople",method:"GET",path:"/analytics/people",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async setPersonProperties(t){return e.send({op:"SetPersonProperties",method:"POST",path:"/analytics/people",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPerson(t){return e.send({op:"GetPerson",method:"GET",path:"/analytics/people/"+c("GetPerson","person_id",t.path.person_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listPersonEvents(t){return e.send({op:"ListPersonEvents",method:"GET",path:"/analytics/people/"+c("ListPersonEvents","person_id",t.path.person_id)+"/events",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getEventCatalog(t){return e.send({op:"GetEventCatalog",method:"GET",path:"/analytics/catalog",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async defineEvent(t){return e.send({op:"DefineEvent",method:"PUT",path:"/analytics/catalog/"+c("DefineEvent","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})}}}var Ms={};We(Ms,{client:()=>Iw});function Iw(e){return{async getAppleAppSiteAssociation(t){return e.send({op:"GetAppleAppSiteAssociation",method:"GET",path:"/.well-known/apple-app-site-association",auth:[],answers:{200:"json"},signal:t?.signal})},async getAssetLinks(t){return e.send({op:"GetAssetLinks",method:"GET",path:"/.well-known/assetlinks.json",auth:[],answers:{200:"json"},signal:t?.signal})},async getJwks(t){return e.send({op:"GetJWKS",method:"GET",path:"/.well-known/jwks.json",auth:[],answers:{200:"json"},signal:t?.signal})},async getOidcDiscovery(t){return e.send({op:"GetOIDCDiscovery",method:"GET",path:"/.well-known/openid-configuration",auth:[],answers:{200:"json"},signal:t?.signal})},async getWebAuthnRelatedOrigins(t){return e.send({op:"GetWebAuthnRelatedOrigins",method:"GET",path:"/.well-known/webauthn",auth:[],answers:{200:"json"},signal:t?.signal})},async adminVerifyDeviceAssertion(t){return e.send({op:"AdminVerifyDeviceAssertion",method:"POST",path:"/admin/attest/devices/assert",auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetAttestPolicy(t){return e.send({op:"AdminGetAttestPolicy",method:"GET",path:"/admin/attest/devices/attest-policy",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminGetAttestObservations(t){return e.send({op:"AdminGetAttestObservations",method:"GET",path:"/admin/attest/devices/observations",auth:[["AdminAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminRecordAttestObservations(t){return e.send({op:"AdminRecordAttestObservations",method:"POST",path:"/admin/attest/devices/observations",auth:[["AdminAuth"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListAuditEvents(t){return e.send({op:"AdminListAuditEvents",method:"GET",path:"/admin/audit",auth:[["AdminAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminExportAuditEvents(t){return e.send({op:"AdminExportAuditEvents",method:"GET",path:"/admin/audit/export",auth:[["AdminAuth"]],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async adminVerifyAuditTrail(t){return e.send({op:"AdminVerifyAuditTrail",method:"GET",path:"/admin/audit/verify",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminGetAuthSettings(t){return e.send({op:"AdminGetAuthSettings",method:"GET",path:"/admin/auth-settings",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminUpdateAuthSettings(t){return e.send({op:"AdminUpdateAuthSettings",method:"PUT",path:"/admin/auth-settings",auth:[["AdminAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetBreachWatch(t){return e.send({op:"AdminGetBreachWatch",method:"GET",path:"/admin/breach-watch",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminListHooks(t){return e.send({op:"AdminListHooks",method:"GET",path:"/admin/hooks",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminCreateHook(t){return e.send({op:"AdminCreateHook",method:"POST",path:"/admin/hooks",auth:[["AdminAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminUpdateHook(t){return e.send({op:"AdminUpdateHook",method:"PUT",path:"/admin/hooks/"+c("AdminUpdateHook","id",t.path.id),auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminDeleteHook(t){return e.send({op:"AdminDeleteHook",method:"DELETE",path:"/admin/hooks/"+c("AdminDeleteHook","id",t.path.id),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminListHookExecutions(t){return e.send({op:"AdminListHookExecutions",method:"GET",path:"/admin/hooks/"+c("AdminListHookExecutions","id",t.path.id)+"/executions",auth:[["AdminAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async adminListIntegrations(t){return e.send({op:"AdminListIntegrations",method:"GET",path:"/admin/integrations",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminPutIntegration(t){return e.send({op:"AdminPutIntegration",method:"PUT",path:"/admin/integrations/"+c("AdminPutIntegration","name",t.path.name),auth:[["AdminAuth"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminDeleteIntegration(t){return e.send({op:"AdminDeleteIntegration",method:"DELETE",path:"/admin/integrations/"+c("AdminDeleteIntegration","name",t.path.name),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminListOAuthClients(t){return e.send({op:"AdminListOAuthClients",method:"GET",path:"/admin/oauth-clients",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminCreateOAuthClient(t){return e.send({op:"AdminCreateOAuthClient",method:"POST",path:"/admin/oauth-clients",auth:[["AdminAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetOAuthClient(t){return e.send({op:"AdminGetOAuthClient",method:"GET",path:"/admin/oauth-clients/"+c("AdminGetOAuthClient","id",t.path.id),auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminDeleteOAuthClient(t){return e.send({op:"AdminDeleteOAuthClient",method:"DELETE",path:"/admin/oauth-clients/"+c("AdminDeleteOAuthClient","id",t.path.id),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminUpdateOAuthClient(t){return e.send({op:"AdminUpdateOAuthClient",method:"PATCH",path:"/admin/oauth-clients/"+c("AdminUpdateOAuthClient","id",t.path.id),auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListProviders(t){return e.send({op:"AdminListProviders",method:"GET",path:"/admin/providers",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminGetPhoneSettings(t){return e.send({op:"AdminGetPhoneSettings",method:"GET",path:"/admin/providers/phone/settings",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminUpdatePhoneSettings(t){return e.send({op:"AdminUpdatePhoneSettings",method:"PUT",path:"/admin/providers/phone/settings",auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminToggleProvider(t){return e.send({op:"AdminToggleProvider",method:"POST",path:"/admin/providers/"+c("AdminToggleProvider","name",t.path.name),auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListRoles(t){return e.send({op:"AdminListRoles",method:"GET",path:"/admin/roles",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminUpsertRole(t){return e.send({op:"AdminUpsertRole",method:"PUT",path:"/admin/roles/"+c("AdminUpsertRole","name",t.path.name),auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminDeleteRole(t){return e.send({op:"AdminDeleteRole",method:"DELETE",path:"/admin/roles/"+c("AdminDeleteRole","name",t.path.name),auth:[["AdminAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async adminListServiceAccounts(t){return e.send({op:"AdminListServiceAccounts",method:"GET",path:"/admin/service-accounts",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminCreateServiceAccount(t){return e.send({op:"AdminCreateServiceAccount",method:"POST",path:"/admin/service-accounts",auth:[["AdminAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetServiceAccount(t){return e.send({op:"AdminGetServiceAccount",method:"GET",path:"/admin/service-accounts/"+c("AdminGetServiceAccount","id",t.path.id),auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminRevokeServiceAccount(t){return e.send({op:"AdminRevokeServiceAccount",method:"DELETE",path:"/admin/service-accounts/"+c("AdminRevokeServiceAccount","id",t.path.id),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminRotateServiceAccount(t){return e.send({op:"AdminRotateServiceAccount",method:"POST",path:"/admin/service-accounts/"+c("AdminRotateServiceAccount","id",t.path.id)+"/rotate",auth:[["AdminAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async adminListSessions(t){return e.send({op:"AdminListSessions",method:"GET",path:"/admin/sessions",auth:[["AdminAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminRevokeSession(t){return e.send({op:"AdminRevokeSession",method:"DELETE",path:"/admin/sessions/"+c("AdminRevokeSession","id",t.path.id),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminListSigningKeys(t){return e.send({op:"AdminListSigningKeys",method:"GET",path:"/admin/signing-keys",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminRotateSigningKey(t){return e.send({op:"AdminRotateSigningKey",method:"POST",path:"/admin/signing-keys/rotate",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async socialAdminConfig(t){return e.send({op:"SocialAdminConfig",method:"GET",path:"/admin/social-auth",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async socialCredentialPut(t){return e.send({op:"SocialCredentialPut",method:"PUT",path:"/admin/social-auth/credentials/"+c("SocialCredentialPut","key",t.path.key),auth:[["AdminAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async socialCredentialDelete(t){return e.send({op:"SocialCredentialDelete",method:"DELETE",path:"/admin/social-auth/credentials/"+c("SocialCredentialDelete","key",t.path.key),auth:[["AdminAuth"]],answers:{204:"empty"},headers:t.headers,signal:t.signal})},async socialProviderPatch(t){return e.send({op:"SocialProviderPatch",method:"PATCH",path:"/admin/social-auth/providers/"+c("SocialProviderPatch","provider",t.path.provider),auth:[["AdminAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetStats(t){return e.send({op:"AdminGetStats",method:"GET",path:"/admin/stats",auth:[["AdminAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminSendTestTemplate(t){return e.send({op:"AdminSendTestTemplate",method:"POST",path:"/admin/templates/"+c("AdminSendTestTemplate","key",t.path.key)+"/send-test",auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListTestUsers(t){return e.send({op:"AdminListTestUsers",method:"GET",path:"/admin/test-users",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminCreateTestUsers(t){return e.send({op:"AdminCreateTestUsers",method:"POST",path:"/admin/test-users",auth:[["AdminAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminSetTestUserPhone(t){return e.send({op:"AdminSetTestUserPhone",method:"PUT",path:"/admin/test-users/phone",auth:[["AdminAuth"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminCreateTestSignupAddress(t){return e.send({op:"AdminCreateTestSignupAddress",method:"POST",path:"/admin/test-users/addresses",auth:[["AdminAuth"]],answers:{201:"json"},signal:t?.signal})},async adminDeleteTestUser(t){return e.send({op:"AdminDeleteTestUser",method:"DELETE",path:"/admin/test-users/"+c("AdminDeleteTestUser","uid",t.path.uid),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminCreateCustomToken(t){return e.send({op:"AdminCreateCustomToken",method:"POST",path:"/admin/token/custom",auth:[["AdminAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListUsers(t){return e.send({op:"AdminListUsers",method:"GET",path:"/admin/users",auth:[["AdminAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminCreateUser(t){return e.send({op:"AdminCreateUser",method:"POST",path:"/admin/users",auth:[["AdminAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminImportUsers(t){return e.send({op:"AdminImportUsers",method:"POST",path:"/admin/users/import",auth:[["AdminAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetUser(t){return e.send({op:"AdminGetUser",method:"GET",path:"/admin/users/"+c("AdminGetUser","uid",t.path.uid),auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminDeleteUser(t){return e.send({op:"AdminDeleteUser",method:"DELETE",path:"/admin/users/"+c("AdminDeleteUser","uid",t.path.uid),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminUpdateUser(t){return e.send({op:"AdminUpdateUser",method:"PATCH",path:"/admin/users/"+c("AdminUpdateUser","uid",t.path.uid),auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminBanUser(t){return e.send({op:"AdminBanUser",method:"POST",path:"/admin/users/"+c("AdminBanUser","uid",t.path.uid)+"/ban",auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetUserConsents(t){return e.send({op:"AdminGetUserConsents",method:"GET",path:"/admin/users/"+c("AdminGetUserConsents","uid",t.path.uid)+"/consents",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminRevokeUserCredentials(t){return e.send({op:"AdminRevokeUserCredentials",method:"POST",path:"/admin/users/"+c("AdminRevokeUserCredentials","uid",t.path.uid)+"/credentials/revoke-all",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminExportUser(t){return e.send({op:"AdminExportUser",method:"GET",path:"/admin/users/"+c("AdminExportUser","uid",t.path.uid)+"/export",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminListUserMfaFactors(t){return e.send({op:"AdminListUserMFAFactors",method:"GET",path:"/admin/users/"+c("AdminListUserMFAFactors","uid",t.path.uid)+"/mfa",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminResetUserMfa(t){return e.send({op:"AdminResetUserMFA",method:"DELETE",path:"/admin/users/"+c("AdminResetUserMFA","uid",t.path.uid)+"/mfa",auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminResetUserPassword(t){return e.send({op:"AdminResetUserPassword",method:"POST",path:"/admin/users/"+c("AdminResetUserPassword","uid",t.path.uid)+"/reset-password",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminListUserRoles(t){return e.send({op:"AdminListUserRoles",method:"GET",path:"/admin/users/"+c("AdminListUserRoles","uid",t.path.uid)+"/roles",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminAssignUserRole(t){return e.send({op:"AdminAssignUserRole",method:"PUT",path:"/admin/users/"+c("AdminAssignUserRole","uid",t.path.uid)+"/roles/"+c("AdminAssignUserRole","role",t.path.role),auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminRevokeUserRole(t){return e.send({op:"AdminRevokeUserRole",method:"DELETE",path:"/admin/users/"+c("AdminRevokeUserRole","uid",t.path.uid)+"/roles/"+c("AdminRevokeUserRole","role",t.path.role),auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminRevokeUserSessions(t){return e.send({op:"AdminRevokeUserSessions",method:"POST",path:"/admin/users/"+c("AdminRevokeUserSessions","uid",t.path.uid)+"/sessions/revoke-all",auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminUnbanUser(t){return e.send({op:"AdminUnbanUser",method:"POST",path:"/admin/users/"+c("AdminUnbanUser","uid",t.path.uid)+"/unban",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async signInAnonymously(t){return e.send({op:"SignInAnonymously",method:"POST",path:"/auth/anonymous",auth:[["ApiKeyAuth"]],answers:{201:"json"},headers:t?.headers,body:{kind:"json",contentType:"application/json",value:t?.body},signal:t?.signal})},async convertAnonymousUser(t){return e.send({op:"ConvertAnonymousUser",method:"POST",path:"/auth/anonymous/convert",auth:[["ApiKeyAuth","userJWT"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async verifyAnonymousConversion(t){return e.send({op:"VerifyAnonymousConversion",method:"POST",path:"/auth/anonymous/convert/verify",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async devicePendingRequest(t){return e.send({op:"DevicePendingRequest",method:"GET",path:"/auth/device/requests/"+c("DevicePendingRequest","user_code",t.path.user_code),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async deviceVerifyPage(t){return e.send({op:"DeviceVerifyPage",method:"GET",path:"/auth/device/verify",auth:[["ApiKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async deviceVerifySubmit(t){return e.send({op:"DeviceVerifySubmit",method:"POST",path:"/auth/device/verify",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async listDevices(t){return e.send({op:"ListDevices",method:"GET",path:"/auth/devices",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async attestAndroidDevice(t){return e.send({op:"AttestAndroidDevice",method:"POST",path:"/auth/devices/attest/android",auth:[["ApiKeyAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async attestIosDevice(t){return e.send({op:"AttestIOSDevice",method:"POST",path:"/auth/devices/attest/ios",auth:[["ApiKeyAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async bindDeviceKey(t){return e.send({op:"BindDeviceKey",method:"POST",path:"/auth/devices/bind",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createDeviceChallenge(t){return e.send({op:"CreateDeviceChallenge",method:"POST",path:"/auth/devices/challenge",auth:[["ApiKeyAuth"]],answers:{200:"json"},headers:t?.headers,signal:t?.signal})},async verifyAndroidIntegrity(t){return e.send({op:"VerifyAndroidIntegrity",method:"POST",path:"/auth/devices/verify/android",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteDevice(t){return e.send({op:"DeleteDevice",method:"DELETE",path:"/auth/devices/"+c("DeleteDevice","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async verifyDeviceSignature(t){return e.send({op:"VerifyDeviceSignature",method:"POST",path:"/auth/devices/"+c("VerifyDeviceSignature","id",t.path.id)+"/verify",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listIdentities(t){return e.send({op:"ListIdentities",method:"GET",path:"/auth/identities",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async unlinkIdentity(t){return e.send({op:"UnlinkIdentity",method:"DELETE",path:"/auth/identities/"+c("UnlinkIdentity","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async createInstallation(t){return e.send({op:"CreateInstallation",method:"POST",path:"/auth/installations",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async bindInstallation(t){return e.send({op:"BindInstallation",method:"POST",path:"/auth/installations/"+c("BindInstallation","id",t.path.id)+"/bind",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async refreshInstallation(t){return e.send({op:"RefreshInstallation",method:"POST",path:"/auth/installations/"+c("RefreshInstallation","id",t.path.id)+"/refresh",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async revokeInstallation(t){return e.send({op:"RevokeInstallation",method:"POST",path:"/auth/installations/"+c("RevokeInstallation","id",t.path.id)+"/revoke",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async unbindInstallation(t){return e.send({op:"UnbindInstallation",method:"POST",path:"/auth/installations/"+c("UnbindInstallation","id",t.path.id)+"/unbind",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async login(t){return e.send({op:"Login",method:"POST",path:"/auth/login",auth:[["ApiKeyAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async logout(t){return e.send({op:"Logout",method:"POST",path:"/auth/logout",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async magicLinkRequest(t){return e.send({op:"MagicLinkRequest",method:"POST",path:"/auth/magic-link",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async magicLinkVerify(t){return e.send({op:"MagicLinkVerify",method:"POST",path:"/auth/magic-link/verify",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getMe(t){return e.send({op:"GetMe",method:"GET",path:"/auth/me",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async updateMe(t){return e.send({op:"UpdateMe",method:"PATCH",path:"/auth/me",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaChallenge(t){return e.send({op:"MfaChallenge",method:"POST",path:"/auth/mfa/challenge",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaEmailChallenge(t){return e.send({op:"MfaEmailChallenge",method:"POST",path:"/auth/mfa/email/challenge",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaEmailEnroll(t){return e.send({op:"MfaEmailEnroll",method:"POST",path:"/auth/mfa/email/enroll",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async mfaEmailVerify(t){return e.send({op:"MfaEmailVerify",method:"POST",path:"/auth/mfa/email/verify",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaEnroll(t){return e.send({op:"MfaEnroll",method:"POST",path:"/auth/mfa/enroll",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaListFactors(t){return e.send({op:"MfaListFactors",method:"GET",path:"/auth/mfa/factors",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async mfaRemoveFactor(t){return e.send({op:"MfaRemoveFactor",method:"DELETE",path:"/auth/mfa/factors/"+c("MfaRemoveFactor","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaRecovery(t){return e.send({op:"MfaRecovery",method:"POST",path:"/auth/mfa/recovery",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaRegenerateRecoveryCodes(t){return e.send({op:"MfaRegenerateRecoveryCodes",method:"POST",path:"/auth/mfa/recovery-codes/regenerate",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async mfaSmsChallenge(t){return e.send({op:"MfaSMSChallenge",method:"POST",path:"/auth/mfa/sms/challenge",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaSmsEnroll(t){return e.send({op:"MfaSMSEnroll",method:"POST",path:"/auth/mfa/sms/enroll",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaSmsVerifyEnrollment(t){return e.send({op:"MfaSMSVerifyEnrollment",method:"POST",path:"/auth/mfa/sms/verify",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaVerifyEnrollment(t){return e.send({op:"MfaVerifyEnrollment",method:"POST",path:"/auth/mfa/verify",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async socialCallbackApple(t){return e.send({op:"SocialCallbackApple",method:"GET",path:"/auth/oauth/callback/apple",auth:[],answers:{},signal:t?.signal})},async socialCallbackApplePost(t){return e.send({op:"SocialCallbackApplePost",method:"POST",path:"/auth/oauth/callback/apple",auth:[],answers:{303:"redirect"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async socialCallbackGitHub(t){return e.send({op:"SocialCallbackGitHub",method:"GET",path:"/auth/oauth/callback/github",auth:[],answers:{303:"redirect"},query:t.query,signal:t.signal})},async socialCallbackGitHubPost(t){return e.send({op:"SocialCallbackGitHubPost",method:"POST",path:"/auth/oauth/callback/github",auth:[],answers:{},signal:t?.signal})},async socialCallbackGoogle(t){return e.send({op:"SocialCallbackGoogle",method:"GET",path:"/auth/oauth/callback/google",auth:[],answers:{303:"redirect"},query:t.query,signal:t.signal})},async socialCallbackGooglePost(t){return e.send({op:"SocialCallbackGooglePost",method:"POST",path:"/auth/oauth/callback/google",auth:[],answers:{},signal:t?.signal})},async socialCallbackMicrosoft(t){return e.send({op:"SocialCallbackMicrosoft",method:"GET",path:"/auth/oauth/callback/microsoft",auth:[],answers:{303:"redirect"},query:t.query,signal:t.signal})},async socialCallbackMicrosoftPost(t){return e.send({op:"SocialCallbackMicrosoftPost",method:"POST",path:"/auth/oauth/callback/microsoft",auth:[],answers:{},signal:t?.signal})},async socialConfig(t){return e.send({op:"SocialConfig",method:"GET",path:"/auth/oauth/config",auth:[["ApiKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async socialBegin(t){return e.send({op:"SocialBegin",method:"POST",path:"/auth/oauth/transactions",auth:[["ApiKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async socialCancel(t){return e.send({op:"SocialCancel",method:"POST",path:"/auth/oauth/transactions/"+c("SocialCancel","id",t.path.id)+"/cancel",auth:[["ApiKeyAuth"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async socialComplete(t){return e.send({op:"SocialComplete",method:"POST",path:"/auth/oauth/transactions/"+c("SocialComplete","id",t.path.id)+"/complete",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async requestPhoneOtp(t){return e.send({op:"RequestPhoneOTP",method:"POST",path:"/auth/otp",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async verifyPhoneOtp(t){return e.send({op:"VerifyPhoneOTP",method:"POST",path:"/auth/otp/verify",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async hostedRecoveryApprovalPage(t){return e.send({op:"HostedRecoveryApprovalPage",method:"GET",path:"/auth/pages/recovery-approval",auth:[],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async hostedRecoveryApprovalSubmit(t){return e.send({op:"HostedRecoveryApprovalSubmit",method:"POST",path:"/auth/pages/recovery-approval",auth:[],answers:{200:"raw"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async hostedRecoveryContactPage(t){return e.send({op:"HostedRecoveryContactPage",method:"GET",path:"/auth/pages/recovery-contact",auth:[],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async hostedRecoveryContactSubmit(t){return e.send({op:"HostedRecoveryContactSubmit",method:"POST",path:"/auth/pages/recovery-contact",auth:[],answers:{200:"raw"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async hostedResetPasswordPage(t){return e.send({op:"HostedResetPasswordPage",method:"GET",path:"/auth/pages/reset-password",auth:[],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async hostedResetPasswordSubmit(t){return e.send({op:"HostedResetPasswordSubmit",method:"POST",path:"/auth/pages/reset-password",auth:[],answers:{200:"raw"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async hostedVerifyEmailPage(t){return e.send({op:"HostedVerifyEmailPage",method:"GET",path:"/auth/pages/verify-email",auth:[],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async hostedVerifyEmailSubmit(t){return e.send({op:"HostedVerifyEmailSubmit",method:"POST",path:"/auth/pages/verify-email",auth:[],answers:{200:"raw"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async passwordChange(t){return e.send({op:"PasswordChange",method:"POST",path:"/auth/password/change",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async passwordResetRequest(t){return e.send({op:"PasswordResetRequest",method:"POST",path:"/auth/password/reset",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async passwordResetConfirm(t){return e.send({op:"PasswordResetConfirm",method:"POST",path:"/auth/password/reset/confirm",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async setPassword(t){return e.send({op:"SetPassword",method:"POST",path:"/auth/password/set",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async powChallenge(t){return e.send({op:"PowChallenge",method:"POST",path:"/auth/pow/challenge",auth:[["ApiKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async approveRecovery(t){return e.send({op:"ApproveRecovery",method:"POST",path:"/auth/recovery/approve",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listRecoveryContacts(t){return e.send({op:"ListRecoveryContacts",method:"GET",path:"/auth/recovery/contacts",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async addRecoveryContact(t){return e.send({op:"AddRecoveryContact",method:"POST",path:"/auth/recovery/contacts",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteRecoveryContact(t){return e.send({op:"DeleteRecoveryContact",method:"DELETE",path:"/auth/recovery/contacts/"+c("DeleteRecoveryContact","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async verifyRecoveryContact(t){return e.send({op:"VerifyRecoveryContact",method:"POST",path:"/auth/recovery/contacts/"+c("VerifyRecoveryContact","id",t.path.id)+"/verify",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async denyRecovery(t){return e.send({op:"DenyRecovery",method:"POST",path:"/auth/recovery/deny",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async initiateRecovery(t){return e.send({op:"InitiateRecovery",method:"POST",path:"/auth/recovery/initiate",auth:[["ApiKeyAuth"]],answers:{200:"json",202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getRecoveryStatus(t){return e.send({op:"GetRecoveryStatus",method:"GET",path:"/auth/recovery/status",auth:[["ApiKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async resendVerification(t){return e.send({op:"ResendVerification",method:"POST",path:"/auth/resend-verification",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listSessions(t){return e.send({op:"ListSessions",method:"GET",path:"/auth/sessions",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async revokeAllSessions(t){return e.send({op:"RevokeAllSessions",method:"DELETE",path:"/auth/sessions",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async revokeSession(t){return e.send({op:"RevokeSession",method:"DELETE",path:"/auth/sessions/"+c("RevokeSession","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async signup(t){return e.send({op:"Signup",method:"POST",path:"/auth/signup",auth:[["ApiKeyAuth"]],answers:{201:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async stepUp(t){return e.send({op:"StepUp",method:"POST",path:"/auth/step-up",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async stepUpStatus(t){return e.send({op:"StepUpStatus",method:"GET",path:"/auth/step-up/status",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async stepUpWebAuthnBegin(t){return e.send({op:"StepUpWebAuthnBegin",method:"POST",path:"/auth/step-up/webauthn/begin",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async stepUpSmsSend(t){return e.send({op:"StepUpSMSSend",method:"POST",path:"/auth/step-up/sms/send",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async exchangeCustomToken(t){return e.send({op:"ExchangeCustomToken",method:"POST",path:"/auth/token/exchange",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async refreshToken(t){return e.send({op:"RefreshToken",method:"POST",path:"/auth/token/refresh",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async revokeRefreshToken(t){return e.send({op:"RevokeRefreshToken",method:"POST",path:"/auth/token/revoke",auth:[["ApiKeyAuth"]],answers:{200:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listTransactions(t){return e.send({op:"ListTransactions",method:"GET",path:"/auth/transactions",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createTransaction(t){return e.send({op:"CreateTransaction",method:"POST",path:"/auth/transactions",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getTransaction(t){return e.send({op:"GetTransaction",method:"GET",path:"/auth/transactions/"+c("GetTransaction","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async approveTransaction(t){return e.send({op:"ApproveTransaction",method:"POST",path:"/auth/transactions/"+c("ApproveTransaction","id",t.path.id)+"/approve",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async denyTransaction(t){return e.send({op:"DenyTransaction",method:"POST",path:"/auth/transactions/"+c("DenyTransaction","id",t.path.id)+"/deny",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listTrustedDevices(t){return e.send({op:"ListTrustedDevices",method:"GET",path:"/auth/trusted-devices",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async registerTrustedDevice(t){return e.send({op:"RegisterTrustedDevice",method:"POST",path:"/auth/trusted-devices",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async revokeTrustedDevice(t){return e.send({op:"RevokeTrustedDevice",method:"DELETE",path:"/auth/trusted-devices/"+c("RevokeTrustedDevice","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async verifyTokenUser(t){return e.send({op:"VerifyTokenUser",method:"GET",path:"/auth/user",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async deleteAccount(t){return e.send({op:"DeleteAccount",method:"DELETE",path:"/auth/user",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t?.body},signal:t?.signal})},async verifyEmail(t){return e.send({op:"VerifyEmail",method:"POST",path:"/auth/verify-email",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnListCredentials(t){return e.send({op:"WebauthnListCredentials",method:"GET",path:"/auth/webauthn/credentials",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async webauthnRenameCredential(t){return e.send({op:"WebauthnRenameCredential",method:"PUT",path:"/auth/webauthn/credentials/"+c("WebauthnRenameCredential","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnDeleteCredential(t){return e.send({op:"WebauthnDeleteCredential",method:"DELETE",path:"/auth/webauthn/credentials/"+c("WebauthnDeleteCredential","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async webauthnLoginBegin(t){return e.send({op:"WebauthnLoginBegin",method:"POST",path:"/auth/webauthn/login/begin",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t?.body},signal:t?.signal})},async webauthnLoginFinish(t){return e.send({op:"WebauthnLoginFinish",method:"POST",path:"/auth/webauthn/login/finish",auth:[["ApiKeyAuth"]],answers:{200:"json"},query:t.query,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnRecoveryBegin(t){return e.send({op:"WebauthnRecoveryBegin",method:"POST",path:"/auth/webauthn/recovery/begin",auth:[["ApiKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async webauthnRecoveryFinish(t){return e.send({op:"WebauthnRecoveryFinish",method:"POST",path:"/auth/webauthn/recovery/finish",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnRecoveryRegisterBegin(t){return e.send({op:"WebauthnRecoveryRegisterBegin",method:"POST",path:"/auth/webauthn/recovery/register/begin",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t?.body},signal:t?.signal})},async webauthnRecoveryRegisterFinish(t){return e.send({op:"WebauthnRecoveryRegisterFinish",method:"POST",path:"/auth/webauthn/recovery/register/finish",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnRegisterBegin(t){return e.send({op:"WebauthnRegisterBegin",method:"POST",path:"/auth/webauthn/register/begin",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t?.body},signal:t?.signal})},async webauthnRegisterFinish(t){return e.send({op:"WebauthnRegisterFinish",method:"POST",path:"/auth/webauthn/register/finish",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnSignupBegin(t){return e.send({op:"WebauthnSignupBegin",method:"POST",path:"/auth/webauthn/signup/begin",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnSignupFinish(t){return e.send({op:"WebauthnSignupFinish",method:"POST",path:"/auth/webauthn/signup/finish",auth:[["ApiKeyAuth"]],answers:{201:"json"},query:t.query,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async oauthAuthorize(t){return e.send({op:"OauthAuthorize",method:"GET",path:"/oauth/authorize",auth:[],answers:{302:"redirect",303:"redirect"},query:t?.query,signal:t?.signal})},async oauthAuthorizePost(t){return e.send({op:"OauthAuthorizePost",method:"POST",path:"/oauth/authorize",auth:[],answers:{302:"redirect",303:"redirect"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async oauthAuthorizeCallback(t){return e.send({op:"OauthAuthorizeCallback",method:"GET",path:"/oauth/authorize/callback",auth:[],answers:{303:"redirect"},query:t.query,signal:t.signal})},async oauthDeviceAuthorize(t){return e.send({op:"OauthDeviceAuthorize",method:"POST",path:"/oauth/device",auth:[["OAuthClient"],[]],answers:{200:"json"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async oauthIntrospect(t){return e.send({op:"OauthIntrospect",method:"POST",path:"/oauth/introspect",auth:[["AdminAuth"],["OAuthClient"],[]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async oauthLogout(t){return e.send({op:"OauthLogout",method:"GET",path:"/oauth/logout",auth:[],answers:{302:"redirect"},query:t?.query,signal:t?.signal})},async oauthLogoutPost(t){return e.send({op:"OauthLogoutPost",method:"POST",path:"/oauth/logout",auth:[],answers:{302:"redirect"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t?.body},signal:t?.signal})},async oauthPar(t){return e.send({op:"OauthPAR",method:"POST",path:"/oauth/par",auth:[["OAuthClient"],[]],answers:{201:"json"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async oauthRevoke(t){return e.send({op:"OauthRevoke",method:"POST",path:"/oauth/revoke",auth:[["OAuthClient"],[]],answers:{200:"empty"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async oauthToken(t){return e.send({op:"OauthToken",method:"POST",path:"/oauth/token",auth:[["OAuthClient"],[]],answers:{200:"json"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async oauthUserinfo(t){return e.send({op:"OauthUserinfo",method:"GET",path:"/oauth/userinfo",auth:[["OAuthAccessToken"]],answers:{200:"json"},signal:t?.signal})},async oauthUserinfoPost(t){return e.send({op:"OauthUserinfoPost",method:"POST",path:"/oauth/userinfo",auth:[["OAuthAccessToken"]],answers:{200:"json"},signal:t?.signal})},async ownerCliCode(t){return e.send({op:"OwnerCLICode",method:"POST",path:"/auth/cli/owner-code",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listConsentKeys(t){return e.send({op:"ListConsentKeys",method:"GET",path:"/auth/consents/keys",auth:[["ApiKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getConsents(t){return e.send({op:"GetConsents",method:"GET",path:"/auth/consents",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,headers:t.headers,signal:t.signal})},async chooseConsents(t){return e.send({op:"ChooseConsents",method:"PUT",path:"/auth/consents",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async linkConsents(t){return e.send({op:"LinkConsents",method:"POST",path:"/auth/consents/link",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetInstallationConsents(t){return e.send({op:"AdminGetInstallationConsents",method:"GET",path:"/admin/installations/"+c("AdminGetInstallationConsents","installation_id",t.path.installation_id)+"/consents",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminRefuseConsents(t){return e.send({op:"AdminRefuseConsents",method:"POST",path:"/admin/consents/refuse",auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})}}}var Ua={};We(Ua,{client:()=>Lw});function Lw(e){return{async getCacheEntry(t){return e.send({op:"GetCacheEntry",method:"GET",path:"/cache/entry",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async putCacheEntry(t){return e.send({op:"PutCacheEntry",method:"PUT",path:"/cache/entry",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteCacheEntry(t){return e.send({op:"DeleteCacheEntry",method:"DELETE",path:"/cache/entry",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async incrementCacheEntry(t){return e.send({op:"IncrementCacheEntry",method:"POST",path:"/cache/entry/increment",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getCacheUsage(t){return e.send({op:"GetCacheUsage",method:"GET",path:"/cache/usage",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})}}}var za={};We(za,{client:()=>Dw});function Dw(e){return{async listCalls(t){return e.send({op:"ListCalls",method:"GET",path:"/calls",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async startCall(t){return e.send({op:"StartCall",method:"POST",path:"/calls",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json",201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListCalls(t){return e.send({op:"AdminListCalls",method:"GET",path:"/calls/admin/calls",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminGetCall(t){return e.send({op:"AdminGetCall",method:"GET",path:"/calls/admin/calls/"+c("AdminGetCall","call_id",t.path.call_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async adminEndCall(t){return e.send({op:"AdminEndCall",method:"POST",path:"/calls/admin/calls/"+c("AdminEndCall","call_id",t.path.call_id)+"/end",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async createCallTicket(t){return e.send({op:"CreateCallTicket",method:"POST",path:"/calls/admin/calls/"+c("CreateCallTicket","call_id",t.path.call_id)+"/tickets",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getCallPlace(t){return e.send({op:"GetCallPlace",method:"GET",path:"/calls/places/"+c("GetCallPlace","place",t.path.place),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async watchCallPlace(t){return e.send({op:"WatchCallPlace",method:"POST",path:"/calls/places/"+c("WatchCallPlace","place",t.path.place)+"/watch",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async unwatchCallPlace(t){return e.send({op:"UnwatchCallPlace",method:"DELETE",path:"/calls/places/"+c("UnwatchCallPlace","place",t.path.place)+"/watch",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async getCallSettings(t){return e.send({op:"GetCallSettings",method:"GET",path:"/calls/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putCallSettings(t){return e.send({op:"PutCallSettings",method:"PUT",path:"/calls/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async rotateCallHookSecret(t){return e.send({op:"RotateCallHookSecret",method:"POST",path:"/calls/settings/hook-secret",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getCall(t){return e.send({op:"GetCall",method:"GET",path:"/calls/"+c("GetCall","call_id",t.path.call_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async acceptCall(t){return e.send({op:"AcceptCall",method:"POST",path:"/calls/"+c("AcceptCall","call_id",t.path.call_id)+"/accept",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async declineCall(t){return e.send({op:"DeclineCall",method:"POST",path:"/calls/"+c("DeclineCall","call_id",t.path.call_id)+"/decline",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async callHeartbeat(t){return e.send({op:"CallHeartbeat",method:"POST",path:"/calls/"+c("CallHeartbeat","call_id",t.path.call_id)+"/heartbeat",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async joinCall(t){return e.send({op:"JoinCall",method:"POST",path:"/calls/"+c("JoinCall","call_id",t.path.call_id)+"/join",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async leaveCall(t){return e.send({op:"LeaveCall",method:"POST",path:"/calls/"+c("LeaveCall","call_id",t.path.call_id)+"/leave",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async getCallMedia(t){return e.send({op:"GetCallMedia",method:"POST",path:"/calls/"+c("GetCallMedia","call_id",t.path.call_id)+"/media",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async inviteToCall(t){return e.send({op:"InviteToCall",method:"POST",path:"/calls/"+c("InviteToCall","call_id",t.path.call_id)+"/participants",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})}}}var xs={};We(xs,{client:()=>qw});function qw(e){return{async getValues(t){return e.send({op:"GetValues",method:"GET",path:"/flags",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},headers:t?.headers,signal:t?.signal})},async batchUserValues(t){return e.send({op:"BatchUserValues",method:"POST",path:"/flags/batch",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getDelta(t){return e.send({op:"GetDelta",method:"GET",path:"/flags/delta",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json",304:"empty"},query:t?.query,headers:t?.headers,signal:t?.signal})},async getEvaluations(t){return e.send({op:"GetEvaluations",method:"GET",path:"/flags/evaluations",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listExperiments(t){return e.send({op:"ListExperiments",method:"GET",path:"/flags/experiments",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async startExperiment(t){return e.send({op:"StartExperiment",method:"POST",path:"/flags/experiments",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getExperiment(t){return e.send({op:"GetExperiment",method:"GET",path:"/flags/experiments/"+c("GetExperiment","experiment_id",t.path.experiment_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getExperimentResults(t){return e.send({op:"GetExperimentResults",method:"GET",path:"/flags/experiments/"+c("GetExperimentResults","experiment_id",t.path.experiment_id)+"/results",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async stopExperiment(t){return e.send({op:"StopExperiment",method:"POST",path:"/flags/experiments/"+c("StopExperiment","experiment_id",t.path.experiment_id)+"/stop",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async declareExperimentWinner(t){return e.send({op:"DeclareExperimentWinner",method:"POST",path:"/flags/experiments/"+c("DeclareExperimentWinner","experiment_id",t.path.experiment_id)+"/winner",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getCurrentInstallations(t){return e.send({op:"GetCurrentInstallations",method:"GET",path:"/flags/installations/current",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getInstallationsDaily(t){return e.send({op:"GetInstallationsDaily",method:"GET",path:"/flags/installations/daily",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getSnapshot(t){return e.send({op:"GetSnapshot",method:"GET",path:"/flags/snapshot",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json",304:"empty"},headers:t?.headers,signal:t?.signal})},async listDefinitions(t){return e.send({op:"ListDefinitions",method:"GET",path:"/flags/system",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getDefinition(t){return e.send({op:"GetDefinition",method:"GET",path:"/flags/system/"+c("GetDefinition","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putDefinition(t){return e.send({op:"PutDefinition",method:"PUT",path:"/flags/system/"+c("PutDefinition","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteDefinition(t){return e.send({op:"DeleteDefinition",method:"DELETE",path:"/flags/system/"+c("DeleteDefinition","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async activateTemplates(t){return e.send({op:"ActivateTemplates",method:"POST",path:"/flags/templates/activation",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getActiveTemplate(t){return e.send({op:"GetActiveTemplate",method:"GET",path:"/flags/templates/active",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getTemplateCapabilities(t){return e.send({op:"GetTemplateCapabilities",method:"GET",path:"/flags/templates/capabilities",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getTemplateDraft(t){return e.send({op:"GetTemplateDraft",method:"GET",path:"/flags/templates/draft",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async createTemplateDraft(t){return e.send({op:"CreateTemplateDraft",method:"POST",path:"/flags/templates/draft",auth:[["SecretKeyAuth"]],answers:{201:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async discardTemplateDraft(t){return e.send({op:"DiscardTemplateDraft",method:"DELETE",path:"/flags/templates/draft",auth:[["SecretKeyAuth"]],answers:{204:"empty"},headers:t.headers,signal:t.signal})},async putTemplateParameter(t){return e.send({op:"PutTemplateParameter",method:"PUT",path:"/flags/templates/draft/parameters/"+c("PutTemplateParameter","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async removeTemplateParameter(t){return e.send({op:"RemoveTemplateParameter",method:"DELETE",path:"/flags/templates/draft/parameters/"+c("RemoveTemplateParameter","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},headers:t.headers,signal:t.signal})},async reviewTemplateDraft(t){return e.send({op:"ReviewTemplateDraft",method:"GET",path:"/flags/templates/draft/review",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async publishTemplate(t){return e.send({op:"PublishTemplate",method:"POST",path:"/flags/templates/publish",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPublishReceipt(t){return e.send({op:"GetPublishReceipt",method:"POST",path:"/flags/templates/publish/receipt",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async restoreTemplateVersion(t){return e.send({op:"RestoreTemplateVersion",method:"POST",path:"/flags/templates/restore/"+c("RestoreTemplateVersion","version",t.path.version),auth:[["SecretKeyAuth"]],answers:{201:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listTemplateVersions(t){return e.send({op:"ListTemplateVersions",method:"GET",path:"/flags/templates/versions",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getTemplateVersion(t){return e.send({op:"GetTemplateVersion",method:"GET",path:"/flags/templates/versions/"+c("GetTemplateVersion","version",t.path.version),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getUserValues(t){return e.send({op:"GetUserValues",method:"GET",path:"/flags/users/"+c("GetUserValues","user_id",t.path.user_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},headers:t.headers,signal:t.signal})},async putUserValues(t){return e.send({op:"PutUserValues",method:"PUT",path:"/flags/users/"+c("PutUserValues","user_id",t.path.user_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteUserValues(t){return e.send({op:"DeleteUserValues",method:"DELETE",path:"/flags/users/"+c("DeleteUserValues","user_id",t.path.user_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putUserValue(t){return e.send({op:"PutUserValue",method:"PUT",path:"/flags/users/"+c("PutUserValue","user_id",t.path.user_id)+"/"+c("PutUserValue","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteUserValue(t){return e.send({op:"DeleteUserValue",method:"DELETE",path:"/flags/users/"+c("DeleteUserValue","user_id",t.path.user_id)+"/"+c("DeleteUserValue","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},headers:t.headers,signal:t.signal})}}}var Is={};We(Is,{client:()=>Kw});function Kw(e){return{async listMachines(t){return e.send({op:"ListMachines",method:"GET",path:"/machines",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createMachine(t){return e.send({op:"CreateMachine",method:"POST",path:"/machines",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listMachineSizes(t){return e.send({op:"ListMachineSizes",method:"GET",path:"/machines/sizes",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getMachineNetwork(t){return e.send({op:"GetMachineNetwork",method:"GET",path:"/machines/network",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async connectGitHub(t){return e.send({op:"ConnectGitHub",method:"POST",path:"/machines/github/connect",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listInstallations(t){return e.send({op:"ListInstallations",method:"GET",path:"/machines/github/installations",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async linkInstallation(t){return e.send({op:"LinkInstallation",method:"POST",path:"/machines/github/installations",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async shareInstallation(t){return e.send({op:"ShareInstallation",method:"POST",path:"/machines/github/installations/share",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async unlinkInstallation(t){return e.send({op:"UnlinkInstallation",method:"DELETE",path:"/machines/github/installations/"+c("UnlinkInstallation","installation",t.path.installation),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listRepositories(t){return e.send({op:"ListRepositories",method:"GET",path:"/machines/github/repositories",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getMachine(t){return e.send({op:"GetMachine",method:"GET",path:"/machines/"+c("GetMachine","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deleteMachine(t){return e.send({op:"DeleteMachine",method:"DELETE",path:"/machines/"+c("DeleteMachine","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async updateMachine(t){return e.send({op:"UpdateMachine",method:"PATCH",path:"/machines/"+c("UpdateMachine","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listBuilds(t){return e.send({op:"ListBuilds",method:"GET",path:"/machines/"+c("ListBuilds","name",t.path.name)+"/builds",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async deployMachine(t){return e.send({op:"DeployMachine",method:"POST",path:"/machines/"+c("DeployMachine","name",t.path.name)+"/builds",auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listMachinePreviews(t){return e.send({op:"ListMachinePreviews",method:"GET",path:"/machines/"+c("ListMachinePreviews","name",t.path.name)+"/previews",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putMachinePreview(t){return e.send({op:"PutMachinePreview",method:"PUT",path:"/machines/"+c("PutMachinePreview","name",t.path.name)+"/previews/"+c("PutMachinePreview","pull_request",t.path.pull_request),auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteMachinePreview(t){return e.send({op:"DeleteMachinePreview",method:"DELETE",path:"/machines/"+c("DeleteMachinePreview","name",t.path.name)+"/previews/"+c("DeleteMachinePreview","pull_request",t.path.pull_request),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listMachineDomains(t){return e.send({op:"ListMachineDomains",method:"GET",path:"/machines/"+c("ListMachineDomains","name",t.path.name)+"/domains",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async addMachineDomain(t){return e.send({op:"AddMachineDomain",method:"POST",path:"/machines/"+c("AddMachineDomain","name",t.path.name)+"/domains",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteMachineDomain(t){return e.send({op:"DeleteMachineDomain",method:"DELETE",path:"/machines/"+c("DeleteMachineDomain","name",t.path.name)+"/domains/"+c("DeleteMachineDomain","host",t.path.host),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async updateMachineDomain(t){return e.send({op:"UpdateMachineDomain",method:"PATCH",path:"/machines/"+c("UpdateMachineDomain","name",t.path.name)+"/domains/"+c("UpdateMachineDomain","host",t.path.host),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getBuild(t){return e.send({op:"GetBuild",method:"GET",path:"/machines/"+c("GetBuild","name",t.path.name)+"/builds/"+c("GetBuild","build",t.path.build),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getBuildLog(t){return e.send({op:"GetBuildLog",method:"GET",path:"/machines/"+c("GetBuildLog","name",t.path.name)+"/builds/"+c("GetBuildLog","build",t.path.build)+"/log",auth:[["SecretKeyAuth"]],answers:{200:"raw"},signal:t.signal})},async rollbackMachine(t){return e.send({op:"RollbackMachine",method:"POST",path:"/machines/"+c("RollbackMachine","name",t.path.name)+"/rollback",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listDatabases(t){return e.send({op:"ListDatabases",method:"GET",path:"/databases",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createDatabase(t){return e.send({op:"CreateDatabase",method:"POST",path:"/databases",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listDatabaseSizes(t){return e.send({op:"ListDatabaseSizes",method:"GET",path:"/databases/sizes",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getDatabase(t){return e.send({op:"GetDatabase",method:"GET",path:"/databases/"+c("GetDatabase","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deleteDatabase(t){return e.send({op:"DeleteDatabase",method:"DELETE",path:"/databases/"+c("DeleteDatabase","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async updateDatabase(t){return e.send({op:"UpdateDatabase",method:"PATCH",path:"/databases/"+c("UpdateDatabase","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json",202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async undeleteDatabase(t){return e.send({op:"UndeleteDatabase",method:"POST",path:"/databases/"+c("UndeleteDatabase","name",t.path.name)+"/undelete",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async purgeDatabase(t){return e.send({op:"PurgeDatabase",method:"POST",path:"/databases/"+c("PurgeDatabase","name",t.path.name)+"/purge",auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async getDatabaseCredentials(t){return e.send({op:"GetDatabaseCredentials",method:"GET",path:"/databases/"+c("GetDatabaseCredentials","name",t.path.name)+"/credentials",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async changeDatabasePassword(t){return e.send({op:"ChangeDatabasePassword",method:"POST",path:"/databases/"+c("ChangeDatabasePassword","name",t.path.name)+"/password",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async readMachineLogs(t){return e.send({op:"ReadMachineLogs",method:"GET",path:"/machines/"+c("ReadMachineLogs","name",t.path.name)+"/logs",auth:[["SecretKeyAuth"]],answers:{200:"raw"},query:t.query,signal:t.signal})},async getMachineMetrics(t){return e.send({op:"GetMachineMetrics",method:"GET",path:"/machines/"+c("GetMachineMetrics","name",t.path.name)+"/metrics",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getMachineContract(t){return e.send({op:"GetMachineContract",method:"GET",path:"/machines/"+c("GetMachineContract","name",t.path.name)+"/openapi",auth:[["SecretKeyAuth"]],answers:{200:"json",304:"empty"},headers:t.headers,signal:t.signal})},async restoreDatabase(t){return e.send({op:"RestoreDatabase",method:"POST",path:"/databases/"+c("RestoreDatabase","name",t.path.name)+"/restore",auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getDatabaseSchema(t){return e.send({op:"GetDatabaseSchema",method:"GET",path:"/databases/"+c("GetDatabaseSchema","name",t.path.name)+"/schema",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getDatabaseMetrics(t){return e.send({op:"GetDatabaseMetrics",method:"GET",path:"/databases/"+c("GetDatabaseMetrics","name",t.path.name)+"/metrics",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async queryDatabase(t){return e.send({op:"QueryDatabase",method:"POST",path:"/databases/"+c("QueryDatabase","name",t.path.name)+"/sql",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listCrons(t){return e.send({op:"ListCrons",method:"GET",path:"/machines/"+c("ListCrons","name",t.path.name)+"/crons",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listCronRuns(t){return e.send({op:"ListCronRuns",method:"GET",path:"/machines/"+c("ListCronRuns","name",t.path.name)+"/crons/"+c("ListCronRuns","cron",t.path.cron)+"/runs",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async runCron(t){return e.send({op:"RunCron",method:"POST",path:"/machines/"+c("RunCron","name",t.path.name)+"/crons/"+c("RunCron","cron",t.path.cron)+"/run",auth:[["SecretKeyAuth"]],answers:{201:"json"},signal:t.signal})},async pauseCron(t){return e.send({op:"PauseCron",method:"POST",path:"/machines/"+c("PauseCron","name",t.path.name)+"/crons/"+c("PauseCron","cron",t.path.cron)+"/pause",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async resumeCron(t){return e.send({op:"ResumeCron",method:"POST",path:"/machines/"+c("ResumeCron","name",t.path.name)+"/crons/"+c("ResumeCron","cron",t.path.cron)+"/resume",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listTasks(t){return e.send({op:"ListTasks",method:"GET",path:"/machines/"+c("ListTasks","name",t.path.name)+"/tasks",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async enqueueTask(t){return e.send({op:"EnqueueTask",method:"POST",path:"/machines/"+c("EnqueueTask","name",t.path.name)+"/tasks",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getTask(t){return e.send({op:"GetTask",method:"GET",path:"/machines/"+c("GetTask","name",t.path.name)+"/tasks/"+c("GetTask","task",t.path.task),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async cancelTask(t){return e.send({op:"CancelTask",method:"POST",path:"/machines/"+c("CancelTask","name",t.path.name)+"/tasks/"+c("CancelTask","task",t.path.task)+"/cancel",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async retryTask(t){return e.send({op:"RetryTask",method:"POST",path:"/machines/"+c("RetryTask","name",t.path.name)+"/tasks/"+c("RetryTask","task",t.path.task)+"/retry",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listTaskTypes(t){return e.send({op:"ListTaskTypes",method:"GET",path:"/machines/"+c("ListTaskTypes","name",t.path.name)+"/task-types",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async makeTemplatedTestUsers(t){return e.send({op:"MakeTemplatedTestUsers",method:"POST",path:"/machines/"+c("MakeTemplatedTestUsers","name",t.path.name)+"/test-users",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async templateTestUser(t){return e.send({op:"TemplateTestUser",method:"POST",path:"/machines/"+c("TemplateTestUser","name",t.path.name)+"/test-users/"+c("TemplateTestUser","user",t.path.user)+"/templates/"+c("TemplateTestUser","template",t.path.template),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deleteTemplatedTestUser(t){return e.send({op:"DeleteTemplatedTestUser",method:"DELETE",path:"/machines/"+c("DeleteTemplatedTestUser","name",t.path.name)+"/test-users/"+c("DeleteTemplatedTestUser","user",t.path.user),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listSites(t){return e.send({op:"ListSites",method:"GET",path:"/sites",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createSite(t){return e.send({op:"CreateSite",method:"POST",path:"/sites",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSite(t){return e.send({op:"GetSite",method:"GET",path:"/sites/"+c("GetSite","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deleteSite(t){return e.send({op:"DeleteSite",method:"DELETE",path:"/sites/"+c("DeleteSite","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async updateSite(t){return e.send({op:"UpdateSite",method:"PATCH",path:"/sites/"+c("UpdateSite","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listSiteReleases(t){return e.send({op:"ListSiteReleases",method:"GET",path:"/sites/"+c("ListSiteReleases","name",t.path.name)+"/releases",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async createSiteRelease(t){return e.send({op:"CreateSiteRelease",method:"POST",path:"/sites/"+c("CreateSiteRelease","name",t.path.name)+"/releases",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async uploadSiteFile(t){return e.send({op:"UploadSiteFile",method:"PUT",path:"/sites/"+c("UploadSiteFile","name",t.path.name)+"/releases/"+c("UploadSiteFile","release",t.path.release)+"/files/"+c("UploadSiteFile","digest",t.path.digest),auth:[["SecretKeyAuth"]],answers:{204:"empty"},body:{kind:"raw",contentType:t.contentType??"application/octet-stream",value:t.body},signal:t.signal})},async finishSiteRelease(t){return e.send({op:"FinishSiteRelease",method:"POST",path:"/sites/"+c("FinishSiteRelease","name",t.path.name)+"/releases/"+c("FinishSiteRelease","release",t.path.release)+"/finish",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async rollbackSite(t){return e.send({op:"RollbackSite",method:"POST",path:"/sites/"+c("RollbackSite","name",t.path.name)+"/rollback",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listSiteBuilds(t){return e.send({op:"ListSiteBuilds",method:"GET",path:"/sites/"+c("ListSiteBuilds","name",t.path.name)+"/builds",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deploySite(t){return e.send({op:"DeploySite",method:"POST",path:"/sites/"+c("DeploySite","name",t.path.name)+"/builds",auth:[["SecretKeyAuth"]],answers:{202:"json"},signal:t.signal})},async listSitePreviews(t){return e.send({op:"ListSitePreviews",method:"GET",path:"/sites/"+c("ListSitePreviews","name",t.path.name)+"/previews",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listSiteDomains(t){return e.send({op:"ListSiteDomains",method:"GET",path:"/sites/"+c("ListSiteDomains","name",t.path.name)+"/domains",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async addSiteDomain(t){return e.send({op:"AddSiteDomain",method:"POST",path:"/sites/"+c("AddSiteDomain","name",t.path.name)+"/domains",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteSiteDomain(t){return e.send({op:"DeleteSiteDomain",method:"DELETE",path:"/sites/"+c("DeleteSiteDomain","name",t.path.name)+"/domains/"+c("DeleteSiteDomain","host",t.path.host),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async updateSiteDomain(t){return e.send({op:"UpdateSiteDomain",method:"PATCH",path:"/sites/"+c("UpdateSiteDomain","name",t.path.name)+"/domains/"+c("UpdateSiteDomain","host",t.path.host),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSiteBuild(t){return e.send({op:"GetSiteBuild",method:"GET",path:"/sites/"+c("GetSiteBuild","name",t.path.name)+"/builds/"+c("GetSiteBuild","build",t.path.build),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async authorizeSitePreview(t){return e.send({op:"AuthorizeSitePreview",method:"POST",path:"/sites/"+c("AuthorizeSitePreview","name",t.path.name)+"/previews/"+c("AuthorizeSitePreview","pull_request",t.path.pull_request)+"/authorize",auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async authorizeMachinePreview(t){return e.send({op:"AuthorizeMachinePreview",method:"POST",path:"/machines/"+c("AuthorizeMachinePreview","name",t.path.name)+"/previews/"+c("AuthorizeMachinePreview","pull_request",t.path.pull_request)+"/authorize",auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async openMachinePreview(t){return e.send({op:"OpenMachinePreview",method:"POST",path:"/machines/"+c("OpenMachinePreview","name",t.path.name)+"/previews/"+c("OpenMachinePreview","pull_request",t.path.pull_request)+"/open",auth:[["SecretKeyAuth"]],answers:{202:"json"},signal:t.signal})},async moveMachine(t){return e.send({op:"MoveMachine",method:"POST",path:"/machines/"+c("MoveMachine","name",t.path.name)+"/move",auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})}}}var Ba={};We(Ba,{client:()=>Gw});function Gw(e){return{async adminAccessLog(t){return e.send({op:"AdminAccessLog",method:"GET",path:"/messaging/admin/access-log",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminListConversations(t){return e.send({op:"AdminListConversations",method:"GET",path:"/messaging/admin/conversations",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminCreateConversation(t){return e.send({op:"AdminCreateConversation",method:"POST",path:"/messaging/admin/conversations",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetConversation(t){return e.send({op:"AdminGetConversation",method:"GET",path:"/messaging/admin/conversations/"+c("AdminGetConversation","conversation_id",t.path.conversation_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async adminDeleteConversation(t){return e.send({op:"AdminDeleteConversation",method:"DELETE",path:"/messaging/admin/conversations/"+c("AdminDeleteConversation","conversation_id",t.path.conversation_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async adminUpdateConversation(t){return e.send({op:"AdminUpdateConversation",method:"PATCH",path:"/messaging/admin/conversations/"+c("AdminUpdateConversation","conversation_id",t.path.conversation_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminAddMembers(t){return e.send({op:"AdminAddMembers",method:"POST",path:"/messaging/admin/conversations/"+c("AdminAddMembers","conversation_id",t.path.conversation_id)+"/members",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminRemoveMember(t){return e.send({op:"AdminRemoveMember",method:"DELETE",path:"/messaging/admin/conversations/"+c("AdminRemoveMember","conversation_id",t.path.conversation_id)+"/members/"+c("AdminRemoveMember","user_id",t.path.user_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async adminListMessages(t){return e.send({op:"AdminListMessages",method:"GET",path:"/messaging/admin/conversations/"+c("AdminListMessages","conversation_id",t.path.conversation_id)+"/messages",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async adminSendMessage(t){return e.send({op:"AdminSendMessage",method:"POST",path:"/messaging/admin/conversations/"+c("AdminSendMessage","conversation_id",t.path.conversation_id)+"/messages",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminDeleteMessage(t){return e.send({op:"AdminDeleteMessage",method:"DELETE",path:"/messaging/admin/conversations/"+c("AdminDeleteMessage","conversation_id",t.path.conversation_id)+"/messages/"+c("AdminDeleteMessage","message_id",t.path.message_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async adminFileUrl(t){return e.send({op:"AdminFileURL",method:"GET",path:"/messaging/admin/conversations/"+c("AdminFileURL","conversation_id",t.path.conversation_id)+"/messages/"+c("AdminFileURL","message_id",t.path.message_id)+"/attachments/"+c("AdminFileURL","attachment_id",t.path.attachment_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async adminPutProfile(t){return e.send({op:"AdminPutProfile",method:"PUT",path:"/messaging/admin/profiles/"+c("AdminPutProfile","user_id",t.path.user_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListReports(t){return e.send({op:"AdminListReports",method:"GET",path:"/messaging/admin/reports",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminGetReport(t){return e.send({op:"AdminGetReport",method:"GET",path:"/messaging/admin/reports/"+c("AdminGetReport","report_id",t.path.report_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async adminReportFileUrl(t){return e.send({op:"AdminReportFileURL",method:"GET",path:"/messaging/admin/reports/"+c("AdminReportFileURL","report_id",t.path.report_id)+"/attachments/"+c("AdminReportFileURL","attachment_id",t.path.attachment_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async adminResolveReport(t){return e.send({op:"AdminResolveReport",method:"POST",path:"/messaging/admin/reports/"+c("AdminResolveReport","report_id",t.path.report_id)+"/resolve",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listBlocks(t){return e.send({op:"ListBlocks",method:"GET",path:"/messaging/blocks",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async block(t){return e.send({op:"Block",method:"PUT",path:"/messaging/blocks/"+c("Block","user_id",t.path.user_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async unblock(t){return e.send({op:"Unblock",method:"DELETE",path:"/messaging/blocks/"+c("Unblock","user_id",t.path.user_id),auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async listConversations(t){return e.send({op:"ListConversations",method:"GET",path:"/messaging/conversations",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async openDirectConversation(t){return e.send({op:"OpenDirectConversation",method:"POST",path:"/messaging/conversations/direct",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json",201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createGroup(t){return e.send({op:"CreateGroup",method:"POST",path:"/messaging/conversations/group",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getConversation(t){return e.send({op:"GetConversation",method:"GET",path:"/messaging/conversations/"+c("GetConversation","conversation_id",t.path.conversation_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async deleteConversation(t){return e.send({op:"DeleteConversation",method:"DELETE",path:"/messaging/conversations/"+c("DeleteConversation","conversation_id",t.path.conversation_id),auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async updateConversation(t){return e.send({op:"UpdateConversation",method:"PATCH",path:"/messaging/conversations/"+c("UpdateConversation","conversation_id",t.path.conversation_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async clearConversation(t){return e.send({op:"ClearConversation",method:"POST",path:"/messaging/conversations/"+c("ClearConversation","conversation_id",t.path.conversation_id)+"/clear",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async closeConversation(t){return e.send({op:"CloseConversation",method:"POST",path:"/messaging/conversations/"+c("CloseConversation","conversation_id",t.path.conversation_id)+"/close",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async joinGroup(t){return e.send({op:"JoinGroup",method:"POST",path:"/messaging/conversations/"+c("JoinGroup","conversation_id",t.path.conversation_id)+"/join",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async listMembers(t){return e.send({op:"ListMembers",method:"GET",path:"/messaging/conversations/"+c("ListMembers","conversation_id",t.path.conversation_id)+"/members",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async addMembers(t){return e.send({op:"AddMembers",method:"POST",path:"/messaging/conversations/"+c("AddMembers","conversation_id",t.path.conversation_id)+"/members",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async removeMember(t){return e.send({op:"RemoveMember",method:"DELETE",path:"/messaging/conversations/"+c("RemoveMember","conversation_id",t.path.conversation_id)+"/members/"+c("RemoveMember","user_id",t.path.user_id),auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async updateMember(t){return e.send({op:"UpdateMember",method:"PATCH",path:"/messaging/conversations/"+c("UpdateMember","conversation_id",t.path.conversation_id)+"/members/"+c("UpdateMember","user_id",t.path.user_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listMessages(t){return e.send({op:"ListMessages",method:"GET",path:"/messaging/conversations/"+c("ListMessages","conversation_id",t.path.conversation_id)+"/messages",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async sendMessage(t){return e.send({op:"SendMessage",method:"POST",path:"/messaging/conversations/"+c("SendMessage","conversation_id",t.path.conversation_id)+"/messages",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json",201:"json",202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getMessage(t){return e.send({op:"GetMessage",method:"GET",path:"/messaging/conversations/"+c("GetMessage","conversation_id",t.path.conversation_id)+"/messages/"+c("GetMessage","message_id",t.path.message_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async deleteMessage(t){return e.send({op:"DeleteMessage",method:"DELETE",path:"/messaging/conversations/"+c("DeleteMessage","conversation_id",t.path.conversation_id)+"/messages/"+c("DeleteMessage","message_id",t.path.message_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json",204:"empty"},query:t.query,signal:t.signal})},async editMessage(t){return e.send({op:"EditMessage",method:"PATCH",path:"/messaging/conversations/"+c("EditMessage","conversation_id",t.path.conversation_id)+"/messages/"+c("EditMessage","message_id",t.path.message_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async attachmentUrl(t){return e.send({op:"AttachmentURL",method:"GET",path:"/messaging/conversations/"+c("AttachmentURL","conversation_id",t.path.conversation_id)+"/messages/"+c("AttachmentURL","message_id",t.path.message_id)+"/attachments/"+c("AttachmentURL","attachment_id",t.path.attachment_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async react(t){return e.send({op:"React",method:"PUT",path:"/messaging/conversations/"+c("React","conversation_id",t.path.conversation_id)+"/messages/"+c("React","message_id",t.path.message_id)+"/reactions/"+c("React","emoji",t.path.emoji),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async unreact(t){return e.send({op:"Unreact",method:"DELETE",path:"/messaging/conversations/"+c("Unreact","conversation_id",t.path.conversation_id)+"/messages/"+c("Unreact","message_id",t.path.message_id)+"/reactions/"+c("Unreact","emoji",t.path.emoji),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async messageReaders(t){return e.send({op:"MessageReaders",method:"GET",path:"/messaging/conversations/"+c("MessageReaders","conversation_id",t.path.conversation_id)+"/messages/"+c("MessageReaders","message_id",t.path.message_id)+"/readers",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async listReplies(t){return e.send({op:"ListReplies",method:"GET",path:"/messaging/conversations/"+c("ListReplies","conversation_id",t.path.conversation_id)+"/messages/"+c("ListReplies","message_id",t.path.message_id)+"/replies",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async viewOnce(t){return e.send({op:"ViewOnce",method:"POST",path:"/messaging/conversations/"+c("ViewOnce","conversation_id",t.path.conversation_id)+"/messages/"+c("ViewOnce","message_id",t.path.message_id)+"/view",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async setConversationNotifications(t){return e.send({op:"SetConversationNotifications",method:"PUT",path:"/messaging/conversations/"+c("SetConversationNotifications","conversation_id",t.path.conversation_id)+"/notifications",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async reportScreenshot(t){return e.send({op:"ReportScreenshot",method:"POST",path:"/messaging/conversations/"+c("ReportScreenshot","conversation_id",t.path.conversation_id)+"/screenshot",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},signal:t.signal})},async typing(t){return e.send({op:"Typing",method:"POST",path:"/messaging/conversations/"+c("Typing","conversation_id",t.path.conversation_id)+"/typing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createUpload(t){return e.send({op:"CreateUpload",method:"POST",path:"/messaging/conversations/"+c("CreateUpload","conversation_id",t.path.conversation_id)+"/uploads",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listOpenGroups(t){return e.send({op:"ListOpenGroups",method:"GET",path:"/messaging/groups/open",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getMyProfile(t){return e.send({op:"GetMyProfile",method:"GET",path:"/messaging/me",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async updateMyProfile(t){return e.send({op:"UpdateMyProfile",method:"PATCH",path:"/messaging/me",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async presence(t){return e.send({op:"Presence",method:"POST",path:"/messaging/me/presence",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t?.signal})},async getProfiles(t){return e.send({op:"GetProfiles",method:"GET",path:"/messaging/profiles",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async receipts(t){return e.send({op:"Receipts",method:"POST",path:"/messaging/receipts",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async report(t){return e.send({op:"Report",method:"POST",path:"/messaging/reports",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listScheduled(t){return e.send({op:"ListScheduled",method:"GET",path:"/messaging/scheduled",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async cancelScheduled(t){return e.send({op:"CancelScheduled",method:"DELETE",path:"/messaging/scheduled/"+c("CancelScheduled","scheduled_id",t.path.scheduled_id),auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async updateScheduled(t){return e.send({op:"UpdateScheduled",method:"PATCH",path:"/messaging/scheduled/"+c("UpdateScheduled","scheduled_id",t.path.scheduled_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async searchMessages(t){return e.send({op:"SearchMessages",method:"GET",path:"/messaging/search",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getSettings(t){return e.send({op:"GetSettings",method:"GET",path:"/messaging/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putSettings(t){return e.send({op:"PutSettings",method:"PUT",path:"/messaging/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async rotateHookSecret(t){return e.send({op:"RotateHookSecret",method:"POST",path:"/messaging/settings/hook-secret",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async sync(t){return e.send({op:"Sync",method:"GET",path:"/messaging/sync",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listThreads(t){return e.send({op:"ListThreads",method:"GET",path:"/messaging/threads",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})}}}var Ls={};We(Ls,{client:()=>Uw});function Uw(e){return{async getDeliverability(t){return e.send({op:"GetDeliverability",method:"GET",path:"/notify/deliverability",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listDevices(t){return e.send({op:"ListDevices",method:"GET",path:"/notify/devices",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async registerDevice(t){return e.send({op:"RegisterDevice",method:"POST",path:"/notify/devices",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getDeviceStats(t){return e.send({op:"GetDeviceStats",method:"GET",path:"/notify/devices/stats",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async deleteMyDevice(t){return e.send({op:"DeleteMyDevice",method:"DELETE",path:"/notify/devices/"+c("DeleteMyDevice","device_id",t.path.device_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async sendEmail(t){return e.send({op:"SendEmail",method:"POST",path:"/notify/email",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listInAppCampaigns(t){return e.send({op:"ListInAppCampaigns",method:"GET",path:"/notify/in-app/campaigns",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async createInAppCampaign(t){return e.send({op:"CreateInAppCampaign",method:"POST",path:"/notify/in-app/campaigns",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getInAppCampaign(t){return e.send({op:"GetInAppCampaign",method:"GET",path:"/notify/in-app/campaigns/"+c("GetInAppCampaign","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putInAppCampaign(t){return e.send({op:"PutInAppCampaign",method:"PUT",path:"/notify/in-app/campaigns/"+c("PutInAppCampaign","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteInAppCampaign(t){return e.send({op:"DeleteInAppCampaign",method:"DELETE",path:"/notify/in-app/campaigns/"+c("DeleteInAppCampaign","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async getInAppCampaignStats(t){return e.send({op:"GetInAppCampaignStats",method:"GET",path:"/notify/in-app/campaigns/"+c("GetInAppCampaignStats","id",t.path.id)+"/stats",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async showInAppMessage(t){return e.send({op:"ShowInAppMessage",method:"POST",path:"/notify/in-app/impressions",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async reportInAppEvent(t){return e.send({op:"ReportInAppEvent",method:"POST",path:"/notify/in-app/impressions/"+c("ReportInAppEvent","id",t.path.id)+"/events",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{204:"empty"},idempotent:!0,query:t.query,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listMyInAppMessages(t){return e.send({op:"ListMyInAppMessages",method:"GET",path:"/notify/in-app/messages",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async listInAppTemplates(t){return e.send({op:"ListInAppTemplates",method:"GET",path:"/notify/in-app/templates",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listMyInbox(t){return e.send({op:"ListMyInbox",method:"GET",path:"/notify/inbox",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async sendInbox(t){return e.send({op:"SendInbox",method:"POST",path:"/notify/inbox",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listInboxMessages(t){return e.send({op:"ListInboxMessages",method:"GET",path:"/notify/inbox/messages",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async readMyInbox(t){return e.send({op:"ReadMyInbox",method:"POST",path:"/notify/inbox/read",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteMyInboxMessage(t){return e.send({op:"DeleteMyInboxMessage",method:"DELETE",path:"/notify/inbox/"+c("DeleteMyInboxMessage","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listNotifyMessages(t){return e.send({op:"ListNotifyMessages",method:"GET",path:"/notify/messages",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getNotifyMessage(t){return e.send({op:"GetNotifyMessage",method:"GET",path:"/notify/messages/"+c("GetNotifyMessage","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async cancelMessage(t){return e.send({op:"CancelMessage",method:"POST",path:"/notify/messages/"+c("CancelMessage","id",t.path.id)+"/cancel",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getMetricsSummary(t){return e.send({op:"GetMetricsSummary",method:"GET",path:"/notify/metrics/summary",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getMyPreferences(t){return e.send({op:"GetMyPreferences",method:"GET",path:"/notify/preferences",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async setMyPreferences(t){return e.send({op:"SetMyPreferences",method:"PUT",path:"/notify/preferences",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listNotifyProviders(t){return e.send({op:"ListNotifyProviders",method:"GET",path:"/notify/providers",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putNotifyProvider(t){return e.send({op:"PutNotifyProvider",method:"PUT",path:"/notify/providers/"+c("PutNotifyProvider","channel",t.path.channel)+"/"+c("PutNotifyProvider","provider",t.path.provider),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteNotifyProvider(t){return e.send({op:"DeleteNotifyProvider",method:"DELETE",path:"/notify/providers/"+c("DeleteNotifyProvider","channel",t.path.channel)+"/"+c("DeleteNotifyProvider","provider",t.path.provider),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async sendPush(t){return e.send({op:"SendPush",method:"POST",path:"/notify/push",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async recordPushReceipts(t){return e.send({op:"RecordPushReceipts",method:"POST",path:"/notify/receipts",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getNotifySettings(t){return e.send({op:"GetNotifySettings",method:"GET",path:"/notify/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putNotifySettings(t){return e.send({op:"PutNotifySettings",method:"PUT",path:"/notify/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async sendSms(t){return e.send({op:"SendSMS",method:"POST",path:"/notify/sms",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listEmailTemplates(t){return e.send({op:"ListEmailTemplates",method:"GET",path:"/notify/templates/email",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getEmailTemplate(t){return e.send({op:"GetEmailTemplate",method:"GET",path:"/notify/templates/email/"+c("GetEmailTemplate","slug",t.path.slug)+"/"+c("GetEmailTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putEmailTemplate(t){return e.send({op:"PutEmailTemplate",method:"PUT",path:"/notify/templates/email/"+c("PutEmailTemplate","slug",t.path.slug)+"/"+c("PutEmailTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteEmailTemplate(t){return e.send({op:"DeleteEmailTemplate",method:"DELETE",path:"/notify/templates/email/"+c("DeleteEmailTemplate","slug",t.path.slug)+"/"+c("DeleteEmailTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listPushTemplates(t){return e.send({op:"ListPushTemplates",method:"GET",path:"/notify/templates/push",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getPushTemplate(t){return e.send({op:"GetPushTemplate",method:"GET",path:"/notify/templates/push/"+c("GetPushTemplate","slug",t.path.slug)+"/"+c("GetPushTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putPushTemplate(t){return e.send({op:"PutPushTemplate",method:"PUT",path:"/notify/templates/push/"+c("PutPushTemplate","slug",t.path.slug)+"/"+c("PutPushTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deletePushTemplate(t){return e.send({op:"DeletePushTemplate",method:"DELETE",path:"/notify/templates/push/"+c("DeletePushTemplate","slug",t.path.slug)+"/"+c("DeletePushTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listSmsTemplates(t){return e.send({op:"ListSMSTemplates",method:"GET",path:"/notify/templates/sms",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getSmsTemplate(t){return e.send({op:"GetSMSTemplate",method:"GET",path:"/notify/templates/sms/"+c("GetSMSTemplate","slug",t.path.slug)+"/"+c("GetSMSTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putSmsTemplate(t){return e.send({op:"PutSMSTemplate",method:"PUT",path:"/notify/templates/sms/"+c("PutSMSTemplate","slug",t.path.slug)+"/"+c("PutSMSTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteSmsTemplate(t){return e.send({op:"DeleteSMSTemplate",method:"DELETE",path:"/notify/templates/sms/"+c("DeleteSMSTemplate","slug",t.path.slug)+"/"+c("DeleteSMSTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listWhatsAppTemplates(t){return e.send({op:"ListWhatsAppTemplates",method:"GET",path:"/notify/templates/whatsapp",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getWhatsAppTemplate(t){return e.send({op:"GetWhatsAppTemplate",method:"GET",path:"/notify/templates/whatsapp/"+c("GetWhatsAppTemplate","slug",t.path.slug)+"/"+c("GetWhatsAppTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putWhatsAppTemplate(t){return e.send({op:"PutWhatsAppTemplate",method:"PUT",path:"/notify/templates/whatsapp/"+c("PutWhatsAppTemplate","slug",t.path.slug)+"/"+c("PutWhatsAppTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteWhatsAppTemplate(t){return e.send({op:"DeleteWhatsAppTemplate",method:"DELETE",path:"/notify/templates/whatsapp/"+c("DeleteWhatsAppTemplate","slug",t.path.slug)+"/"+c("DeleteWhatsAppTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listTestUserMessages(t){return e.send({op:"ListTestUserMessages",method:"GET",path:"/notify/test-users/"+c("ListTestUserMessages","user_id",t.path.user_id)+"/messages",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async listTopics(t){return e.send({op:"ListTopics",method:"GET",path:"/notify/topics",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createTopic(t){return e.send({op:"CreateTopic",method:"POST",path:"/notify/topics",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteTopic(t){return e.send({op:"DeleteTopic",method:"DELETE",path:"/notify/topics/"+c("DeleteTopic","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async changeTopic(t){return e.send({op:"ChangeTopic",method:"PATCH",path:"/notify/topics/"+c("ChangeTopic","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async addTopicSubscribers(t){return e.send({op:"AddTopicSubscribers",method:"POST",path:"/notify/topics/"+c("AddTopicSubscribers","name",t.path.name)+"/subscribers",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async removeTopicSubscriber(t){return e.send({op:"RemoveTopicSubscriber",method:"DELETE",path:"/notify/topics/"+c("RemoveTopicSubscriber","name",t.path.name)+"/subscribers/"+c("RemoveTopicSubscriber","user_id",t.path.user_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async followTopic(t){return e.send({op:"FollowTopic",method:"POST",path:"/notify/topics/"+c("FollowTopic","name",t.path.name)+"/subscription",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async unfollowTopic(t){return e.send({op:"UnfollowTopic",method:"DELETE",path:"/notify/topics/"+c("UnfollowTopic","name",t.path.name)+"/subscription",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listUserDevices(t){return e.send({op:"ListUserDevices",method:"GET",path:"/notify/users/"+c("ListUserDevices","user_id",t.path.user_id)+"/devices",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getUserPreferences(t){return e.send({op:"GetUserPreferences",method:"GET",path:"/notify/users/"+c("GetUserPreferences","user_id",t.path.user_id)+"/preferences",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async setUserPreferences(t){return e.send({op:"SetUserPreferences",method:"PUT",path:"/notify/users/"+c("SetUserPreferences","user_id",t.path.user_id)+"/preferences",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async startVerification(t){return e.send({op:"StartVerification",method:"POST",path:"/notify/verifications",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async checkVerification(t){return e.send({op:"CheckVerification",method:"POST",path:"/notify/verifications/check",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async receiveSendGridEvents(t){return e.send({op:"ReceiveSendGridEvents",method:"POST",path:"/notify/webhooks/email/sendgrid",auth:[],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async receiveTwilioStatus(t){return e.send({op:"ReceiveTwilioStatus",method:"POST",path:"/notify/webhooks/sms/twilio",auth:[],answers:{204:"empty"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async receiveTwilioText(t){return e.send({op:"ReceiveTwilioText",method:"POST",path:"/notify/webhooks/sms/twilio/inbound",auth:[],answers:{204:"empty"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async receiveVonageReceiptQuery(t){return e.send({op:"ReceiveVonageReceiptQuery",method:"GET",path:"/notify/webhooks/sms/vonage",auth:[],answers:{204:"empty"},query:t?.query,signal:t?.signal})},async receiveVonageReceipt(t){return e.send({op:"ReceiveVonageReceipt",method:"POST",path:"/notify/webhooks/sms/vonage",auth:[],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async subscribeMetaWebhook(t){return e.send({op:"SubscribeMetaWebhook",method:"GET",path:"/notify/webhooks/whatsapp/meta",auth:[],answers:{200:"raw"},query:t.query,signal:t.signal})},async receiveMetaNotification(t){return e.send({op:"ReceiveMetaNotification",method:"POST",path:"/notify/webhooks/whatsapp/meta",auth:[],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getWebPushStatus(t){return e.send({op:"GetWebPushStatus",method:"GET",path:"/notify/webpush",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getWebPushKey(t){return e.send({op:"GetWebPushKey",method:"GET",path:"/notify/webpush/key",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async sendWhatsApp(t){return e.send({op:"SendWhatsApp",method:"POST",path:"/notify/whatsapp",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listWhatsAppInbound(t){return e.send({op:"ListWhatsAppInbound",method:"GET",path:"/notify/whatsapp/inbound",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})}}}var Ds={};We(Ds,{client:()=>zw});function zw(e){return{async getAppleAccount(t){return e.send({op:"GetAppleAccount",method:"GET",path:"/purchases/apple",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async disconnectApple(t){return e.send({op:"DisconnectApple",method:"DELETE",path:"/purchases/apple",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getAppleAccountToken(t){return e.send({op:"GetAppleAccountToken",method:"POST",path:"/purchases/apple/account-token",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async getAppleConnectPage(t){return e.send({op:"GetAppleConnectPage",method:"GET",path:"/purchases/apple/connect",auth:[],answers:{200:"raw"},signal:t?.signal})},async connectAppleKey(t){return e.send({op:"ConnectAppleKey",method:"POST",path:"/purchases/apple/connect",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createAppleGrant(t){return e.send({op:"CreateAppleGrant",method:"POST",path:"/purchases/apple/grants",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getAppleReadiness(t){return e.send({op:"GetAppleReadiness",method:"GET",path:"/purchases/apple/readiness",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async reportAppleTransactions(t){return e.send({op:"ReportAppleTransactions",method:"POST",path:"/purchases/apple/transactions",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getGoogleAccountId(t){return e.send({op:"GetGoogleAccountID",method:"POST",path:"/purchases/google/account-id",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async reportGooglePurchases(t){return e.send({op:"ReportGooglePurchases",method:"POST",path:"/purchases/google/purchases",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async setXcodeCertificate(t){return e.send({op:"SetXcodeCertificate",method:"PUT",path:"/purchases/apple/xcode-certificate",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async clearXcodeCertificate(t){return e.send({op:"ClearXcodeCertificate",method:"DELETE",path:"/purchases/apple/xcode-certificate",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getGoogleAccount(t){return e.send({op:"GetGoogleAccount",method:"GET",path:"/purchases/google",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async connectGoogle(t){return e.send({op:"ConnectGoogle",method:"POST",path:"/purchases/google",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async disconnectGoogle(t){return e.send({op:"DisconnectGoogle",method:"DELETE",path:"/purchases/google",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getCatalog(t){return e.send({op:"GetCatalog",method:"GET",path:"/purchases/catalog",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async saveCatalog(t){return e.send({op:"SaveCatalog",method:"PUT",path:"/purchases/catalog",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async planCatalog(t){return e.send({op:"PlanCatalog",method:"POST",path:"/purchases/catalog/plans",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getCatalogPlan(t){return e.send({op:"GetCatalogPlan",method:"GET",path:"/purchases/catalog/plans/"+c("GetCatalogPlan","plan_id",t.path.plan_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async confirmCatalogPlan(t){return e.send({op:"ConfirmCatalogPlan",method:"POST",path:"/purchases/catalog/plans/"+c("ConfirmCatalogPlan","plan_id",t.path.plan_id)+"/confirm",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async declineCatalogPlan(t){return e.send({op:"DeclineCatalogPlan",method:"POST",path:"/purchases/catalog/plans/"+c("DeclineCatalogPlan","plan_id",t.path.plan_id)+"/decline",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async validateCatalog(t){return e.send({op:"ValidateCatalog",method:"POST",path:"/purchases/catalog/validate",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listCharts(t){return e.send({op:"ListCharts",method:"GET",path:"/purchases/charts",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getChartsOverview(t){return e.send({op:"GetChartsOverview",method:"GET",path:"/purchases/charts/overview",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getChart(t){return e.send({op:"GetChart",method:"GET",path:"/purchases/charts/"+c("GetChart","chart",t.path.chart),auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getStripeConnectPage(t){return e.send({op:"GetStripeConnectPage",method:"GET",path:"/purchases/connect",auth:[],answers:{200:"raw"},signal:t?.signal})},async connectStripeKey(t){return e.send({op:"ConnectStripeKey",method:"POST",path:"/purchases/connect",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getStripeAppInstallPage(t){return e.send({op:"GetStripeAppInstallPage",method:"GET",path:"/purchases/stripe/app/install",auth:[],answers:{200:"raw"},signal:t?.signal})},async startStripeAppInstall(t){return e.send({op:"StartStripeAppInstall",method:"POST",path:"/purchases/stripe/app/install",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async completeStripeAppInstall(t){return e.send({op:"CompleteStripeAppInstall",method:"GET",path:"/purchases/stripe/app/callback",auth:[],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async getCustomer(t){return e.send({op:"GetCustomer",method:"GET",path:"/purchases/customers/"+c("GetCustomer","customer_id",t.path.customer_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async grantCredits(t){return e.send({op:"GrantCredits",method:"POST",path:"/purchases/customers/"+c("GrantCredits","customer_id",t.path.customer_id)+"/credits",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listCreditEntries(t){return e.send({op:"ListCreditEntries",method:"GET",path:"/purchases/customers/"+c("ListCreditEntries","customer_id",t.path.customer_id)+"/credits/entries",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async forgiveCredits(t){return e.send({op:"ForgiveCredits",method:"POST",path:"/purchases/customers/"+c("ForgiveCredits","customer_id",t.path.customer_id)+"/credits/forgive",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listCustomerGrants(t){return e.send({op:"ListCustomerGrants",method:"GET",path:"/purchases/customers/"+c("ListCustomerGrants","customer_id",t.path.customer_id)+"/grants",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async grantEntitlement(t){return e.send({op:"GrantEntitlement",method:"POST",path:"/purchases/customers/"+c("GrantEntitlement","customer_id",t.path.customer_id)+"/grants",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async revokeGrant(t){return e.send({op:"RevokeGrant",method:"DELETE",path:"/purchases/customers/"+c("RevokeGrant","customer_id",t.path.customer_id)+"/grants/"+c("RevokeGrant","grant_id",t.path.grant_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async holdSpend(t){return e.send({op:"HoldSpend",method:"POST",path:"/purchases/customers/"+c("HoldSpend","customer_id",t.path.customer_id)+"/holds",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async setCustomerLimit(t){return e.send({op:"SetCustomerLimit",method:"PUT",path:"/purchases/customers/"+c("SetCustomerLimit","customer_id",t.path.customer_id)+"/limits/"+c("SetCustomerLimit","limit_key",t.path.limit_key),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async clearCustomerLimit(t){return e.send({op:"ClearCustomerLimit",method:"DELETE",path:"/purchases/customers/"+c("ClearCustomerLimit","customer_id",t.path.customer_id)+"/limits/"+c("ClearCustomerLimit","limit_key",t.path.limit_key),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async grantLimit(t){return e.send({op:"GrantLimit",method:"POST",path:"/purchases/customers/"+c("GrantLimit","customer_id",t.path.customer_id)+"/limits/"+c("GrantLimit","limit_key",t.path.limit_key)+"/grants",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async spend(t){return e.send({op:"Spend",method:"POST",path:"/purchases/customers/"+c("Spend","customer_id",t.path.customer_id)+"/spend",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async commitSpend(t){return e.send({op:"CommitSpend",method:"POST",path:"/purchases/customers/"+c("CommitSpend","customer_id",t.path.customer_id)+"/spends/"+c("CommitSpend","spend_id",t.path.spend_id)+"/commit",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async extendHold(t){return e.send({op:"ExtendHold",method:"POST",path:"/purchases/customers/"+c("ExtendHold","customer_id",t.path.customer_id)+"/spends/"+c("ExtendHold","spend_id",t.path.spend_id)+"/extend",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async releaseSpend(t){return e.send({op:"ReleaseSpend",method:"POST",path:"/purchases/customers/"+c("ReleaseSpend","customer_id",t.path.customer_id)+"/spends/"+c("ReleaseSpend","spend_id",t.path.spend_id)+"/release",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async reverseSpend(t){return e.send({op:"ReverseSpend",method:"POST",path:"/purchases/customers/"+c("ReverseSpend","customer_id",t.path.customer_id)+"/spends/"+c("ReverseSpend","spend_id",t.path.spend_id)+"/reverse",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listExperiments(t){return e.send({op:"ListExperiments",method:"GET",path:"/purchases/experiments",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async startExperiment(t){return e.send({op:"StartExperiment",method:"POST",path:"/purchases/experiments",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getExperiment(t){return e.send({op:"GetExperiment",method:"GET",path:"/purchases/experiments/"+c("GetExperiment","experiment_id",t.path.experiment_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getExperimentResults(t){return e.send({op:"GetExperimentResults",method:"GET",path:"/purchases/experiments/"+c("GetExperimentResults","experiment_id",t.path.experiment_id)+"/results",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async stopExperiment(t){return e.send({op:"StopExperiment",method:"POST",path:"/purchases/experiments/"+c("StopExperiment","experiment_id",t.path.experiment_id)+"/stop",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async declareExperimentWinner(t){return e.send({op:"DeclareExperimentWinner",method:"POST",path:"/purchases/experiments/"+c("DeclareExperimentWinner","experiment_id",t.path.experiment_id)+"/winner",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getMyCustomerInfo(t){return e.send({op:"GetMyCustomerInfo",method:"GET",path:"/purchases/me",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async mergeGuest(t){return e.send({op:"MergeGuest",method:"POST",path:"/purchases/me/merge",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createMergeGrant(t){return e.send({op:"CreateMergeGrant",method:"POST",path:"/purchases/me/merge-grant",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},signal:t?.signal})},async getOfferings(t){return e.send({op:"GetOfferings",method:"GET",path:"/purchases/offerings",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listPaywalls(t){return e.send({op:"ListPaywalls",method:"GET",path:"/purchases/paywalls",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async createPaywall(t){return e.send({op:"CreatePaywall",method:"POST",path:"/purchases/paywalls",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listPaywallAssets(t){return e.send({op:"ListPaywallAssets",method:"GET",path:"/purchases/paywalls/assets",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async registerPaywallAsset(t){return e.send({op:"RegisterPaywallAsset",method:"POST",path:"/purchases/paywalls/assets",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deletePaywallAsset(t){return e.send({op:"DeletePaywallAsset",method:"DELETE",path:"/purchases/paywalls/assets/"+c("DeletePaywallAsset","asset_id",t.path.asset_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listPaywallTemplates(t){return e.send({op:"ListPaywallTemplates",method:"GET",path:"/purchases/paywalls/templates",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getPaywallTemplateAsset(t){return e.send({op:"GetPaywallTemplateAsset",method:"GET",path:"/purchases/paywalls/templates/"+c("GetPaywallTemplateAsset","key",t.path.key)+"/assets/"+c("GetPaywallTemplateAsset","asset_id",t.path.asset_id),auth:[["SecretKeyAuth"]],answers:{200:"raw",304:"empty"},headers:t.headers,signal:t.signal})},async validatePaywall(t){return e.send({op:"ValidatePaywall",method:"POST",path:"/purchases/paywalls/validate",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPaywall(t){return e.send({op:"GetPaywall",method:"GET",path:"/purchases/paywalls/"+c("GetPaywall","paywall_id",t.path.paywall_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deletePaywall(t){return e.send({op:"DeletePaywall",method:"DELETE",path:"/purchases/paywalls/"+c("DeletePaywall","paywall_id",t.path.paywall_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async savePaywallDraft(t){return e.send({op:"SavePaywallDraft",method:"PUT",path:"/purchases/paywalls/"+c("SavePaywallDraft","paywall_id",t.path.paywall_id)+"/draft",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async publishPaywall(t){return e.send({op:"PublishPaywall",method:"POST",path:"/purchases/paywalls/"+c("PublishPaywall","paywall_id",t.path.paywall_id)+"/publish",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async listPaywallVersions(t){return e.send({op:"ListPaywallVersions",method:"GET",path:"/purchases/paywalls/"+c("ListPaywallVersions","paywall_id",t.path.paywall_id)+"/versions",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getPaywallVersion(t){return e.send({op:"GetPaywallVersion",method:"GET",path:"/purchases/paywalls/"+c("GetPaywallVersion","paywall_id",t.path.paywall_id)+"/versions/"+c("GetPaywallVersion","version",t.path.version),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listPlacements(t){return e.send({op:"ListPlacements",method:"GET",path:"/purchases/placements",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listAttributeKeys(t){return e.send({op:"ListAttributeKeys",method:"GET",path:"/purchases/placements/attributes",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async setPlacement(t){return e.send({op:"SetPlacement",method:"PUT",path:"/purchases/placements/"+c("SetPlacement","placement",t.path.placement),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deletePlacement(t){return e.send({op:"DeletePlacement",method:"DELETE",path:"/purchases/placements/"+c("DeletePlacement","placement",t.path.placement),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async recordPaywallExposure(t){return e.send({op:"RecordPaywallExposure",method:"POST",path:"/purchases/placements/"+c("RecordPaywallExposure","placement",t.path.placement)+"/exposures",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPlacementPaywall(t){return e.send({op:"GetPlacementPaywall",method:"GET",path:"/purchases/placements/"+c("GetPlacementPaywall","placement",t.path.placement)+"/paywall",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json",204:"empty",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async previewPlacement(t){return e.send({op:"PreviewPlacement",method:"POST",path:"/purchases/placements/"+c("PreviewPlacement","placement",t.path.placement)+"/resolve-preview",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPlacementResults(t){return e.send({op:"GetPlacementResults",method:"GET",path:"/purchases/placements/"+c("GetPlacementResults","placement",t.path.placement)+"/results",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getPlacementRules(t){return e.send({op:"GetPlacementRules",method:"GET",path:"/purchases/placements/"+c("GetPlacementRules","placement",t.path.placement)+"/rules",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async setPlacementRules(t){return e.send({op:"SetPlacementRules",method:"PUT",path:"/purchases/placements/"+c("SetPlacementRules","placement",t.path.placement)+"/rules",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSettings(t){return e.send({op:"GetSettings",method:"GET",path:"/purchases/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async updateSettings(t){return e.send({op:"UpdateSettings",method:"PUT",path:"/purchases/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getStripeAccount(t){return e.send({op:"GetStripeAccount",method:"GET",path:"/purchases/stripe",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async disconnectStripe(t){return e.send({op:"DisconnectStripe",method:"DELETE",path:"/purchases/stripe",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async checkStripeAccount(t){return e.send({op:"CheckStripeAccount",method:"POST",path:"/purchases/stripe/check",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async createCheckout(t){return e.send({op:"CreateCheckout",method:"POST",path:"/purchases/stripe/checkout",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createCheckoutRedemption(t){return e.send({op:"CreateCheckoutRedemption",method:"POST",path:"/purchases/stripe/checkout/redemption",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async redeemPurchase(t){return e.send({op:"RedeemPurchase",method:"POST",path:"/purchases/redemptions/redeem",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getRedemptionPage(t){return e.send({op:"GetRedemptionPage",method:"GET",path:"/purchases/redeem",auth:[],answers:{200:"raw"},query:t.query,signal:t.signal})},async createStripeGrant(t){return e.send({op:"CreateStripeGrant",method:"POST",path:"/purchases/stripe/grants",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async createStripeAppInstall(t){return e.send({op:"CreateStripeAppInstall",method:"POST",path:"/purchases/stripe/app/grants",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createPortalSession(t){return e.send({op:"CreatePortalSession",method:"POST",path:"/purchases/stripe/portal",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async receiveAppleNotification(t){return e.send({op:"ReceiveAppleNotification",method:"POST",path:"/purchases/webhooks/apple",auth:[],answers:{200:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async receiveGoogleNotification(t){return e.send({op:"ReceiveGoogleNotification",method:"POST",path:"/purchases/webhooks/google",auth:[],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async receiveStripeEvent(t){return e.send({op:"ReceiveStripeEvent",method:"POST",path:"/purchases/webhooks/stripe",auth:[],answers:{200:"empty"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async receiveStripeAppEvent(t){return e.send({op:"ReceiveStripeAppEvent",method:"POST",path:"/purchases/webhooks/stripe-app",auth:[],answers:{200:"empty"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listMyOffers(t){return e.send({op:"ListMyOffers",method:"GET",path:"/purchases/offers",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async recordOfferView(t){return e.send({op:"RecordOfferView",method:"POST",path:"/purchases/offers/"+c("RecordOfferView","offer_key",t.path.offer_key)+"/views",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async signAppleOffer(t){return e.send({op:"SignAppleOffer",method:"POST",path:"/purchases/offers/"+c("SignAppleOffer","offer_key",t.path.offer_key)+"/apple-signature",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async claimOffer(t){return e.send({op:"ClaimOffer",method:"POST",path:"/purchases/offers/"+c("ClaimOffer","offer_key",t.path.offer_key)+"/claim",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},signal:t.signal})},async redeemCoupon(t){return e.send({op:"RedeemCoupon",method:"POST",path:"/purchases/coupons/redeem",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getOfferStats(t){return e.send({op:"GetOfferStats",method:"GET",path:"/purchases/offers/stats",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listCoupons(t){return e.send({op:"ListCoupons",method:"GET",path:"/purchases/coupons",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async createCoupon(t){return e.send({op:"CreateCoupon",method:"POST",path:"/purchases/coupons",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getCoupon(t){return e.send({op:"GetCoupon",method:"GET",path:"/purchases/coupons/"+c("GetCoupon","coupon_key",t.path.coupon_key),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async revokeCoupon(t){return e.send({op:"RevokeCoupon",method:"DELETE",path:"/purchases/coupons/"+c("RevokeCoupon","coupon_key",t.path.coupon_key),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listCouponCodes(t){return e.send({op:"ListCouponCodes",method:"GET",path:"/purchases/coupons/"+c("ListCouponCodes","coupon_key",t.path.coupon_key)+"/codes",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async setXcodeOfferKey(t){return e.send({op:"SetXcodeOfferKey",method:"PUT",path:"/purchases/apple/xcode-offer-key",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async searchCustomers(t){return e.send({op:"SearchCustomers",method:"GET",path:"/purchases/customers",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getCustomerHistory(t){return e.send({op:"GetCustomerHistory",method:"GET",path:"/purchases/customers/"+c("GetCustomerHistory","customer_id",t.path.customer_id)+"/history",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async listCatalogRevisions(t){return e.send({op:"ListCatalogRevisions",method:"GET",path:"/purchases/catalog/revisions",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getCatalogRevision(t){return e.send({op:"GetCatalogRevision",method:"GET",path:"/purchases/catalog/revisions/"+c("GetCatalogRevision","revision",t.path.revision),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async restoreCatalogRevision(t){return e.send({op:"RestoreCatalogRevision",method:"POST",path:"/purchases/catalog/revisions/"+c("RestoreCatalogRevision","revision",t.path.revision)+"/restore",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async extendSubscription(t){return e.send({op:"ExtendSubscription",method:"POST",path:"/purchases/customers/"+c("ExtendSubscription","customer_id",t.path.customer_id)+"/subscriptions/"+c("ExtendSubscription","subscription_id",t.path.subscription_id)+"/extend",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async refundSubscription(t){return e.send({op:"RefundSubscription",method:"POST",path:"/purchases/customers/"+c("RefundSubscription","customer_id",t.path.customer_id)+"/subscriptions/"+c("RefundSubscription","subscription_id",t.path.subscription_id)+"/refund",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async cancelSubscription(t){return e.send({op:"CancelSubscription",method:"POST",path:"/purchases/customers/"+c("CancelSubscription","customer_id",t.path.customer_id)+"/subscriptions/"+c("CancelSubscription","subscription_id",t.path.subscription_id)+"/cancel",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async setRefundDataConsent(t){return e.send({op:"SetRefundDataConsent",method:"PUT",path:"/purchases/me/refund-data-consent",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})}}}var qs={};We(qs,{client:()=>Bw});function Bw(e){return{async broadcast(t){return e.send({op:"Broadcast",method:"POST",path:"/realtime/broadcast",auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getChannels(t){return e.send({op:"GetChannels",method:"GET",path:"/realtime/channels",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putChannels(t){return e.send({op:"PutChannels",method:"PUT",path:"/realtime/channels",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getLimits(t){return e.send({op:"GetLimits",method:"GET",path:"/realtime/limits",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putLimits(t){return e.send({op:"PutLimits",method:"PUT",path:"/realtime/limits",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async revalidate(t){return e.send({op:"Revalidate",method:"POST",path:"/realtime/revalidate",auth:[["SecretKeyAuth"]],answers:{202:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async writeState(t){return e.send({op:"WriteState",method:"POST",path:"/realtime/state",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getStats(t){return e.send({op:"GetStats",method:"GET",path:"/realtime/stats",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})}}}var Ns={};We(Ns,{client:()=>Fw});function Fw(e){return{async listSecretAudit(t){return e.send({op:"ListSecretAudit",method:"GET",path:"/secrets/audit",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listFieldKeys(t){return e.send({op:"ListFieldKeys",method:"GET",path:"/secrets/fields",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getFieldKeys(t){return e.send({op:"GetFieldKeys",method:"GET",path:"/secrets/fields/keys",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async openFields(t){return e.send({op:"OpenFields",method:"POST",path:"/secrets/fields/open",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async sealPlaceholder(t){return e.send({op:"SealPlaceholder",method:"POST",path:"/secrets/fields/placeholder",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async rotateFieldKeys(t){return e.send({op:"RotateFieldKeys",method:"POST",path:"/secrets/fields/rotate",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async listTransitKeys(t){return e.send({op:"ListTransitKeys",method:"GET",path:"/secrets/transit",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getTransitKeys(t){return e.send({op:"GetTransitKeys",method:"GET",path:"/secrets/transit/keys",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getTransitPublicKeys(t){return e.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",auth:[["ApiKeyAuth"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async rotateTransitKeys(t){return e.send({op:"RotateTransitKeys",method:"POST",path:"/secrets/transit/rotate",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t?.headers,body:{kind:"json",contentType:"application/json",value:t?.body},signal:t?.signal})},async retireTransitKey(t){return e.send({op:"RetireTransitKey",method:"POST",path:"/secrets/transit/"+c("RetireTransitKey","kid",t.path.kid)+"/retire",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async listSecrets(t){return e.send({op:"ListSecrets",method:"GET",path:"/secrets/"+c("ListSecrets","environment",t.path.environment),auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getEnvironmentValues(t){return e.send({op:"GetEnvironmentValues",method:"GET",path:"/secrets/"+c("GetEnvironmentValues","environment",t.path.environment)+"/values",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getSecret(t){return e.send({op:"GetSecret",method:"GET",path:"/secrets/"+c("GetSecret","environment",t.path.environment)+"/"+c("GetSecret","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putSecret(t){return e.send({op:"PutSecret",method:"PUT",path:"/secrets/"+c("PutSecret","environment",t.path.environment)+"/"+c("PutSecret","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteSecret(t){return e.send({op:"DeleteSecret",method:"DELETE",path:"/secrets/"+c("DeleteSecret","environment",t.path.environment)+"/"+c("DeleteSecret","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async rollbackSecret(t){return e.send({op:"RollbackSecret",method:"POST",path:"/secrets/"+c("RollbackSecret","environment",t.path.environment)+"/"+c("RollbackSecret","name",t.path.name)+"/rollback",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listSecretVersions(t){return e.send({op:"ListSecretVersions",method:"GET",path:"/secrets/"+c("ListSecretVersions","environment",t.path.environment)+"/"+c("ListSecretVersions","name",t.path.name)+"/versions",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})}}}var Ks={};We(Ks,{client:()=>Jw});function Jw(e){return{async listBuckets(t){return e.send({op:"ListBuckets",method:"GET",path:"/storage/buckets",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getBucket(t){return e.send({op:"GetBucket",method:"GET",path:"/storage/buckets/"+c("GetBucket","bucket",t.path.bucket),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putBucket(t){return e.send({op:"PutBucket",method:"PUT",path:"/storage/buckets/"+c("PutBucket","bucket",t.path.bucket),auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteBucket(t){return e.send({op:"DeleteBucket",method:"DELETE",path:"/storage/buckets/"+c("DeleteBucket","bucket",t.path.bucket),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async copyObject(t){return e.send({op:"CopyObject",method:"POST",path:"/storage/buckets/"+c("CopyObject","bucket",t.path.bucket)+"/copy",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async moveObject(t){return e.send({op:"MoveObject",method:"POST",path:"/storage/buckets/"+c("MoveObject","bucket",t.path.bucket)+"/move",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listObjects(t){return e.send({op:"ListObjects",method:"GET",path:"/storage/buckets/"+c("ListObjects","bucket",t.path.bucket)+"/objects",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getObject(t){return e.send({op:"GetObject",method:"GET",path:"/storage/buckets/"+c("GetObject","bucket",t.path.bucket)+"/objects/"+c("GetObject","path",t.path.path),auth:[["SecretKeyAuth"]],answers:{200:"raw",206:"raw",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async putObject(t){return e.send({op:"PutObject",method:"PUT",path:"/storage/buckets/"+c("PutObject","bucket",t.path.bucket)+"/objects/"+c("PutObject","path",t.path.path),auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},query:t.query,headers:t.headers,body:{kind:"raw",contentType:t.contentType??"application/octet-stream",value:t.body},signal:t.signal})},async deleteObject(t){return e.send({op:"DeleteObject",method:"DELETE",path:"/storage/buckets/"+c("DeleteObject","bucket",t.path.bucket)+"/objects/"+c("DeleteObject","path",t.path.path),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async headObject(t){return e.send({op:"HeadObject",method:"HEAD",path:"/storage/buckets/"+c("HeadObject","bucket",t.path.bucket)+"/objects/"+c("HeadObject","path",t.path.path),auth:[["SecretKeyAuth"]],answers:{200:"empty",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async createSignedUrl(t){return e.send({op:"CreateSignedUrl",method:"POST",path:"/storage/buckets/"+c("CreateSignedUrl","bucket",t.path.bucket)+"/signed-urls",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createUploadUrl(t){return e.send({op:"CreateUploadUrl",method:"POST",path:"/storage/buckets/"+c("CreateUploadUrl","bucket",t.path.bucket)+"/upload-urls",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPublicObject(t){return e.send({op:"GetPublicObject",method:"GET",path:"/storage/public/"+c("GetPublicObject","bucket",t.path.bucket)+"/"+c("GetPublicObject","path",t.path.path),auth:[],answers:{200:"raw",206:"raw",302:"redirect",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async headPublicObject(t){return e.send({op:"HeadPublicObject",method:"HEAD",path:"/storage/public/"+c("HeadPublicObject","bucket",t.path.bucket)+"/"+c("HeadPublicObject","path",t.path.path),auth:[],answers:{200:"empty",302:"redirect",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async getSignedObject(t){return e.send({op:"GetSignedObject",method:"GET",path:"/storage/signed/"+c("GetSignedObject","bucket",t.path.bucket)+"/"+c("GetSignedObject","path",t.path.path),auth:[],answers:{200:"raw",206:"raw",302:"redirect",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async putSignedObject(t){return e.send({op:"PutSignedObject",method:"PUT",path:"/storage/signed/"+c("PutSignedObject","bucket",t.path.bucket)+"/"+c("PutSignedObject","path",t.path.path),auth:[],answers:{200:"json",201:"json"},query:t.query,headers:t.headers,body:{kind:"raw",contentType:t.contentType??"application/octet-stream",value:t.body},signal:t.signal})},async headSignedObject(t){return e.send({op:"HeadSignedObject",method:"HEAD",path:"/storage/signed/"+c("HeadSignedObject","bucket",t.path.bucket)+"/"+c("HeadSignedObject","path",t.path.path),auth:[],answers:{200:"empty",302:"redirect",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async getStorageStats(t){return e.send({op:"GetStorageStats",method:"GET",path:"/storage/stats",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async upload(t){return e.send({op:"Upload",method:"POST",path:"/storage/upload/"+c("Upload","machine",t.path.machine)+"/"+c("Upload","route",t.path.route),auth:[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]],answers:{},body:{kind:"raw",contentType:t.contentType??"multipart/form-data",value:t.body},signal:t.signal})}}}var Gs={};We(Gs,{client:()=>Ww});function Ww(e){return{async listActions(t){return e.send({op:"ListActions",method:"GET",path:"/stores/actions",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getAction(t){return e.send({op:"GetAction",method:"GET",path:"/stores/actions/"+c("GetAction","action_id",t.path.action_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async confirmAction(t){return e.send({op:"ConfirmAction",method:"POST",path:"/stores/actions/"+c("ConfirmAction","action_id",t.path.action_id)+"/confirm",auth:[["SecretKeyAuth"]],answers:{200:"json",202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async declineAction(t){return e.send({op:"DeclineAction",method:"POST",path:"/stores/actions/"+c("DeclineAction","action_id",t.path.action_id)+"/decline",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async getAppleAccount(t){return e.send({op:"GetAppleAccount",method:"GET",path:"/stores/apple",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async disconnectApple(t){return e.send({op:"DisconnectApple",method:"DELETE",path:"/stores/apple",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async checkAppleAccount(t){return e.send({op:"CheckAppleAccount",method:"POST",path:"/stores/apple/check",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async createAppleGrant(t){return e.send({op:"CreateAppleGrant",method:"POST",path:"/stores/apple/grants",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getSandboxReadiness(t){return e.send({op:"GetSandboxReadiness",method:"GET",path:"/stores/apple/readiness",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listSandboxTesters(t){return e.send({op:"ListSandboxTesters",method:"GET",path:"/stores/apple/sandbox-testers",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async clearSandboxPurchaseHistory(t){return e.send({op:"ClearSandboxPurchaseHistory",method:"POST",path:"/stores/apple/sandbox-testers/clear-purchase-history",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async updateSandboxTester(t){return e.send({op:"UpdateSandboxTester",method:"PATCH",path:"/stores/apple/sandbox-testers/"+c("UpdateSandboxTester","tester_id",t.path.tester_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listApps(t){return e.send({op:"ListApps",method:"GET",path:"/stores/apps",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listFeedback(t){return e.send({op:"ListFeedback",method:"GET",path:"/stores/apps/"+c("ListFeedback","app_id",t.path.app_id)+"/feedback",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getFeedback(t){return e.send({op:"GetFeedback",method:"GET",path:"/stores/apps/"+c("GetFeedback","app_id",t.path.app_id)+"/feedback/"+c("GetFeedback","kind",t.path.kind)+"/"+c("GetFeedback","feedback_id",t.path.feedback_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listGroups(t){return e.send({op:"ListGroups",method:"GET",path:"/stores/apps/"+c("ListGroups","app_id",t.path.app_id)+"/groups",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async createGroup(t){return e.send({op:"CreateGroup",method:"POST",path:"/stores/apps/"+c("CreateGroup","app_id",t.path.app_id)+"/groups",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async linkApp(t){return e.send({op:"LinkApp",method:"POST",path:"/stores/apps/"+c("LinkApp","app_id",t.path.app_id)+"/link",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getListing(t){return e.send({op:"GetListing",method:"GET",path:"/stores/apps/"+c("GetListing","app_id",t.path.app_id)+"/listing",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async setListing(t){return e.send({op:"SetListing",method:"PUT",path:"/stores/apps/"+c("SetListing","app_id",t.path.app_id)+"/listing",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async planListing(t){return e.send({op:"PlanListing",method:"POST",path:"/stores/apps/"+c("PlanListing","app_id",t.path.app_id)+"/listing/plan",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async createPackage(t){return e.send({op:"CreatePackage",method:"POST",path:"/stores/apps/"+c("CreatePackage","app_id",t.path.app_id)+"/packages",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async uploadScreenshot(t){return e.send({op:"UploadScreenshot",method:"PUT",path:"/stores/apps/"+c("UploadScreenshot","app_id",t.path.app_id)+"/screenshots",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,query:t.query,headers:t.headers,body:{kind:"raw",contentType:t.contentType??"image/png",value:t.body},signal:t.signal})},async getReviewInfo(t){return e.send({op:"GetReviewInfo",method:"GET",path:"/stores/apps/"+c("GetReviewInfo","app_id",t.path.app_id)+"/testflight/review-info",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async setReviewInfo(t){return e.send({op:"SetReviewInfo",method:"PUT",path:"/stores/apps/"+c("SetReviewInfo","app_id",t.path.app_id)+"/testflight/review-info",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getUploadKey(t){return e.send({op:"GetUploadKey",method:"GET",path:"/stores/apps/"+c("GetUploadKey","app_id",t.path.app_id)+"/upload-key",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getAppStoreVersion(t){return e.send({op:"GetAppStoreVersion",method:"GET",path:"/stores/apps/"+c("GetAppStoreVersion","app_id",t.path.app_id)+"/version",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async prepareAppStoreVersion(t){return e.send({op:"PrepareAppStoreVersion",method:"PUT",path:"/stores/apps/"+c("PrepareAppStoreVersion","app_id",t.path.app_id)+"/version",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async planPhasedRelease(t){return e.send({op:"PlanPhasedRelease",method:"POST",path:"/stores/apps/"+c("PlanPhasedRelease","app_id",t.path.app_id)+"/version/phased-release",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async planReleaseVersion(t){return e.send({op:"PlanReleaseVersion",method:"POST",path:"/stores/apps/"+c("PlanReleaseVersion","app_id",t.path.app_id)+"/version/release",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async planSubmitReview(t){return e.send({op:"PlanSubmitReview",method:"POST",path:"/stores/apps/"+c("PlanSubmitReview","app_id",t.path.app_id)+"/version/submit",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async planWithdrawReview(t){return e.send({op:"PlanWithdrawReview",method:"POST",path:"/stores/apps/"+c("PlanWithdrawReview","app_id",t.path.app_id)+"/version/withdraw",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async getAppVitals(t){return e.send({op:"GetAppVitals",method:"GET",path:"/stores/apps/"+c("GetAppVitals","app_id",t.path.app_id)+"/vitals",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getAppWebhook(t){return e.send({op:"GetAppWebhook",method:"GET",path:"/stores/apps/"+c("GetAppWebhook","app_id",t.path.app_id)+"/webhook",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async makeAppWebhook(t){return e.send({op:"MakeAppWebhook",method:"POST",path:"/stores/apps/"+c("MakeAppWebhook","app_id",t.path.app_id)+"/webhook",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async pingAppWebhook(t){return e.send({op:"PingAppWebhook",method:"POST",path:"/stores/apps/"+c("PingAppWebhook","app_id",t.path.app_id)+"/webhook/ping",auth:[["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async downloadSignedBundle(t){return e.send({op:"DownloadSignedBundle",method:"GET",path:"/stores/bundles",auth:[],answers:{200:"raw"},query:t.query,signal:t.signal})},async getConnectPage(t){return e.send({op:"GetConnectPage",method:"GET",path:"/stores/connect",auth:[],answers:{200:"raw"},signal:t?.signal})},async connectAppleKey(t){return e.send({op:"ConnectAppleKey",method:"POST",path:"/stores/connect",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getGoogleAccount(t){return e.send({op:"GetGoogleAccount",method:"GET",path:"/stores/google",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async connectGoogle(t){return e.send({op:"ConnectGoogle",method:"POST",path:"/stores/google",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async disconnectGoogle(t){return e.send({op:"DisconnectGoogle",method:"DELETE",path:"/stores/google",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async checkGoogleAccount(t){return e.send({op:"CheckGoogleAccount",method:"POST",path:"/stores/google/check",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async deleteGroup(t){return e.send({op:"DeleteGroup",method:"DELETE",path:"/stores/groups/"+c("DeleteGroup","group_id",t.path.group_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async renameGroup(t){return e.send({op:"RenameGroup",method:"PATCH",path:"/stores/groups/"+c("RenameGroup","group_id",t.path.group_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async addGroupBuild(t){return e.send({op:"AddGroupBuild",method:"POST",path:"/stores/groups/"+c("AddGroupBuild","group_id",t.path.group_id)+"/builds",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listTesters(t){return e.send({op:"ListTesters",method:"GET",path:"/stores/groups/"+c("ListTesters","group_id",t.path.group_id)+"/testers",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async setTesters(t){return e.send({op:"SetTesters",method:"PUT",path:"/stores/groups/"+c("SetTesters","group_id",t.path.group_id)+"/testers",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listPackages(t){return e.send({op:"ListPackages",method:"GET",path:"/stores/packages",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getPackage(t){return e.send({op:"GetPackage",method:"GET",path:"/stores/packages/"+c("GetPackage","package_id",t.path.package_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async uploadArtifact(t){return e.send({op:"UploadArtifact",method:"PUT",path:"/stores/packages/"+c("UploadArtifact","package_id",t.path.package_id)+"/artifact",auth:[],answers:{200:"json"},headers:t.headers,body:{kind:"raw",contentType:t.contentType??"application/octet-stream",value:t.body},signal:t.signal})},async planBetaReview(t){return e.send({op:"PlanBetaReview",method:"POST",path:"/stores/packages/"+c("PlanBetaReview","package_id",t.path.package_id)+"/beta-review",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async listDeliveries(t){return e.send({op:"ListDeliveries",method:"GET",path:"/stores/packages/"+c("ListDeliveries","package_id",t.path.package_id)+"/deliveries",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deliver(t){return e.send({op:"Deliver",method:"POST",path:"/stores/packages/"+c("Deliver","package_id",t.path.package_id)+"/deliveries",auth:[["SecretKeyAuth"]],answers:{200:"json",202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSignedBundleLink(t){return e.send({op:"GetSignedBundleLink",method:"POST",path:"/stores/packages/"+c("GetSignedBundleLink","package_id",t.path.package_id)+"/deliveries/"+c("GetSignedBundleLink","channel",t.path.channel)+"/bundle-link",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async planExpire(t){return e.send({op:"PlanExpire",method:"POST",path:"/stores/packages/"+c("PlanExpire","package_id",t.path.package_id)+"/expire",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async planExportCompliance(t){return e.send({op:"PlanExportCompliance",method:"POST",path:"/stores/packages/"+c("PlanExportCompliance","package_id",t.path.package_id)+"/export-compliance",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async setWhatToTest(t){return e.send({op:"SetWhatToTest",method:"PUT",path:"/stores/packages/"+c("SetWhatToTest","package_id",t.path.package_id)+"/what-to-test",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async takeAppleWebhook(t){return e.send({op:"TakeAppleWebhook",method:"POST",path:"/stores/webhooks/apple/"+c("TakeAppleWebhook","app_id",t.path.app_id),auth:[],answers:{200:"empty"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getAppleSession(t){return e.send({op:"GetAppleSession",method:"GET",path:"/stores/apple/session",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async disconnectAppleSession(t){return e.send({op:"DisconnectAppleSession",method:"DELETE",path:"/stores/apple/session",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async checkAppleSession(t){return e.send({op:"CheckAppleSession",method:"POST",path:"/stores/apple/session/check",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async createAppleIdGrant(t){return e.send({op:"CreateAppleIDGrant",method:"POST",path:"/stores/apple/session/grants",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getAppleIdPage(t){return e.send({op:"GetAppleIDPage",method:"GET",path:"/stores/connect/apple-id",auth:[],answers:{200:"raw"},signal:t?.signal})},async signInAppleId(t){return e.send({op:"SignInAppleID",method:"POST",path:"/stores/connect/apple-id",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async submitAppleIdCode(t){return e.send({op:"SubmitAppleIDCode",method:"POST",path:"/stores/connect/apple-id/code",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async chooseAppleIdTeam(t){return e.send({op:"ChooseAppleIDTeam",method:"POST",path:"/stores/connect/apple-id/team",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getAppReview(t){return e.send({op:"GetAppReview",method:"GET",path:"/stores/apps/"+c("GetAppReview","app_id",t.path.app_id)+"/review",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getReviewAttachment(t){return e.send({op:"GetReviewAttachment",method:"GET",path:"/stores/apps/"+c("GetReviewAttachment","app_id",t.path.app_id)+"/review/threads/"+c("GetReviewAttachment","thread_id",t.path.thread_id)+"/attachments/"+c("GetReviewAttachment","attachment_id",t.path.attachment_id),auth:[["SecretKeyAuth"]],answers:{200:"raw"},signal:t.signal})},async setReviewDraft(t){return e.send({op:"SetReviewDraft",method:"PUT",path:"/stores/apps/"+c("SetReviewDraft","app_id",t.path.app_id)+"/review/threads/"+c("SetReviewDraft","thread_id",t.path.thread_id)+"/draft",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async sendReviewDraft(t){return e.send({op:"SendReviewDraft",method:"POST",path:"/stores/apps/"+c("SendReviewDraft","app_id",t.path.app_id)+"/review/threads/"+c("SendReviewDraft","thread_id",t.path.thread_id)+"/draft/send",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async getAppPrivacy(t){return e.send({op:"GetAppPrivacy",method:"GET",path:"/stores/apps/"+c("GetAppPrivacy","app_id",t.path.app_id)+"/privacy",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async setAppPrivacy(t){return e.send({op:"SetAppPrivacy",method:"PUT",path:"/stores/apps/"+c("SetAppPrivacy","app_id",t.path.app_id)+"/privacy",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async makeAppRecord(t){return e.send({op:"MakeAppRecord",method:"POST",path:"/stores/apps/"+c("MakeAppRecord","app_id",t.path.app_id)+"/record",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async removeAppRecord(t){return e.send({op:"RemoveAppRecord",method:"DELETE",path:"/stores/apps/"+c("RemoveAppRecord","app_id",t.path.app_id)+"/record",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listMadeAppleKeys(t){return e.send({op:"ListMadeAppleKeys",method:"GET",path:"/stores/apple/keys",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async makeAppleKey(t){return e.send({op:"MakeAppleKey",method:"POST",path:"/stores/apple/keys",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async revokeMadeAppleKey(t){return e.send({op:"RevokeMadeAppleKey",method:"DELETE",path:"/stores/apple/keys/"+c("RevokeMadeAppleKey","key_id",t.path.key_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async shareAppleSession(t){return e.send({op:"ShareAppleSession",method:"PUT",path:"/stores/apple/session/shares/"+c("ShareAppleSession","environment",t.path.environment),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async unshareAppleSession(t){return e.send({op:"UnshareAppleSession",method:"DELETE",path:"/stores/apple/session/shares/"+c("UnshareAppleSession","environment",t.path.environment),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})}}}var Fa={attempts:3,maxWaitSeconds:30},Vw=new Set([429,502,503,504]);function Ti(e,t=Fa){let n=t.sleep??Xw;return{async send(s){let a=Hw(s),r=a.body,i=!r||r.kind!=="raw"||Vn(r.value),o=(a.method==="GET"||a.method==="HEAD"||a.idempotent===!0)&&i;for(let l=1;;l++)try{return await e.send(a)}catch(d){if(!o||l>=t.attempts||!(d instanceof j)||a.signal?.aborted)throw d;let p=Yw(d,l,t.maxWaitSeconds);if(p===void 0)throw d;await n(p*1e3,a.signal)}}}}function Hw(e){return e.idempotent?Object.entries(e.headers??{}).some(([n,s])=>n.toLowerCase()==="idempotency-key"&&s!==void 0&&s!==null&&s!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":Zw()}}:e}function Yw(e,t,n){return Vw.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=n?e.retryAfter:void 0:Math.min(.5*2**(t-1),n)*(.8+Math.random()*.4):void 0}function Xw(e,t){return new Promise((n,s)=>{if(t?.aborted)return s(t.reason);let a=()=>{clearTimeout(r),s(t?.reason)},r=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}function Zw(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}import{hostname as Qw}from"node:os";var ev=new Set(["apikey","authorization",Pi]);function tv(e){let t={accept:"application/json"};for(let[n,s]of Object.entries(e??{}))s!=null&&!ev.has(n.toLowerCase())&&(t[n.toLowerCase()]=String(s));return t}function nv(e,t,n){let s=null;try{s=n.startsWith("/")?new URL(n,e):null}catch{s=null}if(!s||s.origin!==new URL(e).origin)throw new j({op:t,status:0,code:"invalid_path",message:`${t}: a module's path stays at its environment's address`});return s.href}async function sv(e){let t=e.status===204||e.status===304?"":await e.text();if(t!=="")try{return JSON.parse(t)}catch{return t}}function av(e,t,n){let s=n??{},a=Number(t.headers.get("retry-after")??"");return new j({op:e,status:t.status,code:typeof s.error=="string"?s.error:`http_${t.status}`,message:Ja(n,t.status),requestId:typeof s.request_id=="string"?s.request_id:t.headers.get("x-request-id")??void 0,retryAfter:Number.isFinite(a)&&a>0?a:typeof s.retry_after=="number"?s.retry_after:void 0,body:n})}var wn=class{bytes;contentType;constructor(t,n){this.bytes=t,this.contentType=n}};function rv(e){return e instanceof wn?{headers:{"content-type":e.contentType,"content-length":String(e.bytes.size)},body:e.bytes}:e===void 0?{headers:{}}:{headers:{"content-type":"application/json"},body:JSON.stringify(e)}}async function ye(e,t,n,s,a,r){let i=`${n} ${s}`,o=rv(a),l=await e.module(nv(et(e.cloud,t),i,s),{method:n,headers:{...tv(r),...o.headers},body:o.body}),d=await sv(l);if(l.status>=200&&l.status<300)return{status:l.status,body:Oa(d),etag:l.headers.get("etag")??void 0};throw av(i,l,d)}var iv=10080*60*1e3;async function Ei(e,t,n=!1){let s=await e.state.personalKey(t);if(!n&&s&&Date.parse(s.expires_at)-e.io.now()>iv)return s;let a=await e.post(`/environments/${D("the environment's ref",t)}/personal-key`,{host:Qw().slice(0,100)||"computer"});return await e.state.keepPersonalKey(t,a),a}function Ja(e,t){let n=e??{},s=typeof n.error_description=="string"?n.error_description:`the module answered ${t}`,a=Array.isArray(n.field_errors)?n.field_errors.flatMap(r=>{let{pointer:i,message:o}=r??{};return typeof o=="string"?[`${typeof i=="string"&&i!==""?`${i}: `:""}${o}`]:[]}):[];return a.length>0?`${s}: ${a.join("; ")}`:s}import{relative as ov}from"node:path";async function Us(e,t){let n=await e.run("git",["rev-parse","--show-toplevel"],{cwd:t});if(n.code!==0)return null;let s=n.stdout.trim(),a=await e.run("git",["remote","get-url","origin"],{cwd:t}),r=await e.run("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t}),i=r.code===0?r.stdout.trim():"";return{root:s,repository:a.code===0?lv(a.stdout.trim()):void 0,branch:i!==""&&i!=="HEAD"?i:void 0,path:ov(s,t).split("\\").join("/")}}function lv(e){let t=/^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/.exec(e);return t?`${t[1]}/${t[2]}`:void 0}async function zs(e,t){let n=await Re(e);return new Map(n.filter(s=>s.project_id===t.project_id).map(s=>[s.ref,s.slug]))}function Yn(e,t){return t?e.get(t.ref)??t.ref:""}var Ue="main";async function Re(e){let[t,n]=await Promise.all([e.get("/environments"),e.get("/orgs")]),s=new Map(n.organizations.map(a=>[a.id,a.name]));return t.environments.map(a=>({...a,org_name:s.get(a.organization_id)??a.organization_id}))}function $e(e){return{org_id:e.organization_id,org_name:e.org_name,project_id:e.project_id,project_name:e.project_name,env_ref:e.ref,env_slug:e.slug,env_name:e.name}}function q(e){return`${e.org_name} \u203A ${e.project_name} \u203A ${e.env_name}${e.env_name!==e.env_slug?` (${e.env_slug})`:""}`}function vn(e){return(e.env.PALBASE_TOKEN??"").startsWith("pbe_")}async function Oi(e){let[t]=await Re(e.studio);if(!t)throw new y("token_refused","Studio names no environment for PALBASE_TOKEN",{hint:"mint another: palbase env:tokens:create"});let n=$e(t),s=i=>new y("token_environment",`PALBASE_TOKEN is ${q(n)}'s environment token: it acts there alone, not in ${i}`,{hint:"mint one there: palbase env:tokens:create -P <project> -E <env>"}),{project:a,env:r}=e.global;if(a!==void 0&&t.project_id!==a&&!ji(t.project_name,a.slice(a.indexOf("/")+1)))throw s(a);if(r!==void 0&&r!==t.slug&&r!==t.ref)throw s(r);if(a===void 0&&r===void 0){let i=await e.state.targetFor(e.io.cwd);if(i&&i.target.env_ref!==t.ref)throw s(`${q(i.target)}, chosen for ${i.dir}`)}return t}async function f(e){if(vn(e.io))return $e(await Oi(e));let{project:t,env:n}=e.global;if(t!==void 0||n!==void 0){let i=await Re(e.studio),o;if(t!==void 0)o=_n(i,t);else{let l=await e.state.targetFor(e.io.cwd);if(!l)throw Ci("-E names an environment of the project chosen here, and none is chosen: add -P <project>");o=i.filter(d=>d.project_id===l.target.project_id)}if(n!==void 0){let l=o.find(d=>d.slug===n||d.ref===n);if(!l)throw new y("no_such_environment",`the project has no environment ${JSON.stringify(n)}`,{hint:`its environments: ${o.map(d=>d.slug).join(", ")}`});return $e(l)}return o.length===1?$e(o[0]):$e(await Mp(e,o,"Which environment?"))}let s=await e.state.targetFor(e.io.cwd);if(s)return s.target;if(!e.interactive)throw Ci("no environment is chosen for this directory");let a=await Re(e.studio);if(a.length===0)throw new y("no_environments","your account reaches no environment yet",{hint:"make one: palbase projects:create <name>"});let r=$e(await Mp(e,a,"Which environment?"));return e.out.note(`Acting on ${q(r)}. palbase use remembers it for this directory.`),r}function _n(e,t){let n=e.filter(l=>l.project_id===t);if(n.length>0)return n;let s=t.indexOf("/"),[a,r]=s>=0?[t.slice(0,s),t.slice(s+1)]:[void 0,t],i=e.filter(l=>ji(l.project_name,r)&&(a===void 0||ji(l.org_name,a)||l.organization_id===a)),o=new Set(i.map(l=>l.project_id));if(o.size===0)throw new y("no_such_project",`no project ${JSON.stringify(t)} among yours`,{hint:"palbase projects:list shows them"});if(o.size>1){let l=[...new Set(i.map(d=>`${d.org_name}/${d.project_name}`))].join(", ");throw new y("ambiguous_project",`${JSON.stringify(t)} is a project in more than one organization: ${l}`,{hint:"name it as org/project"})}return i}async function v(e,t,n,s){e.out.note(`${q(t)}: ${n}`);let a=t.env_slug===Ue;if(!a&&s===void 0||e.global.yes)return;if(!e.interactive){let i=vn(e.io)?"confirm with -y: with PALBASE_TOKEN, -y is the go-ahead (the CLI asks no one else, and a person's yes elsewhere is not one)":"confirm with -y";throw new y("confirmation_needed",a?`${t.project_name} \u203A ${t.env_name} is the project's production environment`:s,{hint:i})}let r=(await e.io.prompt(K(`${a?`This is ${t.project_name}'s production environment`:s}. Go ahead? [y/N] `))).trim().toLowerCase();if(r!=="y"&&r!=="yes")throw new y("cancelled","nothing was changed")}async function Mp(e,t,n){if(!e.interactive)throw Ci(`${n.replace(/\?$/,"")}: ${t.map(s=>`${s.project_name}/${s.slug}`).join(", ")}`);for(t.forEach((s,a)=>e.out.note(` ${String(a+1).padStart(2)}) ${q($e(s))}`));;){let s=(await e.io.prompt(`${n} [1-${t.length}] `)).trim(),a=Number(s);if(Number.isInteger(a)&&a>=1&&a<=t.length)return t[a-1];e.out.note(`answer with a number from 1 to ${t.length}`)}}function Ci(e){return new y("no_target",e,{hint:"choose one here with palbase use, or pass -P <project> -E <env>"})}function ji(e,t){return e.localeCompare(t,void 0,{sensitivity:"accent"})===0}import{randomUUID as pv}from"node:crypto";import{readFile as dv}from"node:fs/promises";import{resolve as uv}from"node:path";var cv=6,Mi=0,xp=[];async function hv(e){Mi<cv?Mi++:await new Promise(t=>xp.push(t));try{return await e()}finally{let t=xp.shift();t?t():Mi--}}async function qe(e,t,n,s,a,r){return hv(()=>ye(e.studio,t.env_ref,n,s,a,r))}async function h(e,t,n,s,a,r){return(await qe(e,t,n,s,a,r)).body}async function Ne(e,t,n){let s=await qe(e,t,"GET",n);return{body:s.body,etag:s.etag}}function Te(e){return e?{"if-match":e}:void 0}function C(){return{"idempotency-key":pv()}}function k(e){return encodeURIComponent(e)}function Zt(e){return e.map(t=>{let n=t.indexOf("=");if(n<=0)throw g(`a setting is key=value, not ${JSON.stringify(t)}`);let s=t.slice(0,n).split(".");if(s.some(a=>a===""||a==="__proto__"||a==="constructor"||a==="prototype"))throw g(`${JSON.stringify(t.slice(0,n))} is not a key`);return{path:s,value:St(t.slice(n+1))}})}function St(e){try{return JSON.parse(e)}catch{return e}}function Qt(e,t){let n=structuredClone(e);for(let{path:s,value:a}of t){let r=n;for(let i of s.slice(0,-1)){let o=r[i];(typeof o!="object"||o===null)&&(r[i]={}),r=r[i]}r[s[s.length-1]]=a}return n}function Dt(e,t){return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!Me(e[n],t[n])).sort()}function Ip(e){return JSON.stringify(e,(t,n)=>n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.entries(n).sort(([s],[a])=>s<a?-1:s>a?1:0)):n)}function Me(e,t){return Ip(e)===Ip(t)}function Ee(e){return e===void 0?"(not set)":typeof e=="string"&&e!==""?e:JSON.stringify(e)}function Xn(e,t){let n=Object.keys(t).sort(),s=Math.max(0,...n.map(a=>a.length));for(let a of n)e.out.line(`${a.padEnd(s)} ${Ee(t[a])}`)}function ze(e,t,n){e.out.result({settings:n,changed:[]},()=>e.out.line(`Nothing to change: ${t} already ${t.endsWith("s")?"are":"is"} so.`))}async function be(e,t,n){let s;if(t!==void 0&&t!=="-")try{s=await dv(uv(e.io.cwd,t),"utf8")}catch(a){throw new y("unreadable_file",`${t} could not be read: ${a instanceof Error?a.message:String(a)}`)}else e.io.interactive&&e.out.note(`Reading ${n} from stdin; end it with Ctrl-D.`),s=await e.io.readStdin();if(s.trim()==="")throw g(`no ${n} was given`,t===void 0?"pass --file <path>, or pipe it in":void 0);return s}function ue(e,t){try{return JSON.parse(e)}catch(n){throw g(`${t} is not JSON: ${n instanceof Error?n.message:String(n)}`)}}async function xe(e,t){e.io.interactive&&e.out.note(`Paste ${t}, then Ctrl-D (it is read from stdin, never from the command line):`);let n=(await e.io.readStdin()).trim();if(n==="")throw g(`no ${t} was piped in`,"pipe it in: palbase \u2026 < file");return n}function Zn(e){if(e.flags.enable===!0&&e.flags.disable===!0)throw g("--enable and --disable are one or the other");if(e.flags.enable===!0)return!0;if(e.flags.disable===!0)return!1}function en(e,t){if(e!==void 0){if(e==="yes"||e==="true")return!0;if(e==="no"||e==="false")return!1;throw g(`--${t} is yes or no`)}}function re(e){return e===void 0?void 0:(Array.isArray(e)?e:[e]).flatMap(n=>String(n).split(",")).map(n=>n.trim()).filter(n=>n!=="")}function ne(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw g(`--${t} is a whole number`);return n}var Bs={enable:{type:"boolean",description:"turn it on"},disable:{type:"boolean",description:"turn it off"}};async function V(e,t,n){try{await n(),e.done(t)}catch(s){if(!(s instanceof j))throw s;e.left(`${t}: refused \u2014 ${s.message}`)}}function pe(e,t){return e.filter(n=>n.key.startsWith(t)).map(n=>({...n,name:n.key.slice(t.length)}))}function xi(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>!(t==null||t===""||Array.isArray(t)&&t.length===0)))}import{randomBytes as ad}from"node:crypto";import{chmod as Lv,lstat as Dv,readFile as Qp,rename as qv,writeFile as ed}from"node:fs/promises";function Lp(){let e=globalThis;if(typeof e.document<"u"||e.navigator?.product==="ReactNative")return!0;let t=e.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}var qt=class extends Error{code;constructor(t,n){super(n),this.name="FieldError",this.code=t}},Wa="pbe1.",mv="pbl1.",gv=6e4,Ii="[A-Za-z_][A-Za-z0-9_$]{0,62}",fv=new RegExp(`^${Ii}\\.${Ii}(\\.${Ii})?$`);function yv(e){return fv.test(e)}var Fs=class{crypto;keys=new Map;lookupKey;timer;opts;now;constructor(t){this.opts=t,this.now=t.now??Date.now}get loaded(){return this.lookupKey!==void 0}async load(t){this.crypto??=await import("node:crypto"),this.take(await this.opts.fetch(t)),this.timer===void 0&&(this.timer=setInterval(()=>{this.opts.fetch().then(n=>this.take(n),()=>{})},gv),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}take(t){let n=new Map;for(let s of t.keys)n.set(s.id,{id:s.id,key:Buffer.from(s.key,"base64url"),activatesAt:Date.parse(s.activates_at)});this.keys=n,this.lookupKey=Buffer.from(t.lookup,"base64url")}ready(){if(this.crypto===void 0||this.lookupKey===void 0)throw new qt("not_loaded","the project's field keys are not loaded: await palbase.fields.load() at startup");return this.crypto}currentKey(){this.ready();let t;for(let n of this.keys.values())n.activatesAt<=this.now()&&(t===void 0||n.activatesAt>=t.activatesAt)&&(t=n);if(t===void 0)throw new qt("unknown_key","the project has no field key in force");return t.id}encrypt(t,n){let s=this.ready();Li(t);let a=this.currentKey(),r=s.randomBytes(12);return bv(s,this.keys.get(a).key,r,a,t,n)}decrypt(t,n){let s=this.ready();if(Li(t),!n.startsWith(Wa))throw new qt("not_encrypted",`${t} holds a value that is not encrypted`);let a=n.slice(Wa.length),r=a.indexOf("."),i=r<0?a:a.slice(0,r),o=this.keys.get(i);if(o===void 0)throw new qt("unknown_key",`${t} was sealed with field key ${i}, which this project does not hold`);let l=Buffer.from(a.slice(r+1),"base64url");if(r<0||l.length<28||l.toString("base64url")!==a.slice(r+1))throw new qt("unopenable",`${t} holds a value that does not open here`);try{let d=s.createDecipheriv("aes-256-gcm",o.key,l.subarray(0,12));return d.setAAD(Dp(t)),d.setAuthTag(l.subarray(l.length-16)),Buffer.concat([d.update(l.subarray(12,l.length-16)),d.final()]).toString("utf8")}catch{throw new qt("unopenable",`${t} holds a value that does not open here: tampered, or another column's`)}}isEncrypted(t){return t.startsWith(Wa)}lookup(t,n){let s=this.ready();return Li(t),wv(s,this.lookupKey,t,n)}};function Li(e){if(!yv(e))throw new TypeError(`a field's address is table.column, or schema.table.column, not ${JSON.stringify(e)}`)}function Dp(e){return Buffer.from(`pbe1\0${e}`,"utf8")}function bv(e,t,n,s,a,r){let i=e.createCipheriv("aes-256-gcm",t,n);i.setAAD(Dp(a));let o=Buffer.concat([n,i.update(r,"utf8"),i.final(),i.getAuthTag()]);return`${Wa}${s}.${o.toString("base64url")}`}function wv(e,t,n,s){let a=e.createHmac("sha256",t);return a.update(`pbl1\0${n}\0`,"utf8"),a.update(s,"utf8"),`${mv}${a.digest("base64url")}`}var qi="pbt1.",ut="Palbase-Encryption";var Ya="x-palbase-encrypted",_e=class extends Error{code;constructor(t,n){super(n),this.name="TransitError",this.code=t}},tn=new TextEncoder,vv=new TextDecoder("utf-8",{fatal:!0}),ct=()=>{let e=globalThis.crypto?.subtle;if(!e)throw new Error("encrypted fields need WebCrypto (crypto.subtle): a secure context \u2014 https, or localhost");return e};function Ge(e){return new Uint8Array(new ArrayBuffer(e))}function ht(...e){let t=Ge(e.reduce((s,a)=>s+a.length,0)),n=0;for(let s of e)t.set(s,n),n+=s.length;return t}function $t(e){return ht(e)}function Ws(e,t){let n=Ge(t);for(let s=t-1;s>=0;s--)n[s]=e&255,e>>>=8;return n}function Vs(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Pt(e){let t=e.replace(/=+$/,"");if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)throw new _e("malformed","not base64url");let n=atob(t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4)),s=Ge(n.length);for(let a=0;a<n.length;a++)s[a]=n.charCodeAt(a);return s}var qp=ht(tn.encode("KEM"),Ws(32,2)),Js=ht(tn.encode("HPKE"),Ws(32,2),Ws(1,2),Ws(1,2)),Np=tn.encode("HPKE-v1"),_v=16,kv=12,Sv=32,Kp=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function Gp(e,t){let n=await ct().importKey("raw",e.length===0?Ge(32):$t(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await ct().sign("HMAC",n,$t(t)))}async function Va(e,t,n,s){return Gp(t,ht(Np,e,tn.encode(n),s))}async function Di(e,t,n,s,a){let r=ht(Ws(a,2),Np,e,tn.encode(n),s),i=Ge(a),o=Ge(0);for(let l=1,d=0;d<a;l++)o=await Gp(t,ht(o,r,Uint8Array.of(l))),i.set(o.subarray(0,Math.min(o.length,a-d)),d),d+=o.length;return i}async function Up(e){if(e.length!==32)throw new _e("malformed","an X25519 private key is 32 bytes");return ct().importKey("pkcs8",ht(Kp,e),{name:"X25519"},!1,["deriveBits"])}async function zp(e){if(e.length!==32)throw new _e("malformed","an X25519 public key is 32 bytes");return ct().importKey("raw",$t(e),{name:"X25519"},!1,[])}async function Bp(e,t){return new Uint8Array(await ct().deriveBits({name:"X25519",public:t},e,256))}async function Fp(e,t,n){let s=await Va(qp,Ge(0),"eae_prk",e);return Di(qp,s,"shared_secret",ht(t,n),Sv)}async function Jp(e,t){let n=await Va(Js,Ge(0),"psk_id_hash",Ge(0)),s=await Va(Js,Ge(0),"info_hash",t),a=ht(Uint8Array.of(0),n,s),r=await Va(Js,e,"secret",Ge(0));return{key:await Di(Js,r,"key",a,_v),nonce:await Di(Js,r,"base_nonce",a,kv)}}async function Xa(e,t,n,s,a){let r=await ct().importKey("raw",$t(t),"AES-GCM",!1,[e]);return new Uint8Array(await ct()[e]({name:"AES-GCM",iv:$t(n),additionalData:$t(s)},r,$t(a)))}async function Ni(e,t,n,s=Ge(0),a){let r,i;if(a)r=await Up(a.privateKey),i=$t(a.publicKey);else{let p=await ct().generateKey({name:"X25519"},!0,["deriveBits"]);r=p.privateKey,i=new Uint8Array(await ct().exportKey("raw",p.publicKey))}let o=await Fp(await Bp(r,await zp(e)),i,e),{key:l,nonce:d}=await Jp(o,t);return{enc:i,ct:await Xa("encrypt",l,d,s,n)}}async function $v(e,t,n,s,a,r=Ge(0)){if(n.length!==32)throw new _e("malformed","an encapsulated X25519 key is 32 bytes");try{let i=await Fp(await Bp(await Up(e),await zp(n)),n,t),{key:o,nonce:l}=await Jp(i,s);return await Xa("decrypt",o,l,r,a)}catch{throw new _e("unopenable","the request's key does not open with the project's key it names")}}async function Wp(e){let t=await ct().importKey("pkcs8",ht(Kp,e),{name:"X25519"},!0,["deriveBits"]),n=await ct().exportKey("jwk",t);return Pt(n.x)}function Za(e,t,n,s=[]){if(s.some(a=>a.includes("\0")))throw new _e("malformed","a path's value holds no NUL");return tn.encode(["palbase-encryption","1",e,t.toUpperCase(),Pv(n),...s].join("\0"))}function Pv(e){return e.replace(/\{[^/{}]*\}/g,"{}")}async function Vp(e,t,n,s={}){let a=s.key?$t(s.key):crypto.getRandomValues(Ge(32)),{enc:r,ct:i}=await Ni(t,n,a,Ge(0),s.ephemeral);return{kid:e,key:a,header:`1.${e}.${Vs(r)}.${Vs(i)}`}}function Ki(e){let t=e.trim().split(".");if(t.length!==4||t[0]!=="1"||!/^t[1-9][0-9]{0,5}$/.test(t[1]))throw new _e("malformed",`${ut} is 1.<key id>.<enc>.<ct>`);let n=Pt(t[2]),s=Pt(t[3]);if(n.length!==32||s.length!==48)throw new _e("malformed",`${ut} carries a 32-byte encapsulated key and a sealed 32-byte key`);return{kid:t[1],enc:n,ct:s}}async function Hp(e,t,n,s){let{enc:a,ct:r}=Ki(e),i=await $v(t,n,a,s,r);if(i.length!==32)throw new _e("unopenable","the request's key is not 32 bytes");return i}function Yp(e){return tn.encode(`pbt1\0${e}`)}async function Hs(e,t,n,s){let a=s?$t(s):crypto.getRandomValues(Ge(12)),r=JSON.stringify(n);if(r===void 0)throw new _e("malformed",`${t}: an encrypted field holds a JSON value`);let i=await Xa("encrypt",e,a,Yp(t),tn.encode(r));return qi+Vs(ht(a,i))}function Ys(e){return typeof e=="string"&&e.startsWith(qi)}async function Qa(e,t,n){if(!Ys(n))throw new _e("unopenable",`${t} is not an encrypted field`);let s;try{s=Pt(n.slice(qi.length))}catch{throw new _e("unopenable",`${t} is not an encrypted field`)}if(s.length<28)throw new _e("unopenable",`${t} is too short to be an encrypted field`);let a;try{a=await Xa("decrypt",e,s.subarray(0,12),Yp(t),s.subarray(12))}catch{throw new _e("unopenable",`${t} does not open: changed, moved from another field, or another request's`)}try{return JSON.parse(vv.decode(a))}catch{throw new _e("unopenable",`${t} opens to no JSON value`)}}function er(e){return e.replace(/~/g,"~0").replace(/\//g,"~1").replace(/\*/g,"~2")}function Av(e){return e.replace(/~2/g,"*").replace(/~1/g,"/").replace(/~0/g,"~")}var Xp=Symbol("items");function Rv(e,t){if(!(e!==t&&!e.startsWith(t+"/")))return e===t?[]:e.slice(t.length+1).split("/").map(n=>n==="*"?Xp:Av(n))}async function Qn(e,t,n,s){let a=e;for(let r of n){let i=Rv(r,t);i!==void 0&&(a=await Ha(a,i,t,s))}return a}async function Ha(e,t,n,s){if(t.length===0)return e===void 0?void 0:s(n,e);let[a,...r]=t;if(a===Xp){if(!Array.isArray(e))return e;let o=[];for(let[l,d]of e.entries())o.push(await Ha(d,r,`${n}/${l}`,s));return o}if(Array.isArray(e)){if(!/^(0|[1-9][0-9]*)$/.test(a)||Number(a)>=e.length)return e;let o=[...e];return o[Number(a)]=await Ha(o[Number(a)],r,`${n}/${a}`,s),o}if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,a))return e;let i={...e};return i[a]=await Ha(i[a],r,`${n}/${er(a)}`,s),i}var mt=class extends Error{status=400;code;data;constructor(t,n,s={}){super(n),this.name="TransitRefusal",this.code=t,this.data=s}},Tv=6e4,Ev=1e3;function Gi(e){return/^t[1-9][0-9]{0,5}$/.test(e)?Number(e.slice(1)):0}var Xs=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(t){this.opts=t,this.now=t.now??Date.now,this.sleep=t.sleep??(n=>new Promise(s=>setTimeout(s,n)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(t){await this.refresh(t),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Tv),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(t){return this.fetching??=(async()=>{let n=this.now();try{let s=await this.opts.fetch(t),a=new Map;for(let r of s.keys){let i=Pt(r.key);a.set(r.id,{privateKey:i,publicKey:this.keys.get(r.id)?.publicKey??await Wp(i)})}this.keys=a,this.order=s.keys.map(r=>r.id),this.retired=new Set(s.retired),this.project=s.project,this.fetchedAt=this.now(),this.heldFrom=n}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(Gi),...[...this.retired].map(Gi))}async key(t){let n=this.now();for(;Gi(t)>this.newest()&&this.heldFrom<n;){let r=this.fetchedAt+Ev-this.now();if(r>0){await this.sleep(r);continue}await this.refresh()}let s=this.keys.get(t),a=this.current();if(this.retired.has(t))throw new mt("encryption_key_retired",`the request is sealed to ${t}, retired: fetch the project's keys again`,{current:a});if(s===void 0)throw new mt("encryption_key_unknown",`the request is sealed to ${t}, which the project has not made`,{current:a});return s}async request(t){if(t.header===void 0||t.header===null||t.header==="")throw new mt("encryption_required",`this route carries encrypted fields: the request names its key in ${ut}`,{field:ut,current:this.current()});let n;try{n=Ki(t.header).kid}catch{throw new mt("encryption_unopenable",`${ut} is not one`,{field:ut})}let s=await this.key(n),a;try{a=Za(this.projectId,t.method,t.path,t.params??[])}catch{throw new mt("encryption_unopenable","the request's path holds a value no key is sealed for",{field:ut})}try{return new tr(n,await Hp(t.header,s.privateKey,s.publicKey,a))}catch(r){throw r instanceof _e?new mt("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:ut}):r}}},tr=class{kid;key;constructor(t,n){this.kid=t,this.key=n}async open(t,n,s){return Qn(t,n,s,async(a,r)=>{if(!Ys(r))throw new mt("encryption_required",`${a} is an encrypted field: it came plain`,{field:a});try{return await Qa(this.key,a,r)}catch{throw new mt("encryption_unopenable",`${a} does not open: changed, moved from another field, or another request's`,{field:a})}})}async seal(t,n){return Qn(t,"/response",n,(s,a)=>Hs(this.key,s,a))}sealField(t,n){return Hs(this.key,t,n)}};var Cv=/^pb_[a-z0-9]+_s/;function nr(e){if(Lp())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof e.secretKey!="string"||!Cv.test(e.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let t=Ti(vi({baseUrl:e.url,credentials:{secretKey:e.secretKey},fetch:e.fetch,solveProofOfWork:e.solveProofOfWork??!1}),e.retry??Fa),n=Ns.client(t);return{ai:Ga.client(t),analytics:Os.client(t),auth:Ms.client(t),cache:Ua.client(t),calls:za.client(t),fields:new Fs({fetch:async s=>(await n.getFieldKeys({signal:s})).data}),flags:xs.client(t),machines:Is.client(t),messaging:Ba.client(t),notify:Ls.client(t),purchases:Ds.client(t),realtime:qs.client(t),secrets:n,storage:Ks.client(t),stores:Gs.client(t),transit:new Xs({fetch:async s=>(await n.getTransitKeys({signal:s})).data}),transport:t,url:new URL(e.url).origin}}var Nx=1024*1024;var Ux=8*1024;var Vx=16*1024,Hx=10*6e4;var Mv=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,xv=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function Ui(e){return!Mv.test(e)||xv.test(e)||/_PROXY$/i.test(e)}var Iv=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function zi(e){return Iv.test(e)}import"node:os";import{join as Nv,resolve as Kv}from"node:path";var II=10080*60*1e3,Zp="# >>> palbase (palbase env:pull writes this block; edit outside it)",Bi="# <<< palbase";async function Zs(e,t){let n=await Ei(e.studio,t.env_ref),{keys:s}=await e.studio.get(`/environments/${D("the environment's ref",t.env_ref)}/keys`),a=s.find(r=>r.id===n.id);return a&&!a.revoked_at?n:Ei(e.studio,t.env_ref,!0)}async function sr(e,t){return{...await Ji(e,t),key:await Zs(e,t)}}async function Ji(e,t){let n=await e.studio.get(`/environments/${t.env_ref}`);return{url:et(e.cloud,t.env_ref),projectId:n.platform_id}}function ar(e){let t=e.flags.secrets??"development";if(t!=="development"&&t!=="production")throw g("--secrets is development or production");return t}function rr(e,t){return t==="production"?`the app reads ${e.project_name} \u203A ${e.env_name}'s production secrets here`:void 0}var ir={type:"string",value:"set",description:"the project's secrets the app reads at boot: development (default) or production"},td={name:"env:pull",summary:"write what the backend needs to run here into .env.local: the environment's address and your own key \u2014 no secret's value",usage:"[--file <path>] [--secrets development|production]",details:["The app reads the project's secrets at boot (PALBASE_SECRETS); their names are listed as comments: set one in the file to override it.","The key is yours (CLI \u2014 you (this computer)), good for 30 days, made again by env:pull and run; palbase logout revokes it.","Only the block between the palbase markers is written; the rest of the file stays as it is."],flags:{file:{type:"string",value:"path",description:"the file (default .env.local)"},secrets:ir},scope:"environment",async run(e){let t=await f(e),n=ar(e);(t.env_slug===Ue||n==="production")&&await v(e,t,`write a key of ${t.env_slug===Ue?"the production environment":`${t.env_slug}`} into a file on this computer`,rr(t,n));let s=await sr(e,t),a=await ye(e.studio,t.env_ref,"GET",`/secrets/${n}`).then(b=>(b.body.secrets??b.body.items??[]).map(w=>w.name).filter(w=>typeof w=="string"&&!Ui(w)).sort(),()=>[]),r=Kv(e.io.cwd,e.flags.file??".env.local"),i=[Zp,`# ${Fi(q(t))} \u2014 ${new Date(e.io.now()).toISOString()}`,`# PALBASE_SECRET_KEY is your own: ${Fi(s.key.label)}, good until ${Fi(s.key.expires_at)}.`,`PALBASE_URL=${s.url}`,`PALBASE_PROJECT_ID=${s.projectId}`,`PALBASE_SECRET_KEY=${s.key.key}`,`PALBASE_SECRETS=${n}`,...a.length>0?[`# The ${n} secrets, read at boot \u2014 set one here to override it:`,...a.map(b=>`# ${b}=`)]:[],Bi].join(`
|
|
21
|
+
`}import{createHash as gM,randomBytes as fM,timingSafeEqual as yM}from"node:crypto";import{createServer as wM}from"node:http";var Ri="owner.json";var kM=300*1e3;function D(e,t){try{return c("palbase",e,t)}catch(n){throw n instanceof j&&n.code==="invalid_path_parameter"?new y("unsafe_path",`${e} cannot be ${t===""?"empty":JSON.stringify(t)}: a request's path cannot carry it`):n}}var Tp={name:"login",summary:"sign in with your Studio account",details:["Shows a one-time code and opens Studio, where you approve it while signed in there.","The CLI then holds a session of yours: Studio lists it with your others, and ending it there signs the CLI out.","On a machine with no browser (a server, an agent), open the address it prints on any device."],flags:{"no-browser":{type:"boolean",description:"print the address instead of opening a browser"}},scope:"none",async run(e){if(e.io.env.PALBASE_TOKEN)throw new y("token_in_use","PALBASE_TOKEN is set: the CLI acts with that token, and a sign-in would not be used",{hint:"unset PALBASE_TOKEN to sign in as yourself"});let t=await gp(e.io,e.cloud),n=`${e.cloud.studioWeb}/device`;e.out.note(""),e.out.note(` Enter this code in your browser: ${t.user_code}`),e.out.note("");let s=e.flags["no-browser"]!==!0&&e.interactive&&await e.io.openBrowser(n);e.out.note(s?`Opened ${n} \u2014 sign in there if asked, then enter the code.`:`Open ${n} on any device, sign in, and enter the code.`),e.out.note("Waiting for the approval\u2026");let a=await fp(e.io,e.cloud,t);await e.state.writeSession(a),e.out.result({user:a.user},()=>e.out.line(`Signed in as ${a.user.email??a.user.id}.`))}},Ep={name:"logout",summary:"sign out: the session is ended at Palbase and forgotten on this computer",scope:"none",async run(e){if(e.io.env.PALBASE_TOKEN)throw new y("token_in_use","PALBASE_TOKEN is set: logout ends your own sign-in, and the CLI acts with the token",{hint:"unset PALBASE_TOKEN to sign out"});let t=await e.state.readSession();if(!t){e.out.result({signed_out:!0},()=>e.out.line("You were not signed in."));return}for(let[n,s]of Object.entries(await e.state.personalKeys()))try{await e.studio.request("DELETE",`/environments/${D("the environment's ref",n)}/personal-key/${D("the personal key's id",s.id)}`)}catch(a){a instanceof Error&&"status"in a&&a.status===404||e.out.warn(`your key at ${n} (${s.label}) could not be revoked: ${a instanceof Error?a.message:String(a)} \u2014 revoke it in Studio, or it ends ${s.expires_at}`)}await e.state.forgetPersonalKeys(),await e.state.forget(Ri);try{await bp(e.io,e.cloud,t)}catch(n){e.out.warn(`${n instanceof Error?n.message:String(n)} \u2014 end the session in Studio (Account \u203A Sessions)`)}await e.state.clearSession(),e.out.result({signed_out:!0},()=>e.out.line(`Signed out ${t.user.email??t.user.id}.`))}},Cp={name:"whoami",summary:"the account the CLI acts as, and the environment chosen for this directory",scope:"account",async run(e){let t=e.io.env.PALBASE_TOKEN,n;if(t?.startsWith("pbu_")){let{organizations:a}=await e.studio.get("/orgs");n={id:`account token \u2026${t.slice(-4)}`,via:"token",organizations:a.length}}else if(t?.startsWith("pbo_")){let{organizations:a}=await e.studio.get("/orgs"),r=a[0];n={id:`token \u2026${t.slice(-4)}`,via:"token",...r&&{organization:{id:r.id,name:r.name,role:r.role}}}}else if(t){let a=Da(t);n={id:String(a.sub??""),...typeof a.email=="string"?{email:a.email}:{},via:"token"}}else n={...(await e.studio.currentSession()).user,via:"session"};let s=await e.state.targetFor(e.io.cwd);e.out.result({user:n,target:s?.target??null,target_dir:s?.dir??null},()=>{e.out.line(n.organization?`an access token of ${K(n.organization.name)} (${n.organization.role}), ${n.id} (PALBASE_TOKEN)`:n.organizations!==void 0?`an ${n.id} (PALBASE_TOKEN): an admin of the ${n.organizations} organization${n.organizations===1?"":"s"} it opened`:`${n.email??n.id}${n.via==="token"?" (PALBASE_TOKEN)":""}`),s&&e.out.line(`${s.target.org_name} \u203A ${s.target.project_name} \u203A ${s.target.env_name} (${s.target.env_slug}) \u2014 chosen for ${s.dir}`)})}};var Cw={name:"account:tokens:list",summary:"your account tokens (for a program that opens organizations): name, how many organizations they reach, when they end and were last used \u2014 never their values",scope:"account",async run(e){let{tokens:t}=await e.studio.get("/account/tokens");e.out.result({tokens:t},()=>{t.length===0?e.out.line("You have no account token yet: palbase account:tokens:create <name> makes one."):e.out.table(t,[{header:"name",value:n=>K(n.name)},{header:"token",value:n=>`pbu_\u2026${n.hint}`},{header:"organizations",value:n=>String(n.organizations)},{header:"ends",value:n=>n.expires_at.slice(0,10)},{header:"last used",value:n=>n.last_used_at?.slice(0,16).replace("T"," ")??"never"},{header:"id",value:n=>n.id}])})}},jw={name:"account:tokens:create",summary:"make an account token for a program that opens organizations; its value is shown this once",usage:"<name> [--days <n>]",details:["Give it to the program as its secret (PALBASE_TOKEN, or palbase/cloud's token): it opens organizations \u2014 you their owner, the token their admin \u2014 and builds projects and environments there.","It reaches only the organizations it opened, never your others; it makes no token or key and changes no one's place. It ends after --days (default 90, at most 365), when it is revoked, and, in an organization, when you leave it."],args:{min:1,max:1},flags:{days:{type:"string",value:"n",description:"how many days it is good for (default 90)"}},scope:"account",async run(e){let t=e.flags.days===void 0?90:Number(e.flags.days);if(!Number.isInteger(t)||t<1||t>365)throw g("--days is a whole number from 1 to 365");let n=await e.studio.post("/account/tokens",{name:e.args[0],expires_in_days:t});e.out.result(n,()=>{e.out.line(`Made the account token ${K(n.name)} (until ${n.expires_at.slice(0,10)}).`),e.out.line(`token (shown this once \u2014 keep it as the program's secret PALBASE_TOKEN): ${n.token}`)})}},Ow={name:"account:tokens:revoke",summary:"revoke one of your account tokens (by its name or id): refused from its next request on; the organizations it opened stay yours",usage:"<name|id>",args:{min:1,max:1},scope:"account",async run(e){let{tokens:t}=await e.studio.get("/account/tokens"),n=t.filter(s=>s.id===e.args[0]||s.name===e.args[0]);if(n.length===0)throw new y("no_such_token",`you have no account token ${JSON.stringify(e.args[0])}`,{hint:"palbase account:tokens:list shows them"});if(n.length>1)throw new y("ambiguous_token",`${JSON.stringify(e.args[0])} names more than one token`,{hint:"pass its id"});await e.studio.request("DELETE",`/account/tokens/${D("the token's id",n[0].id)}`),e.out.result({revoked:n[0].id},()=>e.out.line(`Revoked the account token ${K(n[0].name)}.`))}},jp=[Cw,jw,Ow];var Ga={};We(Ga,{client:()=>Mw});function Mw(e){return{async draftAgent(t){return e.send({op:"DraftAgent",method:"POST",path:"/ai/agent-drafts",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listAgents(t){return e.send({op:"ListAgents",method:"GET",path:"/ai/agents",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getAgent(t){return e.send({op:"GetAgent",method:"GET",path:"/ai/agents/"+c("GetAgent","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putAgent(t){return e.send({op:"PutAgent",method:"PUT",path:"/ai/agents/"+c("PutAgent","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteAgent(t){return e.send({op:"DeleteAgent",method:"DELETE",path:"/ai/agents/"+c("DeleteAgent","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async publishAgent(t){return e.send({op:"PublishAgent",method:"POST",path:"/ai/agents/"+c("PublishAgent","name",t.path.name)+"/publish",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async rollbackAgent(t){return e.send({op:"RollbackAgent",method:"POST",path:"/ai/agents/"+c("RollbackAgent","name",t.path.name)+"/rollback",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listAgentVersions(t){return e.send({op:"ListAgentVersions",method:"GET",path:"/ai/agents/"+c("ListAgentVersions","name",t.path.name)+"/versions",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async listChats(t){return e.send({op:"ListChats",method:"GET",path:"/ai/chats",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createChat(t){return e.send({op:"CreateChat",method:"POST",path:"/ai/chats",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getChat(t){return e.send({op:"GetChat",method:"GET",path:"/ai/chats/"+c("GetChat","chat_id",t.path.chat_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deleteChat(t){return e.send({op:"DeleteChat",method:"DELETE",path:"/ai/chats/"+c("DeleteChat","chat_id",t.path.chat_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async decideChatApproval(t){return e.send({op:"DecideChatApproval",method:"POST",path:"/ai/chats/"+c("DecideChatApproval","chat_id",t.path.chat_id)+"/approvals/"+c("DecideChatApproval","approval_id",t.path.approval_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async forkChat(t){return e.send({op:"ForkChat",method:"POST",path:"/ai/chats/"+c("ForkChat","chat_id",t.path.chat_id)+"/fork",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getChatGoal(t){return e.send({op:"GetChatGoal",method:"GET",path:"/ai/chats/"+c("GetChatGoal","chat_id",t.path.chat_id)+"/goal",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async setChatGoal(t){return e.send({op:"SetChatGoal",method:"PUT",path:"/ai/chats/"+c("SetChatGoal","chat_id",t.path.chat_id)+"/goal",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async clearChatGoal(t){return e.send({op:"ClearChatGoal",method:"DELETE",path:"/ai/chats/"+c("ClearChatGoal","chat_id",t.path.chat_id)+"/goal",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},query:t.query,signal:t.signal})},async updateChatGoal(t){return e.send({op:"UpdateChatGoal",method:"PATCH",path:"/ai/chats/"+c("UpdateChatGoal","chat_id",t.path.chat_id)+"/goal",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async putChatMember(t){return e.send({op:"PutChatMember",method:"PUT",path:"/ai/chats/"+c("PutChatMember","chat_id",t.path.chat_id)+"/members/"+c("PutChatMember","user_id",t.path.user_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteChatMember(t){return e.send({op:"DeleteChatMember",method:"DELETE",path:"/ai/chats/"+c("DeleteChatMember","chat_id",t.path.chat_id)+"/members/"+c("DeleteChatMember","user_id",t.path.user_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listChatMessages(t){return e.send({op:"ListChatMessages",method:"GET",path:"/ai/chats/"+c("ListChatMessages","chat_id",t.path.chat_id)+"/messages",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async sendChatMessage(t){return e.send({op:"SendChatMessage",method:"POST",path:"/ai/chats/"+c("SendChatMessage","chat_id",t.path.chat_id)+"/messages",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json",202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getChatMessageAttachment(t){return e.send({op:"GetChatMessageAttachment",method:"GET",path:"/ai/chats/"+c("GetChatMessageAttachment","chat_id",t.path.chat_id)+"/messages/"+c("GetChatMessageAttachment","message_id",t.path.message_id)+"/attachments/"+c("GetChatMessageAttachment","position",t.path.position),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"raw"},signal:t.signal})},async listChatParts(t){return e.send({op:"ListChatParts",method:"GET",path:"/ai/chats/"+c("ListChatParts","chat_id",t.path.chat_id)+"/parts",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async putChatPipe(t){return e.send({op:"PutChatPipe",method:"PUT",path:"/ai/chats/"+c("PutChatPipe","chat_id",t.path.chat_id)+"/pipe",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteChatPipe(t){return e.send({op:"DeleteChatPipe",method:"DELETE",path:"/ai/chats/"+c("DeleteChatPipe","chat_id",t.path.chat_id)+"/pipe",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async sendSubagentMessage(t){return e.send({op:"SendSubagentMessage",method:"POST",path:"/ai/chats/"+c("SendSubagentMessage","chat_id",t.path.chat_id)+"/runs/"+c("SendSubagentMessage","run_id",t.path.run_id)+"/messages",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async stopSubagent(t){return e.send({op:"StopSubagent",method:"POST",path:"/ai/chats/"+c("StopSubagent","chat_id",t.path.chat_id)+"/runs/"+c("StopSubagent","run_id",t.path.run_id)+"/stop",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async stopChat(t){return e.send({op:"StopChat",method:"POST",path:"/ai/chats/"+c("StopChat","chat_id",t.path.chat_id)+"/stop",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listTurnToolCalls(t){return e.send({op:"ListTurnToolCalls",method:"GET",path:"/ai/chats/"+c("ListTurnToolCalls","chat_id",t.path.chat_id)+"/tool-calls",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getChatToolCall(t){return e.send({op:"GetChatToolCall",method:"GET",path:"/ai/chats/"+c("GetChatToolCall","chat_id",t.path.chat_id)+"/tool-calls/"+c("GetChatToolCall","call_id",t.path.call_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async answerChatToolCall(t){return e.send({op:"AnswerChatToolCall",method:"POST",path:"/ai/chats/"+c("AnswerChatToolCall","chat_id",t.path.chat_id)+"/tool-outputs/"+c("AnswerChatToolCall","call_id",t.path.call_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listChatTurnArtifacts(t){return e.send({op:"ListChatTurnArtifacts",method:"GET",path:"/ai/chats/"+c("ListChatTurnArtifacts","chat_id",t.path.chat_id)+"/turns/"+c("ListChatTurnArtifacts","response_id",t.path.response_id)+"/artifacts",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getChatTurnArtifact(t){return e.send({op:"GetChatTurnArtifact",method:"GET",path:"/ai/chats/"+c("GetChatTurnArtifact","chat_id",t.path.chat_id)+"/turns/"+c("GetChatTurnArtifact","response_id",t.path.response_id)+"/artifacts/"+c("GetChatTurnArtifact","artifact_id",t.path.artifact_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"raw"},signal:t.signal})},async getChatTurnCost(t){return e.send({op:"GetChatTurnCost",method:"GET",path:"/ai/chats/"+c("GetChatTurnCost","chat_id",t.path.chat_id)+"/turns/"+c("GetChatTurnCost","response_id",t.path.response_id)+"/cost",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async startChatVoice(t){return e.send({op:"StartChatVoice",method:"POST",path:"/ai/chats/"+c("StartChatVoice","chat_id",t.path.chat_id)+"/voice",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getChatVoice(t){return e.send({op:"GetChatVoice",method:"GET",path:"/ai/chats/"+c("GetChatVoice","chat_id",t.path.chat_id)+"/voice/"+c("GetChatVoice","voice_id",t.path.voice_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async closeChatVoice(t){return e.send({op:"CloseChatVoice",method:"DELETE",path:"/ai/chats/"+c("CloseChatVoice","chat_id",t.path.chat_id)+"/voice/"+c("CloseChatVoice","voice_id",t.path.voice_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async commandChatVoice(t){return e.send({op:"CommandChatVoice",method:"POST",path:"/ai/chats/"+c("CommandChatVoice","chat_id",t.path.chat_id)+"/voice/"+c("CommandChatVoice","voice_id",t.path.voice_id)+"/commands",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getChatWorkspaceFile(t){return e.send({op:"GetChatWorkspaceFile",method:"GET",path:"/ai/chats/"+c("GetChatWorkspaceFile","chat_id",t.path.chat_id)+"/workspace/files",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"raw"},query:t.query,signal:t.signal})},async addChatWorkspaceRepo(t){return e.send({op:"AddChatWorkspaceRepo",method:"POST",path:"/ai/chats/"+c("AddChatWorkspaceRepo","chat_id",t.path.chat_id)+"/workspace/repos",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createEmbeddings(t){return e.send({op:"CreateEmbeddings",method:"POST",path:"/ai/embeddings",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listEndpoints(t){return e.send({op:"ListEndpoints",method:"GET",path:"/ai/endpoints",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putEndpoint(t){return e.send({op:"PutEndpoint",method:"PUT",path:"/ai/endpoints/"+c("PutEndpoint","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteEndpoint(t){return e.send({op:"DeleteEndpoint",method:"DELETE",path:"/ai/endpoints/"+c("DeleteEndpoint","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async createImage(t){return e.send({op:"CreateImage",method:"POST",path:"/ai/images",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getImage(t){return e.send({op:"GetImage",method:"GET",path:"/ai/images/"+c("GetImage","image_id",t.path.image_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getImageFile(t){return e.send({op:"GetImageFile",method:"GET",path:"/ai/images/"+c("GetImageFile","image_id",t.path.image_id)+"/files/"+c("GetImageFile","position",t.path.position),auth:[["SecretKeyAuth"]],answers:{200:"raw"},signal:t.signal})},async listModels(t){return e.send({op:"ListModels",method:"GET",path:"/ai/models",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listProviders(t){return e.send({op:"ListProviders",method:"GET",path:"/ai/providers",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async connectProvider(t){return e.send({op:"ConnectProvider",method:"PUT",path:"/ai/providers/"+c("ConnectProvider","provider",t.path.provider),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async disconnectProvider(t){return e.send({op:"DisconnectProvider",method:"DELETE",path:"/ai/providers/"+c("DisconnectProvider","provider",t.path.provider),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listRepos(t){return e.send({op:"ListRepos",method:"GET",path:"/ai/repos",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async putRepo(t){return e.send({op:"PutRepo",method:"PUT",path:"/ai/repos/"+c("PutRepo","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteRepo(t){return e.send({op:"DeleteRepo",method:"DELETE",path:"/ai/repos/"+c("DeleteRepo","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async createResponse(t){return e.send({op:"CreateResponse",method:"POST",path:"/ai/responses",auth:[["SecretKeyAuth"]],answers:{200:"raw",202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getResponse(t){return e.send({op:"GetResponse",method:"GET",path:"/ai/responses/"+c("GetResponse","response_id",t.path.response_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async cancelResponse(t){return e.send({op:"CancelResponse",method:"POST",path:"/ai/responses/"+c("CancelResponse","response_id",t.path.response_id)+"/cancel",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async followResponse(t){return e.send({op:"FollowResponse",method:"GET",path:"/ai/responses/"+c("FollowResponse","response_id",t.path.response_id)+"/live",auth:[["SecretKeyAuth"]],answers:{200:"raw"},query:t.query,signal:t.signal})},async getSettings(t){return e.send({op:"GetSettings",method:"GET",path:"/ai/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putSettings(t){return e.send({op:"PutSettings",method:"PUT",path:"/ai/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSpend(t){return e.send({op:"GetSpend",method:"GET",path:"/ai/spend",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async askSupport(t){return e.send({op:"AskSupport",method:"POST",path:"/ai/support-questions",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listTools(t){return e.send({op:"ListTools",method:"GET",path:"/ai/tools",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listUsage(t){return e.send({op:"ListUsage",method:"GET",path:"/ai/usage",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})}}}var Os={};We(Os,{client:()=>xw});function xw(e){return{async listAudiences(t){return e.send({op:"ListAudiences",method:"GET",path:"/analytics/audiences",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async createAudience(t){return e.send({op:"CreateAudience",method:"POST",path:"/analytics/audiences",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async previewAudience(t){return e.send({op:"PreviewAudience",method:"POST",path:"/analytics/audiences/preview",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getAudience(t){return e.send({op:"GetAudience",method:"GET",path:"/analytics/audiences/"+c("GetAudience","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deleteAudience(t){return e.send({op:"DeleteAudience",method:"DELETE",path:"/analytics/audiences/"+c("DeleteAudience","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async updateAudience(t){return e.send({op:"UpdateAudience",method:"PATCH",path:"/analytics/audiences/"+c("UpdateAudience","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listAudienceMembers(t){return e.send({op:"ListAudienceMembers",method:"GET",path:"/analytics/audiences/"+c("ListAudienceMembers","id",t.path.id)+"/members",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async alias(t){return e.send({op:"Alias",method:"POST",path:"/analytics/alias",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async batch(t){return e.send({op:"Batch",method:"POST",path:"/analytics/batch",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"json",207:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getEventBreakdown(t){return e.send({op:"GetEventBreakdown",method:"GET",path:"/analytics/breakdown",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async capture(t){return e.send({op:"Capture",method:"POST",path:"/analytics/capture",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async sendConsoleHistory(t){return e.send({op:"SendConsoleHistory",method:"POST",path:"/analytics/console-breadcrumbs",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getConsoleConfig(t){return e.send({op:"GetConsoleConfig",method:"GET",path:"/analytics/console-breadcrumbs/config",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listConsoleRecords(t){return e.send({op:"ListConsoleRecords",method:"GET",path:"/analytics/console-records",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listEventNames(t){return e.send({op:"ListEventNames",method:"GET",path:"/analytics/event-names",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listEvents(t){return e.send({op:"ListEvents",method:"GET",path:"/analytics/events",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getEventTimeline(t){return e.send({op:"GetEventTimeline",method:"GET",path:"/analytics/events/timeline",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async runFunnel(t){return e.send({op:"RunFunnel",method:"POST",path:"/analytics/funnel",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async identify(t){return e.send({op:"Identify",method:"POST",path:"/analytics/identify",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async page(t){return e.send({op:"Page",method:"POST",path:"/analytics/page",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async sendPerf(t){return e.send({op:"SendPerf",method:"POST",path:"/analytics/perf",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listPerfGroups(t){return e.send({op:"ListPerfGroups",method:"GET",path:"/analytics/perf/client",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getPerfConfig(t){return e.send({op:"GetPerfConfig",method:"GET",path:"/analytics/perf/config",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json",304:"empty"},headers:t?.headers,signal:t?.signal})},async getPerfTimeline(t){return e.send({op:"GetPerfTimeline",method:"GET",path:"/analytics/perf/timeline",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async listRequestLines(t){return e.send({op:"ListRequestLines",method:"GET",path:"/analytics/requests",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getMachineTraffic(t){return e.send({op:"GetMachineTraffic",method:"GET",path:"/analytics/machines/"+c("GetMachineTraffic","name",t.path.name)+"/traffic",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async runRetention(t){return e.send({op:"RunRetention",method:"POST",path:"/analytics/retention",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async screen(t){return e.send({op:"Screen",method:"POST",path:"/analytics/screen",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSettings(t){return e.send({op:"GetSettings",method:"GET",path:"/analytics/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putSettings(t){return e.send({op:"PutSettings",method:"PUT",path:"/analytics/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSummary(t){return e.send({op:"GetSummary",method:"GET",path:"/analytics/summary",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listTraces(t){return e.send({op:"ListTraces",method:"GET",path:"/analytics/traces",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async sendTrace(t){return e.send({op:"SendTrace",method:"POST",path:"/analytics/traces",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async sendTraceBatch(t){return e.send({op:"SendTraceBatch",method:"POST",path:"/analytics/traces/batch",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"json",207:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getTraceHops(t){return e.send({op:"GetTraceHops",method:"GET",path:"/analytics/traces/by-trace",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async listSessionTraces(t){return e.send({op:"ListSessionTraces",method:"GET",path:"/analytics/traces/session",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getTraceSummary(t){return e.send({op:"GetTraceSummary",method:"GET",path:"/analytics/traces/summary",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getTraceTimeline(t){return e.send({op:"GetTraceTimeline",method:"GET",path:"/analytics/traces/timeline",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async searchPeople(t){return e.send({op:"SearchPeople",method:"GET",path:"/analytics/people",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async setPersonProperties(t){return e.send({op:"SetPersonProperties",method:"POST",path:"/analytics/people",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{202:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPerson(t){return e.send({op:"GetPerson",method:"GET",path:"/analytics/people/"+c("GetPerson","person_id",t.path.person_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listPersonEvents(t){return e.send({op:"ListPersonEvents",method:"GET",path:"/analytics/people/"+c("ListPersonEvents","person_id",t.path.person_id)+"/events",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getEventCatalog(t){return e.send({op:"GetEventCatalog",method:"GET",path:"/analytics/catalog",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async defineEvent(t){return e.send({op:"DefineEvent",method:"PUT",path:"/analytics/catalog/"+c("DefineEvent","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})}}}var Ms={};We(Ms,{client:()=>Iw});function Iw(e){return{async getAppleAppSiteAssociation(t){return e.send({op:"GetAppleAppSiteAssociation",method:"GET",path:"/.well-known/apple-app-site-association",auth:[],answers:{200:"json"},signal:t?.signal})},async getAssetLinks(t){return e.send({op:"GetAssetLinks",method:"GET",path:"/.well-known/assetlinks.json",auth:[],answers:{200:"json"},signal:t?.signal})},async getJwks(t){return e.send({op:"GetJWKS",method:"GET",path:"/.well-known/jwks.json",auth:[],answers:{200:"json"},signal:t?.signal})},async getOidcDiscovery(t){return e.send({op:"GetOIDCDiscovery",method:"GET",path:"/.well-known/openid-configuration",auth:[],answers:{200:"json"},signal:t?.signal})},async getWebAuthnRelatedOrigins(t){return e.send({op:"GetWebAuthnRelatedOrigins",method:"GET",path:"/.well-known/webauthn",auth:[],answers:{200:"json"},signal:t?.signal})},async adminVerifyDeviceAssertion(t){return e.send({op:"AdminVerifyDeviceAssertion",method:"POST",path:"/admin/attest/devices/assert",auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetAttestPolicy(t){return e.send({op:"AdminGetAttestPolicy",method:"GET",path:"/admin/attest/devices/attest-policy",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminGetAttestObservations(t){return e.send({op:"AdminGetAttestObservations",method:"GET",path:"/admin/attest/devices/observations",auth:[["AdminAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminRecordAttestObservations(t){return e.send({op:"AdminRecordAttestObservations",method:"POST",path:"/admin/attest/devices/observations",auth:[["AdminAuth"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListAuditEvents(t){return e.send({op:"AdminListAuditEvents",method:"GET",path:"/admin/audit",auth:[["AdminAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminExportAuditEvents(t){return e.send({op:"AdminExportAuditEvents",method:"GET",path:"/admin/audit/export",auth:[["AdminAuth"]],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async adminVerifyAuditTrail(t){return e.send({op:"AdminVerifyAuditTrail",method:"GET",path:"/admin/audit/verify",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminGetAuthSettings(t){return e.send({op:"AdminGetAuthSettings",method:"GET",path:"/admin/auth-settings",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminUpdateAuthSettings(t){return e.send({op:"AdminUpdateAuthSettings",method:"PUT",path:"/admin/auth-settings",auth:[["AdminAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetBreachWatch(t){return e.send({op:"AdminGetBreachWatch",method:"GET",path:"/admin/breach-watch",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminListHooks(t){return e.send({op:"AdminListHooks",method:"GET",path:"/admin/hooks",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminCreateHook(t){return e.send({op:"AdminCreateHook",method:"POST",path:"/admin/hooks",auth:[["AdminAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminUpdateHook(t){return e.send({op:"AdminUpdateHook",method:"PUT",path:"/admin/hooks/"+c("AdminUpdateHook","id",t.path.id),auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminDeleteHook(t){return e.send({op:"AdminDeleteHook",method:"DELETE",path:"/admin/hooks/"+c("AdminDeleteHook","id",t.path.id),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminListHookExecutions(t){return e.send({op:"AdminListHookExecutions",method:"GET",path:"/admin/hooks/"+c("AdminListHookExecutions","id",t.path.id)+"/executions",auth:[["AdminAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async adminListIntegrations(t){return e.send({op:"AdminListIntegrations",method:"GET",path:"/admin/integrations",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminPutIntegration(t){return e.send({op:"AdminPutIntegration",method:"PUT",path:"/admin/integrations/"+c("AdminPutIntegration","name",t.path.name),auth:[["AdminAuth"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminDeleteIntegration(t){return e.send({op:"AdminDeleteIntegration",method:"DELETE",path:"/admin/integrations/"+c("AdminDeleteIntegration","name",t.path.name),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminListOAuthClients(t){return e.send({op:"AdminListOAuthClients",method:"GET",path:"/admin/oauth-clients",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminCreateOAuthClient(t){return e.send({op:"AdminCreateOAuthClient",method:"POST",path:"/admin/oauth-clients",auth:[["AdminAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetOAuthClient(t){return e.send({op:"AdminGetOAuthClient",method:"GET",path:"/admin/oauth-clients/"+c("AdminGetOAuthClient","id",t.path.id),auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminDeleteOAuthClient(t){return e.send({op:"AdminDeleteOAuthClient",method:"DELETE",path:"/admin/oauth-clients/"+c("AdminDeleteOAuthClient","id",t.path.id),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminUpdateOAuthClient(t){return e.send({op:"AdminUpdateOAuthClient",method:"PATCH",path:"/admin/oauth-clients/"+c("AdminUpdateOAuthClient","id",t.path.id),auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListProviders(t){return e.send({op:"AdminListProviders",method:"GET",path:"/admin/providers",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminGetPhoneSettings(t){return e.send({op:"AdminGetPhoneSettings",method:"GET",path:"/admin/providers/phone/settings",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminUpdatePhoneSettings(t){return e.send({op:"AdminUpdatePhoneSettings",method:"PUT",path:"/admin/providers/phone/settings",auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminToggleProvider(t){return e.send({op:"AdminToggleProvider",method:"POST",path:"/admin/providers/"+c("AdminToggleProvider","name",t.path.name),auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListRoles(t){return e.send({op:"AdminListRoles",method:"GET",path:"/admin/roles",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminUpsertRole(t){return e.send({op:"AdminUpsertRole",method:"PUT",path:"/admin/roles/"+c("AdminUpsertRole","name",t.path.name),auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminDeleteRole(t){return e.send({op:"AdminDeleteRole",method:"DELETE",path:"/admin/roles/"+c("AdminDeleteRole","name",t.path.name),auth:[["AdminAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async adminListServiceAccounts(t){return e.send({op:"AdminListServiceAccounts",method:"GET",path:"/admin/service-accounts",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminCreateServiceAccount(t){return e.send({op:"AdminCreateServiceAccount",method:"POST",path:"/admin/service-accounts",auth:[["AdminAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetServiceAccount(t){return e.send({op:"AdminGetServiceAccount",method:"GET",path:"/admin/service-accounts/"+c("AdminGetServiceAccount","id",t.path.id),auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminRevokeServiceAccount(t){return e.send({op:"AdminRevokeServiceAccount",method:"DELETE",path:"/admin/service-accounts/"+c("AdminRevokeServiceAccount","id",t.path.id),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminRotateServiceAccount(t){return e.send({op:"AdminRotateServiceAccount",method:"POST",path:"/admin/service-accounts/"+c("AdminRotateServiceAccount","id",t.path.id)+"/rotate",auth:[["AdminAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async adminListSessions(t){return e.send({op:"AdminListSessions",method:"GET",path:"/admin/sessions",auth:[["AdminAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminRevokeSession(t){return e.send({op:"AdminRevokeSession",method:"DELETE",path:"/admin/sessions/"+c("AdminRevokeSession","id",t.path.id),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminListSigningKeys(t){return e.send({op:"AdminListSigningKeys",method:"GET",path:"/admin/signing-keys",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminRotateSigningKey(t){return e.send({op:"AdminRotateSigningKey",method:"POST",path:"/admin/signing-keys/rotate",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async socialAdminConfig(t){return e.send({op:"SocialAdminConfig",method:"GET",path:"/admin/social-auth",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async socialCredentialPut(t){return e.send({op:"SocialCredentialPut",method:"PUT",path:"/admin/social-auth/credentials/"+c("SocialCredentialPut","key",t.path.key),auth:[["AdminAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async socialCredentialDelete(t){return e.send({op:"SocialCredentialDelete",method:"DELETE",path:"/admin/social-auth/credentials/"+c("SocialCredentialDelete","key",t.path.key),auth:[["AdminAuth"]],answers:{204:"empty"},headers:t.headers,signal:t.signal})},async socialProviderPatch(t){return e.send({op:"SocialProviderPatch",method:"PATCH",path:"/admin/social-auth/providers/"+c("SocialProviderPatch","provider",t.path.provider),auth:[["AdminAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetStats(t){return e.send({op:"AdminGetStats",method:"GET",path:"/admin/stats",auth:[["AdminAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminSendTestTemplate(t){return e.send({op:"AdminSendTestTemplate",method:"POST",path:"/admin/templates/"+c("AdminSendTestTemplate","key",t.path.key)+"/send-test",auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListTestUsers(t){return e.send({op:"AdminListTestUsers",method:"GET",path:"/admin/test-users",auth:[["AdminAuth"]],answers:{200:"json"},signal:t?.signal})},async adminCreateTestUsers(t){return e.send({op:"AdminCreateTestUsers",method:"POST",path:"/admin/test-users",auth:[["AdminAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminSetTestUserPhone(t){return e.send({op:"AdminSetTestUserPhone",method:"PUT",path:"/admin/test-users/phone",auth:[["AdminAuth"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminCreateTestSignupAddress(t){return e.send({op:"AdminCreateTestSignupAddress",method:"POST",path:"/admin/test-users/addresses",auth:[["AdminAuth"]],answers:{201:"json"},signal:t?.signal})},async adminDeleteTestUser(t){return e.send({op:"AdminDeleteTestUser",method:"DELETE",path:"/admin/test-users/"+c("AdminDeleteTestUser","uid",t.path.uid),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminCreateCustomToken(t){return e.send({op:"AdminCreateCustomToken",method:"POST",path:"/admin/token/custom",auth:[["AdminAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListUsers(t){return e.send({op:"AdminListUsers",method:"GET",path:"/admin/users",auth:[["AdminAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminCreateUser(t){return e.send({op:"AdminCreateUser",method:"POST",path:"/admin/users",auth:[["AdminAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminImportUsers(t){return e.send({op:"AdminImportUsers",method:"POST",path:"/admin/users/import",auth:[["AdminAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetUser(t){return e.send({op:"AdminGetUser",method:"GET",path:"/admin/users/"+c("AdminGetUser","uid",t.path.uid),auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminDeleteUser(t){return e.send({op:"AdminDeleteUser",method:"DELETE",path:"/admin/users/"+c("AdminDeleteUser","uid",t.path.uid),auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminUpdateUser(t){return e.send({op:"AdminUpdateUser",method:"PATCH",path:"/admin/users/"+c("AdminUpdateUser","uid",t.path.uid),auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminBanUser(t){return e.send({op:"AdminBanUser",method:"POST",path:"/admin/users/"+c("AdminBanUser","uid",t.path.uid)+"/ban",auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetUserConsents(t){return e.send({op:"AdminGetUserConsents",method:"GET",path:"/admin/users/"+c("AdminGetUserConsents","uid",t.path.uid)+"/consents",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminRevokeUserCredentials(t){return e.send({op:"AdminRevokeUserCredentials",method:"POST",path:"/admin/users/"+c("AdminRevokeUserCredentials","uid",t.path.uid)+"/credentials/revoke-all",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminExportUser(t){return e.send({op:"AdminExportUser",method:"GET",path:"/admin/users/"+c("AdminExportUser","uid",t.path.uid)+"/export",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminListUserMfaFactors(t){return e.send({op:"AdminListUserMFAFactors",method:"GET",path:"/admin/users/"+c("AdminListUserMFAFactors","uid",t.path.uid)+"/mfa",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminResetUserMfa(t){return e.send({op:"AdminResetUserMFA",method:"DELETE",path:"/admin/users/"+c("AdminResetUserMFA","uid",t.path.uid)+"/mfa",auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminResetUserPassword(t){return e.send({op:"AdminResetUserPassword",method:"POST",path:"/admin/users/"+c("AdminResetUserPassword","uid",t.path.uid)+"/reset-password",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminListUserRoles(t){return e.send({op:"AdminListUserRoles",method:"GET",path:"/admin/users/"+c("AdminListUserRoles","uid",t.path.uid)+"/roles",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminAssignUserRole(t){return e.send({op:"AdminAssignUserRole",method:"PUT",path:"/admin/users/"+c("AdminAssignUserRole","uid",t.path.uid)+"/roles/"+c("AdminAssignUserRole","role",t.path.role),auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminRevokeUserRole(t){return e.send({op:"AdminRevokeUserRole",method:"DELETE",path:"/admin/users/"+c("AdminRevokeUserRole","uid",t.path.uid)+"/roles/"+c("AdminRevokeUserRole","role",t.path.role),auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminRevokeUserSessions(t){return e.send({op:"AdminRevokeUserSessions",method:"POST",path:"/admin/users/"+c("AdminRevokeUserSessions","uid",t.path.uid)+"/sessions/revoke-all",auth:[["AdminAuth"]],answers:{204:"empty"},signal:t.signal})},async adminUnbanUser(t){return e.send({op:"AdminUnbanUser",method:"POST",path:"/admin/users/"+c("AdminUnbanUser","uid",t.path.uid)+"/unban",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async signInAnonymously(t){return e.send({op:"SignInAnonymously",method:"POST",path:"/auth/anonymous",auth:[["ApiKeyAuth"]],answers:{201:"json"},headers:t?.headers,body:{kind:"json",contentType:"application/json",value:t?.body},signal:t?.signal})},async convertAnonymousUser(t){return e.send({op:"ConvertAnonymousUser",method:"POST",path:"/auth/anonymous/convert",auth:[["ApiKeyAuth","userJWT"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async verifyAnonymousConversion(t){return e.send({op:"VerifyAnonymousConversion",method:"POST",path:"/auth/anonymous/convert/verify",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async devicePendingRequest(t){return e.send({op:"DevicePendingRequest",method:"GET",path:"/auth/device/requests/"+c("DevicePendingRequest","user_code",t.path.user_code),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async deviceVerifyPage(t){return e.send({op:"DeviceVerifyPage",method:"GET",path:"/auth/device/verify",auth:[["ApiKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async deviceVerifySubmit(t){return e.send({op:"DeviceVerifySubmit",method:"POST",path:"/auth/device/verify",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async listDevices(t){return e.send({op:"ListDevices",method:"GET",path:"/auth/devices",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async attestAndroidDevice(t){return e.send({op:"AttestAndroidDevice",method:"POST",path:"/auth/devices/attest/android",auth:[["ApiKeyAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async attestIosDevice(t){return e.send({op:"AttestIOSDevice",method:"POST",path:"/auth/devices/attest/ios",auth:[["ApiKeyAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async bindDeviceKey(t){return e.send({op:"BindDeviceKey",method:"POST",path:"/auth/devices/bind",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createDeviceChallenge(t){return e.send({op:"CreateDeviceChallenge",method:"POST",path:"/auth/devices/challenge",auth:[["ApiKeyAuth"]],answers:{200:"json"},headers:t?.headers,signal:t?.signal})},async verifyAndroidIntegrity(t){return e.send({op:"VerifyAndroidIntegrity",method:"POST",path:"/auth/devices/verify/android",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteDevice(t){return e.send({op:"DeleteDevice",method:"DELETE",path:"/auth/devices/"+c("DeleteDevice","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async verifyDeviceSignature(t){return e.send({op:"VerifyDeviceSignature",method:"POST",path:"/auth/devices/"+c("VerifyDeviceSignature","id",t.path.id)+"/verify",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listIdentities(t){return e.send({op:"ListIdentities",method:"GET",path:"/auth/identities",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async unlinkIdentity(t){return e.send({op:"UnlinkIdentity",method:"DELETE",path:"/auth/identities/"+c("UnlinkIdentity","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async createInstallation(t){return e.send({op:"CreateInstallation",method:"POST",path:"/auth/installations",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async bindInstallation(t){return e.send({op:"BindInstallation",method:"POST",path:"/auth/installations/"+c("BindInstallation","id",t.path.id)+"/bind",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async refreshInstallation(t){return e.send({op:"RefreshInstallation",method:"POST",path:"/auth/installations/"+c("RefreshInstallation","id",t.path.id)+"/refresh",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async revokeInstallation(t){return e.send({op:"RevokeInstallation",method:"POST",path:"/auth/installations/"+c("RevokeInstallation","id",t.path.id)+"/revoke",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async unbindInstallation(t){return e.send({op:"UnbindInstallation",method:"POST",path:"/auth/installations/"+c("UnbindInstallation","id",t.path.id)+"/unbind",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async login(t){return e.send({op:"Login",method:"POST",path:"/auth/login",auth:[["ApiKeyAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async logout(t){return e.send({op:"Logout",method:"POST",path:"/auth/logout",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async magicLinkRequest(t){return e.send({op:"MagicLinkRequest",method:"POST",path:"/auth/magic-link",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async magicLinkVerify(t){return e.send({op:"MagicLinkVerify",method:"POST",path:"/auth/magic-link/verify",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getMe(t){return e.send({op:"GetMe",method:"GET",path:"/auth/me",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async updateMe(t){return e.send({op:"UpdateMe",method:"PATCH",path:"/auth/me",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaChallenge(t){return e.send({op:"MfaChallenge",method:"POST",path:"/auth/mfa/challenge",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaEmailChallenge(t){return e.send({op:"MfaEmailChallenge",method:"POST",path:"/auth/mfa/email/challenge",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaEmailEnroll(t){return e.send({op:"MfaEmailEnroll",method:"POST",path:"/auth/mfa/email/enroll",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async mfaEmailVerify(t){return e.send({op:"MfaEmailVerify",method:"POST",path:"/auth/mfa/email/verify",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaEnroll(t){return e.send({op:"MfaEnroll",method:"POST",path:"/auth/mfa/enroll",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaListFactors(t){return e.send({op:"MfaListFactors",method:"GET",path:"/auth/mfa/factors",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async mfaRemoveFactor(t){return e.send({op:"MfaRemoveFactor",method:"DELETE",path:"/auth/mfa/factors/"+c("MfaRemoveFactor","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaRecovery(t){return e.send({op:"MfaRecovery",method:"POST",path:"/auth/mfa/recovery",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaRegenerateRecoveryCodes(t){return e.send({op:"MfaRegenerateRecoveryCodes",method:"POST",path:"/auth/mfa/recovery-codes/regenerate",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async mfaSmsChallenge(t){return e.send({op:"MfaSMSChallenge",method:"POST",path:"/auth/mfa/sms/challenge",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaSmsEnroll(t){return e.send({op:"MfaSMSEnroll",method:"POST",path:"/auth/mfa/sms/enroll",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaSmsVerifyEnrollment(t){return e.send({op:"MfaSMSVerifyEnrollment",method:"POST",path:"/auth/mfa/sms/verify",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async mfaVerifyEnrollment(t){return e.send({op:"MfaVerifyEnrollment",method:"POST",path:"/auth/mfa/verify",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async socialCallbackApple(t){return e.send({op:"SocialCallbackApple",method:"GET",path:"/auth/oauth/callback/apple",auth:[],answers:{},signal:t?.signal})},async socialCallbackApplePost(t){return e.send({op:"SocialCallbackApplePost",method:"POST",path:"/auth/oauth/callback/apple",auth:[],answers:{303:"redirect"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async socialCallbackGitHub(t){return e.send({op:"SocialCallbackGitHub",method:"GET",path:"/auth/oauth/callback/github",auth:[],answers:{303:"redirect"},query:t.query,signal:t.signal})},async socialCallbackGitHubPost(t){return e.send({op:"SocialCallbackGitHubPost",method:"POST",path:"/auth/oauth/callback/github",auth:[],answers:{},signal:t?.signal})},async socialCallbackGoogle(t){return e.send({op:"SocialCallbackGoogle",method:"GET",path:"/auth/oauth/callback/google",auth:[],answers:{303:"redirect"},query:t.query,signal:t.signal})},async socialCallbackGooglePost(t){return e.send({op:"SocialCallbackGooglePost",method:"POST",path:"/auth/oauth/callback/google",auth:[],answers:{},signal:t?.signal})},async socialCallbackMicrosoft(t){return e.send({op:"SocialCallbackMicrosoft",method:"GET",path:"/auth/oauth/callback/microsoft",auth:[],answers:{303:"redirect"},query:t.query,signal:t.signal})},async socialCallbackMicrosoftPost(t){return e.send({op:"SocialCallbackMicrosoftPost",method:"POST",path:"/auth/oauth/callback/microsoft",auth:[],answers:{},signal:t?.signal})},async socialConfig(t){return e.send({op:"SocialConfig",method:"GET",path:"/auth/oauth/config",auth:[["ApiKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async socialBegin(t){return e.send({op:"SocialBegin",method:"POST",path:"/auth/oauth/transactions",auth:[["ApiKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async socialCancel(t){return e.send({op:"SocialCancel",method:"POST",path:"/auth/oauth/transactions/"+c("SocialCancel","id",t.path.id)+"/cancel",auth:[["ApiKeyAuth"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async socialComplete(t){return e.send({op:"SocialComplete",method:"POST",path:"/auth/oauth/transactions/"+c("SocialComplete","id",t.path.id)+"/complete",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async requestPhoneOtp(t){return e.send({op:"RequestPhoneOTP",method:"POST",path:"/auth/otp",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async verifyPhoneOtp(t){return e.send({op:"VerifyPhoneOTP",method:"POST",path:"/auth/otp/verify",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async hostedRecoveryApprovalPage(t){return e.send({op:"HostedRecoveryApprovalPage",method:"GET",path:"/auth/pages/recovery-approval",auth:[],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async hostedRecoveryApprovalSubmit(t){return e.send({op:"HostedRecoveryApprovalSubmit",method:"POST",path:"/auth/pages/recovery-approval",auth:[],answers:{200:"raw"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async hostedRecoveryContactPage(t){return e.send({op:"HostedRecoveryContactPage",method:"GET",path:"/auth/pages/recovery-contact",auth:[],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async hostedRecoveryContactSubmit(t){return e.send({op:"HostedRecoveryContactSubmit",method:"POST",path:"/auth/pages/recovery-contact",auth:[],answers:{200:"raw"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async hostedResetPasswordPage(t){return e.send({op:"HostedResetPasswordPage",method:"GET",path:"/auth/pages/reset-password",auth:[],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async hostedResetPasswordSubmit(t){return e.send({op:"HostedResetPasswordSubmit",method:"POST",path:"/auth/pages/reset-password",auth:[],answers:{200:"raw"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async hostedVerifyEmailPage(t){return e.send({op:"HostedVerifyEmailPage",method:"GET",path:"/auth/pages/verify-email",auth:[],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async hostedVerifyEmailSubmit(t){return e.send({op:"HostedVerifyEmailSubmit",method:"POST",path:"/auth/pages/verify-email",auth:[],answers:{200:"raw"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async passwordChange(t){return e.send({op:"PasswordChange",method:"POST",path:"/auth/password/change",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async passwordResetRequest(t){return e.send({op:"PasswordResetRequest",method:"POST",path:"/auth/password/reset",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async passwordResetConfirm(t){return e.send({op:"PasswordResetConfirm",method:"POST",path:"/auth/password/reset/confirm",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async setPassword(t){return e.send({op:"SetPassword",method:"POST",path:"/auth/password/set",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async powChallenge(t){return e.send({op:"PowChallenge",method:"POST",path:"/auth/pow/challenge",auth:[["ApiKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async approveRecovery(t){return e.send({op:"ApproveRecovery",method:"POST",path:"/auth/recovery/approve",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listRecoveryContacts(t){return e.send({op:"ListRecoveryContacts",method:"GET",path:"/auth/recovery/contacts",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async addRecoveryContact(t){return e.send({op:"AddRecoveryContact",method:"POST",path:"/auth/recovery/contacts",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteRecoveryContact(t){return e.send({op:"DeleteRecoveryContact",method:"DELETE",path:"/auth/recovery/contacts/"+c("DeleteRecoveryContact","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async verifyRecoveryContact(t){return e.send({op:"VerifyRecoveryContact",method:"POST",path:"/auth/recovery/contacts/"+c("VerifyRecoveryContact","id",t.path.id)+"/verify",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async denyRecovery(t){return e.send({op:"DenyRecovery",method:"POST",path:"/auth/recovery/deny",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async initiateRecovery(t){return e.send({op:"InitiateRecovery",method:"POST",path:"/auth/recovery/initiate",auth:[["ApiKeyAuth"]],answers:{200:"json",202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getRecoveryStatus(t){return e.send({op:"GetRecoveryStatus",method:"GET",path:"/auth/recovery/status",auth:[["ApiKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async resendVerification(t){return e.send({op:"ResendVerification",method:"POST",path:"/auth/resend-verification",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listSessions(t){return e.send({op:"ListSessions",method:"GET",path:"/auth/sessions",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async revokeAllSessions(t){return e.send({op:"RevokeAllSessions",method:"DELETE",path:"/auth/sessions",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async revokeSession(t){return e.send({op:"RevokeSession",method:"DELETE",path:"/auth/sessions/"+c("RevokeSession","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async signup(t){return e.send({op:"Signup",method:"POST",path:"/auth/signup",auth:[["ApiKeyAuth"]],answers:{201:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async stepUp(t){return e.send({op:"StepUp",method:"POST",path:"/auth/step-up",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async stepUpStatus(t){return e.send({op:"StepUpStatus",method:"GET",path:"/auth/step-up/status",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async stepUpWebAuthnBegin(t){return e.send({op:"StepUpWebAuthnBegin",method:"POST",path:"/auth/step-up/webauthn/begin",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async stepUpSmsSend(t){return e.send({op:"StepUpSMSSend",method:"POST",path:"/auth/step-up/sms/send",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async exchangeCustomToken(t){return e.send({op:"ExchangeCustomToken",method:"POST",path:"/auth/token/exchange",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async refreshToken(t){return e.send({op:"RefreshToken",method:"POST",path:"/auth/token/refresh",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async revokeRefreshToken(t){return e.send({op:"RevokeRefreshToken",method:"POST",path:"/auth/token/revoke",auth:[["ApiKeyAuth"]],answers:{200:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listTransactions(t){return e.send({op:"ListTransactions",method:"GET",path:"/auth/transactions",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createTransaction(t){return e.send({op:"CreateTransaction",method:"POST",path:"/auth/transactions",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getTransaction(t){return e.send({op:"GetTransaction",method:"GET",path:"/auth/transactions/"+c("GetTransaction","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async approveTransaction(t){return e.send({op:"ApproveTransaction",method:"POST",path:"/auth/transactions/"+c("ApproveTransaction","id",t.path.id)+"/approve",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async denyTransaction(t){return e.send({op:"DenyTransaction",method:"POST",path:"/auth/transactions/"+c("DenyTransaction","id",t.path.id)+"/deny",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listTrustedDevices(t){return e.send({op:"ListTrustedDevices",method:"GET",path:"/auth/trusted-devices",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async registerTrustedDevice(t){return e.send({op:"RegisterTrustedDevice",method:"POST",path:"/auth/trusted-devices",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async revokeTrustedDevice(t){return e.send({op:"RevokeTrustedDevice",method:"DELETE",path:"/auth/trusted-devices/"+c("RevokeTrustedDevice","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async verifyTokenUser(t){return e.send({op:"VerifyTokenUser",method:"GET",path:"/auth/user",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async deleteAccount(t){return e.send({op:"DeleteAccount",method:"DELETE",path:"/auth/user",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t?.body},signal:t?.signal})},async verifyEmail(t){return e.send({op:"VerifyEmail",method:"POST",path:"/auth/verify-email",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnListCredentials(t){return e.send({op:"WebauthnListCredentials",method:"GET",path:"/auth/webauthn/credentials",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async webauthnRenameCredential(t){return e.send({op:"WebauthnRenameCredential",method:"PUT",path:"/auth/webauthn/credentials/"+c("WebauthnRenameCredential","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnDeleteCredential(t){return e.send({op:"WebauthnDeleteCredential",method:"DELETE",path:"/auth/webauthn/credentials/"+c("WebauthnDeleteCredential","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async webauthnLoginBegin(t){return e.send({op:"WebauthnLoginBegin",method:"POST",path:"/auth/webauthn/login/begin",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t?.body},signal:t?.signal})},async webauthnLoginFinish(t){return e.send({op:"WebauthnLoginFinish",method:"POST",path:"/auth/webauthn/login/finish",auth:[["ApiKeyAuth"]],answers:{200:"json"},query:t.query,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnRecoveryBegin(t){return e.send({op:"WebauthnRecoveryBegin",method:"POST",path:"/auth/webauthn/recovery/begin",auth:[["ApiKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async webauthnRecoveryFinish(t){return e.send({op:"WebauthnRecoveryFinish",method:"POST",path:"/auth/webauthn/recovery/finish",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnRecoveryRegisterBegin(t){return e.send({op:"WebauthnRecoveryRegisterBegin",method:"POST",path:"/auth/webauthn/recovery/register/begin",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t?.body},signal:t?.signal})},async webauthnRecoveryRegisterFinish(t){return e.send({op:"WebauthnRecoveryRegisterFinish",method:"POST",path:"/auth/webauthn/recovery/register/finish",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnRegisterBegin(t){return e.send({op:"WebauthnRegisterBegin",method:"POST",path:"/auth/webauthn/register/begin",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t?.body},signal:t?.signal})},async webauthnRegisterFinish(t){return e.send({op:"WebauthnRegisterFinish",method:"POST",path:"/auth/webauthn/register/finish",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnSignupBegin(t){return e.send({op:"WebauthnSignupBegin",method:"POST",path:"/auth/webauthn/signup/begin",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async webauthnSignupFinish(t){return e.send({op:"WebauthnSignupFinish",method:"POST",path:"/auth/webauthn/signup/finish",auth:[["ApiKeyAuth"]],answers:{201:"json"},query:t.query,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async oauthAuthorize(t){return e.send({op:"OauthAuthorize",method:"GET",path:"/oauth/authorize",auth:[],answers:{302:"redirect",303:"redirect"},query:t?.query,signal:t?.signal})},async oauthAuthorizePost(t){return e.send({op:"OauthAuthorizePost",method:"POST",path:"/oauth/authorize",auth:[],answers:{302:"redirect",303:"redirect"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async oauthAuthorizeCallback(t){return e.send({op:"OauthAuthorizeCallback",method:"GET",path:"/oauth/authorize/callback",auth:[],answers:{303:"redirect"},query:t.query,signal:t.signal})},async oauthDeviceAuthorize(t){return e.send({op:"OauthDeviceAuthorize",method:"POST",path:"/oauth/device",auth:[["OAuthClient"],[]],answers:{200:"json"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async oauthIntrospect(t){return e.send({op:"OauthIntrospect",method:"POST",path:"/oauth/introspect",auth:[["AdminAuth"],["OAuthClient"],[]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async oauthLogout(t){return e.send({op:"OauthLogout",method:"GET",path:"/oauth/logout",auth:[],answers:{302:"redirect"},query:t?.query,signal:t?.signal})},async oauthLogoutPost(t){return e.send({op:"OauthLogoutPost",method:"POST",path:"/oauth/logout",auth:[],answers:{302:"redirect"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t?.body},signal:t?.signal})},async oauthPar(t){return e.send({op:"OauthPAR",method:"POST",path:"/oauth/par",auth:[["OAuthClient"],[]],answers:{201:"json"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async oauthRevoke(t){return e.send({op:"OauthRevoke",method:"POST",path:"/oauth/revoke",auth:[["OAuthClient"],[]],answers:{200:"empty"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async oauthToken(t){return e.send({op:"OauthToken",method:"POST",path:"/oauth/token",auth:[["OAuthClient"],[]],answers:{200:"json"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async oauthUserinfo(t){return e.send({op:"OauthUserinfo",method:"GET",path:"/oauth/userinfo",auth:[["OAuthAccessToken"]],answers:{200:"json"},signal:t?.signal})},async oauthUserinfoPost(t){return e.send({op:"OauthUserinfoPost",method:"POST",path:"/oauth/userinfo",auth:[["OAuthAccessToken"]],answers:{200:"json"},signal:t?.signal})},async ownerCliCode(t){return e.send({op:"OwnerCLICode",method:"POST",path:"/auth/cli/owner-code",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listConsentKeys(t){return e.send({op:"ListConsentKeys",method:"GET",path:"/auth/consents/keys",auth:[["ApiKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getConsents(t){return e.send({op:"GetConsents",method:"GET",path:"/auth/consents",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,headers:t.headers,signal:t.signal})},async chooseConsents(t){return e.send({op:"ChooseConsents",method:"PUT",path:"/auth/consents",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async linkConsents(t){return e.send({op:"LinkConsents",method:"POST",path:"/auth/consents/link",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetInstallationConsents(t){return e.send({op:"AdminGetInstallationConsents",method:"GET",path:"/admin/installations/"+c("AdminGetInstallationConsents","installation_id",t.path.installation_id)+"/consents",auth:[["AdminAuth"]],answers:{200:"json"},signal:t.signal})},async adminRefuseConsents(t){return e.send({op:"AdminRefuseConsents",method:"POST",path:"/admin/consents/refuse",auth:[["AdminAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})}}}var Ua={};We(Ua,{client:()=>Lw});function Lw(e){return{async getCacheEntry(t){return e.send({op:"GetCacheEntry",method:"GET",path:"/cache/entry",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async putCacheEntry(t){return e.send({op:"PutCacheEntry",method:"PUT",path:"/cache/entry",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteCacheEntry(t){return e.send({op:"DeleteCacheEntry",method:"DELETE",path:"/cache/entry",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async incrementCacheEntry(t){return e.send({op:"IncrementCacheEntry",method:"POST",path:"/cache/entry/increment",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getCacheUsage(t){return e.send({op:"GetCacheUsage",method:"GET",path:"/cache/usage",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})}}}var za={};We(za,{client:()=>Dw});function Dw(e){return{async listCalls(t){return e.send({op:"ListCalls",method:"GET",path:"/calls",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async startCall(t){return e.send({op:"StartCall",method:"POST",path:"/calls",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json",201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListCalls(t){return e.send({op:"AdminListCalls",method:"GET",path:"/calls/admin/calls",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminGetCall(t){return e.send({op:"AdminGetCall",method:"GET",path:"/calls/admin/calls/"+c("AdminGetCall","call_id",t.path.call_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async adminEndCall(t){return e.send({op:"AdminEndCall",method:"POST",path:"/calls/admin/calls/"+c("AdminEndCall","call_id",t.path.call_id)+"/end",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async createCallTicket(t){return e.send({op:"CreateCallTicket",method:"POST",path:"/calls/admin/calls/"+c("CreateCallTicket","call_id",t.path.call_id)+"/tickets",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getCallPlace(t){return e.send({op:"GetCallPlace",method:"GET",path:"/calls/places/"+c("GetCallPlace","place",t.path.place),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async watchCallPlace(t){return e.send({op:"WatchCallPlace",method:"POST",path:"/calls/places/"+c("WatchCallPlace","place",t.path.place)+"/watch",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async unwatchCallPlace(t){return e.send({op:"UnwatchCallPlace",method:"DELETE",path:"/calls/places/"+c("UnwatchCallPlace","place",t.path.place)+"/watch",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async getCallSettings(t){return e.send({op:"GetCallSettings",method:"GET",path:"/calls/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putCallSettings(t){return e.send({op:"PutCallSettings",method:"PUT",path:"/calls/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async rotateCallHookSecret(t){return e.send({op:"RotateCallHookSecret",method:"POST",path:"/calls/settings/hook-secret",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getCall(t){return e.send({op:"GetCall",method:"GET",path:"/calls/"+c("GetCall","call_id",t.path.call_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async acceptCall(t){return e.send({op:"AcceptCall",method:"POST",path:"/calls/"+c("AcceptCall","call_id",t.path.call_id)+"/accept",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async declineCall(t){return e.send({op:"DeclineCall",method:"POST",path:"/calls/"+c("DeclineCall","call_id",t.path.call_id)+"/decline",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async callHeartbeat(t){return e.send({op:"CallHeartbeat",method:"POST",path:"/calls/"+c("CallHeartbeat","call_id",t.path.call_id)+"/heartbeat",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async joinCall(t){return e.send({op:"JoinCall",method:"POST",path:"/calls/"+c("JoinCall","call_id",t.path.call_id)+"/join",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async leaveCall(t){return e.send({op:"LeaveCall",method:"POST",path:"/calls/"+c("LeaveCall","call_id",t.path.call_id)+"/leave",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async getCallMedia(t){return e.send({op:"GetCallMedia",method:"POST",path:"/calls/"+c("GetCallMedia","call_id",t.path.call_id)+"/media",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async inviteToCall(t){return e.send({op:"InviteToCall",method:"POST",path:"/calls/"+c("InviteToCall","call_id",t.path.call_id)+"/participants",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})}}}var xs={};We(xs,{client:()=>qw});function qw(e){return{async getValues(t){return e.send({op:"GetValues",method:"GET",path:"/flags",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},headers:t?.headers,signal:t?.signal})},async batchUserValues(t){return e.send({op:"BatchUserValues",method:"POST",path:"/flags/batch",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getDelta(t){return e.send({op:"GetDelta",method:"GET",path:"/flags/delta",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json",304:"empty"},query:t?.query,headers:t?.headers,signal:t?.signal})},async getEvaluations(t){return e.send({op:"GetEvaluations",method:"GET",path:"/flags/evaluations",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listExperiments(t){return e.send({op:"ListExperiments",method:"GET",path:"/flags/experiments",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async startExperiment(t){return e.send({op:"StartExperiment",method:"POST",path:"/flags/experiments",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getExperiment(t){return e.send({op:"GetExperiment",method:"GET",path:"/flags/experiments/"+c("GetExperiment","experiment_id",t.path.experiment_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getExperimentResults(t){return e.send({op:"GetExperimentResults",method:"GET",path:"/flags/experiments/"+c("GetExperimentResults","experiment_id",t.path.experiment_id)+"/results",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async stopExperiment(t){return e.send({op:"StopExperiment",method:"POST",path:"/flags/experiments/"+c("StopExperiment","experiment_id",t.path.experiment_id)+"/stop",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async declareExperimentWinner(t){return e.send({op:"DeclareExperimentWinner",method:"POST",path:"/flags/experiments/"+c("DeclareExperimentWinner","experiment_id",t.path.experiment_id)+"/winner",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getCurrentInstallations(t){return e.send({op:"GetCurrentInstallations",method:"GET",path:"/flags/installations/current",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getInstallationsDaily(t){return e.send({op:"GetInstallationsDaily",method:"GET",path:"/flags/installations/daily",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getSnapshot(t){return e.send({op:"GetSnapshot",method:"GET",path:"/flags/snapshot",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json",304:"empty"},headers:t?.headers,signal:t?.signal})},async listDefinitions(t){return e.send({op:"ListDefinitions",method:"GET",path:"/flags/system",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getDefinition(t){return e.send({op:"GetDefinition",method:"GET",path:"/flags/system/"+c("GetDefinition","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putDefinition(t){return e.send({op:"PutDefinition",method:"PUT",path:"/flags/system/"+c("PutDefinition","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteDefinition(t){return e.send({op:"DeleteDefinition",method:"DELETE",path:"/flags/system/"+c("DeleteDefinition","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async activateTemplates(t){return e.send({op:"ActivateTemplates",method:"POST",path:"/flags/templates/activation",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getActiveTemplate(t){return e.send({op:"GetActiveTemplate",method:"GET",path:"/flags/templates/active",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getTemplateCapabilities(t){return e.send({op:"GetTemplateCapabilities",method:"GET",path:"/flags/templates/capabilities",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getTemplateDraft(t){return e.send({op:"GetTemplateDraft",method:"GET",path:"/flags/templates/draft",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async createTemplateDraft(t){return e.send({op:"CreateTemplateDraft",method:"POST",path:"/flags/templates/draft",auth:[["SecretKeyAuth"]],answers:{201:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async discardTemplateDraft(t){return e.send({op:"DiscardTemplateDraft",method:"DELETE",path:"/flags/templates/draft",auth:[["SecretKeyAuth"]],answers:{204:"empty"},headers:t.headers,signal:t.signal})},async putTemplateParameter(t){return e.send({op:"PutTemplateParameter",method:"PUT",path:"/flags/templates/draft/parameters/"+c("PutTemplateParameter","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async removeTemplateParameter(t){return e.send({op:"RemoveTemplateParameter",method:"DELETE",path:"/flags/templates/draft/parameters/"+c("RemoveTemplateParameter","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},headers:t.headers,signal:t.signal})},async reviewTemplateDraft(t){return e.send({op:"ReviewTemplateDraft",method:"GET",path:"/flags/templates/draft/review",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async publishTemplate(t){return e.send({op:"PublishTemplate",method:"POST",path:"/flags/templates/publish",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPublishReceipt(t){return e.send({op:"GetPublishReceipt",method:"POST",path:"/flags/templates/publish/receipt",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async restoreTemplateVersion(t){return e.send({op:"RestoreTemplateVersion",method:"POST",path:"/flags/templates/restore/"+c("RestoreTemplateVersion","version",t.path.version),auth:[["SecretKeyAuth"]],answers:{201:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listTemplateVersions(t){return e.send({op:"ListTemplateVersions",method:"GET",path:"/flags/templates/versions",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getTemplateVersion(t){return e.send({op:"GetTemplateVersion",method:"GET",path:"/flags/templates/versions/"+c("GetTemplateVersion","version",t.path.version),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getUserValues(t){return e.send({op:"GetUserValues",method:"GET",path:"/flags/users/"+c("GetUserValues","user_id",t.path.user_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},headers:t.headers,signal:t.signal})},async putUserValues(t){return e.send({op:"PutUserValues",method:"PUT",path:"/flags/users/"+c("PutUserValues","user_id",t.path.user_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteUserValues(t){return e.send({op:"DeleteUserValues",method:"DELETE",path:"/flags/users/"+c("DeleteUserValues","user_id",t.path.user_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putUserValue(t){return e.send({op:"PutUserValue",method:"PUT",path:"/flags/users/"+c("PutUserValue","user_id",t.path.user_id)+"/"+c("PutUserValue","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteUserValue(t){return e.send({op:"DeleteUserValue",method:"DELETE",path:"/flags/users/"+c("DeleteUserValue","user_id",t.path.user_id)+"/"+c("DeleteUserValue","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},headers:t.headers,signal:t.signal})}}}var Is={};We(Is,{client:()=>Kw});function Kw(e){return{async listMachines(t){return e.send({op:"ListMachines",method:"GET",path:"/machines",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createMachine(t){return e.send({op:"CreateMachine",method:"POST",path:"/machines",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listMachineSizes(t){return e.send({op:"ListMachineSizes",method:"GET",path:"/machines/sizes",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getMachineNetwork(t){return e.send({op:"GetMachineNetwork",method:"GET",path:"/machines/network",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async connectGitHub(t){return e.send({op:"ConnectGitHub",method:"POST",path:"/machines/github/connect",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listInstallations(t){return e.send({op:"ListInstallations",method:"GET",path:"/machines/github/installations",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async linkInstallation(t){return e.send({op:"LinkInstallation",method:"POST",path:"/machines/github/installations",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async shareInstallation(t){return e.send({op:"ShareInstallation",method:"POST",path:"/machines/github/installations/share",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async unlinkInstallation(t){return e.send({op:"UnlinkInstallation",method:"DELETE",path:"/machines/github/installations/"+c("UnlinkInstallation","installation",t.path.installation),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listRepositories(t){return e.send({op:"ListRepositories",method:"GET",path:"/machines/github/repositories",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getMachine(t){return e.send({op:"GetMachine",method:"GET",path:"/machines/"+c("GetMachine","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deleteMachine(t){return e.send({op:"DeleteMachine",method:"DELETE",path:"/machines/"+c("DeleteMachine","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async updateMachine(t){return e.send({op:"UpdateMachine",method:"PATCH",path:"/machines/"+c("UpdateMachine","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listBuilds(t){return e.send({op:"ListBuilds",method:"GET",path:"/machines/"+c("ListBuilds","name",t.path.name)+"/builds",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async deployMachine(t){return e.send({op:"DeployMachine",method:"POST",path:"/machines/"+c("DeployMachine","name",t.path.name)+"/builds",auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listMachinePreviews(t){return e.send({op:"ListMachinePreviews",method:"GET",path:"/machines/"+c("ListMachinePreviews","name",t.path.name)+"/previews",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putMachinePreview(t){return e.send({op:"PutMachinePreview",method:"PUT",path:"/machines/"+c("PutMachinePreview","name",t.path.name)+"/previews/"+c("PutMachinePreview","pull_request",t.path.pull_request),auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteMachinePreview(t){return e.send({op:"DeleteMachinePreview",method:"DELETE",path:"/machines/"+c("DeleteMachinePreview","name",t.path.name)+"/previews/"+c("DeleteMachinePreview","pull_request",t.path.pull_request),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listMachineDomains(t){return e.send({op:"ListMachineDomains",method:"GET",path:"/machines/"+c("ListMachineDomains","name",t.path.name)+"/domains",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async addMachineDomain(t){return e.send({op:"AddMachineDomain",method:"POST",path:"/machines/"+c("AddMachineDomain","name",t.path.name)+"/domains",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteMachineDomain(t){return e.send({op:"DeleteMachineDomain",method:"DELETE",path:"/machines/"+c("DeleteMachineDomain","name",t.path.name)+"/domains/"+c("DeleteMachineDomain","host",t.path.host),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async updateMachineDomain(t){return e.send({op:"UpdateMachineDomain",method:"PATCH",path:"/machines/"+c("UpdateMachineDomain","name",t.path.name)+"/domains/"+c("UpdateMachineDomain","host",t.path.host),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getBuild(t){return e.send({op:"GetBuild",method:"GET",path:"/machines/"+c("GetBuild","name",t.path.name)+"/builds/"+c("GetBuild","build",t.path.build),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getBuildLog(t){return e.send({op:"GetBuildLog",method:"GET",path:"/machines/"+c("GetBuildLog","name",t.path.name)+"/builds/"+c("GetBuildLog","build",t.path.build)+"/log",auth:[["SecretKeyAuth"]],answers:{200:"raw"},signal:t.signal})},async rollbackMachine(t){return e.send({op:"RollbackMachine",method:"POST",path:"/machines/"+c("RollbackMachine","name",t.path.name)+"/rollback",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listDatabases(t){return e.send({op:"ListDatabases",method:"GET",path:"/databases",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createDatabase(t){return e.send({op:"CreateDatabase",method:"POST",path:"/databases",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listDatabaseSizes(t){return e.send({op:"ListDatabaseSizes",method:"GET",path:"/databases/sizes",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getDatabase(t){return e.send({op:"GetDatabase",method:"GET",path:"/databases/"+c("GetDatabase","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deleteDatabase(t){return e.send({op:"DeleteDatabase",method:"DELETE",path:"/databases/"+c("DeleteDatabase","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async updateDatabase(t){return e.send({op:"UpdateDatabase",method:"PATCH",path:"/databases/"+c("UpdateDatabase","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json",202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async undeleteDatabase(t){return e.send({op:"UndeleteDatabase",method:"POST",path:"/databases/"+c("UndeleteDatabase","name",t.path.name)+"/undelete",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async purgeDatabase(t){return e.send({op:"PurgeDatabase",method:"POST",path:"/databases/"+c("PurgeDatabase","name",t.path.name)+"/purge",auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async getDatabaseCredentials(t){return e.send({op:"GetDatabaseCredentials",method:"GET",path:"/databases/"+c("GetDatabaseCredentials","name",t.path.name)+"/credentials",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async changeDatabasePassword(t){return e.send({op:"ChangeDatabasePassword",method:"POST",path:"/databases/"+c("ChangeDatabasePassword","name",t.path.name)+"/password",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async readMachineLogs(t){return e.send({op:"ReadMachineLogs",method:"GET",path:"/machines/"+c("ReadMachineLogs","name",t.path.name)+"/logs",auth:[["SecretKeyAuth"]],answers:{200:"raw"},query:t.query,signal:t.signal})},async getMachineMetrics(t){return e.send({op:"GetMachineMetrics",method:"GET",path:"/machines/"+c("GetMachineMetrics","name",t.path.name)+"/metrics",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getMachineContract(t){return e.send({op:"GetMachineContract",method:"GET",path:"/machines/"+c("GetMachineContract","name",t.path.name)+"/openapi",auth:[["SecretKeyAuth"]],answers:{200:"json",304:"empty"},headers:t.headers,signal:t.signal})},async restoreDatabase(t){return e.send({op:"RestoreDatabase",method:"POST",path:"/databases/"+c("RestoreDatabase","name",t.path.name)+"/restore",auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getDatabaseSchema(t){return e.send({op:"GetDatabaseSchema",method:"GET",path:"/databases/"+c("GetDatabaseSchema","name",t.path.name)+"/schema",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getDatabaseMetrics(t){return e.send({op:"GetDatabaseMetrics",method:"GET",path:"/databases/"+c("GetDatabaseMetrics","name",t.path.name)+"/metrics",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async queryDatabase(t){return e.send({op:"QueryDatabase",method:"POST",path:"/databases/"+c("QueryDatabase","name",t.path.name)+"/sql",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listCrons(t){return e.send({op:"ListCrons",method:"GET",path:"/machines/"+c("ListCrons","name",t.path.name)+"/crons",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listCronRuns(t){return e.send({op:"ListCronRuns",method:"GET",path:"/machines/"+c("ListCronRuns","name",t.path.name)+"/crons/"+c("ListCronRuns","cron",t.path.cron)+"/runs",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async runCron(t){return e.send({op:"RunCron",method:"POST",path:"/machines/"+c("RunCron","name",t.path.name)+"/crons/"+c("RunCron","cron",t.path.cron)+"/run",auth:[["SecretKeyAuth"]],answers:{201:"json"},signal:t.signal})},async pauseCron(t){return e.send({op:"PauseCron",method:"POST",path:"/machines/"+c("PauseCron","name",t.path.name)+"/crons/"+c("PauseCron","cron",t.path.cron)+"/pause",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async resumeCron(t){return e.send({op:"ResumeCron",method:"POST",path:"/machines/"+c("ResumeCron","name",t.path.name)+"/crons/"+c("ResumeCron","cron",t.path.cron)+"/resume",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listTasks(t){return e.send({op:"ListTasks",method:"GET",path:"/machines/"+c("ListTasks","name",t.path.name)+"/tasks",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async enqueueTask(t){return e.send({op:"EnqueueTask",method:"POST",path:"/machines/"+c("EnqueueTask","name",t.path.name)+"/tasks",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getTask(t){return e.send({op:"GetTask",method:"GET",path:"/machines/"+c("GetTask","name",t.path.name)+"/tasks/"+c("GetTask","task",t.path.task),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async cancelTask(t){return e.send({op:"CancelTask",method:"POST",path:"/machines/"+c("CancelTask","name",t.path.name)+"/tasks/"+c("CancelTask","task",t.path.task)+"/cancel",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async retryTask(t){return e.send({op:"RetryTask",method:"POST",path:"/machines/"+c("RetryTask","name",t.path.name)+"/tasks/"+c("RetryTask","task",t.path.task)+"/retry",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listTaskTypes(t){return e.send({op:"ListTaskTypes",method:"GET",path:"/machines/"+c("ListTaskTypes","name",t.path.name)+"/task-types",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async makeTemplatedTestUsers(t){return e.send({op:"MakeTemplatedTestUsers",method:"POST",path:"/machines/"+c("MakeTemplatedTestUsers","name",t.path.name)+"/test-users",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async templateTestUser(t){return e.send({op:"TemplateTestUser",method:"POST",path:"/machines/"+c("TemplateTestUser","name",t.path.name)+"/test-users/"+c("TemplateTestUser","user",t.path.user)+"/templates/"+c("TemplateTestUser","template",t.path.template),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deleteTemplatedTestUser(t){return e.send({op:"DeleteTemplatedTestUser",method:"DELETE",path:"/machines/"+c("DeleteTemplatedTestUser","name",t.path.name)+"/test-users/"+c("DeleteTemplatedTestUser","user",t.path.user),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listSites(t){return e.send({op:"ListSites",method:"GET",path:"/sites",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createSite(t){return e.send({op:"CreateSite",method:"POST",path:"/sites",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSite(t){return e.send({op:"GetSite",method:"GET",path:"/sites/"+c("GetSite","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deleteSite(t){return e.send({op:"DeleteSite",method:"DELETE",path:"/sites/"+c("DeleteSite","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async updateSite(t){return e.send({op:"UpdateSite",method:"PATCH",path:"/sites/"+c("UpdateSite","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listSiteReleases(t){return e.send({op:"ListSiteReleases",method:"GET",path:"/sites/"+c("ListSiteReleases","name",t.path.name)+"/releases",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async createSiteRelease(t){return e.send({op:"CreateSiteRelease",method:"POST",path:"/sites/"+c("CreateSiteRelease","name",t.path.name)+"/releases",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async uploadSiteFile(t){return e.send({op:"UploadSiteFile",method:"PUT",path:"/sites/"+c("UploadSiteFile","name",t.path.name)+"/releases/"+c("UploadSiteFile","release",t.path.release)+"/files/"+c("UploadSiteFile","digest",t.path.digest),auth:[["SecretKeyAuth"]],answers:{204:"empty"},body:{kind:"raw",contentType:t.contentType??"application/octet-stream",value:t.body},signal:t.signal})},async finishSiteRelease(t){return e.send({op:"FinishSiteRelease",method:"POST",path:"/sites/"+c("FinishSiteRelease","name",t.path.name)+"/releases/"+c("FinishSiteRelease","release",t.path.release)+"/finish",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async rollbackSite(t){return e.send({op:"RollbackSite",method:"POST",path:"/sites/"+c("RollbackSite","name",t.path.name)+"/rollback",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listSiteBuilds(t){return e.send({op:"ListSiteBuilds",method:"GET",path:"/sites/"+c("ListSiteBuilds","name",t.path.name)+"/builds",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deploySite(t){return e.send({op:"DeploySite",method:"POST",path:"/sites/"+c("DeploySite","name",t.path.name)+"/builds",auth:[["SecretKeyAuth"]],answers:{202:"json"},signal:t.signal})},async listSitePreviews(t){return e.send({op:"ListSitePreviews",method:"GET",path:"/sites/"+c("ListSitePreviews","name",t.path.name)+"/previews",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listSiteDomains(t){return e.send({op:"ListSiteDomains",method:"GET",path:"/sites/"+c("ListSiteDomains","name",t.path.name)+"/domains",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async addSiteDomain(t){return e.send({op:"AddSiteDomain",method:"POST",path:"/sites/"+c("AddSiteDomain","name",t.path.name)+"/domains",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteSiteDomain(t){return e.send({op:"DeleteSiteDomain",method:"DELETE",path:"/sites/"+c("DeleteSiteDomain","name",t.path.name)+"/domains/"+c("DeleteSiteDomain","host",t.path.host),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async updateSiteDomain(t){return e.send({op:"UpdateSiteDomain",method:"PATCH",path:"/sites/"+c("UpdateSiteDomain","name",t.path.name)+"/domains/"+c("UpdateSiteDomain","host",t.path.host),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSiteBuild(t){return e.send({op:"GetSiteBuild",method:"GET",path:"/sites/"+c("GetSiteBuild","name",t.path.name)+"/builds/"+c("GetSiteBuild","build",t.path.build),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async authorizeSitePreview(t){return e.send({op:"AuthorizeSitePreview",method:"POST",path:"/sites/"+c("AuthorizeSitePreview","name",t.path.name)+"/previews/"+c("AuthorizeSitePreview","pull_request",t.path.pull_request)+"/authorize",auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async authorizeMachinePreview(t){return e.send({op:"AuthorizeMachinePreview",method:"POST",path:"/machines/"+c("AuthorizeMachinePreview","name",t.path.name)+"/previews/"+c("AuthorizeMachinePreview","pull_request",t.path.pull_request)+"/authorize",auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async openMachinePreview(t){return e.send({op:"OpenMachinePreview",method:"POST",path:"/machines/"+c("OpenMachinePreview","name",t.path.name)+"/previews/"+c("OpenMachinePreview","pull_request",t.path.pull_request)+"/open",auth:[["SecretKeyAuth"]],answers:{202:"json"},signal:t.signal})},async moveMachine(t){return e.send({op:"MoveMachine",method:"POST",path:"/machines/"+c("MoveMachine","name",t.path.name)+"/move",auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})}}}var Ba={};We(Ba,{client:()=>Gw});function Gw(e){return{async adminAccessLog(t){return e.send({op:"AdminAccessLog",method:"GET",path:"/messaging/admin/access-log",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminListConversations(t){return e.send({op:"AdminListConversations",method:"GET",path:"/messaging/admin/conversations",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminCreateConversation(t){return e.send({op:"AdminCreateConversation",method:"POST",path:"/messaging/admin/conversations",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminGetConversation(t){return e.send({op:"AdminGetConversation",method:"GET",path:"/messaging/admin/conversations/"+c("AdminGetConversation","conversation_id",t.path.conversation_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async adminDeleteConversation(t){return e.send({op:"AdminDeleteConversation",method:"DELETE",path:"/messaging/admin/conversations/"+c("AdminDeleteConversation","conversation_id",t.path.conversation_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async adminUpdateConversation(t){return e.send({op:"AdminUpdateConversation",method:"PATCH",path:"/messaging/admin/conversations/"+c("AdminUpdateConversation","conversation_id",t.path.conversation_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminAddMembers(t){return e.send({op:"AdminAddMembers",method:"POST",path:"/messaging/admin/conversations/"+c("AdminAddMembers","conversation_id",t.path.conversation_id)+"/members",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminRemoveMember(t){return e.send({op:"AdminRemoveMember",method:"DELETE",path:"/messaging/admin/conversations/"+c("AdminRemoveMember","conversation_id",t.path.conversation_id)+"/members/"+c("AdminRemoveMember","user_id",t.path.user_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async adminListMessages(t){return e.send({op:"AdminListMessages",method:"GET",path:"/messaging/admin/conversations/"+c("AdminListMessages","conversation_id",t.path.conversation_id)+"/messages",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async adminSendMessage(t){return e.send({op:"AdminSendMessage",method:"POST",path:"/messaging/admin/conversations/"+c("AdminSendMessage","conversation_id",t.path.conversation_id)+"/messages",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminDeleteMessage(t){return e.send({op:"AdminDeleteMessage",method:"DELETE",path:"/messaging/admin/conversations/"+c("AdminDeleteMessage","conversation_id",t.path.conversation_id)+"/messages/"+c("AdminDeleteMessage","message_id",t.path.message_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async adminFileUrl(t){return e.send({op:"AdminFileURL",method:"GET",path:"/messaging/admin/conversations/"+c("AdminFileURL","conversation_id",t.path.conversation_id)+"/messages/"+c("AdminFileURL","message_id",t.path.message_id)+"/attachments/"+c("AdminFileURL","attachment_id",t.path.attachment_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async adminPutProfile(t){return e.send({op:"AdminPutProfile",method:"PUT",path:"/messaging/admin/profiles/"+c("AdminPutProfile","user_id",t.path.user_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async adminListReports(t){return e.send({op:"AdminListReports",method:"GET",path:"/messaging/admin/reports",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async adminGetReport(t){return e.send({op:"AdminGetReport",method:"GET",path:"/messaging/admin/reports/"+c("AdminGetReport","report_id",t.path.report_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async adminReportFileUrl(t){return e.send({op:"AdminReportFileURL",method:"GET",path:"/messaging/admin/reports/"+c("AdminReportFileURL","report_id",t.path.report_id)+"/attachments/"+c("AdminReportFileURL","attachment_id",t.path.attachment_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async adminResolveReport(t){return e.send({op:"AdminResolveReport",method:"POST",path:"/messaging/admin/reports/"+c("AdminResolveReport","report_id",t.path.report_id)+"/resolve",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listBlocks(t){return e.send({op:"ListBlocks",method:"GET",path:"/messaging/blocks",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async block(t){return e.send({op:"Block",method:"PUT",path:"/messaging/blocks/"+c("Block","user_id",t.path.user_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async unblock(t){return e.send({op:"Unblock",method:"DELETE",path:"/messaging/blocks/"+c("Unblock","user_id",t.path.user_id),auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async listConversations(t){return e.send({op:"ListConversations",method:"GET",path:"/messaging/conversations",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async openDirectConversation(t){return e.send({op:"OpenDirectConversation",method:"POST",path:"/messaging/conversations/direct",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json",201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createGroup(t){return e.send({op:"CreateGroup",method:"POST",path:"/messaging/conversations/group",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getConversation(t){return e.send({op:"GetConversation",method:"GET",path:"/messaging/conversations/"+c("GetConversation","conversation_id",t.path.conversation_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async deleteConversation(t){return e.send({op:"DeleteConversation",method:"DELETE",path:"/messaging/conversations/"+c("DeleteConversation","conversation_id",t.path.conversation_id),auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async updateConversation(t){return e.send({op:"UpdateConversation",method:"PATCH",path:"/messaging/conversations/"+c("UpdateConversation","conversation_id",t.path.conversation_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async clearConversation(t){return e.send({op:"ClearConversation",method:"POST",path:"/messaging/conversations/"+c("ClearConversation","conversation_id",t.path.conversation_id)+"/clear",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async closeConversation(t){return e.send({op:"CloseConversation",method:"POST",path:"/messaging/conversations/"+c("CloseConversation","conversation_id",t.path.conversation_id)+"/close",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async joinGroup(t){return e.send({op:"JoinGroup",method:"POST",path:"/messaging/conversations/"+c("JoinGroup","conversation_id",t.path.conversation_id)+"/join",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async listMembers(t){return e.send({op:"ListMembers",method:"GET",path:"/messaging/conversations/"+c("ListMembers","conversation_id",t.path.conversation_id)+"/members",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async addMembers(t){return e.send({op:"AddMembers",method:"POST",path:"/messaging/conversations/"+c("AddMembers","conversation_id",t.path.conversation_id)+"/members",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async removeMember(t){return e.send({op:"RemoveMember",method:"DELETE",path:"/messaging/conversations/"+c("RemoveMember","conversation_id",t.path.conversation_id)+"/members/"+c("RemoveMember","user_id",t.path.user_id),auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async updateMember(t){return e.send({op:"UpdateMember",method:"PATCH",path:"/messaging/conversations/"+c("UpdateMember","conversation_id",t.path.conversation_id)+"/members/"+c("UpdateMember","user_id",t.path.user_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listMessages(t){return e.send({op:"ListMessages",method:"GET",path:"/messaging/conversations/"+c("ListMessages","conversation_id",t.path.conversation_id)+"/messages",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async sendMessage(t){return e.send({op:"SendMessage",method:"POST",path:"/messaging/conversations/"+c("SendMessage","conversation_id",t.path.conversation_id)+"/messages",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json",201:"json",202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getMessage(t){return e.send({op:"GetMessage",method:"GET",path:"/messaging/conversations/"+c("GetMessage","conversation_id",t.path.conversation_id)+"/messages/"+c("GetMessage","message_id",t.path.message_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async deleteMessage(t){return e.send({op:"DeleteMessage",method:"DELETE",path:"/messaging/conversations/"+c("DeleteMessage","conversation_id",t.path.conversation_id)+"/messages/"+c("DeleteMessage","message_id",t.path.message_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json",204:"empty"},query:t.query,signal:t.signal})},async editMessage(t){return e.send({op:"EditMessage",method:"PATCH",path:"/messaging/conversations/"+c("EditMessage","conversation_id",t.path.conversation_id)+"/messages/"+c("EditMessage","message_id",t.path.message_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async attachmentUrl(t){return e.send({op:"AttachmentURL",method:"GET",path:"/messaging/conversations/"+c("AttachmentURL","conversation_id",t.path.conversation_id)+"/messages/"+c("AttachmentURL","message_id",t.path.message_id)+"/attachments/"+c("AttachmentURL","attachment_id",t.path.attachment_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async react(t){return e.send({op:"React",method:"PUT",path:"/messaging/conversations/"+c("React","conversation_id",t.path.conversation_id)+"/messages/"+c("React","message_id",t.path.message_id)+"/reactions/"+c("React","emoji",t.path.emoji),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async unreact(t){return e.send({op:"Unreact",method:"DELETE",path:"/messaging/conversations/"+c("Unreact","conversation_id",t.path.conversation_id)+"/messages/"+c("Unreact","message_id",t.path.message_id)+"/reactions/"+c("Unreact","emoji",t.path.emoji),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async messageReaders(t){return e.send({op:"MessageReaders",method:"GET",path:"/messaging/conversations/"+c("MessageReaders","conversation_id",t.path.conversation_id)+"/messages/"+c("MessageReaders","message_id",t.path.message_id)+"/readers",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async listReplies(t){return e.send({op:"ListReplies",method:"GET",path:"/messaging/conversations/"+c("ListReplies","conversation_id",t.path.conversation_id)+"/messages/"+c("ListReplies","message_id",t.path.message_id)+"/replies",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async viewOnce(t){return e.send({op:"ViewOnce",method:"POST",path:"/messaging/conversations/"+c("ViewOnce","conversation_id",t.path.conversation_id)+"/messages/"+c("ViewOnce","message_id",t.path.message_id)+"/view",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t.signal})},async setConversationNotifications(t){return e.send({op:"SetConversationNotifications",method:"PUT",path:"/messaging/conversations/"+c("SetConversationNotifications","conversation_id",t.path.conversation_id)+"/notifications",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async reportScreenshot(t){return e.send({op:"ReportScreenshot",method:"POST",path:"/messaging/conversations/"+c("ReportScreenshot","conversation_id",t.path.conversation_id)+"/screenshot",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},signal:t.signal})},async typing(t){return e.send({op:"Typing",method:"POST",path:"/messaging/conversations/"+c("Typing","conversation_id",t.path.conversation_id)+"/typing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createUpload(t){return e.send({op:"CreateUpload",method:"POST",path:"/messaging/conversations/"+c("CreateUpload","conversation_id",t.path.conversation_id)+"/uploads",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listOpenGroups(t){return e.send({op:"ListOpenGroups",method:"GET",path:"/messaging/groups/open",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getMyProfile(t){return e.send({op:"GetMyProfile",method:"GET",path:"/messaging/me",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async updateMyProfile(t){return e.send({op:"UpdateMyProfile",method:"PATCH",path:"/messaging/me",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async presence(t){return e.send({op:"Presence",method:"POST",path:"/messaging/me/presence",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t?.signal})},async getProfiles(t){return e.send({op:"GetProfiles",method:"GET",path:"/messaging/profiles",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async receipts(t){return e.send({op:"Receipts",method:"POST",path:"/messaging/receipts",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async report(t){return e.send({op:"Report",method:"POST",path:"/messaging/reports",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listScheduled(t){return e.send({op:"ListScheduled",method:"GET",path:"/messaging/scheduled",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async cancelScheduled(t){return e.send({op:"CancelScheduled",method:"DELETE",path:"/messaging/scheduled/"+c("CancelScheduled","scheduled_id",t.path.scheduled_id),auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async updateScheduled(t){return e.send({op:"UpdateScheduled",method:"PATCH",path:"/messaging/scheduled/"+c("UpdateScheduled","scheduled_id",t.path.scheduled_id),auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async searchMessages(t){return e.send({op:"SearchMessages",method:"GET",path:"/messaging/search",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getSettings(t){return e.send({op:"GetSettings",method:"GET",path:"/messaging/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putSettings(t){return e.send({op:"PutSettings",method:"PUT",path:"/messaging/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async rotateHookSecret(t){return e.send({op:"RotateHookSecret",method:"POST",path:"/messaging/settings/hook-secret",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async sync(t){return e.send({op:"Sync",method:"GET",path:"/messaging/sync",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listThreads(t){return e.send({op:"ListThreads",method:"GET",path:"/messaging/threads",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})}}}var Ls={};We(Ls,{client:()=>Uw});function Uw(e){return{async getDeliverability(t){return e.send({op:"GetDeliverability",method:"GET",path:"/notify/deliverability",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listDevices(t){return e.send({op:"ListDevices",method:"GET",path:"/notify/devices",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async registerDevice(t){return e.send({op:"RegisterDevice",method:"POST",path:"/notify/devices",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getDeviceStats(t){return e.send({op:"GetDeviceStats",method:"GET",path:"/notify/devices/stats",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async deleteMyDevice(t){return e.send({op:"DeleteMyDevice",method:"DELETE",path:"/notify/devices/"+c("DeleteMyDevice","device_id",t.path.device_id),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async sendEmail(t){return e.send({op:"SendEmail",method:"POST",path:"/notify/email",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listInAppCampaigns(t){return e.send({op:"ListInAppCampaigns",method:"GET",path:"/notify/in-app/campaigns",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async createInAppCampaign(t){return e.send({op:"CreateInAppCampaign",method:"POST",path:"/notify/in-app/campaigns",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getInAppCampaign(t){return e.send({op:"GetInAppCampaign",method:"GET",path:"/notify/in-app/campaigns/"+c("GetInAppCampaign","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putInAppCampaign(t){return e.send({op:"PutInAppCampaign",method:"PUT",path:"/notify/in-app/campaigns/"+c("PutInAppCampaign","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteInAppCampaign(t){return e.send({op:"DeleteInAppCampaign",method:"DELETE",path:"/notify/in-app/campaigns/"+c("DeleteInAppCampaign","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async getInAppCampaignStats(t){return e.send({op:"GetInAppCampaignStats",method:"GET",path:"/notify/in-app/campaigns/"+c("GetInAppCampaignStats","id",t.path.id)+"/stats",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async showInAppMessage(t){return e.send({op:"ShowInAppMessage",method:"POST",path:"/notify/in-app/impressions",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async reportInAppEvent(t){return e.send({op:"ReportInAppEvent",method:"POST",path:"/notify/in-app/impressions/"+c("ReportInAppEvent","id",t.path.id)+"/events",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{204:"empty"},idempotent:!0,query:t.query,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listMyInAppMessages(t){return e.send({op:"ListMyInAppMessages",method:"GET",path:"/notify/in-app/messages",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t.query,signal:t.signal})},async listInAppTemplates(t){return e.send({op:"ListInAppTemplates",method:"GET",path:"/notify/in-app/templates",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listMyInbox(t){return e.send({op:"ListMyInbox",method:"GET",path:"/notify/inbox",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async sendInbox(t){return e.send({op:"SendInbox",method:"POST",path:"/notify/inbox",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listInboxMessages(t){return e.send({op:"ListInboxMessages",method:"GET",path:"/notify/inbox/messages",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async readMyInbox(t){return e.send({op:"ReadMyInbox",method:"POST",path:"/notify/inbox/read",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteMyInboxMessage(t){return e.send({op:"DeleteMyInboxMessage",method:"DELETE",path:"/notify/inbox/"+c("DeleteMyInboxMessage","id",t.path.id),auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listNotifyMessages(t){return e.send({op:"ListNotifyMessages",method:"GET",path:"/notify/messages",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getNotifyMessage(t){return e.send({op:"GetNotifyMessage",method:"GET",path:"/notify/messages/"+c("GetNotifyMessage","id",t.path.id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async cancelMessage(t){return e.send({op:"CancelMessage",method:"POST",path:"/notify/messages/"+c("CancelMessage","id",t.path.id)+"/cancel",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getMetricsSummary(t){return e.send({op:"GetMetricsSummary",method:"GET",path:"/notify/metrics/summary",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getMyPreferences(t){return e.send({op:"GetMyPreferences",method:"GET",path:"/notify/preferences",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async setMyPreferences(t){return e.send({op:"SetMyPreferences",method:"PUT",path:"/notify/preferences",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listNotifyProviders(t){return e.send({op:"ListNotifyProviders",method:"GET",path:"/notify/providers",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putNotifyProvider(t){return e.send({op:"PutNotifyProvider",method:"PUT",path:"/notify/providers/"+c("PutNotifyProvider","channel",t.path.channel)+"/"+c("PutNotifyProvider","provider",t.path.provider),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteNotifyProvider(t){return e.send({op:"DeleteNotifyProvider",method:"DELETE",path:"/notify/providers/"+c("DeleteNotifyProvider","channel",t.path.channel)+"/"+c("DeleteNotifyProvider","provider",t.path.provider),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async sendPush(t){return e.send({op:"SendPush",method:"POST",path:"/notify/push",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async recordPushReceipts(t){return e.send({op:"RecordPushReceipts",method:"POST",path:"/notify/receipts",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getNotifySettings(t){return e.send({op:"GetNotifySettings",method:"GET",path:"/notify/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putNotifySettings(t){return e.send({op:"PutNotifySettings",method:"PUT",path:"/notify/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async sendSms(t){return e.send({op:"SendSMS",method:"POST",path:"/notify/sms",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listEmailTemplates(t){return e.send({op:"ListEmailTemplates",method:"GET",path:"/notify/templates/email",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getEmailTemplate(t){return e.send({op:"GetEmailTemplate",method:"GET",path:"/notify/templates/email/"+c("GetEmailTemplate","slug",t.path.slug)+"/"+c("GetEmailTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putEmailTemplate(t){return e.send({op:"PutEmailTemplate",method:"PUT",path:"/notify/templates/email/"+c("PutEmailTemplate","slug",t.path.slug)+"/"+c("PutEmailTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteEmailTemplate(t){return e.send({op:"DeleteEmailTemplate",method:"DELETE",path:"/notify/templates/email/"+c("DeleteEmailTemplate","slug",t.path.slug)+"/"+c("DeleteEmailTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listPushTemplates(t){return e.send({op:"ListPushTemplates",method:"GET",path:"/notify/templates/push",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getPushTemplate(t){return e.send({op:"GetPushTemplate",method:"GET",path:"/notify/templates/push/"+c("GetPushTemplate","slug",t.path.slug)+"/"+c("GetPushTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putPushTemplate(t){return e.send({op:"PutPushTemplate",method:"PUT",path:"/notify/templates/push/"+c("PutPushTemplate","slug",t.path.slug)+"/"+c("PutPushTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deletePushTemplate(t){return e.send({op:"DeletePushTemplate",method:"DELETE",path:"/notify/templates/push/"+c("DeletePushTemplate","slug",t.path.slug)+"/"+c("DeletePushTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listSmsTemplates(t){return e.send({op:"ListSMSTemplates",method:"GET",path:"/notify/templates/sms",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getSmsTemplate(t){return e.send({op:"GetSMSTemplate",method:"GET",path:"/notify/templates/sms/"+c("GetSMSTemplate","slug",t.path.slug)+"/"+c("GetSMSTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putSmsTemplate(t){return e.send({op:"PutSMSTemplate",method:"PUT",path:"/notify/templates/sms/"+c("PutSMSTemplate","slug",t.path.slug)+"/"+c("PutSMSTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteSmsTemplate(t){return e.send({op:"DeleteSMSTemplate",method:"DELETE",path:"/notify/templates/sms/"+c("DeleteSMSTemplate","slug",t.path.slug)+"/"+c("DeleteSMSTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listWhatsAppTemplates(t){return e.send({op:"ListWhatsAppTemplates",method:"GET",path:"/notify/templates/whatsapp",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getWhatsAppTemplate(t){return e.send({op:"GetWhatsAppTemplate",method:"GET",path:"/notify/templates/whatsapp/"+c("GetWhatsAppTemplate","slug",t.path.slug)+"/"+c("GetWhatsAppTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putWhatsAppTemplate(t){return e.send({op:"PutWhatsAppTemplate",method:"PUT",path:"/notify/templates/whatsapp/"+c("PutWhatsAppTemplate","slug",t.path.slug)+"/"+c("PutWhatsAppTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteWhatsAppTemplate(t){return e.send({op:"DeleteWhatsAppTemplate",method:"DELETE",path:"/notify/templates/whatsapp/"+c("DeleteWhatsAppTemplate","slug",t.path.slug)+"/"+c("DeleteWhatsAppTemplate","locale",t.path.locale),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listTestUserMessages(t){return e.send({op:"ListTestUserMessages",method:"GET",path:"/notify/test-users/"+c("ListTestUserMessages","user_id",t.path.user_id)+"/messages",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async listTopics(t){return e.send({op:"ListTopics",method:"GET",path:"/notify/topics",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createTopic(t){return e.send({op:"CreateTopic",method:"POST",path:"/notify/topics",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteTopic(t){return e.send({op:"DeleteTopic",method:"DELETE",path:"/notify/topics/"+c("DeleteTopic","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async changeTopic(t){return e.send({op:"ChangeTopic",method:"PATCH",path:"/notify/topics/"+c("ChangeTopic","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async addTopicSubscribers(t){return e.send({op:"AddTopicSubscribers",method:"POST",path:"/notify/topics/"+c("AddTopicSubscribers","name",t.path.name)+"/subscribers",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async removeTopicSubscriber(t){return e.send({op:"RemoveTopicSubscriber",method:"DELETE",path:"/notify/topics/"+c("RemoveTopicSubscriber","name",t.path.name)+"/subscribers/"+c("RemoveTopicSubscriber","user_id",t.path.user_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async followTopic(t){return e.send({op:"FollowTopic",method:"POST",path:"/notify/topics/"+c("FollowTopic","name",t.path.name)+"/subscription",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async unfollowTopic(t){return e.send({op:"UnfollowTopic",method:"DELETE",path:"/notify/topics/"+c("UnfollowTopic","name",t.path.name)+"/subscription",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listUserDevices(t){return e.send({op:"ListUserDevices",method:"GET",path:"/notify/users/"+c("ListUserDevices","user_id",t.path.user_id)+"/devices",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getUserPreferences(t){return e.send({op:"GetUserPreferences",method:"GET",path:"/notify/users/"+c("GetUserPreferences","user_id",t.path.user_id)+"/preferences",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async setUserPreferences(t){return e.send({op:"SetUserPreferences",method:"PUT",path:"/notify/users/"+c("SetUserPreferences","user_id",t.path.user_id)+"/preferences",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async startVerification(t){return e.send({op:"StartVerification",method:"POST",path:"/notify/verifications",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async checkVerification(t){return e.send({op:"CheckVerification",method:"POST",path:"/notify/verifications/check",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async receiveSendGridEvents(t){return e.send({op:"ReceiveSendGridEvents",method:"POST",path:"/notify/webhooks/email/sendgrid",auth:[],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async receiveTwilioStatus(t){return e.send({op:"ReceiveTwilioStatus",method:"POST",path:"/notify/webhooks/sms/twilio",auth:[],answers:{204:"empty"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async receiveTwilioText(t){return e.send({op:"ReceiveTwilioText",method:"POST",path:"/notify/webhooks/sms/twilio/inbound",auth:[],answers:{204:"empty"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})},async receiveVonageReceiptQuery(t){return e.send({op:"ReceiveVonageReceiptQuery",method:"GET",path:"/notify/webhooks/sms/vonage",auth:[],answers:{204:"empty"},query:t?.query,signal:t?.signal})},async receiveVonageReceipt(t){return e.send({op:"ReceiveVonageReceipt",method:"POST",path:"/notify/webhooks/sms/vonage",auth:[],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async subscribeMetaWebhook(t){return e.send({op:"SubscribeMetaWebhook",method:"GET",path:"/notify/webhooks/whatsapp/meta",auth:[],answers:{200:"raw"},query:t.query,signal:t.signal})},async receiveMetaNotification(t){return e.send({op:"ReceiveMetaNotification",method:"POST",path:"/notify/webhooks/whatsapp/meta",auth:[],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getWebPushStatus(t){return e.send({op:"GetWebPushStatus",method:"GET",path:"/notify/webpush",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getWebPushKey(t){return e.send({op:"GetWebPushKey",method:"GET",path:"/notify/webpush/key",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async sendWhatsApp(t){return e.send({op:"SendWhatsApp",method:"POST",path:"/notify/whatsapp",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listWhatsAppInbound(t){return e.send({op:"ListWhatsAppInbound",method:"GET",path:"/notify/whatsapp/inbound",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})}}}var Ds={};We(Ds,{client:()=>zw});function zw(e){return{async getAppleAccount(t){return e.send({op:"GetAppleAccount",method:"GET",path:"/purchases/apple",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async disconnectApple(t){return e.send({op:"DisconnectApple",method:"DELETE",path:"/purchases/apple",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getAppleAccountToken(t){return e.send({op:"GetAppleAccountToken",method:"POST",path:"/purchases/apple/account-token",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async getAppleConnectPage(t){return e.send({op:"GetAppleConnectPage",method:"GET",path:"/purchases/apple/connect",auth:[],answers:{200:"raw"},signal:t?.signal})},async connectAppleKey(t){return e.send({op:"ConnectAppleKey",method:"POST",path:"/purchases/apple/connect",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createAppleGrant(t){return e.send({op:"CreateAppleGrant",method:"POST",path:"/purchases/apple/grants",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getAppleReadiness(t){return e.send({op:"GetAppleReadiness",method:"GET",path:"/purchases/apple/readiness",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async reportAppleTransactions(t){return e.send({op:"ReportAppleTransactions",method:"POST",path:"/purchases/apple/transactions",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getGoogleAccountId(t){return e.send({op:"GetGoogleAccountID",method:"POST",path:"/purchases/google/account-id",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async reportGooglePurchases(t){return e.send({op:"ReportGooglePurchases",method:"POST",path:"/purchases/google/purchases",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async setXcodeCertificate(t){return e.send({op:"SetXcodeCertificate",method:"PUT",path:"/purchases/apple/xcode-certificate",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async clearXcodeCertificate(t){return e.send({op:"ClearXcodeCertificate",method:"DELETE",path:"/purchases/apple/xcode-certificate",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getGoogleAccount(t){return e.send({op:"GetGoogleAccount",method:"GET",path:"/purchases/google",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async connectGoogle(t){return e.send({op:"ConnectGoogle",method:"POST",path:"/purchases/google",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async disconnectGoogle(t){return e.send({op:"DisconnectGoogle",method:"DELETE",path:"/purchases/google",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getCatalog(t){return e.send({op:"GetCatalog",method:"GET",path:"/purchases/catalog",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async saveCatalog(t){return e.send({op:"SaveCatalog",method:"PUT",path:"/purchases/catalog",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async planCatalog(t){return e.send({op:"PlanCatalog",method:"POST",path:"/purchases/catalog/plans",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getCatalogPlan(t){return e.send({op:"GetCatalogPlan",method:"GET",path:"/purchases/catalog/plans/"+c("GetCatalogPlan","plan_id",t.path.plan_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async confirmCatalogPlan(t){return e.send({op:"ConfirmCatalogPlan",method:"POST",path:"/purchases/catalog/plans/"+c("ConfirmCatalogPlan","plan_id",t.path.plan_id)+"/confirm",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async declineCatalogPlan(t){return e.send({op:"DeclineCatalogPlan",method:"POST",path:"/purchases/catalog/plans/"+c("DeclineCatalogPlan","plan_id",t.path.plan_id)+"/decline",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async validateCatalog(t){return e.send({op:"ValidateCatalog",method:"POST",path:"/purchases/catalog/validate",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listCharts(t){return e.send({op:"ListCharts",method:"GET",path:"/purchases/charts",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getChartsOverview(t){return e.send({op:"GetChartsOverview",method:"GET",path:"/purchases/charts/overview",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getChart(t){return e.send({op:"GetChart",method:"GET",path:"/purchases/charts/"+c("GetChart","chart",t.path.chart),auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getStripeConnectPage(t){return e.send({op:"GetStripeConnectPage",method:"GET",path:"/purchases/connect",auth:[],answers:{200:"raw"},signal:t?.signal})},async connectStripeKey(t){return e.send({op:"ConnectStripeKey",method:"POST",path:"/purchases/connect",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getStripeAppInstallPage(t){return e.send({op:"GetStripeAppInstallPage",method:"GET",path:"/purchases/stripe/app/install",auth:[],answers:{200:"raw"},signal:t?.signal})},async startStripeAppInstall(t){return e.send({op:"StartStripeAppInstall",method:"POST",path:"/purchases/stripe/app/install",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async completeStripeAppInstall(t){return e.send({op:"CompleteStripeAppInstall",method:"GET",path:"/purchases/stripe/app/callback",auth:[],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async getCustomer(t){return e.send({op:"GetCustomer",method:"GET",path:"/purchases/customers/"+c("GetCustomer","customer_id",t.path.customer_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async grantCredits(t){return e.send({op:"GrantCredits",method:"POST",path:"/purchases/customers/"+c("GrantCredits","customer_id",t.path.customer_id)+"/credits",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listCreditEntries(t){return e.send({op:"ListCreditEntries",method:"GET",path:"/purchases/customers/"+c("ListCreditEntries","customer_id",t.path.customer_id)+"/credits/entries",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async forgiveCredits(t){return e.send({op:"ForgiveCredits",method:"POST",path:"/purchases/customers/"+c("ForgiveCredits","customer_id",t.path.customer_id)+"/credits/forgive",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listCustomerGrants(t){return e.send({op:"ListCustomerGrants",method:"GET",path:"/purchases/customers/"+c("ListCustomerGrants","customer_id",t.path.customer_id)+"/grants",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async grantEntitlement(t){return e.send({op:"GrantEntitlement",method:"POST",path:"/purchases/customers/"+c("GrantEntitlement","customer_id",t.path.customer_id)+"/grants",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async revokeGrant(t){return e.send({op:"RevokeGrant",method:"DELETE",path:"/purchases/customers/"+c("RevokeGrant","customer_id",t.path.customer_id)+"/grants/"+c("RevokeGrant","grant_id",t.path.grant_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async holdSpend(t){return e.send({op:"HoldSpend",method:"POST",path:"/purchases/customers/"+c("HoldSpend","customer_id",t.path.customer_id)+"/holds",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async setCustomerLimit(t){return e.send({op:"SetCustomerLimit",method:"PUT",path:"/purchases/customers/"+c("SetCustomerLimit","customer_id",t.path.customer_id)+"/limits/"+c("SetCustomerLimit","limit_key",t.path.limit_key),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async clearCustomerLimit(t){return e.send({op:"ClearCustomerLimit",method:"DELETE",path:"/purchases/customers/"+c("ClearCustomerLimit","customer_id",t.path.customer_id)+"/limits/"+c("ClearCustomerLimit","limit_key",t.path.limit_key),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async grantLimit(t){return e.send({op:"GrantLimit",method:"POST",path:"/purchases/customers/"+c("GrantLimit","customer_id",t.path.customer_id)+"/limits/"+c("GrantLimit","limit_key",t.path.limit_key)+"/grants",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async spend(t){return e.send({op:"Spend",method:"POST",path:"/purchases/customers/"+c("Spend","customer_id",t.path.customer_id)+"/spend",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async commitSpend(t){return e.send({op:"CommitSpend",method:"POST",path:"/purchases/customers/"+c("CommitSpend","customer_id",t.path.customer_id)+"/spends/"+c("CommitSpend","spend_id",t.path.spend_id)+"/commit",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async extendHold(t){return e.send({op:"ExtendHold",method:"POST",path:"/purchases/customers/"+c("ExtendHold","customer_id",t.path.customer_id)+"/spends/"+c("ExtendHold","spend_id",t.path.spend_id)+"/extend",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async releaseSpend(t){return e.send({op:"ReleaseSpend",method:"POST",path:"/purchases/customers/"+c("ReleaseSpend","customer_id",t.path.customer_id)+"/spends/"+c("ReleaseSpend","spend_id",t.path.spend_id)+"/release",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async reverseSpend(t){return e.send({op:"ReverseSpend",method:"POST",path:"/purchases/customers/"+c("ReverseSpend","customer_id",t.path.customer_id)+"/spends/"+c("ReverseSpend","spend_id",t.path.spend_id)+"/reverse",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listExperiments(t){return e.send({op:"ListExperiments",method:"GET",path:"/purchases/experiments",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async startExperiment(t){return e.send({op:"StartExperiment",method:"POST",path:"/purchases/experiments",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getExperiment(t){return e.send({op:"GetExperiment",method:"GET",path:"/purchases/experiments/"+c("GetExperiment","experiment_id",t.path.experiment_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getExperimentResults(t){return e.send({op:"GetExperimentResults",method:"GET",path:"/purchases/experiments/"+c("GetExperimentResults","experiment_id",t.path.experiment_id)+"/results",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async stopExperiment(t){return e.send({op:"StopExperiment",method:"POST",path:"/purchases/experiments/"+c("StopExperiment","experiment_id",t.path.experiment_id)+"/stop",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async declareExperimentWinner(t){return e.send({op:"DeclareExperimentWinner",method:"POST",path:"/purchases/experiments/"+c("DeclareExperimentWinner","experiment_id",t.path.experiment_id)+"/winner",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getMyCustomerInfo(t){return e.send({op:"GetMyCustomerInfo",method:"GET",path:"/purchases/me",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async mergeGuest(t){return e.send({op:"MergeGuest",method:"POST",path:"/purchases/me/merge",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createMergeGrant(t){return e.send({op:"CreateMergeGrant",method:"POST",path:"/purchases/me/merge-grant",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},signal:t?.signal})},async getOfferings(t){return e.send({op:"GetOfferings",method:"GET",path:"/purchases/offerings",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listPaywalls(t){return e.send({op:"ListPaywalls",method:"GET",path:"/purchases/paywalls",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async createPaywall(t){return e.send({op:"CreatePaywall",method:"POST",path:"/purchases/paywalls",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listPaywallAssets(t){return e.send({op:"ListPaywallAssets",method:"GET",path:"/purchases/paywalls/assets",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async registerPaywallAsset(t){return e.send({op:"RegisterPaywallAsset",method:"POST",path:"/purchases/paywalls/assets",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deletePaywallAsset(t){return e.send({op:"DeletePaywallAsset",method:"DELETE",path:"/purchases/paywalls/assets/"+c("DeletePaywallAsset","asset_id",t.path.asset_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listPaywallTemplates(t){return e.send({op:"ListPaywallTemplates",method:"GET",path:"/purchases/paywalls/templates",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getPaywallTemplateAsset(t){return e.send({op:"GetPaywallTemplateAsset",method:"GET",path:"/purchases/paywalls/templates/"+c("GetPaywallTemplateAsset","key",t.path.key)+"/assets/"+c("GetPaywallTemplateAsset","asset_id",t.path.asset_id),auth:[["SecretKeyAuth"]],answers:{200:"raw",304:"empty"},headers:t.headers,signal:t.signal})},async validatePaywall(t){return e.send({op:"ValidatePaywall",method:"POST",path:"/purchases/paywalls/validate",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPaywall(t){return e.send({op:"GetPaywall",method:"GET",path:"/purchases/paywalls/"+c("GetPaywall","paywall_id",t.path.paywall_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deletePaywall(t){return e.send({op:"DeletePaywall",method:"DELETE",path:"/purchases/paywalls/"+c("DeletePaywall","paywall_id",t.path.paywall_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async savePaywallDraft(t){return e.send({op:"SavePaywallDraft",method:"PUT",path:"/purchases/paywalls/"+c("SavePaywallDraft","paywall_id",t.path.paywall_id)+"/draft",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async publishPaywall(t){return e.send({op:"PublishPaywall",method:"POST",path:"/purchases/paywalls/"+c("PublishPaywall","paywall_id",t.path.paywall_id)+"/publish",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async listPaywallVersions(t){return e.send({op:"ListPaywallVersions",method:"GET",path:"/purchases/paywalls/"+c("ListPaywallVersions","paywall_id",t.path.paywall_id)+"/versions",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getPaywallVersion(t){return e.send({op:"GetPaywallVersion",method:"GET",path:"/purchases/paywalls/"+c("GetPaywallVersion","paywall_id",t.path.paywall_id)+"/versions/"+c("GetPaywallVersion","version",t.path.version),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listPlacements(t){return e.send({op:"ListPlacements",method:"GET",path:"/purchases/placements",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listAttributeKeys(t){return e.send({op:"ListAttributeKeys",method:"GET",path:"/purchases/placements/attributes",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async setPlacement(t){return e.send({op:"SetPlacement",method:"PUT",path:"/purchases/placements/"+c("SetPlacement","placement",t.path.placement),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deletePlacement(t){return e.send({op:"DeletePlacement",method:"DELETE",path:"/purchases/placements/"+c("DeletePlacement","placement",t.path.placement),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async recordPaywallExposure(t){return e.send({op:"RecordPaywallExposure",method:"POST",path:"/purchases/placements/"+c("RecordPaywallExposure","placement",t.path.placement)+"/exposures",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPlacementPaywall(t){return e.send({op:"GetPlacementPaywall",method:"GET",path:"/purchases/placements/"+c("GetPlacementPaywall","placement",t.path.placement)+"/paywall",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json",204:"empty",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async previewPlacement(t){return e.send({op:"PreviewPlacement",method:"POST",path:"/purchases/placements/"+c("PreviewPlacement","placement",t.path.placement)+"/resolve-preview",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPlacementResults(t){return e.send({op:"GetPlacementResults",method:"GET",path:"/purchases/placements/"+c("GetPlacementResults","placement",t.path.placement)+"/results",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getPlacementRules(t){return e.send({op:"GetPlacementRules",method:"GET",path:"/purchases/placements/"+c("GetPlacementRules","placement",t.path.placement)+"/rules",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async setPlacementRules(t){return e.send({op:"SetPlacementRules",method:"PUT",path:"/purchases/placements/"+c("SetPlacementRules","placement",t.path.placement)+"/rules",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSettings(t){return e.send({op:"GetSettings",method:"GET",path:"/purchases/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async updateSettings(t){return e.send({op:"UpdateSettings",method:"PUT",path:"/purchases/settings",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getStripeAccount(t){return e.send({op:"GetStripeAccount",method:"GET",path:"/purchases/stripe",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async disconnectStripe(t){return e.send({op:"DisconnectStripe",method:"DELETE",path:"/purchases/stripe",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async checkStripeAccount(t){return e.send({op:"CheckStripeAccount",method:"POST",path:"/purchases/stripe/check",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async createCheckout(t){return e.send({op:"CreateCheckout",method:"POST",path:"/purchases/stripe/checkout",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createCheckoutRedemption(t){return e.send({op:"CreateCheckoutRedemption",method:"POST",path:"/purchases/stripe/checkout/redemption",auth:[["ApiKeyAuth"],["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async redeemPurchase(t){return e.send({op:"RedeemPurchase",method:"POST",path:"/purchases/redemptions/redeem",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getRedemptionPage(t){return e.send({op:"GetRedemptionPage",method:"GET",path:"/purchases/redeem",auth:[],answers:{200:"raw"},query:t.query,signal:t.signal})},async createStripeGrant(t){return e.send({op:"CreateStripeGrant",method:"POST",path:"/purchases/stripe/grants",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async createStripeAppInstall(t){return e.send({op:"CreateStripeAppInstall",method:"POST",path:"/purchases/stripe/app/grants",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createPortalSession(t){return e.send({op:"CreatePortalSession",method:"POST",path:"/purchases/stripe/portal",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async receiveAppleNotification(t){return e.send({op:"ReceiveAppleNotification",method:"POST",path:"/purchases/webhooks/apple",auth:[],answers:{200:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async receiveGoogleNotification(t){return e.send({op:"ReceiveGoogleNotification",method:"POST",path:"/purchases/webhooks/google",auth:[],answers:{204:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async receiveStripeEvent(t){return e.send({op:"ReceiveStripeEvent",method:"POST",path:"/purchases/webhooks/stripe",auth:[],answers:{200:"empty"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async receiveStripeAppEvent(t){return e.send({op:"ReceiveStripeAppEvent",method:"POST",path:"/purchases/webhooks/stripe-app",auth:[],answers:{200:"empty"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listMyOffers(t){return e.send({op:"ListMyOffers",method:"GET",path:"/purchases/offers",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},signal:t?.signal})},async recordOfferView(t){return e.send({op:"RecordOfferView",method:"POST",path:"/purchases/offers/"+c("RecordOfferView","offer_key",t.path.offer_key)+"/views",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"},signal:t.signal})},async signAppleOffer(t){return e.send({op:"SignAppleOffer",method:"POST",path:"/purchases/offers/"+c("SignAppleOffer","offer_key",t.path.offer_key)+"/apple-signature",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async claimOffer(t){return e.send({op:"ClaimOffer",method:"POST",path:"/purchases/offers/"+c("ClaimOffer","offer_key",t.path.offer_key)+"/claim",auth:[["ApiKeyAuth","userJWT"]],answers:{201:"json"},signal:t.signal})},async redeemCoupon(t){return e.send({op:"RedeemCoupon",method:"POST",path:"/purchases/coupons/redeem",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getOfferStats(t){return e.send({op:"GetOfferStats",method:"GET",path:"/purchases/offers/stats",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listCoupons(t){return e.send({op:"ListCoupons",method:"GET",path:"/purchases/coupons",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async createCoupon(t){return e.send({op:"CreateCoupon",method:"POST",path:"/purchases/coupons",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getCoupon(t){return e.send({op:"GetCoupon",method:"GET",path:"/purchases/coupons/"+c("GetCoupon","coupon_key",t.path.coupon_key),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async revokeCoupon(t){return e.send({op:"RevokeCoupon",method:"DELETE",path:"/purchases/coupons/"+c("RevokeCoupon","coupon_key",t.path.coupon_key),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listCouponCodes(t){return e.send({op:"ListCouponCodes",method:"GET",path:"/purchases/coupons/"+c("ListCouponCodes","coupon_key",t.path.coupon_key)+"/codes",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async setXcodeOfferKey(t){return e.send({op:"SetXcodeOfferKey",method:"PUT",path:"/purchases/apple/xcode-offer-key",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async searchCustomers(t){return e.send({op:"SearchCustomers",method:"GET",path:"/purchases/customers",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getCustomerHistory(t){return e.send({op:"GetCustomerHistory",method:"GET",path:"/purchases/customers/"+c("GetCustomerHistory","customer_id",t.path.customer_id)+"/history",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async listCatalogRevisions(t){return e.send({op:"ListCatalogRevisions",method:"GET",path:"/purchases/catalog/revisions",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getCatalogRevision(t){return e.send({op:"GetCatalogRevision",method:"GET",path:"/purchases/catalog/revisions/"+c("GetCatalogRevision","revision",t.path.revision),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async restoreCatalogRevision(t){return e.send({op:"RestoreCatalogRevision",method:"POST",path:"/purchases/catalog/revisions/"+c("RestoreCatalogRevision","revision",t.path.revision)+"/restore",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async extendSubscription(t){return e.send({op:"ExtendSubscription",method:"POST",path:"/purchases/customers/"+c("ExtendSubscription","customer_id",t.path.customer_id)+"/subscriptions/"+c("ExtendSubscription","subscription_id",t.path.subscription_id)+"/extend",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async refundSubscription(t){return e.send({op:"RefundSubscription",method:"POST",path:"/purchases/customers/"+c("RefundSubscription","customer_id",t.path.customer_id)+"/subscriptions/"+c("RefundSubscription","subscription_id",t.path.subscription_id)+"/refund",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async cancelSubscription(t){return e.send({op:"CancelSubscription",method:"POST",path:"/purchases/customers/"+c("CancelSubscription","customer_id",t.path.customer_id)+"/subscriptions/"+c("CancelSubscription","subscription_id",t.path.subscription_id)+"/cancel",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async setRefundDataConsent(t){return e.send({op:"SetRefundDataConsent",method:"PUT",path:"/purchases/me/refund-data-consent",auth:[["ApiKeyAuth","userJWT"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})}}}var qs={};We(qs,{client:()=>Bw});function Bw(e){return{async broadcast(t){return e.send({op:"Broadcast",method:"POST",path:"/realtime/broadcast",auth:[["SecretKeyAuth"]],answers:{202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getChannels(t){return e.send({op:"GetChannels",method:"GET",path:"/realtime/channels",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putChannels(t){return e.send({op:"PutChannels",method:"PUT",path:"/realtime/channels",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getLimits(t){return e.send({op:"GetLimits",method:"GET",path:"/realtime/limits",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putLimits(t){return e.send({op:"PutLimits",method:"PUT",path:"/realtime/limits",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async revalidate(t){return e.send({op:"Revalidate",method:"POST",path:"/realtime/revalidate",auth:[["SecretKeyAuth"]],answers:{202:"empty"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async writeState(t){return e.send({op:"WriteState",method:"POST",path:"/realtime/state",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getStats(t){return e.send({op:"GetStats",method:"GET",path:"/realtime/stats",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})}}}var Ns={};We(Ns,{client:()=>Fw});function Fw(e){return{async listSecretAudit(t){return e.send({op:"ListSecretAudit",method:"GET",path:"/secrets/audit",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listFieldKeys(t){return e.send({op:"ListFieldKeys",method:"GET",path:"/secrets/fields",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getFieldKeys(t){return e.send({op:"GetFieldKeys",method:"GET",path:"/secrets/fields/keys",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async openFields(t){return e.send({op:"OpenFields",method:"POST",path:"/secrets/fields/open",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async sealPlaceholder(t){return e.send({op:"SealPlaceholder",method:"POST",path:"/secrets/fields/placeholder",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async rotateFieldKeys(t){return e.send({op:"RotateFieldKeys",method:"POST",path:"/secrets/fields/rotate",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async listTransitKeys(t){return e.send({op:"ListTransitKeys",method:"GET",path:"/secrets/transit",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getTransitKeys(t){return e.send({op:"GetTransitKeys",method:"GET",path:"/secrets/transit/keys",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getTransitPublicKeys(t){return e.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",auth:[["ApiKeyAuth"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async rotateTransitKeys(t){return e.send({op:"RotateTransitKeys",method:"POST",path:"/secrets/transit/rotate",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t?.headers,body:{kind:"json",contentType:"application/json",value:t?.body},signal:t?.signal})},async retireTransitKey(t){return e.send({op:"RetireTransitKey",method:"POST",path:"/secrets/transit/"+c("RetireTransitKey","kid",t.path.kid)+"/retire",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async listSecrets(t){return e.send({op:"ListSecrets",method:"GET",path:"/secrets/"+c("ListSecrets","environment",t.path.environment),auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getEnvironmentValues(t){return e.send({op:"GetEnvironmentValues",method:"GET",path:"/secrets/"+c("GetEnvironmentValues","environment",t.path.environment)+"/values",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getSecret(t){return e.send({op:"GetSecret",method:"GET",path:"/secrets/"+c("GetSecret","environment",t.path.environment)+"/"+c("GetSecret","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putSecret(t){return e.send({op:"PutSecret",method:"PUT",path:"/secrets/"+c("PutSecret","environment",t.path.environment)+"/"+c("PutSecret","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteSecret(t){return e.send({op:"DeleteSecret",method:"DELETE",path:"/secrets/"+c("DeleteSecret","environment",t.path.environment)+"/"+c("DeleteSecret","name",t.path.name),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async rollbackSecret(t){return e.send({op:"RollbackSecret",method:"POST",path:"/secrets/"+c("RollbackSecret","environment",t.path.environment)+"/"+c("RollbackSecret","name",t.path.name)+"/rollback",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listSecretVersions(t){return e.send({op:"ListSecretVersions",method:"GET",path:"/secrets/"+c("ListSecretVersions","environment",t.path.environment)+"/"+c("ListSecretVersions","name",t.path.name)+"/versions",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})}}}var Ks={};We(Ks,{client:()=>Jw});function Jw(e){return{async listBuckets(t){return e.send({op:"ListBuckets",method:"GET",path:"/storage/buckets",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async getBucket(t){return e.send({op:"GetBucket",method:"GET",path:"/storage/buckets/"+c("GetBucket","bucket",t.path.bucket),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async putBucket(t){return e.send({op:"PutBucket",method:"PUT",path:"/storage/buckets/"+c("PutBucket","bucket",t.path.bucket),auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteBucket(t){return e.send({op:"DeleteBucket",method:"DELETE",path:"/storage/buckets/"+c("DeleteBucket","bucket",t.path.bucket),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async copyObject(t){return e.send({op:"CopyObject",method:"POST",path:"/storage/buckets/"+c("CopyObject","bucket",t.path.bucket)+"/copy",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async moveObject(t){return e.send({op:"MoveObject",method:"POST",path:"/storage/buckets/"+c("MoveObject","bucket",t.path.bucket)+"/move",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listObjects(t){return e.send({op:"ListObjects",method:"GET",path:"/storage/buckets/"+c("ListObjects","bucket",t.path.bucket)+"/objects",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async getObject(t){return e.send({op:"GetObject",method:"GET",path:"/storage/buckets/"+c("GetObject","bucket",t.path.bucket)+"/objects/"+c("GetObject","path",t.path.path),auth:[["SecretKeyAuth"]],answers:{200:"raw",206:"raw",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async putObject(t){return e.send({op:"PutObject",method:"PUT",path:"/storage/buckets/"+c("PutObject","bucket",t.path.bucket)+"/objects/"+c("PutObject","path",t.path.path),auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},query:t.query,headers:t.headers,body:{kind:"raw",contentType:t.contentType??"application/octet-stream",value:t.body},signal:t.signal})},async deleteObject(t){return e.send({op:"DeleteObject",method:"DELETE",path:"/storage/buckets/"+c("DeleteObject","bucket",t.path.bucket)+"/objects/"+c("DeleteObject","path",t.path.path),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async headObject(t){return e.send({op:"HeadObject",method:"HEAD",path:"/storage/buckets/"+c("HeadObject","bucket",t.path.bucket)+"/objects/"+c("HeadObject","path",t.path.path),auth:[["SecretKeyAuth"]],answers:{200:"empty",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async createSignedUrl(t){return e.send({op:"CreateSignedUrl",method:"POST",path:"/storage/buckets/"+c("CreateSignedUrl","bucket",t.path.bucket)+"/signed-urls",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async createUploadUrl(t){return e.send({op:"CreateUploadUrl",method:"POST",path:"/storage/buckets/"+c("CreateUploadUrl","bucket",t.path.bucket)+"/upload-urls",auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPublicObject(t){return e.send({op:"GetPublicObject",method:"GET",path:"/storage/public/"+c("GetPublicObject","bucket",t.path.bucket)+"/"+c("GetPublicObject","path",t.path.path),auth:[],answers:{200:"raw",206:"raw",302:"redirect",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async headPublicObject(t){return e.send({op:"HeadPublicObject",method:"HEAD",path:"/storage/public/"+c("HeadPublicObject","bucket",t.path.bucket)+"/"+c("HeadPublicObject","path",t.path.path),auth:[],answers:{200:"empty",302:"redirect",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async getSignedObject(t){return e.send({op:"GetSignedObject",method:"GET",path:"/storage/signed/"+c("GetSignedObject","bucket",t.path.bucket)+"/"+c("GetSignedObject","path",t.path.path),auth:[],answers:{200:"raw",206:"raw",302:"redirect",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async putSignedObject(t){return e.send({op:"PutSignedObject",method:"PUT",path:"/storage/signed/"+c("PutSignedObject","bucket",t.path.bucket)+"/"+c("PutSignedObject","path",t.path.path),auth:[],answers:{200:"json",201:"json"},query:t.query,headers:t.headers,body:{kind:"raw",contentType:t.contentType??"application/octet-stream",value:t.body},signal:t.signal})},async headSignedObject(t){return e.send({op:"HeadSignedObject",method:"HEAD",path:"/storage/signed/"+c("HeadSignedObject","bucket",t.path.bucket)+"/"+c("HeadSignedObject","path",t.path.path),auth:[],answers:{200:"empty",302:"redirect",304:"empty"},query:t.query,headers:t.headers,signal:t.signal})},async getStorageStats(t){return e.send({op:"GetStorageStats",method:"GET",path:"/storage/stats",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async upload(t){return e.send({op:"Upload",method:"POST",path:"/storage/upload/"+c("Upload","machine",t.path.machine)+"/"+c("Upload","route",t.path.route),auth:[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]],answers:{},body:{kind:"raw",contentType:t.contentType??"multipart/form-data",value:t.body},signal:t.signal})}}}var Gs={};We(Gs,{client:()=>Ww});function Ww(e){return{async listActions(t){return e.send({op:"ListActions",method:"GET",path:"/stores/actions",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getAction(t){return e.send({op:"GetAction",method:"GET",path:"/stores/actions/"+c("GetAction","action_id",t.path.action_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async confirmAction(t){return e.send({op:"ConfirmAction",method:"POST",path:"/stores/actions/"+c("ConfirmAction","action_id",t.path.action_id)+"/confirm",auth:[["SecretKeyAuth"]],answers:{200:"json",202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async declineAction(t){return e.send({op:"DeclineAction",method:"POST",path:"/stores/actions/"+c("DeclineAction","action_id",t.path.action_id)+"/decline",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async getAppleAccount(t){return e.send({op:"GetAppleAccount",method:"GET",path:"/stores/apple",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async disconnectApple(t){return e.send({op:"DisconnectApple",method:"DELETE",path:"/stores/apple",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async checkAppleAccount(t){return e.send({op:"CheckAppleAccount",method:"POST",path:"/stores/apple/check",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async createAppleGrant(t){return e.send({op:"CreateAppleGrant",method:"POST",path:"/stores/apple/grants",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getSandboxReadiness(t){return e.send({op:"GetSandboxReadiness",method:"GET",path:"/stores/apple/readiness",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async listSandboxTesters(t){return e.send({op:"ListSandboxTesters",method:"GET",path:"/stores/apple/sandbox-testers",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async clearSandboxPurchaseHistory(t){return e.send({op:"ClearSandboxPurchaseHistory",method:"POST",path:"/stores/apple/sandbox-testers/clear-purchase-history",auth:[["SecretKeyAuth"]],answers:{202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async updateSandboxTester(t){return e.send({op:"UpdateSandboxTester",method:"PATCH",path:"/stores/apple/sandbox-testers/"+c("UpdateSandboxTester","tester_id",t.path.tester_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listApps(t){return e.send({op:"ListApps",method:"GET",path:"/stores/apps",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async listFeedback(t){return e.send({op:"ListFeedback",method:"GET",path:"/stores/apps/"+c("ListFeedback","app_id",t.path.app_id)+"/feedback",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getFeedback(t){return e.send({op:"GetFeedback",method:"GET",path:"/stores/apps/"+c("GetFeedback","app_id",t.path.app_id)+"/feedback/"+c("GetFeedback","kind",t.path.kind)+"/"+c("GetFeedback","feedback_id",t.path.feedback_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listGroups(t){return e.send({op:"ListGroups",method:"GET",path:"/stores/apps/"+c("ListGroups","app_id",t.path.app_id)+"/groups",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async createGroup(t){return e.send({op:"CreateGroup",method:"POST",path:"/stores/apps/"+c("CreateGroup","app_id",t.path.app_id)+"/groups",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async linkApp(t){return e.send({op:"LinkApp",method:"POST",path:"/stores/apps/"+c("LinkApp","app_id",t.path.app_id)+"/link",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getListing(t){return e.send({op:"GetListing",method:"GET",path:"/stores/apps/"+c("GetListing","app_id",t.path.app_id)+"/listing",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async setListing(t){return e.send({op:"SetListing",method:"PUT",path:"/stores/apps/"+c("SetListing","app_id",t.path.app_id)+"/listing",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async planListing(t){return e.send({op:"PlanListing",method:"POST",path:"/stores/apps/"+c("PlanListing","app_id",t.path.app_id)+"/listing/plan",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async createPackage(t){return e.send({op:"CreatePackage",method:"POST",path:"/stores/apps/"+c("CreatePackage","app_id",t.path.app_id)+"/packages",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async uploadScreenshot(t){return e.send({op:"UploadScreenshot",method:"PUT",path:"/stores/apps/"+c("UploadScreenshot","app_id",t.path.app_id)+"/screenshots",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,query:t.query,headers:t.headers,body:{kind:"raw",contentType:t.contentType??"image/png",value:t.body},signal:t.signal})},async getReviewInfo(t){return e.send({op:"GetReviewInfo",method:"GET",path:"/stores/apps/"+c("GetReviewInfo","app_id",t.path.app_id)+"/testflight/review-info",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async setReviewInfo(t){return e.send({op:"SetReviewInfo",method:"PUT",path:"/stores/apps/"+c("SetReviewInfo","app_id",t.path.app_id)+"/testflight/review-info",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getUploadKey(t){return e.send({op:"GetUploadKey",method:"GET",path:"/stores/apps/"+c("GetUploadKey","app_id",t.path.app_id)+"/upload-key",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getAppStoreVersion(t){return e.send({op:"GetAppStoreVersion",method:"GET",path:"/stores/apps/"+c("GetAppStoreVersion","app_id",t.path.app_id)+"/version",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async prepareAppStoreVersion(t){return e.send({op:"PrepareAppStoreVersion",method:"PUT",path:"/stores/apps/"+c("PrepareAppStoreVersion","app_id",t.path.app_id)+"/version",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async planPhasedRelease(t){return e.send({op:"PlanPhasedRelease",method:"POST",path:"/stores/apps/"+c("PlanPhasedRelease","app_id",t.path.app_id)+"/version/phased-release",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async planReleaseVersion(t){return e.send({op:"PlanReleaseVersion",method:"POST",path:"/stores/apps/"+c("PlanReleaseVersion","app_id",t.path.app_id)+"/version/release",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async planSubmitReview(t){return e.send({op:"PlanSubmitReview",method:"POST",path:"/stores/apps/"+c("PlanSubmitReview","app_id",t.path.app_id)+"/version/submit",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async planWithdrawReview(t){return e.send({op:"PlanWithdrawReview",method:"POST",path:"/stores/apps/"+c("PlanWithdrawReview","app_id",t.path.app_id)+"/version/withdraw",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async getAppVitals(t){return e.send({op:"GetAppVitals",method:"GET",path:"/stores/apps/"+c("GetAppVitals","app_id",t.path.app_id)+"/vitals",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getAppWebhook(t){return e.send({op:"GetAppWebhook",method:"GET",path:"/stores/apps/"+c("GetAppWebhook","app_id",t.path.app_id)+"/webhook",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async makeAppWebhook(t){return e.send({op:"MakeAppWebhook",method:"POST",path:"/stores/apps/"+c("MakeAppWebhook","app_id",t.path.app_id)+"/webhook",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async pingAppWebhook(t){return e.send({op:"PingAppWebhook",method:"POST",path:"/stores/apps/"+c("PingAppWebhook","app_id",t.path.app_id)+"/webhook/ping",auth:[["SecretKeyAuth"]],answers:{202:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async downloadSignedBundle(t){return e.send({op:"DownloadSignedBundle",method:"GET",path:"/stores/bundles",auth:[],answers:{200:"raw"},query:t.query,signal:t.signal})},async getConnectPage(t){return e.send({op:"GetConnectPage",method:"GET",path:"/stores/connect",auth:[],answers:{200:"raw"},signal:t?.signal})},async connectAppleKey(t){return e.send({op:"ConnectAppleKey",method:"POST",path:"/stores/connect",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getGoogleAccount(t){return e.send({op:"GetGoogleAccount",method:"GET",path:"/stores/google",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async connectGoogle(t){return e.send({op:"ConnectGoogle",method:"POST",path:"/stores/google",auth:[["SecretKeyAuth"]],answers:{200:"json",201:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async disconnectGoogle(t){return e.send({op:"DisconnectGoogle",method:"DELETE",path:"/stores/google",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async checkGoogleAccount(t){return e.send({op:"CheckGoogleAccount",method:"POST",path:"/stores/google/check",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async deleteGroup(t){return e.send({op:"DeleteGroup",method:"DELETE",path:"/stores/groups/"+c("DeleteGroup","group_id",t.path.group_id),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async renameGroup(t){return e.send({op:"RenameGroup",method:"PATCH",path:"/stores/groups/"+c("RenameGroup","group_id",t.path.group_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async addGroupBuild(t){return e.send({op:"AddGroupBuild",method:"POST",path:"/stores/groups/"+c("AddGroupBuild","group_id",t.path.group_id)+"/builds",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listTesters(t){return e.send({op:"ListTesters",method:"GET",path:"/stores/groups/"+c("ListTesters","group_id",t.path.group_id)+"/testers",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async setTesters(t){return e.send({op:"SetTesters",method:"PUT",path:"/stores/groups/"+c("SetTesters","group_id",t.path.group_id)+"/testers",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listPackages(t){return e.send({op:"ListPackages",method:"GET",path:"/stores/packages",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async getPackage(t){return e.send({op:"GetPackage",method:"GET",path:"/stores/packages/"+c("GetPackage","package_id",t.path.package_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async uploadArtifact(t){return e.send({op:"UploadArtifact",method:"PUT",path:"/stores/packages/"+c("UploadArtifact","package_id",t.path.package_id)+"/artifact",auth:[],answers:{200:"json"},headers:t.headers,body:{kind:"raw",contentType:t.contentType??"application/octet-stream",value:t.body},signal:t.signal})},async planBetaReview(t){return e.send({op:"PlanBetaReview",method:"POST",path:"/stores/packages/"+c("PlanBetaReview","package_id",t.path.package_id)+"/beta-review",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async listDeliveries(t){return e.send({op:"ListDeliveries",method:"GET",path:"/stores/packages/"+c("ListDeliveries","package_id",t.path.package_id)+"/deliveries",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async deliver(t){return e.send({op:"Deliver",method:"POST",path:"/stores/packages/"+c("Deliver","package_id",t.path.package_id)+"/deliveries",auth:[["SecretKeyAuth"]],answers:{200:"json",202:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getSignedBundleLink(t){return e.send({op:"GetSignedBundleLink",method:"POST",path:"/stores/packages/"+c("GetSignedBundleLink","package_id",t.path.package_id)+"/deliveries/"+c("GetSignedBundleLink","channel",t.path.channel)+"/bundle-link",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async planExpire(t){return e.send({op:"PlanExpire",method:"POST",path:"/stores/packages/"+c("PlanExpire","package_id",t.path.package_id)+"/expire",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async planExportCompliance(t){return e.send({op:"PlanExportCompliance",method:"POST",path:"/stores/packages/"+c("PlanExportCompliance","package_id",t.path.package_id)+"/export-compliance",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async setWhatToTest(t){return e.send({op:"SetWhatToTest",method:"PUT",path:"/stores/packages/"+c("SetWhatToTest","package_id",t.path.package_id)+"/what-to-test",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async takeAppleWebhook(t){return e.send({op:"TakeAppleWebhook",method:"POST",path:"/stores/webhooks/apple/"+c("TakeAppleWebhook","app_id",t.path.app_id),auth:[],answers:{200:"empty"},headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getAppleSession(t){return e.send({op:"GetAppleSession",method:"GET",path:"/stores/apple/session",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async disconnectAppleSession(t){return e.send({op:"DisconnectAppleSession",method:"DELETE",path:"/stores/apple/session",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async checkAppleSession(t){return e.send({op:"CheckAppleSession",method:"POST",path:"/stores/apple/session/check",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async createAppleIdGrant(t){return e.send({op:"CreateAppleIDGrant",method:"POST",path:"/stores/apple/session/grants",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t?.headers,signal:t?.signal})},async getAppleIdPage(t){return e.send({op:"GetAppleIDPage",method:"GET",path:"/stores/connect/apple-id",auth:[],answers:{200:"raw"},signal:t?.signal})},async signInAppleId(t){return e.send({op:"SignInAppleID",method:"POST",path:"/stores/connect/apple-id",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async submitAppleIdCode(t){return e.send({op:"SubmitAppleIDCode",method:"POST",path:"/stores/connect/apple-id/code",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async chooseAppleIdTeam(t){return e.send({op:"ChooseAppleIDTeam",method:"POST",path:"/stores/connect/apple-id/team",auth:[],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getAppReview(t){return e.send({op:"GetAppReview",method:"GET",path:"/stores/apps/"+c("GetAppReview","app_id",t.path.app_id)+"/review",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async getReviewAttachment(t){return e.send({op:"GetReviewAttachment",method:"GET",path:"/stores/apps/"+c("GetReviewAttachment","app_id",t.path.app_id)+"/review/threads/"+c("GetReviewAttachment","thread_id",t.path.thread_id)+"/attachments/"+c("GetReviewAttachment","attachment_id",t.path.attachment_id),auth:[["SecretKeyAuth"]],answers:{200:"raw"},signal:t.signal})},async setReviewDraft(t){return e.send({op:"SetReviewDraft",method:"PUT",path:"/stores/apps/"+c("SetReviewDraft","app_id",t.path.app_id)+"/review/threads/"+c("SetReviewDraft","thread_id",t.path.thread_id)+"/draft",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async sendReviewDraft(t){return e.send({op:"SendReviewDraft",method:"POST",path:"/stores/apps/"+c("SendReviewDraft","app_id",t.path.app_id)+"/review/threads/"+c("SendReviewDraft","thread_id",t.path.thread_id)+"/draft/send",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async getAppPrivacy(t){return e.send({op:"GetAppPrivacy",method:"GET",path:"/stores/apps/"+c("GetAppPrivacy","app_id",t.path.app_id)+"/privacy",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async setAppPrivacy(t){return e.send({op:"SetAppPrivacy",method:"PUT",path:"/stores/apps/"+c("SetAppPrivacy","app_id",t.path.app_id)+"/privacy",auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async makeAppRecord(t){return e.send({op:"MakeAppRecord",method:"POST",path:"/stores/apps/"+c("MakeAppRecord","app_id",t.path.app_id)+"/record",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async removeAppRecord(t){return e.send({op:"RemoveAppRecord",method:"DELETE",path:"/stores/apps/"+c("RemoveAppRecord","app_id",t.path.app_id)+"/record",auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})},async listMadeAppleKeys(t){return e.send({op:"ListMadeAppleKeys",method:"GET",path:"/stores/apple/keys",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async makeAppleKey(t){return e.send({op:"MakeAppleKey",method:"POST",path:"/stores/apple/keys",auth:[["SecretKeyAuth"]],answers:{201:"json"},idempotent:!0,headers:t.headers,body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async revokeMadeAppleKey(t){return e.send({op:"RevokeMadeAppleKey",method:"DELETE",path:"/stores/apple/keys/"+c("RevokeMadeAppleKey","key_id",t.path.key_id),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async shareAppleSession(t){return e.send({op:"ShareAppleSession",method:"PUT",path:"/stores/apple/session/shares/"+c("ShareAppleSession","environment",t.path.environment),auth:[["SecretKeyAuth"]],answers:{200:"json"},idempotent:!0,headers:t.headers,signal:t.signal})},async unshareAppleSession(t){return e.send({op:"UnshareAppleSession",method:"DELETE",path:"/stores/apple/session/shares/"+c("UnshareAppleSession","environment",t.path.environment),auth:[["SecretKeyAuth"]],answers:{204:"empty"},idempotent:!0,headers:t.headers,signal:t.signal})}}}var Fa={attempts:3,maxWaitSeconds:30},Vw=new Set([429,502,503,504]);function Ti(e,t=Fa){let n=t.sleep??Xw;return{async send(s){let a=Hw(s),r=a.body,i=!r||r.kind!=="raw"||Vn(r.value),o=(a.method==="GET"||a.method==="HEAD"||a.idempotent===!0)&&i;for(let l=1;;l++)try{return await e.send(a)}catch(d){if(!o||l>=t.attempts||!(d instanceof j)||a.signal?.aborted)throw d;let p=Yw(d,l,t.maxWaitSeconds);if(p===void 0)throw d;await n(p*1e3,a.signal)}}}}function Hw(e){return e.idempotent?Object.entries(e.headers??{}).some(([n,s])=>n.toLowerCase()==="idempotency-key"&&s!==void 0&&s!==null&&s!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":Zw()}}:e}function Yw(e,t,n){return Vw.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=n?e.retryAfter:void 0:Math.min(.5*2**(t-1),n)*(.8+Math.random()*.4):void 0}function Xw(e,t){return new Promise((n,s)=>{if(t?.aborted)return s(t.reason);let a=()=>{clearTimeout(r),s(t?.reason)},r=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}function Zw(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}import{hostname as Qw}from"node:os";var ev=new Set(["apikey","authorization",Pi]);function tv(e){let t={accept:"application/json"};for(let[n,s]of Object.entries(e??{}))s!=null&&!ev.has(n.toLowerCase())&&(t[n.toLowerCase()]=String(s));return t}function nv(e,t,n){let s=null;try{s=n.startsWith("/")?new URL(n,e):null}catch{s=null}if(!s||s.origin!==new URL(e).origin)throw new j({op:t,status:0,code:"invalid_path",message:`${t}: a module's path stays at its environment's address`});return s.href}async function sv(e){let t=e.status===204||e.status===304?"":await e.text();if(t!=="")try{return JSON.parse(t)}catch{return t}}function av(e,t,n){let s=n??{},a=Number(t.headers.get("retry-after")??"");return new j({op:e,status:t.status,code:typeof s.error=="string"?s.error:`http_${t.status}`,message:Ja(n,t.status),requestId:typeof s.request_id=="string"?s.request_id:t.headers.get("x-request-id")??void 0,retryAfter:Number.isFinite(a)&&a>0?a:typeof s.retry_after=="number"?s.retry_after:void 0,body:n})}var wn=class{bytes;contentType;constructor(t,n){this.bytes=t,this.contentType=n}};function rv(e){return e instanceof wn?{headers:{"content-type":e.contentType,"content-length":String(e.bytes.size)},body:e.bytes}:e===void 0?{headers:{}}:{headers:{"content-type":"application/json"},body:JSON.stringify(e)}}async function ye(e,t,n,s,a,r){let i=`${n} ${s}`,o=rv(a),l=await e.module(nv(et(e.cloud,t),i,s),{method:n,headers:{...tv(r),...o.headers},body:o.body}),d=await sv(l);if(l.status>=200&&l.status<300)return{status:l.status,body:Oa(d),etag:l.headers.get("etag")??void 0};throw av(i,l,d)}var iv=10080*60*1e3;async function Ei(e,t,n=!1){let s=await e.state.personalKey(t);if(!n&&s&&Date.parse(s.expires_at)-e.io.now()>iv)return s;let a=await e.post(`/environments/${D("the environment's ref",t)}/personal-key`,{host:Qw().slice(0,100)||"computer"});return await e.state.keepPersonalKey(t,a),a}function Ja(e,t){let n=e??{},s=typeof n.error_description=="string"?n.error_description:`the module answered ${t}`,a=Array.isArray(n.field_errors)?n.field_errors.flatMap(r=>{let{pointer:i,message:o}=r??{};return typeof o=="string"?[`${typeof i=="string"&&i!==""?`${i}: `:""}${o}`]:[]}):[];return a.length>0?`${s}: ${a.join("; ")}`:s}import{relative as ov}from"node:path";async function Us(e,t){let n=await e.run("git",["rev-parse","--show-toplevel"],{cwd:t});if(n.code!==0)return null;let s=n.stdout.trim(),a=await e.run("git",["remote","get-url","origin"],{cwd:t}),r=await e.run("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t}),i=r.code===0?r.stdout.trim():"";return{root:s,repository:a.code===0?lv(a.stdout.trim()):void 0,branch:i!==""&&i!=="HEAD"?i:void 0,path:ov(s,t).split("\\").join("/")}}function lv(e){let t=/^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/.exec(e);return t?`${t[1]}/${t[2]}`:void 0}async function zs(e,t){let n=await Re(e);return new Map(n.filter(s=>s.project_id===t.project_id).map(s=>[s.ref,s.slug]))}function Yn(e,t){return t?e.get(t.ref)??t.ref:""}var Ue="main";async function Re(e){let[t,n]=await Promise.all([e.get("/environments"),e.get("/orgs")]),s=new Map(n.organizations.map(a=>[a.id,a.name]));return t.environments.map(a=>({...a,org_name:s.get(a.organization_id)??a.organization_id}))}function _e(e){return{org_id:e.organization_id,org_name:e.org_name,project_id:e.project_id,project_name:e.project_name,env_ref:e.ref,env_slug:e.slug,env_name:e.name}}function q(e){return`${e.org_name} \u203A ${e.project_name} \u203A ${e.env_name}${e.env_name!==e.env_slug?` (${e.env_slug})`:""}`}function vn(e){return(e.env.PALBASE_TOKEN??"").startsWith("pbe_")}async function Oi(e){let[t]=await Re(e.studio);if(!t)throw new y("token_refused","Studio names no environment for PALBASE_TOKEN",{hint:"mint another: palbase env:tokens:create"});let n=_e(t),s=i=>new y("token_environment",`PALBASE_TOKEN is ${q(n)}'s environment token: it acts there alone, not in ${i}`,{hint:"mint one there: palbase env:tokens:create -P <project> -E <env>"}),{project:a,env:r}=e.global;if(a!==void 0&&t.project_id!==a&&!ji(t.project_name,a.slice(a.indexOf("/")+1)))throw s(a);if(r!==void 0&&r!==t.slug&&r!==t.ref)throw s(r);if(a===void 0&&r===void 0){let i=await e.state.targetFor(e.io.cwd);if(i&&i.target.env_ref!==t.ref)throw s(`${q(i.target)}, chosen for ${i.dir}`)}return t}async function f(e){if(vn(e.io))return _e(await Oi(e));let{project:t,env:n}=e.global;if(t!==void 0||n!==void 0){let i=await Re(e.studio),o;if(t!==void 0)o=_n(i,t);else{let l=await e.state.targetFor(e.io.cwd);if(!l)throw Ci("-E names an environment of the project chosen here, and none is chosen: add -P <project>");o=i.filter(d=>d.project_id===l.target.project_id)}if(n!==void 0){let l=o.find(d=>d.slug===n||d.ref===n);if(!l)throw new y("no_such_environment",`the project has no environment ${JSON.stringify(n)}`,{hint:`its environments: ${o.map(d=>d.slug).join(", ")}`});return _e(l)}return o.length===1?_e(o[0]):_e(await Mp(e,o,"Which environment?"))}let s=await e.state.targetFor(e.io.cwd);if(s)return s.target;if(!e.interactive)throw Ci("no environment is chosen for this directory");let a=await Re(e.studio);if(a.length===0)throw new y("no_environments","your account reaches no environment yet",{hint:"make one: palbase projects:create <name>"});let r=_e(await Mp(e,a,"Which environment?"));return e.out.note(`Acting on ${q(r)}. palbase use remembers it for this directory.`),r}function _n(e,t){let n=e.filter(l=>l.project_id===t);if(n.length>0)return n;let s=t.indexOf("/"),[a,r]=s>=0?[t.slice(0,s),t.slice(s+1)]:[void 0,t],i=e.filter(l=>ji(l.project_name,r)&&(a===void 0||ji(l.org_name,a)||l.organization_id===a)),o=new Set(i.map(l=>l.project_id));if(o.size===0)throw new y("no_such_project",`no project ${JSON.stringify(t)} among yours`,{hint:"palbase projects:list shows them"});if(o.size>1){let l=[...new Set(i.map(d=>`${d.org_name}/${d.project_name}`))].join(", ");throw new y("ambiguous_project",`${JSON.stringify(t)} is a project in more than one organization: ${l}`,{hint:"name it as org/project"})}return i}async function v(e,t,n,s){e.out.note(`${q(t)}: ${n}`);let a=t.env_slug===Ue;if(!a&&s===void 0||e.global.yes)return;if(!e.interactive){let i=vn(e.io)?"confirm with -y: with PALBASE_TOKEN, -y is the go-ahead (the CLI asks no one else, and a person's yes elsewhere is not one)":"confirm with -y";throw new y("confirmation_needed",a?`${t.project_name} \u203A ${t.env_name} is the project's production environment`:s,{hint:i})}let r=(await e.io.prompt(K(`${a?`This is ${t.project_name}'s production environment`:s}. Go ahead? [y/N] `))).trim().toLowerCase();if(r!=="y"&&r!=="yes")throw new y("cancelled","nothing was changed")}async function Mp(e,t,n){if(!e.interactive)throw Ci(`${n.replace(/\?$/,"")}: ${t.map(s=>`${s.project_name}/${s.slug}`).join(", ")}`);for(t.forEach((s,a)=>e.out.note(` ${String(a+1).padStart(2)}) ${q(_e(s))}`));;){let s=(await e.io.prompt(`${n} [1-${t.length}] `)).trim(),a=Number(s);if(Number.isInteger(a)&&a>=1&&a<=t.length)return t[a-1];e.out.note(`answer with a number from 1 to ${t.length}`)}}function Ci(e){return new y("no_target",e,{hint:"choose one here with palbase use, or pass -P <project> -E <env>"})}function ji(e,t){return e.localeCompare(t,void 0,{sensitivity:"accent"})===0}import{randomUUID as pv}from"node:crypto";import{readFile as dv}from"node:fs/promises";import{resolve as uv}from"node:path";var cv=6,Mi=0,xp=[];async function hv(e){Mi<cv?Mi++:await new Promise(t=>xp.push(t));try{return await e()}finally{let t=xp.shift();t?t():Mi--}}async function qe(e,t,n,s,a,r){return hv(()=>ye(e.studio,t.env_ref,n,s,a,r))}async function h(e,t,n,s,a,r){return(await qe(e,t,n,s,a,r)).body}async function Ne(e,t,n){let s=await qe(e,t,"GET",n);return{body:s.body,etag:s.etag}}function Te(e){return e?{"if-match":e}:void 0}function C(){return{"idempotency-key":pv()}}function k(e){return encodeURIComponent(e)}function Zt(e){return e.map(t=>{let n=t.indexOf("=");if(n<=0)throw g(`a setting is key=value, not ${JSON.stringify(t)}`);let s=t.slice(0,n).split(".");if(s.some(a=>a===""||a==="__proto__"||a==="constructor"||a==="prototype"))throw g(`${JSON.stringify(t.slice(0,n))} is not a key`);return{path:s,value:St(t.slice(n+1))}})}function St(e){try{return JSON.parse(e)}catch{return e}}function Qt(e,t){let n=structuredClone(e);for(let{path:s,value:a}of t){let r=n;for(let i of s.slice(0,-1)){let o=r[i];(typeof o!="object"||o===null)&&(r[i]={}),r=r[i]}r[s[s.length-1]]=a}return n}function Dt(e,t){return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!Me(e[n],t[n])).sort()}function Ip(e){return JSON.stringify(e,(t,n)=>n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.entries(n).sort(([s],[a])=>s<a?-1:s>a?1:0)):n)}function Me(e,t){return Ip(e)===Ip(t)}function Ee(e){return e===void 0?"(not set)":typeof e=="string"&&e!==""?e:JSON.stringify(e)}function Xn(e,t){let n=Object.keys(t).sort(),s=Math.max(0,...n.map(a=>a.length));for(let a of n)e.out.line(`${a.padEnd(s)} ${Ee(t[a])}`)}function ze(e,t,n){e.out.result({settings:n,changed:[]},()=>e.out.line(`Nothing to change: ${t} already ${t.endsWith("s")?"are":"is"} so.`))}async function be(e,t,n){let s;if(t!==void 0&&t!=="-")try{s=await dv(uv(e.io.cwd,t),"utf8")}catch(a){throw new y("unreadable_file",`${t} could not be read: ${a instanceof Error?a.message:String(a)}`)}else e.io.interactive&&e.out.note(`Reading ${n} from stdin; end it with Ctrl-D.`),s=await e.io.readStdin();if(s.trim()==="")throw g(`no ${n} was given`,t===void 0?"pass --file <path>, or pipe it in":void 0);return s}function ue(e,t){try{return JSON.parse(e)}catch(n){throw g(`${t} is not JSON: ${n instanceof Error?n.message:String(n)}`)}}async function xe(e,t){e.io.interactive&&e.out.note(`Paste ${t}, then Ctrl-D (it is read from stdin, never from the command line):`);let n=(await e.io.readStdin()).trim();if(n==="")throw g(`no ${t} was piped in`,"pipe it in: palbase \u2026 < file");return n}function Zn(e){if(e.flags.enable===!0&&e.flags.disable===!0)throw g("--enable and --disable are one or the other");if(e.flags.enable===!0)return!0;if(e.flags.disable===!0)return!1}function en(e,t){if(e!==void 0){if(e==="yes"||e==="true")return!0;if(e==="no"||e==="false")return!1;throw g(`--${t} is yes or no`)}}function re(e){return e===void 0?void 0:(Array.isArray(e)?e:[e]).flatMap(n=>String(n).split(",")).map(n=>n.trim()).filter(n=>n!=="")}function ne(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw g(`--${t} is a whole number`);return n}var Bs={enable:{type:"boolean",description:"turn it on"},disable:{type:"boolean",description:"turn it off"}};async function V(e,t,n){try{await n(),e.done(t)}catch(s){if(!(s instanceof j))throw s;e.left(`${t}: refused \u2014 ${s.message}`)}}function pe(e,t){return e.filter(n=>n.key.startsWith(t)).map(n=>({...n,name:n.key.slice(t.length)}))}function xi(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>!(t==null||t===""||Array.isArray(t)&&t.length===0)))}import{randomBytes as ad}from"node:crypto";import{chmod as Lv,lstat as Dv,readFile as Qp,rename as qv,writeFile as ed}from"node:fs/promises";function Lp(){let e=globalThis;if(typeof e.document<"u"||e.navigator?.product==="ReactNative")return!0;let t=e.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}var qt=class extends Error{code;constructor(t,n){super(n),this.name="FieldError",this.code=t}},Wa="pbe1.",mv="pbl1.",gv=6e4,Ii="[A-Za-z_][A-Za-z0-9_$]{0,62}",fv=new RegExp(`^${Ii}\\.${Ii}(\\.${Ii})?$`);function yv(e){return fv.test(e)}var Fs=class{crypto;keys=new Map;lookupKey;timer;opts;now;constructor(t){this.opts=t,this.now=t.now??Date.now}get loaded(){return this.lookupKey!==void 0}async load(t){this.crypto??=await import("node:crypto"),this.take(await this.opts.fetch(t)),this.timer===void 0&&(this.timer=setInterval(()=>{this.opts.fetch().then(n=>this.take(n),()=>{})},gv),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}take(t){let n=new Map;for(let s of t.keys)n.set(s.id,{id:s.id,key:Buffer.from(s.key,"base64url"),activatesAt:Date.parse(s.activates_at)});this.keys=n,this.lookupKey=Buffer.from(t.lookup,"base64url")}ready(){if(this.crypto===void 0||this.lookupKey===void 0)throw new qt("not_loaded","the project's field keys are not loaded: await palbase.fields.load() at startup");return this.crypto}currentKey(){this.ready();let t;for(let n of this.keys.values())n.activatesAt<=this.now()&&(t===void 0||n.activatesAt>=t.activatesAt)&&(t=n);if(t===void 0)throw new qt("unknown_key","the project has no field key in force");return t.id}encrypt(t,n){let s=this.ready();Li(t);let a=this.currentKey(),r=s.randomBytes(12);return bv(s,this.keys.get(a).key,r,a,t,n)}decrypt(t,n){let s=this.ready();if(Li(t),!n.startsWith(Wa))throw new qt("not_encrypted",`${t} holds a value that is not encrypted`);let a=n.slice(Wa.length),r=a.indexOf("."),i=r<0?a:a.slice(0,r),o=this.keys.get(i);if(o===void 0)throw new qt("unknown_key",`${t} was sealed with field key ${i}, which this project does not hold`);let l=Buffer.from(a.slice(r+1),"base64url");if(r<0||l.length<28||l.toString("base64url")!==a.slice(r+1))throw new qt("unopenable",`${t} holds a value that does not open here`);try{let d=s.createDecipheriv("aes-256-gcm",o.key,l.subarray(0,12));return d.setAAD(Dp(t)),d.setAuthTag(l.subarray(l.length-16)),Buffer.concat([d.update(l.subarray(12,l.length-16)),d.final()]).toString("utf8")}catch{throw new qt("unopenable",`${t} holds a value that does not open here: tampered, or another column's`)}}isEncrypted(t){return t.startsWith(Wa)}lookup(t,n){let s=this.ready();return Li(t),wv(s,this.lookupKey,t,n)}};function Li(e){if(!yv(e))throw new TypeError(`a field's address is table.column, or schema.table.column, not ${JSON.stringify(e)}`)}function Dp(e){return Buffer.from(`pbe1\0${e}`,"utf8")}function bv(e,t,n,s,a,r){let i=e.createCipheriv("aes-256-gcm",t,n);i.setAAD(Dp(a));let o=Buffer.concat([n,i.update(r,"utf8"),i.final(),i.getAuthTag()]);return`${Wa}${s}.${o.toString("base64url")}`}function wv(e,t,n,s){let a=e.createHmac("sha256",t);return a.update(`pbl1\0${n}\0`,"utf8"),a.update(s,"utf8"),`${mv}${a.digest("base64url")}`}var qi="pbt1.",ut="Palbase-Encryption";var Ya="x-palbase-encrypted",ke=class extends Error{code;constructor(t,n){super(n),this.name="TransitError",this.code=t}},tn=new TextEncoder,vv=new TextDecoder("utf-8",{fatal:!0}),ct=()=>{let e=globalThis.crypto?.subtle;if(!e)throw new Error("encrypted fields need WebCrypto (crypto.subtle): a secure context \u2014 https, or localhost");return e};function Ge(e){return new Uint8Array(new ArrayBuffer(e))}function ht(...e){let t=Ge(e.reduce((s,a)=>s+a.length,0)),n=0;for(let s of e)t.set(s,n),n+=s.length;return t}function $t(e){return ht(e)}function Ws(e,t){let n=Ge(t);for(let s=t-1;s>=0;s--)n[s]=e&255,e>>>=8;return n}function Vs(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Pt(e){let t=e.replace(/=+$/,"");if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)throw new ke("malformed","not base64url");let n=atob(t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4)),s=Ge(n.length);for(let a=0;a<n.length;a++)s[a]=n.charCodeAt(a);return s}var qp=ht(tn.encode("KEM"),Ws(32,2)),Js=ht(tn.encode("HPKE"),Ws(32,2),Ws(1,2),Ws(1,2)),Np=tn.encode("HPKE-v1"),_v=16,kv=12,Sv=32,Kp=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function Gp(e,t){let n=await ct().importKey("raw",e.length===0?Ge(32):$t(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await ct().sign("HMAC",n,$t(t)))}async function Va(e,t,n,s){return Gp(t,ht(Np,e,tn.encode(n),s))}async function Di(e,t,n,s,a){let r=ht(Ws(a,2),Np,e,tn.encode(n),s),i=Ge(a),o=Ge(0);for(let l=1,d=0;d<a;l++)o=await Gp(t,ht(o,r,Uint8Array.of(l))),i.set(o.subarray(0,Math.min(o.length,a-d)),d),d+=o.length;return i}async function Up(e){if(e.length!==32)throw new ke("malformed","an X25519 private key is 32 bytes");return ct().importKey("pkcs8",ht(Kp,e),{name:"X25519"},!1,["deriveBits"])}async function zp(e){if(e.length!==32)throw new ke("malformed","an X25519 public key is 32 bytes");return ct().importKey("raw",$t(e),{name:"X25519"},!1,[])}async function Bp(e,t){return new Uint8Array(await ct().deriveBits({name:"X25519",public:t},e,256))}async function Fp(e,t,n){let s=await Va(qp,Ge(0),"eae_prk",e);return Di(qp,s,"shared_secret",ht(t,n),Sv)}async function Jp(e,t){let n=await Va(Js,Ge(0),"psk_id_hash",Ge(0)),s=await Va(Js,Ge(0),"info_hash",t),a=ht(Uint8Array.of(0),n,s),r=await Va(Js,e,"secret",Ge(0));return{key:await Di(Js,r,"key",a,_v),nonce:await Di(Js,r,"base_nonce",a,kv)}}async function Xa(e,t,n,s,a){let r=await ct().importKey("raw",$t(t),"AES-GCM",!1,[e]);return new Uint8Array(await ct()[e]({name:"AES-GCM",iv:$t(n),additionalData:$t(s)},r,$t(a)))}async function Ni(e,t,n,s=Ge(0),a){let r,i;if(a)r=await Up(a.privateKey),i=$t(a.publicKey);else{let p=await ct().generateKey({name:"X25519"},!0,["deriveBits"]);r=p.privateKey,i=new Uint8Array(await ct().exportKey("raw",p.publicKey))}let o=await Fp(await Bp(r,await zp(e)),i,e),{key:l,nonce:d}=await Jp(o,t);return{enc:i,ct:await Xa("encrypt",l,d,s,n)}}async function $v(e,t,n,s,a,r=Ge(0)){if(n.length!==32)throw new ke("malformed","an encapsulated X25519 key is 32 bytes");try{let i=await Fp(await Bp(await Up(e),await zp(n)),n,t),{key:o,nonce:l}=await Jp(i,s);return await Xa("decrypt",o,l,r,a)}catch{throw new ke("unopenable","the request's key does not open with the project's key it names")}}async function Wp(e){let t=await ct().importKey("pkcs8",ht(Kp,e),{name:"X25519"},!0,["deriveBits"]),n=await ct().exportKey("jwk",t);return Pt(n.x)}function Za(e,t,n,s=[]){if(s.some(a=>a.includes("\0")))throw new ke("malformed","a path's value holds no NUL");return tn.encode(["palbase-encryption","1",e,t.toUpperCase(),Pv(n),...s].join("\0"))}function Pv(e){return e.replace(/\{[^/{}]*\}/g,"{}")}async function Vp(e,t,n,s={}){let a=s.key?$t(s.key):crypto.getRandomValues(Ge(32)),{enc:r,ct:i}=await Ni(t,n,a,Ge(0),s.ephemeral);return{kid:e,key:a,header:`1.${e}.${Vs(r)}.${Vs(i)}`}}function Ki(e){let t=e.trim().split(".");if(t.length!==4||t[0]!=="1"||!/^t[1-9][0-9]{0,5}$/.test(t[1]))throw new ke("malformed",`${ut} is 1.<key id>.<enc>.<ct>`);let n=Pt(t[2]),s=Pt(t[3]);if(n.length!==32||s.length!==48)throw new ke("malformed",`${ut} carries a 32-byte encapsulated key and a sealed 32-byte key`);return{kid:t[1],enc:n,ct:s}}async function Hp(e,t,n,s){let{enc:a,ct:r}=Ki(e),i=await $v(t,n,a,s,r);if(i.length!==32)throw new ke("unopenable","the request's key is not 32 bytes");return i}function Yp(e){return tn.encode(`pbt1\0${e}`)}async function Hs(e,t,n,s){let a=s?$t(s):crypto.getRandomValues(Ge(12)),r=JSON.stringify(n);if(r===void 0)throw new ke("malformed",`${t}: an encrypted field holds a JSON value`);let i=await Xa("encrypt",e,a,Yp(t),tn.encode(r));return qi+Vs(ht(a,i))}function Ys(e){return typeof e=="string"&&e.startsWith(qi)}async function Qa(e,t,n){if(!Ys(n))throw new ke("unopenable",`${t} is not an encrypted field`);let s;try{s=Pt(n.slice(qi.length))}catch{throw new ke("unopenable",`${t} is not an encrypted field`)}if(s.length<28)throw new ke("unopenable",`${t} is too short to be an encrypted field`);let a;try{a=await Xa("decrypt",e,s.subarray(0,12),Yp(t),s.subarray(12))}catch{throw new ke("unopenable",`${t} does not open: changed, moved from another field, or another request's`)}try{return JSON.parse(vv.decode(a))}catch{throw new ke("unopenable",`${t} opens to no JSON value`)}}function er(e){return e.replace(/~/g,"~0").replace(/\//g,"~1").replace(/\*/g,"~2")}function Av(e){return e.replace(/~2/g,"*").replace(/~1/g,"/").replace(/~0/g,"~")}var Xp=Symbol("items");function Rv(e,t){if(!(e!==t&&!e.startsWith(t+"/")))return e===t?[]:e.slice(t.length+1).split("/").map(n=>n==="*"?Xp:Av(n))}async function Qn(e,t,n,s){let a=e;for(let r of n){let i=Rv(r,t);i!==void 0&&(a=await Ha(a,i,t,s))}return a}async function Ha(e,t,n,s){if(t.length===0)return e===void 0?void 0:s(n,e);let[a,...r]=t;if(a===Xp){if(!Array.isArray(e))return e;let o=[];for(let[l,d]of e.entries())o.push(await Ha(d,r,`${n}/${l}`,s));return o}if(Array.isArray(e)){if(!/^(0|[1-9][0-9]*)$/.test(a)||Number(a)>=e.length)return e;let o=[...e];return o[Number(a)]=await Ha(o[Number(a)],r,`${n}/${a}`,s),o}if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,a))return e;let i={...e};return i[a]=await Ha(i[a],r,`${n}/${er(a)}`,s),i}var mt=class extends Error{status=400;code;data;constructor(t,n,s={}){super(n),this.name="TransitRefusal",this.code=t,this.data=s}},Tv=6e4,Ev=1e3;function Gi(e){return/^t[1-9][0-9]{0,5}$/.test(e)?Number(e.slice(1)):0}var Xs=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(t){this.opts=t,this.now=t.now??Date.now,this.sleep=t.sleep??(n=>new Promise(s=>setTimeout(s,n)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(t){await this.refresh(t),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Tv),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(t){return this.fetching??=(async()=>{let n=this.now();try{let s=await this.opts.fetch(t),a=new Map;for(let r of s.keys){let i=Pt(r.key);a.set(r.id,{privateKey:i,publicKey:this.keys.get(r.id)?.publicKey??await Wp(i)})}this.keys=a,this.order=s.keys.map(r=>r.id),this.retired=new Set(s.retired),this.project=s.project,this.fetchedAt=this.now(),this.heldFrom=n}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(Gi),...[...this.retired].map(Gi))}async key(t){let n=this.now();for(;Gi(t)>this.newest()&&this.heldFrom<n;){let r=this.fetchedAt+Ev-this.now();if(r>0){await this.sleep(r);continue}await this.refresh()}let s=this.keys.get(t),a=this.current();if(this.retired.has(t))throw new mt("encryption_key_retired",`the request is sealed to ${t}, retired: fetch the project's keys again`,{current:a});if(s===void 0)throw new mt("encryption_key_unknown",`the request is sealed to ${t}, which the project has not made`,{current:a});return s}async request(t){if(t.header===void 0||t.header===null||t.header==="")throw new mt("encryption_required",`this route carries encrypted fields: the request names its key in ${ut}`,{field:ut,current:this.current()});let n;try{n=Ki(t.header).kid}catch{throw new mt("encryption_unopenable",`${ut} is not one`,{field:ut})}let s=await this.key(n),a;try{a=Za(this.projectId,t.method,t.path,t.params??[])}catch{throw new mt("encryption_unopenable","the request's path holds a value no key is sealed for",{field:ut})}try{return new tr(n,await Hp(t.header,s.privateKey,s.publicKey,a))}catch(r){throw r instanceof ke?new mt("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:ut}):r}}},tr=class{kid;key;constructor(t,n){this.kid=t,this.key=n}async open(t,n,s){return Qn(t,n,s,async(a,r)=>{if(!Ys(r))throw new mt("encryption_required",`${a} is an encrypted field: it came plain`,{field:a});try{return await Qa(this.key,a,r)}catch{throw new mt("encryption_unopenable",`${a} does not open: changed, moved from another field, or another request's`,{field:a})}})}async seal(t,n){return Qn(t,"/response",n,(s,a)=>Hs(this.key,s,a))}sealField(t,n){return Hs(this.key,t,n)}};var Cv=/^pb_[a-z0-9]+_s/;function nr(e){if(Lp())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof e.secretKey!="string"||!Cv.test(e.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let t=Ti(vi({baseUrl:e.url,credentials:{secretKey:e.secretKey},fetch:e.fetch,solveProofOfWork:e.solveProofOfWork??!1}),e.retry??Fa),n=Ns.client(t);return{ai:Ga.client(t),analytics:Os.client(t),auth:Ms.client(t),cache:Ua.client(t),calls:za.client(t),fields:new Fs({fetch:async s=>(await n.getFieldKeys({signal:s})).data}),flags:xs.client(t),machines:Is.client(t),messaging:Ba.client(t),notify:Ls.client(t),purchases:Ds.client(t),realtime:qs.client(t),secrets:n,storage:Ks.client(t),stores:Gs.client(t),transit:new Xs({fetch:async s=>(await n.getTransitKeys({signal:s})).data}),transport:t,url:new URL(e.url).origin}}var Nx=1024*1024;var Ux=8*1024;var Vx=16*1024,Hx=10*6e4;var Mv=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,xv=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function Ui(e){return!Mv.test(e)||xv.test(e)||/_PROXY$/i.test(e)}var Iv=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function zi(e){return Iv.test(e)}import"node:os";import{join as Nv,resolve as Kv}from"node:path";var II=10080*60*1e3,Zp="# >>> palbase (palbase env:pull writes this block; edit outside it)",Bi="# <<< palbase";async function Zs(e,t){let n=await Ei(e.studio,t.env_ref),{keys:s}=await e.studio.get(`/environments/${D("the environment's ref",t.env_ref)}/keys`),a=s.find(r=>r.id===n.id);return a&&!a.revoked_at?n:Ei(e.studio,t.env_ref,!0)}async function sr(e,t){return{...await Ji(e,t),key:await Zs(e,t)}}async function Ji(e,t){let n=await e.studio.get(`/environments/${t.env_ref}`);return{url:et(e.cloud,t.env_ref),projectId:n.platform_id}}function ar(e){let t=e.flags.secrets??"development";if(t!=="development"&&t!=="production")throw g("--secrets is development or production");return t}function rr(e,t){return t==="production"?`the app reads ${e.project_name} \u203A ${e.env_name}'s production secrets here`:void 0}var ir={type:"string",value:"set",description:"the project's secrets the app reads at boot: development (default) or production"},td={name:"env:pull",summary:"write what the backend needs to run here into .env.local: the environment's address and your own key \u2014 no secret's value",usage:"[--file <path>] [--secrets development|production]",details:["The app reads the project's secrets at boot (PALBASE_SECRETS); their names are listed as comments: set one in the file to override it.","The key is yours (CLI \u2014 you (this computer)), good for 30 days, made again by env:pull and run; palbase logout revokes it.","Only the block between the palbase markers is written; the rest of the file stays as it is."],flags:{file:{type:"string",value:"path",description:"the file (default .env.local)"},secrets:ir},scope:"environment",async run(e){let t=await f(e),n=ar(e);(t.env_slug===Ue||n==="production")&&await v(e,t,`write a key of ${t.env_slug===Ue?"the production environment":`${t.env_slug}`} into a file on this computer`,rr(t,n));let s=await sr(e,t),a=await ye(e.studio,t.env_ref,"GET",`/secrets/${n}`).then(b=>(b.body.secrets??b.body.items??[]).map(w=>w.name).filter(w=>typeof w=="string"&&!Ui(w)).sort(),()=>[]),r=Kv(e.io.cwd,e.flags.file??".env.local"),i=[Zp,`# ${Fi(q(t))} \u2014 ${new Date(e.io.now()).toISOString()}`,`# PALBASE_SECRET_KEY is your own: ${Fi(s.key.label)}, good until ${Fi(s.key.expires_at)}.`,`PALBASE_URL=${s.url}`,`PALBASE_PROJECT_ID=${s.projectId}`,`PALBASE_SECRET_KEY=${s.key.key}`,`PALBASE_SECRETS=${n}`,...a.length>0?[`# The ${n} secrets, read at boot \u2014 set one here to override it:`,...a.map(b=>`# ${b}=`)]:[],Bi].join(`
|
|
22
22
|
`),o="";try{if((await Dv(r)).isSymbolicLink())throw new y("symlink",`${r} is a link: env:pull writes the key into a file of its own`,{hint:"remove the link, or pass --file <path>"});o=await Qp(r,"utf8")}catch(b){if(b.code!=="ENOENT")throw b}let l=o.indexOf(Zp),d=o.indexOf(Bi),p=l>=0&&d>l?`${o.slice(0,l)}${i}${o.slice(d+Bi.length)}`:`${o}${o===""||o.endsWith(`
|
|
23
23
|
`)?"":`
|
|
24
24
|
`}${i}
|
|
@@ -28,13 +28,13 @@ var Ub=Object.defineProperty;var We=(e,t)=>{for(var n in t)Ub(e,n,{get:t[n],enum
|
|
|
28
28
|
/${r}
|
|
29
29
|
`),"added"}var nd={name:"run",summary:"run a command with the environment's address and your own key in its environment, nothing written to disk",usage:"[--secrets development|production] -- <command> [args\u2026]",details:["palbase run -- bun dev, palbase run -- npm test: the app reads the project's secrets at boot (PALBASE_SECRETS)."],args:{min:1,max:1e3},flags:{secrets:ir},scope:"environment",async run(e){let t=await f(e),n=ar(e);(t.env_slug===Ue||n==="production")&&await v(e,t,`run ${e.args[0]} with a key of ${t.env_slug}`,rr(t,n));let s=await sr(e,t);e.out.note(`${q(t)}: ${e.args.join(" ")}`);let a=await e.io.run(e.args[0],e.args.slice(1),{cwd:e.io.cwd,env:{PALBASE_URL:s.url,PALBASE_PROJECT_ID:s.projectId,PALBASE_SECRET_KEY:s.key.key,PALBASE_SECRETS:n},inherit:!0});if(a.code===127)throw new y("not_found",`${e.args[0]}: no such program`);return a.code}};var Uv=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,sd=20;async function zv(e,t,n,s){if(n.length===0)return{};let a=n.map(i=>({email:`${i.toLowerCase()}.${s}@test.invalid`,password:ad(18).toString("base64url")})),r=await h(e,t,"POST","/admin/test-users",{users:a,with_tokens:!0},C()).catch(i=>{throw i instanceof j&&i.code==="token_out_of_scope"&&vn(e.io)?new y("token_out_of_scope",`PALBASE_TOKEN, an environment's token, may not make test users: its scopes do not name auth:test-users (${i.message})`,{hint:"a token's scopes are fixed when it is minted, and a person's yes does not widen them: mint one with --scope auth:test-users (palbase env:tokens:create, an admin)"}):i});if(r.users.length!==n.length)throw new y("unexpected_answer",`auth made ${r.users.length} test users of the ${n.length} asked for`);return Object.fromEntries(n.map((i,o)=>{let l=r.users[o];return[i,{id:l.user_id,email:l.email??a[o].email,password:a[o].password,...l.access_token?{accessToken:l.access_token}:{}}]}))}async function Bv(e,t,n){let s=[];for(let a of Object.values(n))try{await h(e,t,"DELETE",`/admin/test-users/${k(a.id)}`)}catch(r){r.status!==404&&s.push(a.id)}return s}async function Fv(e,t,n){if(e.out.note(`${t}'s test command, as the platform holds it: ${Jv(n)}`),e.global.yes)return;if(!e.interactive)throw new y("confirmation_needed",`palbase test would run ${t}'s test command on this computer \u2014 a setting on the platform, not code of this checkout`,{hint:"read it above, then confirm with -y"});let s=(await e.io.prompt("Run it on this computer? [y/N] ")).trim().toLowerCase();if(s!=="y"&&s!=="yes")throw new y("cancelled","nothing was run")}function Jv(e){return A(e).replace(/\p{Cf}/gu,t=>`\\u${t.codePointAt(0).toString(16).padStart(4,"0")}`)}function Wi(e){let t=[...new Set(re(e)??[])];for(let s of t)if(!Uv.test(s))throw g(`${JSON.stringify(s)} is no test user's name: letters, digits, _ and -, 64 at most`);let n=new Map;for(let s of t){let a=n.get(s.toLowerCase());if(a!==void 0)throw g(`${JSON.stringify(a)} and ${JSON.stringify(s)} are one test user (its address is in lower case): name it once`);n.set(s.toLowerCase(),s)}if(t.length>sd)throw g(`--users names ${t.length}; a run makes ${sd} at most`);return t}var rd={SIGHUP:1,SIGINT:2,SIGTERM:15};function Wv(){let e,t=Object.keys(rd).map(n=>[n,()=>{e??=n}]);for(let[n,s]of t)process.on(n,s);return{got:()=>e,release:()=>{for(let[n,s]of t)process.off(n,s)}}}var id={name:"test",summary:"run the backend's tests as the platform does before a build goes out: test users made for the run and deleted after, PALBASE_TEST_* in the command's environment",usage:"[--machine <name>] [--users <names>] [--base-url <url>] [--secrets development|production] [-- <command> [args\u2026]]",details:["palbase test --machine backend --base-url http://localhost:8080: the machine's own test command and test users, as the platform runs them before each build of it rolls out.",'palbase test --users alice,bob --base-url http://localhost:8080 -- bun test: api.signInAs("alice") acts as a test user made for this run.',"The command gets what palbase run gives it, and PALBASE_TEST_AUTH_URL (the environment's address), PALBASE_TEST_IDENTITIES (the run's test users, each with its token) and, with --base-url, PALBASE_TEST_BASE_URL (where the app under test answers; without it HTTP tests skip themselves).","The test users are deleted when the command ends, however it ends \u2014 Ctrl-C too: the command is stopped, they are deleted, and palbase test ends as the signal would have.","With an environment's token (PALBASE_TOKEN, scope auth:test-users) the test users are made and deleted with the token, and no key is made: the command gets no PALBASE_SECRET_KEY, so test the app where it is deployed \u2014 palbase test --users alice,bob --base-url https://<ref>.app.palbase.studio -- bun test ./tests (the machine named backend; https://<name>-<ref>.app.palbase.studio for another, as machines:list shows)."],args:{min:0,max:1e3},flags:{machine:{type:"string",value:"name",description:"a machine whose test command (when no command is given) and test users (when --users is not) are run"},users:{type:"string",value:"names",description:"the test users to make for the run, comma-separated"},"base-url":{type:"string",value:"url",description:"where the app under test answers (http://localhost:8080)"},secrets:ir},scope:"environment",async run(e){let t=Wi(e.flags.users),n=e.flags["base-url"];if(n!==void 0&&!/^https?:\/\/[^\s/]+/.test(n))throw g(`--base-url is an http(s) address, not ${JSON.stringify(n)}`);let s=e.flags.machine;if(e.args.length===0&&s===void 0)throw g("which tests? give their command after --, or --machine <name> to run its own","palbase test -- bun test");let a=await f(e),r=e.args.length>0?{cmd:e.args[0],args:e.args.slice(1)}:void 0;if(s!==void 0){let w=await h(e,a,"GET",`/machines/${k(s)}`);if(e.flags.users===void 0&&(t=w.test_users??[]),r===void 0){if(!w.test_command)throw g(`the machine ${s} runs no tests`,`give their command after --, or set it: palbase machines:update ${s} --test-command "bun test"`);await Fv(e,s,w.test_command),r={cmd:"sh",args:["-c",w.test_command]}}}let i=r,o=vn(e.io);if(o&&e.flags.secrets!==void 0)throw g("--secrets names the secrets an app started here reads with your key, and an environment's token makes no key: leave it out");let l=ar(e);o?(a.env_slug===Ue&&t.length>0&&await v(e,a,`make ${t.length} test user(s) there for ${i.cmd}, deleted when it ends`),e.out.note(`PALBASE_TOKEN is an environment's token: no key is made, and ${i.cmd} gets no PALBASE_SECRET_KEY \u2014 ${n!==void 0?`it tests the app at ${n}`:"with no --base-url the HTTP tests skip themselves: give the deployed machine's address (palbase machines:list shows it)"}`)):(a.env_slug===Ue||l==="production")&&await v(e,a,`run ${i.cmd} with a key of ${a.env_slug}${t.length?` and ${t.length} test user(s) made there`:""}`,rr(a,l));let d=o?{...await Ji(e,a),key:void 0}:await sr(e,a),p=ad(4).toString("hex"),u=t.length>0?Wv():void 0,m=0;try{let w=await zv(e,a,t,p);t.length>0&&e.out.note(`${q(a)}: test users ${t.join(", ")} made for this run (${p})`);try{if(u?.got()===void 0){let _=await e.io.run(i.cmd,i.args,{cwd:e.io.cwd,env:{PALBASE_URL:d.url,PALBASE_PROJECT_ID:d.projectId,...d.key?{PALBASE_SECRET_KEY:d.key.key,PALBASE_SECRETS:l}:{},PALBASE_TEST_AUTH_URL:d.url,PALBASE_TEST_IDENTITIES:JSON.stringify(w),...n!==void 0?{PALBASE_TEST_BASE_URL:n}:{}},inherit:!0});if(_.code===127)throw new y("not_found",`${i.cmd}: no such program`);m=_.code}}finally{if(t.length>0){let _=await Bv(e,a,w);_.length>0?e.out.warn(`test users not deleted: ${_.join(", ")} \u2014 palbase auth:test-users:delete <id> deletes one`):e.out.note(`the run's ${t.length} test user(s) deleted`)}}}finally{u?.release()}let b=u?.got();return b===void 0?m:128+rd[b]}};var od={name:"auth:settings:get",summary:"the environment's auth settings: passwords, email confirmation, sessions, tokens, passkeys, risk",scope:"environment",async run(e){let t=await f(e),{body:n}=await Ne(e,t,"/admin/auth-settings");e.out.result(n,()=>Xn(e,n))}},ld={name:"auth:settings:set",summary:'change auth settings: key=value, a value read as JSON when it is JSON (12, true, ["https://\u2026"])',usage:"<key=value>\u2026",details:[`Text needs no quotes (site_url=https://shop.example); quote text that reads as JSON: from_name='"123"'.`,"The change is made on the revision read: one made beside it in the meantime (Studio, another terminal) is refused, not overwritten.","palbase auth:settings:get lists the keys."],args:{min:1,max:50},scope:"environment",async run(e){let t=await f(e),n=Zt(e.args),{body:s,etag:a}=await Ne(e,t,"/admin/auth-settings"),r=Qt(s,n),i=Dt(s,r);if(i.length===0)return ze(e,"the auth settings",s);await v(e,t,`set the auth settings ${i.join(", ")}`);let o=await h(e,t,"PUT","/admin/auth-settings",Object.fromEntries(i.map(l=>[l,r[l]])),Te(a));e.out.result({settings:o,changed:i},()=>{for(let l of i)e.out.line(`${l}: ${Ee(s[l])} \u2192 ${Ee(o[l])}`)})}},es=["google","apple","github","microsoft"],Vv={google:"web_client_id",apple:"services_id",microsoft:"application_id",github:"oauth_client_id"},Hv=new Set(["organizations","consumers","common"]),pd={name:"auth:providers:list",summary:"the sign-in methods: email, phone and the social providers, whether each is on, their clients and stored secrets (by name)",scope:"environment",async run(e){let t=await f(e),[n,s]=await Promise.all([h(e,t,"GET","/admin/providers"),h(e,t,"GET","/admin/social-auth")]),a=[...n.providers.map(r=>({provider:r.id,on:r.enabled,detail:r.settings?`codes by ${r.settings.sender??"sms"}, ${r.settings.otp_ttl_seconds}s, ${r.settings.otp_max_attempts} tries, sign-up ${r.settings.allow_signups?"on":"off"}`:"",secrets:""})),...es.map(r=>{let i=s.providers[r]??{enabled:!1,browser_clients:[],native_clients:[]},o=[...i.browser_clients.map(l=>`${l.key} (${l.platform})`),...i.native_clients.map(l=>`${l.key} (${l.platform}, native)`)];return{provider:r,on:i.enabled,detail:o.length===0?"no client":o.join(", "),secrets:s.credentials.filter(l=>l.provider===r).map(l=>`${l.key} ${l.configured?"set":"not set"}`).join(", ")}})];e.out.result({providers:n.providers,social:s.providers,credentials:s.credentials},()=>e.out.table(a,[{header:"provider",value:r=>r.provider},{header:"on",value:r=>r.on?"yes":"no"},{header:"clients / settings",value:r=>r.detail},{header:"secrets",value:r=>r.secrets}]))}},dd={name:"auth:providers:set",summary:"turn a sign-in provider on or off and set it up: its client, its secret (from stdin), phone codes",usage:"<provider> [--enable|--disable] [setting=value\u2026] [--client-id <id>] [--secret-stdin] \u2026",details:["email is always on. phone: --enable/--disable, and its code settings as setting=value (allow_signups, otp_ttl_seconds, otp_max_attempts, sender, sms_second_factor).","google, apple, github, microsoft: --client-id sets the browser client --client names (default web), made when the provider has none of that name.","--secret-stdin reads the client's secret from stdin (Apple: the .p8 signing key, with --team-id and --key-id) and keeps it under --credential (default: the provider's name). It is never taken from the command line and never printed.",`--clients-file replaces the provider's clients with the file's {"browser_clients": [\u2026], "native_clients": [\u2026]} (native apps, several clients).`],args:{min:1,max:20},flags:{...Bs,client:{type:"string",value:"key",description:"the browser client --client-id, --return-uri and the secret go to (default web)"},"client-id":{type:"string",value:"id",description:"the provider's id of your app (Google web client id, Apple services id, Microsoft application id, GitHub client id)"},"return-uri":{type:"string",multiple:!0,value:"url",description:"where your app is sent back after sign-in (repeat it; replaces the list)"},application:{type:"string",value:"key",description:"the application the client is for (default app)"},variant:{type:"string",value:"name",description:"the build variant the client is for (default release)"},directory:{type:"string",value:"tenant",description:"microsoft: a tenant id, organizations, consumers or common (default common)"},"secret-stdin":{type:"boolean",description:"read the client's secret (Apple: the .p8 key) from stdin"},credential:{type:"string",value:"key",description:"the name the secret is kept under (default: the provider's)"},"team-id":{type:"string",value:"id",description:"apple: your team's id, with --secret-stdin"},"key-id":{type:"string",value:"id",description:"apple: the signing key's id, with --secret-stdin"},"clients-file":{type:"string",value:"path",description:"replace the provider's clients with the file's (JSON)"}},scope:"environment",async run(e){let t=e.args[0],n=await f(e);if(t==="email")throw new y("always_on","email sign-in is always on, and has no settings of its own here",{hint:"its policy is in palbase auth:settings:set"});if(t==="phone")return Yv(e,n,e.args.slice(1));if(!es.includes(t))throw g(`no provider ${JSON.stringify(t)}`,`the providers: email, phone, ${es.join(", ")}`);if(e.args.length>1)throw g(`${t} takes flags, not settings: palbase help auth:providers:set`);await Zv(e,n,t)}};async function Yv(e,t,n){let s=Zn(e),a=Zt(n);if(s===void 0&&a.length===0)throw g("nothing to change: --enable, --disable or setting=value","palbase help auth:providers:set");let r=await h(e,t,"GET","/admin/providers/phone/settings"),i=Qt(r,a),o=Dt(r,i);if(s===void 0&&o.length===0)return ze(e,"the phone settings",r);await v(e,t,`phone sign-in: ${[...s===void 0?[]:[s?"turn it on":"turn it off"],...o.map(p=>`set ${p}`)].join(", ")}`);let l=o.length>0?await h(e,t,"PUT","/admin/providers/phone/settings",i):r,d=s===void 0?void 0:await h(e,t,"POST","/admin/providers/phone",{enabled:s});e.out.result({provider:"phone",...d?{enabled:d.enabled}:{},settings:l},()=>{d&&e.out.line(`phone sign-in is ${d.enabled?"on":"off"}.`);for(let p of o)e.out.line(`${p}: ${Ee(r[p])} \u2192 ${Ee(l[p])}`)})}function Xv(e){if(Hv.has(e))return{mode:e};if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))return{mode:"tenant",tenant_id:e};throw g("--directory is a tenant id, organizations, consumers or common")}async function Zv(e,t,n){let s=e.flags,a=Zn(e),r=await Ne(e,t,"/admin/social-auth"),i=r.etag,o=r.body.providers[n]??{enabled:!1,browser_clients:[],native_clients:[]},l={},d=[],p=s.credential??n,u;if(s["secret-stdin"]===!0){if(n==="apple"&&(s["team-id"]===void 0||s["key-id"]===void 0))throw g("Apple's signing key goes with --team-id and --key-id");u=await xe(e,n==="apple"?"Apple's .p8 signing key":`${n}'s client secret`),d.push(`keep its secret as ${p}`)}let m=["client","client-id","return-uri","application","variant","directory","credential"].filter(T=>s[T]!==void 0);if(s["clients-file"]!==void 0){if(m.length>0)throw g(`--clients-file and --${m[0]} are one or the other`);let T=ue(await be(e,s["clients-file"],"the clients"),"the clients file");if(typeof T!="object"||T===null||T.browser_clients===void 0&&T.native_clients===void 0)throw g('the clients file is {"browser_clients": [\u2026], "native_clients": [\u2026]}');l.browser_clients=T.browser_clients??o.browser_clients,l.native_clients=T.native_clients??o.native_clients,d.push(`set its clients from ${s["clients-file"]}`)}else if(m.length>0||u!==void 0){let T=s.client??"web",S=[...o.browser_clients],$=S.findIndex(P=>P.key===T),R=u!==void 0&&m.every(P=>P==="credential");if($>=0||!R){let P=$>=0?{...S[$]}:{key:T,enabled:!0,application_key:"app",platform:"web",variant:"release",return_uris:[]},L=Vv[n];if(s["client-id"]!==void 0&&(P[L]=s["client-id"]),!P[L])throw g(`the ${n} client ${T} is new: give it --client-id`);if(s["return-uri"]!==void 0&&(P.return_uris=s["return-uri"]),s.application!==void 0&&(P.application_key=s.application),s.variant!==void 0&&(P.variant=s.variant),n==="microsoft")P.directory=s.directory!==void 0?Xv(s.directory):P.directory??{mode:"common"};else if(s.directory!==void 0)throw g("--directory is a Microsoft client's");(u!==void 0||s.credential!==void 0||!P.credential_ref)&&(P.credential_ref=p),S[$>=0?$:S.length]=P,l.browser_clients=S,d.push(`${$>=0?"change":"add"} its browser client ${T}`)}}if(a!==void 0&&(l.enabled=a,d.push(a?"turn it on":"turn it off")),d.length===0)throw g("nothing to change: give a flag","palbase help auth:providers:set");await v(e,t,`${n} sign-in: ${d.join(", ")}`);let b=r.body;if(u!==void 0){let T=n==="apple"?{provider:n,kind:"apple_signing_key",team_id:s["team-id"],key_id:s["key-id"],private_key:u}:{provider:n,kind:"oauth_client_secret",client_secret:u};i=(await qe(e,t,"PUT",`/admin/social-auth/credentials/${k(p)}`,T,Te(i))).etag??i}Object.keys(l).length>0?b=await h(e,t,"PATCH",`/admin/social-auth/providers/${k(n)}`,l,Te(i)):b=await h(e,t,"GET","/admin/social-auth");let w=b.providers[n],_=b.credentials.filter(T=>T.provider===n);e.out.result({provider:n,...w,credentials:_},()=>{e.out.line(`${n} sign-in is ${w.enabled?"on":"off"}: ${w.browser_clients.length} browser client(s), ${w.native_clients.length} native.`);for(let T of _)e.out.line(` secret ${T.key}: ${T.configured?"set":"not set"}`)})}var ud={name:"auth:providers:secret:delete",summary:"delete a sign-in provider's stored secret by its name; one a client still uses is refused",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0],n=await f(e),{body:s,etag:a}=await Ne(e,n,"/admin/social-auth");if(!s.credentials.some(r=>r.key===t))throw g(`the environment holds no provider secret ${JSON.stringify(t)}`,"palbase auth:providers:list names them");await v(e,n,`delete the provider secret ${t}`),await h(e,n,"DELETE",`/admin/social-auth/credentials/${k(t)}`,void 0,Te(a)),e.out.result({deleted:t},()=>e.out.line(`Deleted the provider secret ${t}.`))}},cd={name:"auth:providers:disable",summary:"turn a sign-in provider off (phone, google, apple, github, microsoft); its clients and secrets stay",usage:"<provider>",args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0],n=await f(e);if(t==="email")throw new y("always_on","email sign-in cannot be turned off");if(t==="phone"){await v(e,n,"turn phone sign-in off");let r=await h(e,n,"POST","/admin/providers/phone",{enabled:!1});e.out.result(r,()=>e.out.line("phone sign-in is off."));return}if(!es.includes(t))throw g(`no provider ${JSON.stringify(t)}`,`the providers: phone, ${es.join(", ")}`);let{etag:s}=await Ne(e,n,"/admin/social-auth");await v(e,n,`turn ${t} sign-in off`);let a=await h(e,n,"PATCH",`/admin/social-auth/providers/${k(t)}`,{enabled:!1},Te(s));e.out.result({provider:t,...a.providers[t]},()=>e.out.line(`${t} sign-in is off; its clients and secrets stay.`))}},hd={name:"auth:roles:list",summary:"the environment's roles: their permissions, which one new users get, how many users hold each",scope:"environment",async run(e){let t=await f(e),{roles:n}=await h(e,t,"GET","/admin/roles");e.out.result({roles:n},()=>{n.length===0&&e.out.line("No role yet: palbase auth:roles:set <name> --permissions \u2026 makes one."),e.out.table(n,[{header:"role",value:s=>`${s.name}${s.is_default?" (default)":""}`},{header:"permissions",value:s=>s.permissions.join(", ")},{header:"users",value:s=>String(s.user_count??0)},{header:"description",value:s=>s.description}])})}},md={name:"auth:roles:set",summary:"make a role, or change one: its permissions (the list is replaced), description, whether new users get it",usage:"<name> [--permissions <a.b,c.d>] [--description <text>] [--default yes|no]",args:{min:1,max:1},flags:{permissions:{type:"string",multiple:!0,value:"list",description:'resource.action permissions, comma-separated or repeated; replaces the list ("" for none)'},description:{type:"string",value:"text",description:"what the role is for"},default:{type:"string",value:"yes|no",description:"whether new users get it (one role at most)"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0],{roles:s}=await h(e,t,"GET","/admin/roles"),a=s.find(p=>p.name===n),r=re(e.flags.permissions),i=en(e.flags.default,"default");if(a&&r===void 0&&e.flags.description===void 0&&i===void 0)throw g("nothing to change: give a flag","palbase help auth:roles:set");let o={permissions:r??a?.permissions??[],description:e.flags.description??a?.description??"",is_default:i??a?.is_default??!1};await v(e,t,`${a?"change":"make"} the role ${n}${a?.user_count?` (${a.user_count} users hold it)`:""}`);let l=await h(e,t,"PUT",`/admin/roles/${k(n)}`,o),d=l.roles.find(p=>p.name===n);e.out.result(d??l,()=>e.out.line(`${a?"Changed":"Made"} the role ${n}: ${(d?.permissions??o.permissions).join(", ")||"no permission"}${d?.is_default?", given to new users":""}.`))}},gd={name:"auth:roles:delete",summary:"delete a role; one users hold is deleted only with --force, and is taken from them",usage:"<name> [--force]",args:{min:1,max:1},flags:{force:{type:"boolean",description:"delete it although users hold it"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0];await v(e,t,`delete the role ${n}${e.flags.force===!0?", taking it from the users who hold it":""}`),await h(e,t,"DELETE",`/admin/roles/${k(n)}${e.flags.force===!0?"?confirm=true":""}`),e.out.result({deleted:n},()=>e.out.line(`Deleted the role ${n}.`))}},fd={event:{type:"string",value:"event",description:"before.user.create, before.login, before.token.issue, \u2026 (the module lists them)"},url:{type:"string",value:"url",description:"the https endpoint auth calls and waits for"},"failure-mode":{type:"string",value:"deny|allow",description:"what auth does when the hook does not answer in time (default deny)"},timeout:{type:"string",value:"ms",description:"how long auth waits, 100\u20135000 ms (default 5000)"}},yd={name:"auth:hooks:list",summary:"the blocking hooks: what auth calls, and waits for, before a sign-up, a sign-in, a token",scope:"environment",async run(e){let t=await f(e),{hooks:n}=await h(e,t,"GET","/admin/hooks");e.out.result({hooks:n},()=>{n.length===0&&e.out.line("No hook: palbase auth:hooks:create --event \u2026 --url \u2026 registers one."),e.out.table(n,[{header:"id",value:s=>s.id},{header:"event",value:s=>s.event},{header:"url",value:s=>s.url},{header:"on failure",value:s=>s.failure_mode},{header:"timeout",value:s=>`${s.timeout_ms} ms`},{header:"on",value:s=>s.enabled?"yes":"no"}])})}},bd={name:"auth:hooks:create",summary:"register a blocking hook; its signing secret is printed this once",usage:"--event <event> --url <url> [--failure-mode deny|allow] [--timeout <ms>] [--disable]",flags:{...fd,disable:{type:"boolean",description:"register it turned off"}},scope:"environment",async run(e){let t=await f(e);if(e.flags.event===void 0||e.flags.url===void 0)throw g("a hook needs --event and --url");let n=xi({event:e.flags.event,url:e.flags.url,failure_mode:e.flags["failure-mode"],timeout_ms:ne(e.flags.timeout,"timeout"),...e.flags.disable===!0?{enabled:!1}:{}});await v(e,t,`register a hook on ${String(n.event)} calling ${String(n.url)}`);let s=await h(e,t,"POST","/admin/hooks",n,C());e.out.result(s,()=>{e.out.line(`Registered ${s.id}: ${s.event} \u2192 ${s.url}.`),s.secret&&e.out.line(`signing secret (shown this once): ${s.secret}`)})}},wd={name:"auth:hooks:update",summary:"change a blocking hook: its event, endpoint, timeout, failure mode, on or off (its secret stays)",usage:"<id> [--event \u2026] [--url \u2026] [--failure-mode \u2026] [--timeout \u2026] [--enable|--disable]",args:{min:1,max:1},flags:{...fd,...Bs},scope:"environment",async run(e){let t=await f(e),{hooks:n}=await h(e,t,"GET","/admin/hooks"),s=n.find(o=>o.id===e.args[0]);if(!s)throw new y("no_such_hook",`no hook ${JSON.stringify(e.args[0])}`,{hint:"palbase auth:hooks:list shows them"});let a={event:e.flags.event??s.event,url:e.flags.url??s.url,failure_mode:e.flags["failure-mode"]??s.failure_mode,timeout_ms:ne(e.flags.timeout,"timeout")??s.timeout_ms,enabled:Zn(e)??s.enabled},r=Dt(Qv(s),a);if(r.length===0)throw g("nothing to change: give a flag","palbase help auth:hooks:update");await v(e,t,`change the hook ${s.id}: ${r.join(", ")}`);let i=await h(e,t,"PUT",`/admin/hooks/${k(s.id)}`,a);e.out.result(i,()=>e.out.line(`${i.id}: ${i.event} \u2192 ${i.url}, ${i.failure_mode} on failure, ${i.timeout_ms} ms, ${i.enabled?"on":"off"}.`))}};function Qv(e){return{event:e.event,url:e.url,failure_mode:e.failure_mode,timeout_ms:e.timeout_ms,enabled:e.enabled}}var vd={name:"auth:hooks:delete",summary:"delete a blocking hook; auth stops calling it",usage:"<id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e);await v(e,t,`delete the hook ${e.args[0]}`),await h(e,t,"DELETE",`/admin/hooks/${k(e.args[0])}`),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the hook ${e.args[0]}.`))}},_d={name:"auth:oauth-clients:list",summary:"the OAuth clients of the environment's OpenID provider (apps that sign in with your users' accounts)",scope:"environment",async run(e){let t=await f(e),{clients:n}=await h(e,t,"GET","/admin/oauth-clients");e.out.result({clients:n},()=>{n.length===0&&e.out.line("No OAuth client: palbase auth:oauth-clients:create <name> registers one."),e.out.table(n,[{header:"id",value:s=>s.id},{header:"client id",value:s=>s.client_id},{header:"name",value:s=>s.client_name},{header:"kind",value:s=>s.is_public?"public":s.token_endpoint_auth_method},{header:"grants",value:s=>s.grant_types.join(", ")},{header:"redirect uris",value:s=>s.redirect_uris.join(", ")}])})}},kd={name:"auth:oauth-clients:create",summary:"register an OAuth client; a confidential client's secret is printed this once",usage:"<name> [--public] [--redirect-uri <url>\u2026] [--grant <type>\u2026] [--scope <scope>\u2026] [--client-id <id>]",args:{min:1,max:1},flags:{public:{type:"boolean",description:"a public client (a CLI, a mobile app): it has no secret"},"redirect-uri":{type:"string",multiple:!0,value:"url",description:"where it may send the browser back (repeat it)"},grant:{type:"string",multiple:!0,value:"type",description:"authorization_code (default), refresh_token, client_credentials, urn:ietf:params:oauth:grant-type:device_code"},scope:{type:"string",multiple:!0,value:"scope",description:"what it may ask for (default openid, profile, email)"},"client-id":{type:"string",value:"id",description:"a client_id to use as it is (default: a random one)"}},scope:"environment",async run(e){let t=await f(e),n=xi({client_name:e.args[0],client_id:e.flags["client-id"],is_public:e.flags.public===!0?!0:void 0,redirect_uris:e.flags["redirect-uri"],grant_types:re(e.flags.grant),scopes:re(e.flags.scope)});await v(e,t,`register the OAuth client ${e.args[0]}`);let s=await h(e,t,"POST","/admin/oauth-clients",n,C());e.out.result(s,()=>{e.out.line(`Registered ${s.client_name}: client_id ${s.client_id} (${s.id}).`),s.client_secret&&e.out.line(`client secret (shown this once): ${s.client_secret}`)})}},Sd={name:"auth:oauth-clients:delete",summary:"delete an OAuth client (by its id or its client_id)",usage:"<id|client-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),{clients:n}=await h(e,t,"GET","/admin/oauth-clients"),s=n.find(a=>a.id===e.args[0]||a.client_id===e.args[0]);if(!s)throw new y("no_such_client",`no OAuth client ${JSON.stringify(e.args[0])}`,{hint:"palbase auth:oauth-clients:list shows them"});await v(e,t,`delete the OAuth client ${s.client_name} (${s.client_id})`),await h(e,t,"DELETE",`/admin/oauth-clients/${k(s.id)}`),e.out.result({deleted:s.id},()=>e.out.line(`Deleted the OAuth client ${s.client_name}.`))}};function e_(e){return{...e.client_id.startsWith("oidc_")?{}:{client_id:e.client_id},is_public:e.is_public,grant_types:[...e.grant_types].sort(),redirect_uris:e.redirect_uris,post_logout_redirect_uris:e.post_logout_redirect_uris,response_types:e.response_types,scopes:e.scopes,token_endpoint_auth_method:e.token_endpoint_auth_method,id_token_lifetime_secs:e.id_token_lifetime_secs,dpop_bound_access_tokens:e.dpop_bound_access_tokens,...e.jwks?{jwks:e.jwks}:{}}}var $d={name:"auth",async read(e,t){let[n,s,a,r,i,o]=await Promise.all([h(e,t,"GET","/admin/auth-settings"),h(e,t,"GET","/admin/providers"),h(e,t,"GET","/admin/social-auth"),h(e,t,"GET","/admin/roles"),h(e,t,"GET","/admin/hooks"),h(e,t,"GET","/admin/oauth-clients")]),l={};for(let[p,u]of Object.entries(n))l[`settings.${p}`]=u;let d=s.providers.find(p=>p.id==="phone");d&&(l["phone.enabled"]=d.enabled,d.settings&&(l["phone.settings"]=d.settings));for(let p of es){let u=a.providers[p];u&&(l[`social.${p}`]={enabled:u.enabled,browser_clients:u.browser_clients,native_clients:u.native_clients})}for(let p of a.credentials)l[`secrets.${p.key}`]={provider:p.provider,kind:p.kind,value:p.configured?"set":"not set"};for(let p of r.roles)l[`roles.${p.name}`]={description:p.description,is_default:p.is_default,permissions:[...p.permissions].sort()};for(let p of i.hooks)l[`hooks.${p.event} ${p.url}`]={failure_mode:p.failure_mode,timeout_ms:p.timeout_ms,enabled:p.enabled};for(let p of o.clients)l[`oauth_clients.${p.client_name}`]=e_(p);return l},async copy(e,t,n,s){await t_(e,t,pe(n,"settings."),s);for(let r of pe(n,"phone."))r.name==="enabled"&&await V(s,`turn phone sign-in ${r.from?"on":"off"}`,async()=>{await h(e,t,"POST","/admin/providers/phone",{enabled:r.from===!0})}),r.name==="settings"&&r.from!==void 0&&await V(s,"set the phone code settings",async()=>{await h(e,t,"PUT","/admin/providers/phone/settings",r.from)});await n_(e,t,pe(n,"social."),pe(n,"secrets."),s);let a=pe(n,"roles.").sort((r,i)=>+(r.from?.is_default===!0)-+(i.from?.is_default===!0));for(let r of a)r.from===void 0?await V(s,`delete the role ${r.name}`,async()=>{await h(e,t,"DELETE",`/admin/roles/${k(r.name)}`)}):await V(s,`set the role ${r.name}`,async()=>{await h(e,t,"PUT",`/admin/roles/${k(r.name)}`,r.from)});await s_(e,t,pe(n,"hooks."),s),await a_(e,t,pe(n,"oauth_clients."),s)}};async function t_(e,t,n,s){let a=n.filter(i=>i.from!==void 0);for(let i of n.filter(o=>o.from===void 0))s.left(`auth settings ${i.name}: set in the target only, and a setting is not taken away (set it with auth:settings:set)`);if(a.length===0)return;let{etag:r}=await Ne(e,t,"/admin/auth-settings");await V(s,`set the auth settings ${a.map(i=>i.name).join(", ")}`,async()=>{await h(e,t,"PUT","/admin/auth-settings",Object.fromEntries(a.map(i=>[i.name,i.from])),Te(r))})}async function n_(e,t,n,s,a){for(let l of s){let d=l.from;d===void 0?a.left(`secret ${l.name}: only in the target, left as it is (delete it with palbase auth:providers:secret:delete ${l.name})`):a.left(`secret ${l.name} (${d.provider}): secrets are not copied \u2014 set it with palbase auth:providers:set ${d.provider} --secret-stdin --credential ${l.name}`)}if(n.length===0)return;let r=await Ne(e,t,"/admin/social-auth"),i=r.etag,o=new Set(r.body.credentials.filter(l=>l.configured).map(l=>l.key));for(let l of n){let d=l.from,p=[...new Set(d.browser_clients.map(u=>u.credential_ref).filter(u=>typeof u=="string"&&!o.has(u)))];if(p.length>0){a.left(`${l.name} sign-in: its clients use the secret ${p.join(", ")}, which the target does not hold \u2014 set it first (auth:providers:set ${l.name} --secret-stdin --credential ${p[0]})`);continue}await V(a,`set ${l.name} sign-in (${d.enabled?"on":"off"}, ${d.browser_clients.length+d.native_clients.length} client(s))`,async()=>{i=(await qe(e,t,"PATCH",`/admin/social-auth/providers/${k(l.name)}`,d,Te(i))).etag??i})}}async function s_(e,t,n,s){if(n.length===0)return;let{hooks:a}=await h(e,t,"GET","/admin/hooks");for(let r of n){let i=r.name.indexOf(" "),o=r.name.slice(0,i),l=r.name.slice(i+1),d=a.find(p=>p.event===o&&p.url===l);if(r.from===void 0)d&&await V(s,`delete the hook ${o} \u2192 ${l}`,async()=>{await h(e,t,"DELETE",`/admin/hooks/${k(d.id)}`)});else if(d)await V(s,`change the hook ${o} \u2192 ${l}`,async()=>{await h(e,t,"PUT",`/admin/hooks/${k(d.id)}`,{event:o,url:l,...r.from})});else{let p;await V(s,`register the hook ${o} \u2192 ${l}`,async()=>{p=(await h(e,t,"POST","/admin/hooks",{event:o,url:l,...r.from},C())).secret}),p&&s.shown(`the hook ${o} \u2192 ${l} signs with`,p)}}}async function a_(e,t,n,s){if(n.length===0)return;let{clients:a}=await h(e,t,"GET","/admin/oauth-clients");for(let r of n){let i=a.find(l=>l.client_name===r.name),o=r.from;if(o===void 0)i&&await V(s,`delete the OAuth client ${r.name}`,async()=>{await h(e,t,"DELETE",`/admin/oauth-clients/${k(i.id)}`)});else if(i)if(!Me(o.is_public,i.is_public)||o.client_id!==void 0&&o.client_id!==i.client_id)s.left(`OAuth client ${r.name}: its client_id or kind (public or not) differs, which a client cannot change \u2014 delete it in the target and run the copy again`);else{let{client_id:l,is_public:d,...p}=o;await V(s,`change the OAuth client ${r.name}`,async()=>{await h(e,t,"PATCH",`/admin/oauth-clients/${k(i.id)}`,p)})}else{let l;await V(s,`register the OAuth client ${r.name}`,async()=>{l=await h(e,t,"POST","/admin/oauth-clients",{client_name:r.name,...o},C())}),l?.client_secret&&s.shown(`the OAuth client ${r.name} (${l.client_id}) has the secret`,l.client_secret)}}}var Pd=["bool","number","string","object"];async function sn(e,t){return(await h(e,t,"GET","/flags/templates/capabilities")).publish_enabled}async function nn(e,t,n){let s=await Ne(e,t,"/flags/templates/draft");if(s.body.draft||!n)return{draft:s.body.draft,etag:s.etag};let a=await Ne(e,t,"/flags/templates/active"),r=await qe(e,t,"POST","/flags/templates/draft",{},Te(a.etag));return{draft:r.body.draft,etag:r.etag}}function Ad(e){return{value_type:e.value_type,value:e.value,...e.description?{description:e.description}:{},...e.variants&&e.variants.length>0?{variants:e.variants}:{},...e.conditions&&e.conditions.length>0?{conditions:e.conditions}:{}}}function r_(e){return typeof e=="boolean"?"bool":typeof e=="number"?"number":typeof e=="string"?"string":"object"}function Rd(e,t){switch(t){case"bool":if(e==="true"||e==="false")return e==="true";throw g(`a bool flag's value is true or false, not ${JSON.stringify(e)}`);case"number":{let n=Number(e);if(e.trim()===""||!Number.isFinite(n))throw g(`a number flag's value is a number, not ${JSON.stringify(e)}`);return n}case"string":{let n=St(e);return typeof n=="string"?n:e}default:{let n=St(e);if(typeof n!="object"||n===null)throw g(`an object flag's value is a JSON object or list, not ${JSON.stringify(e)}`);return n}}}function i_(e,t){let n=e.lastIndexOf("=>");if(n<=0)throw g(`a condition is "<expression> => <value>", not ${JSON.stringify(e)}`,`--condition "client.platform == 'ios' => true"`);return{when:e.slice(0,n).trim(),value:Rd(e.slice(n+2).trim(),t)}}var Td={name:"flags:list",summary:"the environment's flags as they are live: type, default, targeting (and the draft's state when it publishes)",scope:"environment",async run(e){let t=await f(e),n=await sn(e,t),s,a,r;if(n){let[i,o]=await Promise.all([h(e,t,"GET","/flags/templates/active"),nn(e,t,!1)]);s=Object.entries(i.definitions).map(([l,d])=>({key:l,...d})),a=i.version,r=o.draft}else s=await h(e,t,"GET","/flags/system");s.sort((i,o)=>i.key<o.key?-1:1),e.out.result({publishing:n,...a?{version:a}:{},flags:s,...r?{draft:{revision:r.revision,base_version:r.base_version}}:{}},()=>{n&&e.out.line(`Version ${a} is live${r?`; a draft (from ${r.base_version}) is in progress: palbase flags:publish shows and publishes it`:""}.`),s.length===0&&e.out.line("No flag yet: palbase flags:set <key> <value> makes one."),e.out.table(s,[{header:"flag",value:i=>i.key},{header:"type",value:i=>i.value_type},{header:"value",value:i=>JSON.stringify(i.value)},{header:"targeting",value:i=>i.conditions?.length?`${i.conditions.length} condition(s)`:""},{header:"description",value:i=>i.description??""}])})}},Ed={name:"flags:set",summary:"define a flag or change its default and targeting (into the draft when the environment publishes)",usage:'<key> <value> [--type bool|number|string|object] [--condition "<expression> => <value>"\u2026] [--description <text>]',details:["The value is read as the flag's type: true/false, a number, text, or a JSON object; a new flag's type is the value's unless --type says it.","--condition replaces the targeting (first match wins, 8 at most); --clear-conditions takes it away; without either it stays.","An environment that publishes takes the change into its shared draft (palbase flags:publish makes it live); one that does not, live at once."],args:{min:2,max:2},flags:{type:{type:"string",value:"type",description:"bool, number, string or object"},condition:{type:"string",multiple:!0,value:"rule",description:'"<expression> => <value>" (repeat it, in order)'},"clear-conditions":{type:"boolean",description:"take its targeting away"},variants:{type:"string",value:"list",description:"a string flag's allowed values, comma-separated"},description:{type:"string",value:"text",description:"what the flag is for"}},scope:"environment",async run(e){let t=await f(e),[n,s]=e.args,a=e.flags.type;if(a!==void 0&&!Pd.includes(a))throw g(`--type is one of ${Pd.join(", ")}`);if(e.flags.condition!==void 0&&e.flags["clear-conditions"]===!0)throw g("--condition and --clear-conditions are one or the other");let r=await sn(e,t),i,o;r?(o=await nn(e,t,!1),i=o.draft?.definitions[n]??(await h(e,t,"GET","/flags/templates/active")).definitions[n]):i=(await h(e,t,"GET","/flags/system")).find(u=>u.key===n);let l=a??i?.value_type??r_(St(s)),d=e.flags["clear-conditions"]===!0?[]:e.flags.condition!==void 0?e.flags.condition.map(u=>i_(u,l)):i?.value_type===l?i.conditions??[]:[],p=Ad({value_type:l,value:Rd(s,l),description:e.flags.description??i?.description,variants:re(e.flags.variants)??(i?.value_type===l?i.variants:void 0),conditions:d});if(await v(e,t,r?`put ${n} = ${Ee(p.value)} into the flags draft`:`set the flag ${n} = ${Ee(p.value)}, live at once`),r){o?.draft||(o=await nn(e,t,!0));let u=await qe(e,t,"PUT",`/flags/templates/draft/parameters/${k(n)}`,p,Te(o.etag));e.out.result({key:n,...p,draft:{revision:u.body.draft?.revision}},()=>e.out.line(`${n} = ${JSON.stringify(p.value)} is in the draft: palbase flags:publish makes it live.`))}else{let u=await h(e,t,"PUT",`/flags/system/${k(n)}`,p);e.out.result(u,()=>e.out.line(`${n} = ${JSON.stringify(u.value)} (${u.value_type}) is live.`))}}},Cd={name:"flags:delete",summary:"delete a flag, with every user's own value of it (from the draft when the environment publishes)",usage:"<key>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=e.args[0],s=await sn(e,t);if(await v(e,t,s?`take ${n} out of the flags draft`:`delete the flag ${n} and every user's value of it, live at once`),s){let a=await nn(e,t,!0);await h(e,t,"DELETE",`/flags/templates/draft/parameters/${k(n)}`,void 0,Te(a.etag)),e.out.result({deleted:n,draft:!0},()=>e.out.line(`${n} is out of the draft: palbase flags:publish makes it so.`))}else await h(e,t,"DELETE",`/flags/system/${k(n)}`),e.out.result({deleted:n},()=>e.out.line(`Deleted the flag ${n}.`))}};function Vi(){return new y("publishing_off","this environment's flags are not published through drafts: flags:set and flags:delete change them live",{hint:"versions, publishing and rollback are for an environment that publishes"})}function o_(e,t){t.changes.length===0&&e.out.line("The draft changes nothing.");for(let n of t.changes){let s=n.override_count>0?` (${n.override_count} users' own values)`:"";n.kind==="added"?e.out.line(` + ${n.key} = ${JSON.stringify(n.after?.value)}`):n.kind==="removed"?e.out.line(` - ${n.key}${s}`):e.out.line(` ~ ${n.key}: ${n.changed_fields.join(", ")}${n.changed_fields.includes("value")?` \u2192 ${JSON.stringify(n.after?.value)}`:""}${s}`)}for(let n of t.issues)e.out.line(` ! ${n.key?`${n.key}: `:""}${n.message}`)}async function Hi(e,t,n,s){return h(e,t,"POST","/flags/templates/publish",s===""?{}:{note:s},{...Te(n),...C()})}var jd={name:"flags:publish",summary:"show the flags draft's changes against the live version, then publish it as the next version",usage:"[-m <note>]",flags:{note:{type:"string",short:"m",value:"note",description:"why: kept with the version"}},scope:"environment",async run(e){let t=await f(e);if(!await sn(e,t))throw Vi();if(!(await nn(e,t,!1)).draft)throw new y("no_draft","there is no draft to publish",{hint:"palbase flags:set puts a change into one"});let s=await Ne(e,t,"/flags/templates/draft/review");if(e.out.json||o_(e,s.body),!s.body.can_publish)throw new y("cannot_publish",`the draft cannot be published: ${s.body.issues.map(r=>r.message).join("; ")}`);if(s.body.changes.length===0){e.out.result({unchanged:!0,review:s.body},()=>e.out.line("Nothing to publish."));return}await v(e,t,`publish the flags draft (${s.body.changes.length} change(s)) as the version after ${s.body.active_version}`);let a=await Hi(e,t,s.etag,e.flags.note??"");e.out.result({...a,review:s.body},()=>e.out.line(a.unchanged?"The draft changed nothing; nothing was published.":`Published version ${a.template.version}.`))}},Od={name:"flags:publishing:enable",summary:"turn publishing on for the environment's flags: changes go into a shared draft, live once published \u2014 for good",details:["What is live now becomes version 1. From then on flags:set and flags:delete change the draft, flags:publish makes it live as the next version, and flags:rollback brings an earlier one back. It cannot be turned off."],scope:"environment",async run(e){let t=await f(e);if(await sn(e,t)){e.out.result({publishing:!0,changed:!1},()=>e.out.line("The environment's flags are published through drafts already."));return}await v(e,t,"turn publishing on for the flags \u2014 what is live becomes version 1, and it cannot be turned off");let n=await h(e,t,"POST","/flags/templates/activation",{});e.out.result({publishing:!0,changed:!0,version:n.version},()=>e.out.line(`Publishing is on: what was live is version ${n.version}; flags:set changes the draft, flags:publish makes it live.`))}},Md={name:"flags:versions",summary:"the published versions of the flags, newest first, and which one is live",usage:"[--limit <n>]",flags:{limit:{type:"string",value:"n",description:"how many (default 20)"}},scope:"environment",async run(e){let t=await f(e);if(!await sn(e,t))throw Vi();let n=Number(e.flags.limit??20);if(!Number.isInteger(n)||n<=0)throw g("--limit is a whole number");let s=await h(e,t,"GET",`/flags/templates/versions?limit=${n}`);e.out.result(s,()=>e.out.table(s.versions,[{header:"",value:a=>a.version===s.active_version?"*":""},{header:"version",value:a=>a.version},{header:"kind",value:a=>`${a.kind}${a.restored_from?` of ${a.restored_from}`:""}`},{header:"published",value:a=>a.created_at},{header:"by",value:a=>a.actor},{header:"note",value:a=>a.note}]))}},xd={name:"flags:rollback",summary:"make an earlier version of the flags live again (published as the next version)",usage:"<version> [-m <note>]",args:{min:1,max:1},flags:{note:{type:"string",short:"m",value:"note",description:"why (default: rollback to <version>)"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0];if(!await sn(e,t))throw Vi();if((await nn(e,t,!1)).draft)throw new y("draft_in_progress","a draft is in progress: publish it (flags:publish) before a rollback");let s=await Ne(e,t,"/flags/templates/active");await v(e,t,`make version ${n} of the flags live again (now ${s.body.version})`);let a=await qe(e,t,"POST",`/flags/templates/restore/${k(n)}`,{},Te(s.etag)),r=await Hi(e,t,a.etag,e.flags.note??`rollback to ${n}`);e.out.result(r,()=>e.out.line(r.unchanged?`Version ${n} is what is live already.`:`Version ${n} is live again, as version ${r.template.version}.`))}},Id={name:"flags",async read(e,t){let n=await h(e,t,"GET","/flags/system"),s={};for(let a of n)s[`flags.${a.key}`]=Ad(a);return s},async copy(e,t,n,s){let a=pe(n,"flags.");if(a.length===0)return;if(!await sn(e,t)){for(let i of a)i.from===void 0?await V(s,`delete the flag ${i.name}`,async()=>{await h(e,t,"DELETE",`/flags/system/${k(i.name)}`)}):await V(s,`set the flag ${i.name}`,async()=>{await h(e,t,"PUT",`/flags/system/${k(i.name)}`,i.from)});return}if((await nn(e,t,!1)).draft){s.left("flags: the target has a draft in progress \u2014 publish it (flags:publish) and copy again");return}let r=(await nn(e,t,!0)).etag;for(let i of a)await V(s,`${i.from===void 0?"take":"put"} the flag ${i.name} ${i.from===void 0?"out of":"into"} the draft`,async()=>{let o=`/flags/templates/draft/parameters/${k(i.name)}`;r=(i.from===void 0?await qe(e,t,"DELETE",o,void 0,Te(r)):await qe(e,t,"PUT",o,i.from,Te(r))).etag??r});await V(s,"publish the flags draft",async()=>{await Hi(e,t,r,"config:copy")})}};var Ld=["email","sms","verify","whatsapp","push"],Yi=["email","sms","whatsapp"],Dd={name:"notify:providers:list",summary:"the environment's own providers, by channel and the order they are tried (never their credentials)",scope:"environment",async run(e){let t=await f(e),{providers:n}=await h(e,t,"GET","/notify/providers");e.out.result({providers:n},()=>{n.length===0&&e.out.line("No provider of the environment's own: email goes through the platform's sender; texts need one (notify:providers:set)."),e.out.table(n,[{header:"channel",value:s=>s.channel},{header:"provider",value:s=>s.provider},{header:"on",value:s=>s.active?"yes":"no"},{header:"priority",value:s=>String(s.priority)},{header:"credentials",value:()=>"set"}])})}},qd={name:"notify:providers:set",summary:"bring a provider for a channel: its credentials are piped in as JSON, checked as the sender will use them, never shown",usage:"<channel> <provider> [--priority <n>] [--enable|--disable] < credentials.json",details:["email: acs {connection_string, from_email}, ses {region, access_key_id, secret_access_key, from_domain}, sendgrid {api_key, from_domain}, smtp {host, port, username, password, from_email, use_starttls}.","sms: twilio {account_sid, auth_token, from_number}, vonage {api_key, api_secret, from}, acs {connection_string, from_number}. verify: twilio_verify {account_sid, auth_token, service_sid}.","whatsapp: meta {phone_number_id, access_token, api_version, app_secret, verify_token}. push: fcm (the service account JSON), apns {private_key, team_id, key_id, bundle_id, is_production}, expo {access_token}.","The credentials are read from stdin only: never from the command line, where the shell would keep them."],args:{min:2,max:2},flags:{priority:{type:"string",value:"n",description:"lower is tried first"},...Bs},scope:"environment",async run(e){let[t,n]=e.args;if(!Ld.includes(t))throw g(`the channels: ${Ld.join(", ")}`);let s=await f(e),a=ue(await xe(e,`${n}'s credentials (JSON)`),"the credentials");if(typeof a!="object"||a===null||Array.isArray(a))throw g("the credentials are a JSON object");let r=Zn(e),i=ne(e.flags.priority,"priority");await v(e,s,`send ${t} through ${n}`);let o=await h(e,s,"PUT",`/notify/providers/${k(t)}/${k(n)}`,{credentials:a,...r!==void 0?{active:r}:{},...i!==void 0?{priority:i}:{}},C());e.out.result(o,()=>e.out.line(`${o.channel} goes through ${o.provider} (${o.active?"on":"off"}, priority ${o.priority}); its credentials are kept sealed.`))}},Nd={name:"notify:providers:remove",summary:"forget a provider and its credentials",usage:"<channel> <provider>",args:{min:2,max:2},scope:"environment",async run(e){let[t,n]=e.args,s=await f(e);await v(e,s,`forget the ${t} provider ${n} and its credentials`),await h(e,s,"DELETE",`/notify/providers/${k(t)}/${k(n)}`,void 0,C()),e.out.result({removed:{channel:t,provider:n}},()=>e.out.line(`${t} no longer goes through ${n}.`))}},Zi={channel:{type:"string",value:"channel",description:"email (default), sms or whatsapp"},locale:{type:"string",value:"locale",description:"the template's locale: en, tr, pt-BR"}};function Qs(e){let t=e.flags.channel??"email";if(!Yi.includes(t))throw g(`--channel is one of ${Yi.join(", ")}`);return t}function Qi(e,t){let n=e.flags.locale;if(n===void 0)throw g("which locale? pass --locale <locale>");return`/notify/templates/${Qs(e)}/${k(t)}/${k(n)}`}function l_(e,t){if(e==="sms"){let s=p_(t);return typeof s=="object"&&s!==null&&typeof s.body=="string"?{body:s.body}:{body:t.replace(/\n$/,"")}}let n=ue(t,`the ${e} template`);if(e==="email"){for(let s of["subject","html_body","text_body"])if(typeof n[s]!="string")throw g(`an email template is {"subject", "html_body", "text_body"}: ${s} is missing`);return{subject:n.subject,html_body:n.html_body,text_body:n.text_body}}if(typeof n.name!="string"||typeof n.language!="string")throw g('a WhatsApp template is {"name", "language", "variables", "code_button"}: the template approved on your Meta account');return{name:n.name,language:n.language,...n.variables!==void 0?{variables:n.variables}:{},...n.code_button!==void 0?{code_button:n.code_button}:{}}}function p_(e){try{return JSON.parse(e)}catch{return e}}var Kd={name:"notify:templates:list",summary:"the templates messages render from: the platform's defaults and the ones the environment overrides",usage:"[--channel email|sms|whatsapp]",flags:{channel:{type:"string",value:"channel",description:"only this channel's (default: all three)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.channel===void 0?Yi:[Qs(e)],s=await Promise.all(n.map(r=>h(e,t,"GET",`/notify/templates/${r}`))),a=n.flatMap((r,i)=>s[i].templates.map(o=>({channel:r,...o})));e.out.result({templates:a},()=>e.out.table(a,[{header:"channel",value:r=>r.channel},{header:"slug",value:r=>r.slug},{header:"locale",value:r=>r.locale},{header:"yours",value:r=>"customized"in r?r.customized?"yes":"default":"yes"},{header:"subject / text / template",value:r=>"subject"in r?r.subject:"body"in r?r.body.split(`
|
|
30
30
|
`)[0].slice(0,60):`${r.name} (${r.language})`}]))}},Gd={name:"notify:templates:get",summary:"a template as it renders now in a locale (yours, or the platform's default); --json gives the document templates:set takes",usage:"<slug> --locale <locale> [--channel email|sms|whatsapp]",args:{min:1,max:1},flags:Zi,scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET",Qi(e,e.args[0]));e.out.result(n,()=>{e.out.line(`${String(n.slug)} (${String(n.locale)}) \u2014 ${n.customized===!1?"the platform's default":"yours"}`),Array.isArray(n.variables)&&n.variables.length>0&&e.out.line(`variables: ${n.variables.join(", ")}`);for(let s of["subject","name","language"])typeof n[s]=="string"&&e.out.line(`${s}: ${String(n[s])}`);for(let s of["text_body","body","html_body"])if(typeof n[s]=="string"){e.out.line(),e.out.line(`\u2500\u2500 ${s} \u2500\u2500`);for(let a of n[s].split(`
|
|
31
|
-
`))e.out.line(a)}})}},Ud={name:"notify:templates:set",summary:"override a template in a locale, from a file or stdin (email: {subject, html_body, text_body} as JSON)",usage:"<slug> --locale <locale> [--channel email|sms|whatsapp] [--file <path>]",details:['email: {"subject", "html_body", "text_body"}; sms: the text, or {"body"}; whatsapp: {"name", "language", "variables", "code_button"} of a template approved on your Meta account.',"notify:templates:get \u2026 --json > t.json gives a document to edit and set back. Handlebars: {{name}}, {{#if}}, {{#each}}."],args:{min:1,max:1},flags:{...Zi,file:{type:"string",value:"path",description:"the template (default: stdin)"}},scope:"environment",async run(e){let t=await f(e),n=Qs(e),s=Qi(e,e.args[0]),a=l_(n,await be(e,e.flags.file,"the template"));await v(e,t,`override the ${n} template ${e.args[0]} (${e.flags.locale})`);let r=await h(e,t,"PUT",s,a,C());e.out.result(r,()=>e.out.line(`The ${n} template ${e.args[0]} (${e.flags.locale}) is yours now${typeof r.subject=="string"?`: "${r.subject}"`:""}.`))}},zd={name:"notify:templates:delete",summary:"remove an override: the platform's default renders again (a WhatsApp mapping is forgotten)",usage:"<slug> --locale <locale> [--channel email|sms|whatsapp]",args:{min:1,max:1},flags:Zi,scope:"environment",async run(e){let t=await f(e),n=Qi(e,e.args[0]);await v(e,t,`remove the ${Qs(e)} template ${e.args[0]} (${e.flags.locale})`),await h(e,t,"DELETE",n,void 0,C()),e.out.result({deleted:{channel:Qs(e),slug:e.args[0],locale:e.flags.locale}},()=>e.out.line(`Removed the override of ${e.args[0]} (${e.flags.locale}).`))}};async function Xi(e,t){let n=[],s;do{let a=await h(e,t,"GET",`/notify/topics?limit=100${s?`&cursor=${k(s)}`:""}`);n.push(...a.topics),s=a.next_cursor}while(s);return n}var Bd={name:"notify:topics:list",summary:"the topics users follow, how many follow each, whether they follow it from the app",scope:"environment",async run(e){let t=await f(e),n=await Xi(e,t);e.out.result({topics:n},()=>{n.length===0&&e.out.line("No topic: palbase notify:topics:create <name> makes one."),e.out.table(n,[{header:"topic",value:s=>s.name},{header:"followers",value:s=>String(s.subscribers)},{header:"from the app",value:s=>s.self_subscribe?"yes":"no: the project adds them"}])})}},Fd={name:"notify:topics:create",summary:"make a topic users can follow; a push to it reaches its followers",usage:"<name> [--self-subscribe yes|no]",args:{min:1,max:1},flags:{"self-subscribe":{type:"string",value:"yes|no",description:"users follow it from the app (default no: the project adds them)"}},scope:"environment",async run(e){let t=await f(e),n=en(e.flags["self-subscribe"],"self-subscribe");await v(e,t,`make the topic ${e.args[0]}`);let s=await h(e,t,"POST","/notify/topics",{name:e.args[0],...n!==void 0?{self_subscribe:n}:{}},C());e.out.result(s,()=>e.out.line(`Made the topic ${s.name}${s.self_subscribe?", followed from the app":""}.`))}},Jd={name:"notify:topics:delete",summary:"delete a topic and who follows it",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e);await v(e,t,`delete the topic ${e.args[0]} and who follows it`),await h(e,t,"DELETE",`/notify/topics/${k(e.args[0])}`,void 0,C()),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the topic ${e.args[0]}.`))}},Wd={name:"notify:settings:get",summary:"the environment's message settings: the default locale, who email is from, where texts may go",scope:"environment",async run(e){let t=await f(e),{body:n}=await Ne(e,t,"/notify/settings");e.out.result(n,()=>Xn(e,n))}},Vd={name:"notify:settings:set",summary:'change message settings: key=value (from_email=\u2026, sms_countries=["+90","+44"], mx_check=true)',usage:"<key=value>\u2026",details:["The change is made on the revision read: one made beside it in the meantime is refused, not overwritten."],args:{min:1,max:20},scope:"environment",async run(e){let t=await f(e),n=Zt(e.args),{body:s,etag:a}=await Ne(e,t,"/notify/settings"),r=Qt(s,n),i=Dt(s,r);if(i.length===0)return ze(e,"the message settings",s);await v(e,t,`set the message settings ${i.join(", ")}`);let o=await h(e,t,"PUT","/notify/settings",r,{...Te(a),...C()});e.out.result({settings:o,changed:i},()=>{for(let l of i)e.out.line(`${l}: ${Ee(s[l])} \u2192 ${Ee(o[l])}`)})}},d_=new Set(["sms_countries","sms_blocked_countries"]);function u_(e){return{...e,sms_countries:e.sms_countries??[],sms_blocked_countries:e.sms_blocked_countries??[],mx_check:e.mx_check??!1}}var Hd={name:"notify",async read(e,t){let[n,s,a,r,i,o]=await Promise.all([h(e,t,"GET","/notify/settings"),h(e,t,"GET","/notify/providers"),h(e,t,"GET","/notify/templates/email"),h(e,t,"GET","/notify/templates/sms"),h(e,t,"GET","/notify/templates/whatsapp"),Xi(e,t)]),l={};for(let[u,m]of Object.entries(u_(n)))l[`settings.${u}`]=m;for(let u of s.providers)l[`providers.${u.channel}/${u.provider}`]={active:u.active,priority:u.priority,credentials:"set"};let d=a.templates.filter(u=>u.customized),p=await Promise.all(d.map(u=>h(e,t,"GET",`/notify/templates/email/${k(u.slug)}/${k(u.locale)}`)));for(let u of p)l[`templates.email/${u.slug}/${u.locale}`]={subject:u.subject,html_body:u.html_body,text_body:u.text_body};for(let u of r.templates.filter(m=>m.customized))l[`templates.sms/${u.slug}/${u.locale}`]={body:u.body};for(let u of i.templates)l[`templates.whatsapp/${u.slug}/${u.locale}`]={name:u.name,language:u.language,variables:u.variables,code_button:u.code_button};for(let u of o)l[`topics.${u.name}`]={self_subscribe:u.self_subscribe};return l},async copy(e,t,n,s){let a=pe(n,"settings.");if(a.length>0){let{body:o,etag:l}=await Ne(e,t,"/notify/settings"),d={...o};for(let p of a)d[p.name]=d_.has(p.name)&&Array.isArray(p.from)&&p.from.length===0?null:p.from;await V(s,`set the message settings ${a.map(p=>p.name).join(", ")}`,async()=>{await h(e,t,"PUT","/notify/settings",d,{...Te(l),...C()})})}for(let o of pe(n,"providers.")){let[l,d]=o.name.split("/");o.from===void 0?s.left(`the ${l} provider ${d}: only in the target, left as it is (it holds credentials)`):s.left(`the ${l} provider ${d}: credentials are not copied \u2014 set them with palbase notify:providers:set ${l} ${d} < credentials.json`)}for(let o of pe(n,"templates.")){let l=`/notify/templates/${o.name.split("/").map(k).join("/")}`;o.from===void 0?await V(s,`remove the template override ${o.name}`,async()=>{await h(e,t,"DELETE",l,void 0,C())}):await V(s,`override the template ${o.name}`,async()=>{await h(e,t,"PUT",l,o.from,C())})}let r=pe(n,"topics."),i=r.some(o=>o.from===void 0)?new Map((await Xi(e,t)).map(o=>[o.name,o.subscribers])):new Map;for(let o of r){let l=`/notify/topics/${k(o.name)}`,d=o.from?.self_subscribe;if(o.from===void 0){let p=i.get(o.name)??0;p>0?s.left(`the topic ${o.name}: only in the target, and ${p} users follow it \u2014 delete it with notify:topics:delete`):await V(s,`delete the topic ${o.name}`,async()=>{await h(e,t,"DELETE",l,void 0,C())})}else o.change==="only_in_from"?await V(s,`make the topic ${o.name}`,async()=>{await h(e,t,"POST","/notify/topics",{name:o.name,self_subscribe:d},C())}):await V(s,`set the topic ${o.name} ${d?"followed from the app":"followed by the project's adding"}`,async()=>{await h(e,t,"PATCH",l,{self_subscribe:d},C())})}}};var ts=["max_connections","max_events_per_second","max_joins_per_second","max_channels_per_connection"];function c_(e){if(e.kind==="owner")return"the user it names: everything";let t=[e.publish?"publish":"",e.state_read?"read state":"",e.state_write?"write state":""].filter(n=>n!=="");return`any signed-in user: subscribe${t.length>0?`, ${t.join(", ")}`:""}`}function eo(e){return Object.fromEntries(ts.map(t=>[t,e[t]??null]))}var Yd={name:"realtime:channels:get",summary:"the channel declaration, in the order patterns are matched: who may join each, publish, read and write its state",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET","/realtime/channels");e.out.result(n,()=>{n.channels.length===0&&e.out.line("No channel is declared: a channel no pattern matches belongs to no one."),e.out.table(n.channels,[{header:"pattern",value:s=>s.pattern},{header:"kind",value:s=>s.kind},{header:"who",value:s=>c_(s)}])})}},Xd={name:"realtime:channels:set",summary:'replace the channel declaration with a JSON file or stdin ({"channels": [\u2026]} or the list)',usage:"[--file <path>]",details:['Each channel: {"pattern": "room:{id}", "kind": "public", "publish": true, "state_read": true, "state_write": false}, or {"pattern": "user:{uid}", "kind": "owner"}.',"realtime:channels:get --json gives the document to edit. Open sockets are decided again within a heartbeat."],flags:{file:{type:"string",value:"path",description:"the declaration (default: stdin)"}},scope:"environment",async run(e){let t=await f(e),n=ue(await be(e,e.flags.file,"the channel declaration"),"the channel declaration"),s=Array.isArray(n)?n:n.channels;if(!Array.isArray(s))throw g('the declaration is {"channels": [\u2026]} or a list of channels');let a=await h(e,t,"GET","/realtime/channels");if(Me(a.channels,s))return ze(e,"the channel declaration",a);await v(e,t,`declare ${s.length} channel pattern(s) (now ${a.channels.length})`);let r=await h(e,t,"PUT","/realtime/channels",{channels:s});e.out.result(r,()=>e.out.line(r.channels.length===0?"No channel is declared now.":`Declared ${r.channels.length} channel pattern(s): ${r.channels.map(i=>i.pattern).join(", ")}.`))}},Zd={name:"realtime:limits:get",summary:"the limits the environment holds its clients to (null: the platform's), and the platform's",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET","/realtime/limits");e.out.result(n,()=>{let s=n.platform??{},a=Math.max(...ts.map(r=>r.length));for(let r of ts)e.out.line(`${r.padEnd(a)} ${n[r]===void 0||n[r]===null?"the platform's":Ee(n[r])}${s[r]!==void 0?` (platform ${s[r]===0?"no ceiling":Ee(s[r])})`:""}`)})}},Qd={name:"realtime:limits:set",summary:"change realtime limits: key=value (max_connections=500), null for the platform's",usage:"<key=value>\u2026",details:[`The keys: ${ts.join(", ")}. A value above the platform's has no effect beyond it.`],args:{min:1,max:4},scope:"environment",async run(e){let t=await f(e),n=Zt(e.args);for(let o of n)if(o.path.length!==1||!ts.includes(o.path[0]))throw g(`no limit ${JSON.stringify(o.path.join("."))}`,`the limits: ${ts.join(", ")}`);let s=eo(await h(e,t,"GET","/realtime/limits")),a=Qt(s,n),r=Dt(s,a);if(r.length===0)return ze(e,"the realtime limits",s);await v(e,t,`set the realtime limits ${r.join(", ")}`);let i=await h(e,t,"PUT","/realtime/limits",a);e.out.result({limits:i,changed:r},()=>{for(let o of r)e.out.line(`${o}: ${Ee(s[o]??"the platform's")} \u2192 ${Ee(i[o]??"the platform's")}`)})}},eu={name:"realtime",async read(e,t){let[n,s]=await Promise.all([h(e,t,"GET","/realtime/channels"),h(e,t,"GET","/realtime/limits")]),a={channels:n.channels};for(let[r,i]of Object.entries(eo(s)))a[`limits.${r}`]=i;return a},async copy(e,t,n,s){let a=n.find(i=>i.key==="channels");a&&await V(s,"declare the channels",async()=>{await h(e,t,"PUT","/realtime/channels",{channels:a.from??[]})});let r=pe(n,"limits.");if(r.length>0){let i=eo(await h(e,t,"GET","/realtime/limits"));for(let o of r)i[o.name]=o.from??null;await V(s,`set the realtime limits ${r.map(o=>o.name).join(", ")}`,async()=>{await h(e,t,"PUT","/realtime/limits",i)})}}},tu={name:"analytics:settings:get",summary:"how long analytics keeps events and console records, the share of performance samples kept, whether bodies are kept",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET","/analytics/settings");e.out.result(n,()=>Xn(e,n))}},nu={name:"analytics:settings:set",summary:"change analytics settings: key=value (retention_days=30, perf_sample_pct=10, console_bodies=false)",usage:"<key=value>\u2026",details:["A shorter retention removes what is older within minutes."],args:{min:1,max:4},scope:"environment",async run(e){let t=await f(e),n=Zt(e.args),s=await h(e,t,"GET","/analytics/settings"),a=Qt(s,n),r=Dt(s,a);if(r.length===0)return ze(e,"the analytics settings",s);await v(e,t,`set the analytics settings ${r.join(", ")}`);let i=await h(e,t,"PUT","/analytics/settings",a);e.out.result({settings:i,changed:r},()=>{for(let o of r)e.out.line(`${o}: ${Ee(s[o])} \u2192 ${Ee(i[o])}`)})}},su={name:"analytics",async read(e,t){let n=await h(e,t,"GET","/analytics/settings");return Object.fromEntries(Object.entries(n).map(([s,a])=>[`settings.${s}`,a]))},async copy(e,t,n,s){let a=pe(n,"settings.");if(a.length===0)return;let r=await h(e,t,"GET","/analytics/settings");for(let i of a)i.from!==void 0&&(r[i.name]=i.from);await V(s,`set the analytics settings ${a.map(i=>i.name).join(", ")}`,async()=>{await h(e,t,"PUT","/analytics/settings",r)})}};function h_(e){return{source:{repository:e.source.repository.toLowerCase(),branch:e.source.branch,path:e.source.path??"",context:e.source.context??""},size:e.size,replicas:e.replicas,port:e.port,health_path:e.health_path??"",env:e.env??{},secrets:e.secrets??"",database:e.database?{name:e.database.name,migrations:e.database.migrations===!0}:null,deploy_after_checks:e.deploy_after_checks===!0,deploy_checks:[...e.deploy_checks??[]].sort(),deploy_checks_app:e.deploy_checks_app??"github-actions"}}var au={name:"machines",async read(e,t){let{machines:n}=await h(e,t,"GET","/machines?limit=100");return Object.fromEntries(n.filter(s=>!s.preview_of).map(s=>[`machines.${s.name}`,h_(s)]))},async copy(e,t,n,s){for(let a of pe(n,"machines.")){if(a.change==="only_in_to"){s.left(`the machine ${a.name}: only the target has it \u2014 it serves on (palbase machines:delete ${a.name} takes it away)`);continue}let r=a.from;if(a.change==="only_in_from"){await V(s,`opened the machine ${a.name}, built from ${r.source.branch}'s head`,()=>h(e,t,"POST","/machines",{name:a.name,...r,database:r.database??void 0},C()));continue}let i=a.to,o=Object.fromEntries(Object.keys(r).filter(l=>!Me(r[l],i[l])).map(l=>[l,l==="database"&&r[l]===null?{name:""}:r[l]]));await V(s,`changed the machine ${a.name}: ${Object.keys(o).join(", ")} (a new version rolls out beside the one serving)`,()=>h(e,t,"PATCH",`/machines/${k(a.name)}`,o))}}};function m_(e){return{size:e.size,allow:[...e.allow].sort(),backup_days:e.backup_days}}async function g_(e,t,n,s){let a=await h(e,t,"POST","/databases",{name:n,...s},C());await e.state.keepDatabasePasswords(t.env_ref,a.name,{owner:a.credentials.owner.password,app:a.credentials.app.password})}var ru={name:"databases",async read(e,t){let{databases:n}=await h(e,t,"GET","/databases?limit=100");return Object.fromEntries(n.filter(s=>s.size!=="preview").map(s=>[`databases.${s.name}`,m_(s)]))},async copy(e,t,n,s){for(let a of pe(n,"databases.")){if(a.change==="only_in_to"){s.left(`the database ${a.name}: only the target has it \u2014 its data stays (palbase databases:delete ${a.name} takes it away)`);continue}let r=a.from;if(a.change==="only_in_from"){await V(s,`opened the database ${a.name} (${r.size}; its passwords kept on this computer \u2014 palbase db:copy brings its data)`,()=>g_(e,t,a.name,r));continue}let i=a.to,o=Object.fromEntries(["size","allow","backup_days"].filter(d=>!Me(r[d],i[d])).map(d=>[d,r[d]]));if(Object.keys(o).length===0)continue;let l=o.size===void 0?"":` (moving to ${o.size}, serving on)`;await V(s,`changed the database ${a.name}: ${Object.keys(o).join(", ")}${l}`,()=>h(e,t,"PATCH",`/databases/${k(a.name)}`,o))}}};var tt="/messaging/settings",f_=/^[A-Z][A-Z0-9_]{0,127}$/,no=["retention_days","push_preview","deleted_user_messages","search_by_meaning","event_text"];function ns(e,t){switch(e){case"retention_days":return t===null?"off: messages are kept for good":`${String(t)} days: older messages are removed`;case"push_preview":return t===!0?"on: a push says what the message says":"off: a push says only that a message came";case"deleted_user_messages":return t==="delete"?"delete: a deleted user's messages go with them":"keep: a deleted user's messages stay, their writer anonymous";case"search_by_meaning":return t===!0?"on: messages are found by what they mean too, each embedded by the AI module (billed as AI use)":"off: messages are found by their words alone";case"event_text":return t===!0?"on: messaging.message.created says what the message says":"off: messaging.message.created says who wrote to whom, not what (the backend reads it with the secret key)";case"hook":return t?iu(t):"none: anyone may reach anyone"}}function iu(e){return`${A(e.url)} (waited for ${e.timeout_ms} ms; when it does not answer, ${e.on_error==="allow"?"everyone is allowed":"no one is: the app is told to try again"})`}function y_(e,t){let n=[...no.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,r]of n)e.out.line(`${a.padEnd(s)} ${ns(a,r)}`)}function to(e,t){if(e!==void 0){if(e==="on")return!0;if(e==="off")return!1;throw g(`--${t} is on or off`)}}function b_(e){if(e===void 0)return;if(e==="off")return null;let t=Number(e);if(!/^[0-9]+$/.test(String(e))||t<1||t>36500)throw g("--retention-days is a whole number of days from 1 to 36500, or off (kept for good)");return t}var w_={name:"messaging:settings:get",summary:"how the environment runs its conversations: how long messages are kept, whether a push says what one says, what becomes of a deleted user's messages, whether they are found by what they mean, whether a message's event says what it says, the hook",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET",tt);e.out.result(n,()=>y_(e,n))}},v_={name:"messaging:settings:set",summary:"change how the environment runs its conversations: a setting left out is left as it is",usage:"[--retention-days <days>|off] [--push-preview on|off] [--deleted-user-messages keep|delete] [--search-by-meaning on|off] [--event-text on|off]",details:["A shorter retention removes the messages older than it, in every conversation. A deleted user's messages are kept or deleted as the setting is when the user is deleted.","Deleted, what of theirs had already gone from screens (seen once, its time up, vanish mode, taken back) stays its 14 days, sealed, for reports, then goes.","Search by meaning on: the app's search({ by: 'meaning' }) finds the messages nearest what a question means, no word of it needed. Each message's text (not a system message's, one seen a limited number of times, nor one of vanish mode) is embedded by the project's embedding model through the AI module and billed as the project's AI use; the messages written before are embedded in the background (seconds to minutes), a new one is found ~5 s after it is sent. Off: no message goes to a model, and the vectors are removed.","Event text on: messaging.message.created \u2014 told to the backend's webhooks and @On handlers that name it \u2014 carries the message's text (not a vanish-mode message's, one seen a limited number of times, nor one that goes after a time). The words leave the sealed store and stay on the event stream 7 days. Off: the backend reads the message with the secret key.","Only what changes is sent: a change made beside this one to another setting stays."],flags:{"retention-days":{type:"string",value:"days|off",description:"messages older than this many days are removed (1\u201336500); off: kept for good"},"push-preview":{type:"string",value:"on|off",description:"a push says what the message says (on), or only that one came (off)"},"deleted-user-messages":{type:"string",value:"keep|delete",description:"a deleted user's messages: kept, their writer anonymous, or deleted (what went from screens before stays its 14 days for reports)"},"search-by-meaning":{type:"string",value:"on|off",description:"messages are found by what they mean too (on: each embedded through the AI module, billed as AI use), or by their words alone (off)"},"event-text":{type:"string",value:"on|off",description:"messaging.message.created says what the message says (on), or who wrote to whom alone (off)"}},scope:"environment",async run(e){let t={},n=b_(e.flags["retention-days"]);n!==void 0&&(t.retention_days=n);let s=to(e.flags["push-preview"],"push-preview");s!==void 0&&(t.push_preview=s);let a=e.flags["deleted-user-messages"];if(a!==void 0){if(a!=="keep"&&a!=="delete")throw g("--deleted-user-messages is keep or delete");t.deleted_user_messages=a}let r=to(e.flags["search-by-meaning"],"search-by-meaning");r!==void 0&&(t.search_by_meaning=r);let i=to(e.flags["event-text"],"event-text");if(i!==void 0&&(t.event_text=i),Object.keys(t).length===0)throw g("nothing to change","pass --retention-days, --push-preview, --deleted-user-messages, --search-by-meaning or --event-text");let o=await f(e),l=await h(e,o,"GET",tt),d=no.filter(u=>u in t&&!Me(l[u],t[u]));if(d.length===0)return ze(e,"the messaging settings",l);await v(e,o,`set the messaging settings ${d.join(", ")}`);let p=await h(e,o,"PUT",tt,Object.fromEntries(d.map(u=>[u,t[u]])));e.out.result({settings:p,changed:d},()=>{for(let u of d)e.out.line(`${u}: ${ns(u,l[u])} \u2192 ${ns(u,p[u])}`)})}},ou={"secret-to":{type:"string",value:"NAME",description:"keep the new signing secret in the environment's secret NAME instead of printing it"},dev:{type:"boolean",description:"with --secret-to: the development secrets, not production"}};function lu(e){let t=e.flags["secret-to"];if(t!==void 0&&!f_.test(t))throw g(`--secret-to ${JSON.stringify(t)} is not a secret's name: capital letters, digits and _, a letter first`);if(e.flags.dev===!0&&t===void 0)throw g("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function pu(e,t,n,s,a){let{hook_secret:r,...i}=n;if(r===void 0){e.out.result({settings:i},()=>e.out.line(`${a}: ${ns("hook",i.hook)}.`));return}if(s!==void 0){let o=await h(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:r});e.out.result({settings:i,secret_to:{set:s.set,name:s.name,version:o.version}},()=>e.out.line(`${a}: ${ns("hook",i.hook)}; its signing secret is ${s.name} (${s.set}, v${o.version}) in ${q(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${ns("hook",i.hook)}.`),e.out.line(`signing secret (shown this once): ${r}`)})}var __={name:"messaging:hook:get",summary:"the hook asked whom one may reach: where it is, how long it is waited for, what is done when it does not answer (never its secret)",scope:"environment",async run(e){let t=await f(e),{hook:n}=await h(e,t,"GET",tt);e.out.result({hook:n},()=>e.out.line(n?iu(n):"No hook: anyone may reach anyone. palbase messaging:hook:set --url <url> sets one."))}},k_={name:"messaging:hook:set",summary:"set the hook asked whom one may reach, or change it; a new hook's signing secret is printed this once, or kept in a secret with --secret-to",usage:"[--url <url>] [--timeout-ms <ms>] [--on-error allow|deny] [--secret-to <NAME> [--dev]]",details:[`Before a direct conversation opens, people are added to a group, someone makes or opens an open group, a space's open groups are listed or one is joined, the hook is POSTed {"event": "messaging.can_message", "action": "direct" | "group_add" | "open_group" | "list_open" | "join", "from_user_id", "to_user_ids", "conversation_id", "space"}, signed as Standard Webhooks sign (webhook-id, webhook-timestamp, webhook-signature), and answers 200 {"allowed_user_ids": [\u2026]}: whom of to_user_ids from_user_id may reach \u2014 for open_group, list_open and join, to_user_ids is [from_user_id], and naming them lets them in. space is the conversation's (absent: none).`,"A new hook takes --url (an https URL on the public internet). Its signing secret is printed this once, or kept in the environment's secrets with --secret-to (production; --dev: development) and printed nowhere. A hook changed keeps its secret: palbase messaging:hook:secret:rotate makes a new one."],flags:{url:{type:"string",value:"url",description:"where the hook is asked"},"timeout-ms":{type:"string",value:"ms",description:"how long it is waited for: 100 to 5000 (a new hook: 2000)"},"on-error":{type:"string",value:"allow|deny",description:"when it does not answer: allow everyone, or deny and the app is told to try again (a new hook: deny)"},...ou},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw g("--url is where the hook is asked: an https URL");let n;if(e.flags["timeout-ms"]!==void 0&&(n=Number(e.flags["timeout-ms"]),!/^[0-9]+$/.test(String(e.flags["timeout-ms"]))||n<100||n>5e3))throw g("--timeout-ms is a whole number from 100 to 5000");let s=e.flags["on-error"];if(s!==void 0&&s!=="allow"&&s!=="deny")throw g("--on-error is allow or deny");if(t===void 0&&n===void 0&&s===void 0)throw g("nothing to change","pass --url, --timeout-ms or --on-error");let a=lu(e),r=await f(e),i=await h(e,r,"GET",tt),o=i.hook;if(!o&&t===void 0)throw g("the environment has no hook yet: --url names where it is asked");if(o&&a!==void 0)throw g("the hook has its signing secret, and a change keeps it: --secret-to goes with a new hook","palbase messaging:hook:secret:rotate --secret-to <NAME> makes a new secret and keeps it");let l={url:t??o.url},d=n??o?.timeout_ms;d!==void 0&&(l.timeout_ms=d);let p=s??o?.on_error;if(p!==void 0&&(l.on_error=p),o&&Me(o,{...o,...l}))return ze(e,"the hook",i);let u=o?["url","timeout_ms","on_error"].filter(b=>l[b]!==o[b]):[];await v(e,r,o?`change the messaging hook: ${u.join(", ")}`:`set the messaging hook ${l.url}${a?`, its secret kept in ${a.name} (${a.set})`:""}`);let m=await h(e,r,"PUT",tt,{hook:l});await pu(e,r,m,a,o?"Changed the hook":"Set the hook")}},S_={name:"messaging:hook:remove",summary:"remove the hook: anyone may reach anyone, and its signing secret is forgotten",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET",tt);if(!n.hook){e.out.result({settings:n,changed:[]},()=>e.out.line("Nothing to change: the environment has no hook."));return}await v(e,t,`remove the messaging hook ${n.hook.url}: anyone may reach anyone, and its signing secret is forgotten`);let s=await h(e,t,"PUT",tt,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may reach anyone."))}},$_={name:"messaging:hook:secret:rotate",summary:"make the hook's signing secret anew: printed this once, or kept in a secret with --secret-to; the old one signs nothing more",usage:"[--secret-to <NAME> [--dev]]",details:["The hook's calls are signed with the new secret alone from now: the endpoint verifies them with it (a machine reads a secret kept with --secret-to at its next start)."],flags:ou,scope:"environment",async run(e){let t=lu(e),n=await f(e);await v(e,n,`make the messaging hook's signing secret anew; the old one signs nothing more${t?`; the new one kept in ${t.name} (${t.set})`:""}`);let s=await h(e,n,"POST",`${tt}/hook-secret`);await pu(e,n,s,t,"Made the signing secret anew for the hook")}},du={name:"messaging",async read(e,t){let n=await h(e,t,"GET",tt),s={};for(let a of no)s[`settings.${a}`]=n[a];return n.hook&&(s.hook={url:n.hook.url,timeout_ms:n.hook.timeout_ms,on_error:n.hook.on_error}),s},async copy(e,t,n,s){let a=pe(n,"settings.");a.length>0&&await V(s,`set the messaging settings ${a.map(l=>l.name).join(", ")}`,async()=>{await h(e,t,"PUT",tt,Object.fromEntries(a.map(l=>[l.name,l.from])))});let r=n.find(l=>l.key==="hook");if(!r)return;if(r.from===void 0){await V(s,`remove the hook ${r.to.url}`,async()=>{await h(e,t,"PUT",tt,{hook:null})});return}let i=r.from,o;await V(s,`${r.change==="differs"?"change":"set"} the hook ${i.url}`,async()=>{o=(await h(e,t,"PUT",tt,{hook:i})).hook_secret}),o&&s.shown(`the hook ${i.url} signs with`,o)}},uu=[w_,v_,__,k_,S_,$_];var nt="/calls/settings",P_=/^[A-Z][A-Z0-9_]{0,127}$/,ao=["max_participants","calls_per_hour"];function ss(e,t){switch(e){case"max_participants":return`${String(t)}: a call holds at most this many, people and bots together`;case"calls_per_hour":return`${String(t)}: one person may start at most this many calls in an hour`;case"hook":return t?cu(t):"none: anyone may call anyone (blocks aside)"}}function cu(e){return`${A(e.url)} (waited for ${e.timeout_ms??2e3} ms; when it does not answer, ${e.on_error==="allow"?"everyone is allowed":"no one is: the call is refused"})${e.places?"; asked of places too":""}`}function A_(e,t){let n=[...ao.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,r]of n)e.out.line(`${a.padEnd(s)} ${ss(a,r)}`)}function so(e,t,n,s){if(e===void 0)return;let a=Number(e);if(!/^[0-9]+$/.test(String(e))||a<n||a>s)throw g(`--${t} is a whole number from ${n} to ${s}`);return a}var R_={name:"calls:settings:get",summary:"how the environment runs its calls: how many a call holds, how many calls a person may start in an hour, the hook",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET",nt);e.out.result(n,()=>A_(e,n))}},T_={name:"calls:settings:set",summary:"change how the environment runs its calls: a setting left out is left as it is",usage:"[--max-participants <n>] [--calls-per-hour <n>]",details:["A call holds at most --max-participants, people and the project's bots together, as the setting was when the call was made: a change holds for the calls made after it.","Every call's media, one to one or in a group, goes through the platform's media server: no device learns another's address.","A person who has started --calls-per-hour calls in the last hour is refused another (too_many_calls).","Only what changes is sent: a change made beside this one to another setting stays."],flags:{"max-participants":{type:"string",value:"n",description:"how many a call holds, people and bots together (2\u2013100)"},"calls-per-hour":{type:"string",value:"n",description:"how many calls one person may start in an hour (1\u20131000)"}},scope:"environment",async run(e){let t={},n=so(e.flags["max-participants"],"max-participants",2,100);n!==void 0&&(t.max_participants=n);let s=so(e.flags["calls-per-hour"],"calls-per-hour",1,1e3);if(s!==void 0&&(t.calls_per_hour=s),Object.keys(t).length===0)throw g("nothing to change","pass --max-participants or --calls-per-hour");let a=await f(e),r=await h(e,a,"GET",nt),i=ao.filter(l=>l in t&&!Me(r[l],t[l]));if(i.length===0)return ze(e,"the call settings",r);await v(e,a,`set the call settings ${i.join(", ")}`);let o=await h(e,a,"PUT",nt,Object.fromEntries(i.map(l=>[l,t[l]])));e.out.result({settings:o,changed:i},()=>{for(let l of i)e.out.line(`${l}: ${ss(l,r[l])} \u2192 ${ss(l,o[l])}`)})}},hu={"secret-to":{type:"string",value:"NAME",description:"keep the new signing secret in the environment's secret NAME instead of printing it"},dev:{type:"boolean",description:"with --secret-to: the development secrets, not production"}};function mu(e){let t=e.flags["secret-to"];if(t!==void 0&&!P_.test(t))throw g(`--secret-to ${JSON.stringify(t)} is not a secret's name: capital letters, digits and _, a letter first`);if(e.flags.dev===!0&&t===void 0)throw g("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function gu(e,t,n,s,a){let{hook_secret:r,...i}=n;if(r===void 0){e.out.result({settings:i},()=>e.out.line(`${a}: ${ss("hook",i.hook)}.`));return}if(s!==void 0){let o=await h(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:r});e.out.result({settings:i,secret_to:{set:s.set,name:s.name,version:o.version}},()=>e.out.line(`${a}: ${ss("hook",i.hook)}; its signing secret is ${s.name} (${s.set}, v${o.version}) in ${q(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${ss("hook",i.hook)}.`),e.out.line(`signing secret (shown this once): ${r}`)})}var E_={name:"calls:hook:get",summary:"the hook asked whom one may call: where it is, how long it is waited for, what is done when it does not answer (never its secret)",scope:"environment",async run(e){let t=await f(e),{hook:n}=await h(e,t,"GET",nt);e.out.result({hook:n},()=>e.out.line(n?cu(n):"No hook: anyone may call anyone (blocks aside). palbase calls:hook:set --url <url> sets one."))}},C_={name:"calls:hook:set",summary:"set the hook asked whom one may call, or change it; a new hook's signing secret is printed this once, or kept in a secret with --secret-to",usage:"[--url <url>] [--timeout-ms <ms>] [--on-error allow|deny] [--places on|off] [--secret-to <NAME> [--dev]]",details:['Before a call is made, or more people are asked into one, the hook is POSTed {"event": "calls.can_call", "action": "start" | "invite", "from_user_id", "to_user_ids", "video", "call_id", "conversation_id"}, signed as Standard Webhooks sign (webhook-id, webhook-timestamp, webhook-signature), and answers 200 {"allowed_user_ids": [\u2026]}: only those are called, and with none the call is refused.',`With --places on, the hook is asked of places too ({"action": "place", "place", "from_user_id", "to_user_ids": [that person]}): it says who may see and join the meeting held at a place of the app (a channel). Off (a new hook), places are not asked of it, and a place's meeting is seen only by the people asked into it.`,"A new hook takes --url (a URL on the public internet). Its signing secret is printed this once, or kept in the environment's secrets with --secret-to (production; --dev: development) and printed nowhere. A hook changed keeps its secret: palbase calls:hook:secret:rotate makes a new one."],flags:{url:{type:"string",value:"url",description:"where the hook is asked"},"timeout-ms":{type:"string",value:"ms",description:"how long it is waited for: 100 to 5000 (a new hook: 2000)"},"on-error":{type:"string",value:"allow|deny",description:"when it does not answer: allow everyone, or deny and the call is refused (a new hook: deny)"},places:{type:"string",value:"on|off",description:"the hook answers places too: who may see and join a channel's meeting (a new hook: off)"},...hu},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw g("--url is where the hook is asked: a URL");let n=so(e.flags["timeout-ms"],"timeout-ms",100,5e3),s=e.flags["on-error"];if(s!==void 0&&s!=="allow"&&s!=="deny")throw g("--on-error is allow or deny");let a=e.flags.places;if(a!==void 0&&a!=="on"&&a!=="off")throw g("--places is on or off");let r=a===void 0?void 0:a==="on";if(t===void 0&&n===void 0&&s===void 0&&r===void 0)throw g("nothing to change","pass --url, --timeout-ms, --on-error or --places");let i=mu(e),o=await f(e),l=await h(e,o,"GET",nt),d=l.hook;if(!d&&t===void 0)throw g("the environment has no hook yet: --url names where it is asked");if(d&&i!==void 0)throw g("the hook has its signing secret, and a change keeps it: --secret-to goes with a new hook","palbase calls:hook:secret:rotate --secret-to <NAME> makes a new secret and keeps it");let p={url:t??d.url},u=n??d?.timeout_ms;u!==void 0&&(p.timeout_ms=u);let m=s??d?.on_error;m!==void 0&&(p.on_error=m);let b=r??d?.places;if(b!==void 0&&(p.places=b),d&&Me(d,{...d,...p}))return ze(e,"the hook",l);let w=d?["url","timeout_ms","on_error","places"].filter(T=>(p[T]??!1)!==(d[T]??!1)):[];await v(e,o,d?`change the calls hook: ${w.join(", ")}`:`set the calls hook ${p.url}${i?`, its secret kept in ${i.name} (${i.set})`:""}`);let _=await h(e,o,"PUT",nt,{hook:p});await gu(e,o,_,i,d?"Changed the hook":"Set the hook")}},j_={name:"calls:hook:remove",summary:"remove the hook: anyone may call anyone (blocks aside), and its signing secret is forgotten",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET",nt);if(!n.hook){e.out.result({settings:n,changed:[]},()=>e.out.line("Nothing to change: the environment has no hook."));return}await v(e,t,`remove the calls hook ${n.hook.url}: anyone may call anyone, and its signing secret is forgotten`);let s=await h(e,t,"PUT",nt,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may call anyone (blocks aside)."))}},O_={name:"calls:hook:secret:rotate",summary:"make the hook's signing secret anew: printed this once, or kept in a secret with --secret-to; the old one signs nothing more",usage:"[--secret-to <NAME> [--dev]]",details:["The hook's calls are signed with the new secret alone from now: the endpoint verifies them with it (a machine reads a secret kept with --secret-to at its next start)."],flags:hu,scope:"environment",async run(e){let t=mu(e),n=await f(e);await v(e,n,`make the calls hook's signing secret anew; the old one signs nothing more${t?`; the new one kept in ${t.name} (${t.set})`:""}`);let s=await h(e,n,"POST",`${nt}/hook-secret`);await gu(e,n,s,t,"Made the signing secret anew for the hook")}},fu={name:"calls",async read(e,t){let n=await h(e,t,"GET",nt),s={};for(let a of ao)s[`settings.${a}`]=n[a];return n.hook&&(s.hook={url:n.hook.url,timeout_ms:n.hook.timeout_ms,on_error:n.hook.on_error}),s},async copy(e,t,n,s){let a=pe(n,"settings.");a.length>0&&await V(s,`set the call settings ${a.map(l=>l.name).join(", ")}`,async()=>{await h(e,t,"PUT",nt,Object.fromEntries(a.map(l=>[l.name,l.from])))});let r=n.find(l=>l.key==="hook");if(!r)return;if(r.from===void 0){await V(s,`remove the hook ${r.to.url}`,async()=>{await h(e,t,"PUT",nt,{hook:null})});return}let i=r.from,o;await V(s,`${r.change==="differs"?"change":"set"} the hook ${i.url}`,async()=>{o=(await h(e,t,"PUT",nt,{hook:i})).hook_secret}),o&&s.shown(`the hook ${i.url} signs with`,o)}},yu=[R_,T_,E_,C_,j_,O_];var M_=/^[a-z][a-z0-9-]{1,62}$/;function as(e){if(!M_.test(e))throw g(`${JSON.stringify(e)} is not a bucket's name: lowercase letters, digits and dashes, starting with a letter (2\u201363)`);return`/storage/buckets/${k(e)}`}function io(e){if(e==null)return"platform (5 GiB)";for(let[t,n]of[["GiB",2**30],["MiB",2**20],["KiB",2**10]])if(e>=n&&e%n===0)return`${e/n} ${t}`;return`${e} B`}function x_(e){if(e===""||e==="platform")return null;let t=/^(\d+(?:\.\d+)?)\s*(b|kb|kib|mb|mib|gb|gib)?$/i.exec(e.trim());if(!t)throw g(`--max-size ${JSON.stringify(e)} is not a size: 10MB, 512KiB, 1GB, a number of bytes, or platform`);let n=(t[2]??"b").toLowerCase(),s={b:1,kb:1e3,kib:2**10,mb:1e6,mib:2**20,gb:1e9,gib:2**30};return Math.round(Number(t[1])*s[n])}function ro(e){return{public:e.public,file_size_limit:e.file_size_limit??null,allowed_mime_types:e.allowed_mime_types??[],variants:e.variants??[]}}async function I_(e,t,n){try{return await h(e,t,"GET",as(n))}catch(s){if(s instanceof j&&s.status===404)return;throw s}}var bu={name:"storage:buckets:list",summary:"the environment's buckets: who may read each, the largest file and the types it takes",scope:"environment",async run(e){let t=await f(e),{buckets:n}=await h(e,t,"GET","/storage/buckets");e.out.result({buckets:n},()=>{n.length===0&&e.out.line("No bucket yet: palbase storage:buckets:set <name> makes one."),e.out.table(n,[{header:"bucket",value:s=>s.name},{header:"read by",value:s=>s.public?"anyone":"signed URLs, rules"},{header:"largest file",value:s=>io(s.file_size_limit)},{header:"types",value:s=>s.allowed_mime_types.length===0?"any":s.allowed_mime_types.join(", ")},{header:"renditions",value:s=>s.variants.map(a=>a.name).join(", ")}])})}},wu={name:"storage:buckets:get",summary:"a bucket's declaration in full, with its renditions",usage:"<bucket>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET",as(e.args[0]));e.out.result(n,()=>{e.out.line(n.name),e.out.line(` read by ${n.public?"anyone, at /storage/public/":"signed URLs and the rules"}`),e.out.line(` largest file ${io(n.file_size_limit)}`),e.out.line(` types ${n.allowed_mime_types.length===0?"any":n.allowed_mime_types.join(", ")}`);for(let s of n.variants)e.out.line(` rendition ${s.name}: ${s.width}\xD7${s.height} ${s.fit}, ${s.format}${s.quality?` q${s.quality}`:""}`)})}},vu={name:"storage:buckets:set",summary:"make a bucket, or change one: public or private, the largest file, the content types, its renditions",usage:"<bucket> [--public|--private] [--max-size <size>] [--types <a/b,c/*>] [--variants-file <path>]",details:["What is not given is kept as it is (a new bucket: private, the platform's size, any type, no rendition)."],args:{min:1,max:1},flags:{public:{type:"boolean",description:"anyone may read its files at /storage/public/"},private:{type:"boolean",description:"its files are read with signed URLs and the rules"},"max-size":{type:"string",value:"size",description:"the largest file: 10MB, 512KiB, 1GB, bytes, or platform"},types:{type:"string",value:"list",description:'the content types it takes, comma-separated (image/* a family); "" for any'},"variants-file":{type:"string",value:"path",description:"its renditions, a JSON list of {name, width, height, fit, format, quality}"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0];if(e.flags.public===!0&&e.flags.private===!0)throw g("--public and --private are one or the other");let s=await I_(e,t,n),a=ro(s??{name:n,public:!1,allowed_mime_types:[],variants:[]});if(e.flags.public===!0&&(a.public=!0),e.flags.private===!0&&(a.public=!1),e.flags["max-size"]!==void 0&&(a.file_size_limit=x_(e.flags["max-size"])),e.flags.types!==void 0&&(a.allowed_mime_types=re(e.flags.types)??[]),e.flags["variants-file"]!==void 0){let i=ue(await be(e,e.flags["variants-file"],"the renditions"),"the renditions file"),o=Array.isArray(i)?i:i.variants;if(!Array.isArray(o))throw g("the renditions file is a JSON list of {name, width, height, fit, format, quality}");a.variants=o}if(s&&Me(ro(s),a)){e.out.result(s,()=>e.out.line(`Nothing to change: ${n} already is so.`));return}await v(e,t,`${s?"change":"make"} the bucket ${n} (${a.public?"public":"private"})`);let r=await h(e,t,"PUT",as(n),a);e.out.result(r,()=>e.out.line(`${s?"Changed":"Made"} the bucket ${r.name}: ${r.public?"public":"private"}, files up to ${io(r.file_size_limit)}, ${r.allowed_mime_types.length===0?"any type":r.allowed_mime_types.join(", ")}.`))}},_u={name:"storage:buckets:delete",summary:"delete an empty bucket (one that still holds files is refused)",usage:"<bucket>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=as(e.args[0]);await v(e,t,`delete the bucket ${e.args[0]}`),await h(e,t,"DELETE",n),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the bucket ${e.args[0]}.`))}},ku={name:"storage",async read(e,t){let{buckets:n}=await h(e,t,"GET","/storage/buckets"),s={};for(let a of n){let r=ro(a);s[`buckets.${a.name}`]={...r,allowed_mime_types:[...r.allowed_mime_types].sort()}}return s},async copy(e,t,n,s){for(let a of pe(n,"buckets."))a.from===void 0?await V(s,`delete the bucket ${a.name}`,async()=>{await h(e,t,"DELETE",as(a.name))}):await V(s,`declare the bucket ${a.name}`,async()=>{await h(e,t,"PUT",as(a.name),a.from)})}};var rs=[$d,ku,Id,Hd,eu,su,du,fu],lr=[ru,au],Su={from:{type:"string",value:"env",description:"the environment compared from (slug or ref)"},to:{type:"string",value:"env",description:"the environment compared to (slug or ref)"},only:{type:"string",value:"modules",description:`only these, comma-separated: ${rs.map(e=>e.name).join(",")} (the default), and ${lr.map(e=>e.name).join(",")} when named`}};async function $u(e){if(e.global.env!==void 0)throw g("the two environments are named with --from and --to, not -E");let t=e.flags.from,n=e.flags.to;if(t===void 0||n===void 0)throw g("name both environments: --from <env> --to <env>");let s=await Re(e.studio),a;if(e.global.project!==void 0)a=_n(s,e.global.project);else{let l=await e.state.targetFor(e.io.cwd);if(!l)throw new y("no_target","which project? none is chosen for this directory",{hint:"pass -P <project>, or choose one here with palbase use"});a=s.filter(d=>d.project_id===l.target.project_id)}let r=l=>{let d=a.find(p=>p.slug===l||p.ref===l);if(!d)throw new y("no_such_environment",`the project has no environment ${JSON.stringify(l)}`,{hint:`its environments: ${a.map(p=>p.slug).join(", ")}`});return $e(d)},i=r(t),o=r(n);if(i.env_ref===o.env_ref)throw g("--from and --to name the same environment");return{from:i,to:o}}function Pu(e){let t=re(e.flags.only);if(t===void 0)return rs;let n=[...rs,...lr];for(let s of t)if(!n.some(a=>a.name===s))throw g(`no module ${JSON.stringify(s)}`,`the modules: ${n.map(a=>a.name).join(", ")}`);return n.filter(s=>t.includes(s.name))}function L_(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),s=[];for(let a of n){let r=a in e,i=a in t;r&&!i?s.push({key:a,change:"only_in_from",from:e[a]}):!r&&i?s.push({key:a,change:"only_in_to",to:t[a]}):Me(e[a],t[a])||s.push({key:a,change:"differs",from:e[a],to:t[a]})}return s}async function oo(e,t,n,s){let a=l=>Promise.all(t.map(d=>d.read(e,l))),[r,i]=await Promise.all([a(n),a(s)]),o=Object.fromEntries(t.map((l,d)=>[l.name,L_(r[d],i[d])]));return{from:n,to:s,modules:o,count:Object.values(o).reduce((l,d)=>l+d.length,0)}}function lo(e){return{from:{env:e.from.env_slug,ref:e.from.env_ref},to:{env:e.to.env_slug,ref:e.to.env_ref},equal:e.count===0,differences:e.count,modules:e.modules}}function or(e){let t=JSON.stringify(e)??"undefined";return t.length>140?`${t.slice(0,139)}\u2026`:t}function po(e,t){let n=t.from.env_slug,s=t.to.env_slug;for(let[r,i]of Object.entries(t.modules))if(i.length!==0){e.out.line(`${r} (${i.length})`);for(let o of i)o.change==="differs"?e.out.line(` ~ ${o.key}: ${n} ${or(o.from)} \xB7 ${s} ${or(o.to)}`):o.change==="only_in_from"?e.out.line(` - ${o.key}: only in ${n}: ${or(o.from)}`):e.out.line(` + ${o.key}: only in ${s}: ${or(o.to)}`)}let a=Object.keys(t.modules).join(", ");e.out.line(t.count===0?`${n} and ${s} have the same settings (${a}).`:`${t.count} difference(s) between ${n} and ${s} (${a}).`)}var D_={name:"config:diff",summary:"how two environments' module settings differ (auth, storage, flags, notify, realtime, analytics, messaging, calls; machines, databases when named)",usage:"--from <env> --to <env> [--only <modules>]",details:["- a key only in --from, + only in --to, ~ in both with other values. Ids, times and versions are not compared; a secret is compared as set or not, never by its value.","Exit code 0 when they are the same, 1 when they differ. --json gives each difference with both values."],flags:Su,scope:"environment",async run(e){let{from:t,to:n}=await $u(e),s=await oo(e,Pu(e),t,n);return e.out.result(lo(s),()=>po(e,s)),s.count===0?0:1}},q_={name:"config:copy",summary:"make one environment's module settings equal to another's (secrets excepted: their names are said)",usage:"--from <env> --to <env> [--only <modules>]",details:["It shows the differences, asks before changing a production environment (-y confirms), changes the target, and compares again.","A secret is never copied: a provider's credentials and a sign-in client's secret are listed by name for you to set. A new hook or OAuth client gets its own secret, printed this once.","What the target holds that its users depend on is not taken by a copy: a bucket with files, a role users hold, a topic users follow are left and said.","--only machines,databases copies what they are declared as \u2014 a machine's source, size, copies, settings, secrets' name, database; a database's size, who may connect, backups \u2014 never a database's data (palbase db:copy) nor a secret's value. A machine or database only the target has is left serving.","Exit code 0 when the two are the same afterwards, 1 when a difference remains."],flags:Su,scope:"environment",async run(e){let{from:t,to:n}=await $u(e);return uo(e,Pu(e),t,n)}};async function uo(e,t,n,s,a={}){let r=await oo(e,t,n,s);if(r.count===0)return e.out.result({...a,copied:[],left:[],shown_once:[],after:lo(r)},()=>e.out.line(`Nothing to copy: ${n.env_slug} and ${s.env_slug} have the same settings.`)),0;e.out.json||po(e,r);let i=t.filter(u=>r.modules[u.name].length>0).map(u=>u.name);await v(e,s,`make its ${i.join(", ")} settings equal to ${n.env_slug}'s (${r.count} difference(s))`);let o=[],l=[],d=[];e.out.json||e.out.line();for(let u of t){let m=r.modules[u.name];if(m.length===0)continue;let b={done(w){o.push(`${u.name}: ${w}`),e.out.json||e.out.line(`copied ${u.name}: ${w}`)},left(w){l.push(`${u.name}: ${w}`),e.out.json||e.out.line(`left ${u.name}: ${w}`)},shown(w,_){d.push({what:`${u.name}: ${w}`,value:_}),e.out.json||e.out.line(` ${u.name}: ${w} ${_} (shown this once)`)}};await u.copy(e,s,m,b)}let p=await oo(e,t,n,s);return e.out.result({...a,copied:o,left:l,shown_once:d,after:lo(p)},()=>{e.out.line(),e.out.line("Compared again:"),po(e,p)}),p.count===0?0:1}var Au=[od,ld,pd,dd,cd,ud,hd,md,gd,yd,bd,wd,vd,_d,kd,Sd,bu,wu,vu,_u,Td,Ed,Cd,jd,Md,xd,Od,Dd,qd,Nd,Kd,Gd,Ud,zd,Bd,Fd,Jd,Wd,Vd,Yd,Xd,Zd,Qd,tu,nu,...uu,...yu,D_,q_];async function co(e){return(await e.studio.get("/orgs")).organizations}async function gt(e,t){let n=await co(e);if(t===void 0){if(n.length===1)return n[0];throw g(n.length===0?"you are in no organization yet: make one with palbase orgs:create <name>":"which organization? pass --org <name>",`yours: ${n.map(a=>a.name).join(", ")}`)}let s=n.filter(a=>a.id===t||a.name.localeCompare(t,void 0,{sensitivity:"accent"})===0);if(s.length===0)throw new y("no_such_org",`no organization ${JSON.stringify(t)} among yours`,{hint:"palbase orgs:list shows them"});if(s.length>1)throw new y("ambiguous_org",`${JSON.stringify(t)} names more than one of your organizations`,{hint:"pass its id"});return s[0]}var Ru={name:"orgs:list",summary:"your organizations and your role in each",scope:"account",async run(e){let t=await co(e);e.out.result({organizations:t},()=>{t.length===0&&e.out.line("You are in no organization yet: palbase orgs:create <name> makes one."),e.out.table(t,[{header:"name",value:n=>n.name},{header:"role",value:n=>n.role},{header:"id",value:n=>n.id}])})}},Tu={name:"orgs:create",summary:"make an organization; you are its owner",usage:"<name>",details:["With an account token in PALBASE_TOKEN, the token's maker is its owner and the token its admin: one organization more the token reaches."],args:{min:1,max:1},scope:"account",async run(e){let t=await e.studio.post("/orgs",{name:e.args[0]});e.out.result(t,()=>e.out.line(`Made the organization ${K(t.name)} (${t.id}).`))}},Eu={name:"orgs:members:list",summary:"an organization's members, and the invitations still open (for its admins)",flags:{org:{type:"string",value:"org",description:"the organization (name or id); needed when you are in more than one"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),n=await e.studio.get(`/orgs/${t.id}/members`);e.out.result(n,()=>{e.out.table(n.members,[{header:"email",value:s=>s.email??""},{header:"role",value:s=>s.role},{header:"user",value:s=>s.user_id}]),n.invitations.length>0&&(e.out.line(),e.out.line("Invited:"),e.out.table(n.invitations,[{header:"email",value:s=>s.email},{header:"role",value:s=>s.role},{header:"invitation",value:s=>s.id}]))})}},Cu={name:"orgs:members:invite",summary:"invite someone to an organization by email; they accept in Studio",usage:"<email> [--role admin|member]",args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"},role:{type:"string",value:"role",description:"admin or member (default member)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw g("--role is admin or member");let s=await e.studio.post(`/orgs/${t.id}/invitations`,{email:e.args[0],role:n});e.out.result(s,()=>e.out.line(`Invited ${K(s.email)} to ${K(t.name)} as ${s.role}.`))}},ju={name:"orgs:members:remove",summary:"take a member (by email or user id) or an open invitation out of an organization",usage:"<email|user-id>",args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),n=e.args[0],s=await e.studio.get(`/orgs/${t.id}/members`),a=s.members.find(i=>i.user_id===n||i.email!==null&&i.email.toLowerCase()===n.toLowerCase());if(a){await e.studio.request("DELETE",`/orgs/${D("the organization's id",t.id)}/members/${D("the member's id",a.user_id)}`),e.out.result({removed:a},()=>e.out.line(`${K(a.email??a.user_id)} is no longer in ${K(t.name)}.`));return}let r=s.invitations.find(i=>i.id===n||i.email.toLowerCase()===n.toLowerCase());if(!r)throw new y("no_such_member",`${JSON.stringify(n)} is neither a member of ${t.name} nor invited to it`);await e.studio.request("DELETE",`/orgs/${D("the organization's id",t.id)}/invitations/${D("the invitation's id",r.id)}`),e.out.result({withdrawn:r},()=>e.out.line(`The invitation of ${K(r.email)} is withdrawn.`))}},Ou={name:"tokens:list",summary:"an organization's access tokens (PALBASE_TOKEN for CI and agents): name, role, when they end and were last used \u2014 never their values",flags:{org:{type:"string",value:"org",description:"the organization (name or id)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),{tokens:n}=await e.studio.get(`/orgs/${t.id}/tokens`);e.out.result({tokens:n},()=>{n.length===0?e.out.line(`${K(t.name)} has no access token yet: palbase tokens:create <name> makes one.`):e.out.table(n,[{header:"name",value:s=>K(s.name)},{header:"role",value:s=>s.role},{header:"token",value:s=>`pbo_\u2026${s.hint}`},{header:"ends",value:s=>s.expires_at.slice(0,10)},{header:"last used",value:s=>s.last_used_at?.slice(0,16).replace("T"," ")??"never"},{header:"id",value:s=>s.id}])})}},Mu={name:"orgs:audit",summary:"who changed what at an organization's environments, through Studio or the CLI, newest first \u2014 its admins'",usage:"[--org <org>] [--limit <n>]",details:["A module keeps a change made through Studio as Studio's key's: this says whose it was. What was sent is not kept."],flags:{org:{type:"string",value:"org",description:"the organization (name or id)"},limit:{type:"string",value:"n",description:"how many at most (default 50)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),n=e.flags.limit===void 0?50:Number(e.flags.limit);if(!Number.isInteger(n)||n<1||n>1e4)throw g("--limit is a whole number from 1 to 10000");let s=[],a=null;do{let r=new URLSearchParams({limit:String(Math.min(100,n-s.length)),...a?{before:a}:{}}),i=await e.studio.get(`/orgs/${t.id}/audit?${r}`);s.push(...i.entries),a=i.next_before}while(a&&s.length<n);e.out.result({entries:s},()=>{s.length===0?e.out.line(`Nothing changed at ${K(t.name)}'s environments yet.`):e.out.table(s,[{header:"when",value:r=>r.at.slice(0,16).replace("T"," ")},{header:"who",value:r=>K(r.actor_name??r.actor)},{header:"environment",value:r=>K(r.environment_ref)},{header:"what",value:r=>K(`${r.method} ${r.path}`)},{header:"answer",value:r=>String(r.status)}])})}},xu={name:"tokens:create",summary:"make an access token of an organization for CI or an agent; its value is shown this once",usage:"<name> [--role member|admin] [--days <n>]",details:["Give it to the CI as the secret PALBASE_TOKEN: the CLI acts with it in place of a sign-in. It reaches its organization's projects and environments at its role, and nothing of its people or tokens.","It ends after --days (default 90, at most 365), and goes when it is revoked or when the one who made it leaves the organization."],args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"},role:{type:"string",value:"role",description:"member (default) or admin: what it may change"},days:{type:"string",value:"n",description:"how many days it is good for (default 90)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw g("--role is member or admin");let s=e.flags.days===void 0?90:Number(e.flags.days);if(!Number.isInteger(s)||s<1||s>365)throw g("--days is a whole number from 1 to 365");let a=await e.studio.post(`/orgs/${t.id}/tokens`,{name:e.args[0],role:n,expires_in_days:s});e.out.result(a,()=>{e.out.line(`Made the access token ${K(a.name)} of ${K(t.name)} (${a.role}, until ${a.expires_at.slice(0,10)}).`),e.out.line(`token (shown this once \u2014 keep it as the CI's secret PALBASE_TOKEN): ${a.token}`)})}},Iu={name:"tokens:revoke",summary:"revoke an organization's access token (by its name or id): refused from its next request on",usage:"<name|id>",args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),{tokens:n}=await e.studio.get(`/orgs/${t.id}/tokens`),s=n.filter(i=>i.id===e.args[0]||i.name===e.args[0]);if(s.length===0)throw new y("no_such_token",`${K(t.name)} has no access token ${JSON.stringify(e.args[0])}`,{hint:"palbase tokens:list shows them"});if(s.length>1)throw new y("ambiguous_token",`${JSON.stringify(e.args[0])} names more than one token`,{hint:"pass its id"});let a=`/orgs/${D("the organization's id",t.id)}/tokens/${D("the token's id",s[0].id)}`,{endpoints:r}=await e.studio.get(`${a}/webhooks`);await e.studio.request("DELETE",a),e.out.result({revoked:s[0].id,kept_webhooks:r},()=>{if(e.out.line(`Revoked the access token ${K(s[0].name)} of ${K(t.name)}.`),r.length>0){e.out.line("These webhook endpoints it made stay, and keep receiving events (palbase webhooks:delete <id> -E <env> removes one):");for(let i of r)e.out.line(` ${A(i.url)} \u2014 ${A(i.environment_ref)} (${A(i.id)})`)}})}},Lu={name:"projects:list",summary:"every project of your organizations, with its environments",scope:"account",async run(e){let t=await Re(e.studio),n=await e.state.targetFor(e.io.cwd),s=(await e.studio.get("/projects")).projects,a=new Map(t.map(r=>[r.organization_id,r.org_name]));for(let r of await co(e))a.set(r.id,r.name);e.out.result({projects:s.map(r=>({...r,organization_name:a.get(r.organization_id)??null}))},()=>{s.length===0&&e.out.line("No project yet: palbase projects:create <name> makes one.");let r=s.flatMap(i=>i.environments.length===0?[{org:a.get(i.organization_id)??"",project:i.name,env:"(none)",ref:"",here:""}]:i.environments.map(o=>({org:a.get(i.organization_id)??"",project:i.name,env:o.slug,ref:o.ref,here:n?.target.env_ref===o.ref?"*":""})));e.out.table(r,[{header:"",value:i=>i.here},{header:"organization",value:i=>i.org},{header:"project",value:i=>i.project},{header:"env",value:i=>i.env},{header:"ref",value:i=>i.ref}])})}},Du={name:"projects:create",summary:"make a project with its first environment (main), and print its keys",usage:"<name> [--org <org>] [--env-name <name>]",details:["The first environment is the project's production one: its slug is always main.","Its secret key is printed this once; keys:create makes more."],args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"},"env-name":{type:"string",value:"name",description:"what the first environment is called on screen (default Production)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),{project:n}=await e.studio.post(`/orgs/${t.id}/projects`,{name:e.args[0]}),s=await e.studio.post(`/projects/${n.id}/environments`,{name:e.flags["env-name"]??"Production"});e.out.result({project:n,environment:s.environment,keys:s.keys},()=>{e.out.line(`Made ${K(t.name)} \u203A ${K(n.name)} with its environment ${s.environment.slug} (ref ${s.environment.ref}).`),s.keys&&(e.out.line(`publishable key: ${s.keys.publishable.key}`),e.out.line(`secret key (shown this once): ${s.keys.secret.key}`)),e.out.line(`palbase use ${n.name}/${s.environment.slug} chooses it for this directory.`)})}},qu={name:"projects:delete",summary:"delete a project and every environment of it",usage:"<project> [-y]",details:["Its environments' data goes with them (the platform keeps it a week to bring back)."],args:{min:1,max:1},scope:"account",async run(e){let t=_n(await Re(e.studio),e.args[0]),n=t[0];if(e.out.note(`${n.org_name} \u203A ${n.project_name}: delete the project and its environments ${t.map(s=>s.slug).join(", ")}`),!e.global.yes){if(!e.interactive)throw new y("confirmation_needed","deleting a project is confirmed",{hint:"confirm with -y"});if((await e.io.prompt("Type the project's name to delete it: ")).trim()!==n.project_name)throw new y("cancelled","nothing was deleted")}await e.studio.request("DELETE",`/projects/${n.project_id}`),e.out.result({deleted:{project_id:n.project_id,environments:t.map(s=>s.ref)}},()=>e.out.line(`Deleted ${K(n.project_name)}.`))}},Nu={name:"envs:list",summary:"a project's environments (the project chosen here, or -P)",scope:"environment",async run(e){let t=await Nt(e);e.out.result({environments:t},()=>e.out.table(t,[{header:"slug",value:n=>n.slug},{header:"name",value:n=>n.name},{header:"ref",value:n=>n.ref},{header:"your role",value:n=>n.role}]))}},Ku={name:"envs:create",summary:"add an environment to a project (staging, a developer's own)",usage:"<slug> [--name <name>] [--from <env> [--with-cloud]]",details:["Each environment is a project of its own on the platform: its users, data, machines and keys are its own.","--from opens it with another environment's module settings (palbase config:copy: secrets are named, not copied); --with-cloud its machines and databases too \u2014 declared alike, built from the same branches, with no data (palbase db:copy brings it)."],args:{min:1,max:1},flags:{name:{type:"string",value:"name",description:"what it is called on screen (default: the slug)"},from:{type:"string",value:"env",description:"open it with this environment's settings (slug or ref)"},"with-cloud":{type:"boolean",description:"with --from: its machines and databases too (the new environment's GitHub link builds the machines)"}},scope:"environment",async run(e){let t=await N_(e),n=e.args[0],s=e.flags.from;if(e.flags["with-cloud"]===!0&&s===void 0)throw g("--with-cloud goes with --from <env>");let a=s===void 0?[]:(await Re(e.studio)).filter(d=>d.project_id===t.project_id),r=s===void 0?void 0:a.find(d=>d.slug===s||d.ref===s);if(s!==void 0&&!r)throw new y("no_such_environment",`the project has no environment ${JSON.stringify(s)}`,{hint:`its environments: ${a.map(d=>d.slug).join(", ")}`});let i=await e.studio.post(`/projects/${t.project_id}/environments`,{name:e.flags.name??n,slug:n}),o=()=>{e.out.line(`Made ${K(t.project_name)} \u203A ${i.environment.slug} (ref ${i.environment.ref}).`),i.keys&&(e.out.line(`publishable key: ${i.keys.publishable.key}`),e.out.line(`secret key (shown this once): ${i.keys.secret.key}`))};if(!r){e.out.result(i,o);return}e.out.json||o();let l=$e({...r,ref:i.environment.ref,slug:i.environment.slug,name:i.environment.name});return e.out.json||e.out.line(),uo(e,e.flags["with-cloud"]===!0?[...rs,...lr]:rs,$e(r),l,{made:i})}},Gu={name:"envs:delete",summary:"delete an environment of a project, with its data",usage:"<slug> [--delete-bound | --move-to <env>]",details:["A project's machines, databases and sites are the project's, each bound to one environment. What is bound to the environment deleted is deleted with it (--delete-bound), or its machines are moved to another environment of the project first (--move-to <slug>); with neither and something bound to it, a person at the terminal is asked, and anything else is refused with what is bound.","A database keeps its volume, and a site its files, where they were made: they do not move yet \u2014 an environment that keeps one is deleted with them, or kept."],args:{min:1,max:1},flags:{"delete-bound":{type:"boolean",description:"delete the machines, databases and sites bound to it with it"},"move-to":{type:"string",value:"env",description:"move its machines to this environment of the project (its slug) before it is deleted"}},scope:"environment",async run(e){let t=await Nt(e),n=t.find(l=>l.slug===e.args[0]||l.ref===e.args[0]);if(!n)throw new y("no_such_environment",`the project has no environment ${JSON.stringify(e.args[0])}`);let s=$e(n);if(e.out.note(`${q(s)}: delete the environment, its users, data, machines and databases`),!e.global.yes){if(!e.interactive)throw new y("confirmation_needed","deleting an environment is confirmed",{hint:"confirm with -y"});if((await e.io.prompt("Type the environment's slug to delete it: ")).trim()!==n.slug)throw new y("cancelled","nothing was deleted")}let a=e.flags["delete-bound"]===!0,r=typeof e.flags["move-to"]=="string"?e.flags["move-to"]:void 0;if(a&&r!==void 0)throw g("--delete-bound or --move-to: what is bound to it is deleted with it, or its machines are moved");let i=a?"?delete_bound=true":r!==void 0?`?move_to=${encodeURIComponent(r)}`:"";try{await e.studio.request("DELETE",`/environments/${n.ref}${i}`)}catch(l){if(!(l instanceof j)||l.code!=="environment_has_resources"||i!=="")throw l;let d=l.body?.data??{},p=[d.machines?.length?`machines ${d.machines.join(", ")}`:"",d.databases?.length?`databases ${d.databases.join(", ")}`:"",d.sites?.length?`sites ${d.sites.join(", ")}`:""].filter(b=>b!=="").join("; "),u=t.filter(b=>b.ref!==n.ref).map(b=>b.slug);if(!e.interactive||e.global.yes)throw new y("environment_has_resources",`bound to ${n.slug}: ${p}`,{hint:`delete them with it (--delete-bound), or move its machines first (--move-to ${u[0]??"<env>"})`});e.out.line(`Bound to ${n.slug}: ${p}.`);let m=(await e.io.prompt(`Delete them with it (delete), move its machines to another environment (${u.join(", ")}), or keep it (keep)? `)).trim();if(m==="delete")i="?delete_bound=true";else if(u.includes(m))i=`?move_to=${encodeURIComponent(m)}`;else throw new y("cancelled","nothing was deleted");await e.studio.request("DELETE",`/environments/${n.ref}${i}`)}let o=await e.state.targetFor(e.io.cwd);o?.target.env_ref===n.ref&&await e.state.clearTarget(o.dir),e.out.result({deleted:n.ref},()=>e.out.line(`Deleted ${q(s)}.`))}},Uu={name:"use",summary:"choose the environment this directory acts on (kept on this computer)",usage:"[<project>[/<env>] | <org>/<project>/<env>] [--clear]",details:["Commands run in this directory, or a directory under it, then act on that environment unless -P/-E say otherwise.","Nothing is written into the project: two checkouts of it can each act on their own environment.","With no argument and a person at the terminal, it lists your environments to pick from."],args:{min:0,max:1},flags:{clear:{type:"boolean",description:"forget the choice made for this directory"}},scope:"account",async run(e){if(e.flags.clear===!0){let n=await e.state.clearTarget(e.io.cwd);e.out.result({cleared:n},()=>e.out.line(n?"This directory acts on no environment now.":"No environment was chosen for this directory."));return}let t;if(e.args.length===0)t=await f(e);else{let n=await Re(e.studio);t=$e(K_(n,e.args[0]))}await e.state.setTarget(e.io.cwd,t),e.out.result({target:t,dir:e.io.cwd},()=>e.out.line(`This directory acts on ${q(t)}.`))}},zu={name:"status",summary:"the environment this directory acts on: who you are there, its machines and databases",scope:"environment",async run(e){let t=await f(e),n=await e.studio.get(`/environments/${t.env_ref}`),s=d=>ye(e.studio,t.env_ref,"GET",d).then(p=>p.body,p=>p instanceof j?null:Promise.reject(p)),[a,r]=await Promise.all([s("/machines?limit=100"),s("/databases?limit=100")]),i=a?.machines??[],o=r?.databases??[],l=await e.state.targetFor(e.io.cwd);e.out.result({target:t,role:n.role,address:`https://${t.env_ref}.${e.cloud.domain}`,machines:i,databases:o,chosen_for:l?.dir??null},()=>{e.out.line(q(t)),e.out.line(` ref ${t.env_ref} \xB7 your role ${n.role} \xB7 https://${t.env_ref}.${e.cloud.domain}`),l&&l.target.env_ref===t.env_ref&&e.out.line(` chosen for ${l.dir}`),e.out.line(` machines: ${i.length===0?"none":i.map(d=>`${d.name} (${d.size}, ${d.state})`).join(", ")}`),e.out.line(` databases: ${o.length===0?"none":o.map(d=>`${d.name} (${d.size}, ${d.state})`).join(", ")}`)})}},Bu={name:"open",summary:"open the environment in Studio (its overview, or a section: auth, storage, flags, \u2026)",usage:"[section]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=e.args[0]?`/${e.args[0].replace(/^\/+/,"")}`:"",s=`${e.cloud.studioWeb}/projects/${t.project_id}/environments/${t.env_ref}${n}`,a=e.interactive&&await e.io.openBrowser(s);e.out.result({url:s,opened:a},()=>e.out.line(a?`Opened ${s}`:s))}},Fu={name:"keys:list",summary:"the environment's API keys (never their values)",scope:"environment",async run(e){let t=await f(e),{keys:n}=await e.studio.get(`/environments/${t.env_ref}/keys`);e.out.result({keys:n},()=>e.out.table(n,[{header:"id",value:s=>s.id},{header:"kind",value:s=>s.kind},{header:"label",value:s=>s.label},{header:"ends",value:s=>s.hint?`\u2026${s.hint}`:""},{header:"state",value:s=>s.revoked_at?`revoked ${s.revoked_at}`:s.expires_at?`until ${s.expires_at}`:"active"},{header:"created",value:s=>s.created_at}]))}},Ju={name:"keys:create",summary:"make an API key of the environment; its value is shown this once",usage:"--kind publishable|secret [--label <label>]",flags:{kind:{type:"string",value:"kind",description:"publishable (ships in apps) or secret (servers only)"},label:{type:"string",value:"label",description:"what it is for, as Studio lists it"}},scope:"environment",async run(e){let t=e.flags.kind;if(t!=="publishable"&&t!=="secret")throw g("--kind is publishable or secret");let n=await f(e);await v(e,n,`make a ${t} key`);let s=await e.studio.post(`/environments/${n.env_ref}/keys`,{kind:t,label:e.flags.label??""});e.out.result(s,()=>{e.out.line(`${s.kind} key ${s.id}${s.kind==="secret"?" (shown this once)":""}:`),e.out.line(s.key)})}},Wu={name:"keys:revoke",summary:"revoke an API key of the environment; what holds it is refused from then on",usage:"<key-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=`/environments/${D("the environment's ref",t.env_ref)}/keys/${D("the key's id",e.args[0])}`;await v(e,t,`revoke the key ${e.args[0]}`),await e.studio.request("DELETE",n),e.out.result({revoked:e.args[0]},()=>e.out.line(`Revoked ${e.args[0]}.`))}};async function N_(e){return(await Nt(e))[0]}async function Nt(e){if(vn(e.io))return[await Oi(e)];let t=await Re(e.studio);if(e.global.project!==void 0)return _n(t,e.global.project);let n=await e.state.targetFor(e.io.cwd);if(!n)throw new y("no_target","no project is chosen for this directory",{hint:"pass -P <project>, or choose one here with palbase use"});let s=t.filter(a=>a.project_id===n.target.project_id);if(s.length===0)throw new y("no_such_project",`the project chosen here (${n.target.project_name}) is not among yours any more`,{hint:"palbase use another"});return s}function K_(e,t){let n=t.split("/");if(n.length>3||n.some(r=>r===""))throw g(`${JSON.stringify(t)} is not project, project/env or org/project/env`);let s=n.length===3?[{project:`${n[0]}/${n[1]}`,env:n[2]}]:n.length===2?[{project:n[0],env:n[1]},{project:t}]:[{project:t}],a;for(let r of s){let i;try{i=_n(e,r.project)}catch(o){a=o;continue}if(r.env!==void 0){let o=i.find(l=>l.slug===r.env||l.ref===r.env);if(o)return o;a=new y("no_such_environment",`${i[0].project_name} has no environment ${JSON.stringify(r.env)}`,{hint:`its environments: ${i.map(l=>l.slug).join(", ")}`});continue}if(i.length===1)return i[0];throw new y("which_environment",`${i[0].project_name} has more than one environment`,{hint:`name one: ${i.map(o=>`${o.project_name}/${o.slug}`).join(", ")}`})}throw a}import{createReadStream as G_,openAsBlob as U_}from"node:fs";import{lstat as z_,readdir as B_,realpath as Vu,stat as F_}from"node:fs/promises";import{createHash as J_}from"node:crypto";import{join as W_,relative as Hu,resolve as V_,sep as Yu}from"node:path";var ho=2e4,H_=25<<20,Y_=1<<30,X_=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/,Z_=6,ea={previews:{type:"boolean",description:"build each pull request against its branch into a preview of its own, in this environment with its settings \u2014 production's too"},"no-previews":{type:"boolean",description:"preview no pull request from now on"},"preview-forks":{type:"boolean",description:"preview a fork's pull requests without asking (fork protection off): anyone's code runs with this environment's settings and secrets \u2014 a person's to do, signed in with palbase login"},"no-preview-forks":{type:"boolean",description:"a fork's pull request waits for an admin to authorize each push (fork protection, the default): previews:authorize"}};function na(e,t){e.flags.previews===!0&&(t.previews=!0),e.flags["no-previews"]===!0&&(t.previews=!1),e.flags["preview-forks"]===!0&&(t.preview_forks=!0),e.flags["no-preview-forks"]===!0&&(t.preview_forks=!1)}function pr(e,t){if(e.out.line(`${t.host} ${t.state}${t.redirect_to?` \u2192 redirects to ${t.redirect_to} (${t.redirect_status??308})`:""}`),t.state!=="active"){e.out.line(` Add to ${t.host}'s DNS:`);for(let n of t.records){let s=n.type==="CNAME"&&t.apex?"ALIAS (or ANAME, or a flattened CNAME: the apex takes no CNAME)":n.type;e.out.line(` ${s} ${n.name} ${n.value}`)}for(let n of t.problems)e.out.line(` - ${n}`)}}function mo(e,t,n,s){let a={name:`${t}:domains`,summary:`a ${e}'s own domains: whether each answers, and what its DNS still needs`,usage:`[--${e} <name>]`,flags:s,scope:"environment",async run(l){let d=await f(l),{domains:p}=await h(l,d,"GET",`${await n(l,d)}/domains`);l.out.result({domains:p},()=>{p.length===0&&l.out.line(`No domain yet: palbase ${t}:domains:add <host> adds one.`);for(let u of p)pr(l,u)})}},r={name:`${t}:domains:add`,summary:`have a ${e} answer at a domain of your own too (www.example.com, or example.com \u2014 with its www)`,usage:`<host> [--${e} <name>] [--primary www|apex | --only] [--redirect-status 301|302|307|308]`,details:["It answers once its DNS points at the platform and says it is this environment's (the TXT record): both are printed.","At an apex (example.com) its www is added too, and one redirects to the other, as Vercel does: the apex to www.example.com unless --primary apex; --only adds the domain alone.","An apex takes an A record at the platform's address, which any DNS host has; a subdomain a CNAME. A domain is one environment's until it is removed there."],args:{min:1,max:1},flags:{...s,primary:{type:"string",value:"www|apex",description:"at an apex: the address visitors end up at, the other redirecting to it (default: www)"},only:{type:"boolean",description:"add the domain alone: no www, no redirect"},"redirect-status":{type:"string",value:"code",description:"the redirect's status: 301, 302, 307 or 308 (default: 308)"}},scope:"environment",async run(l){let d=l.args[0].trim().toLowerCase().replace(/\.$/,""),p=l.flags.primary??"www";if(p!=="www"&&p!=="apex")throw g("--primary is www or apex");if(l.flags.only===!0&&l.flags.primary!==void 0)throw g("--only adds the domain alone: no --primary");let u=Xu(l.flags["redirect-status"]),m=await f(l),b=await n(l,m),w=`www.${d}`,_=l.flags.only!==!0&&!d.startsWith("www.");await v(l,m,_?`add the domain ${d} \u2014 at an apex, with ${w}, ${p==="www"?`${d} redirecting to ${w}`:`${w} redirecting to ${d}`}`:`add the domain ${d}`);let T=await h(l,m,"POST",`${b}/domains`,{host:d});if(!_||!T.apex){l.out.result(T,()=>pr(l,T));return}let S=P=>({redirect_to:P,...u!==void 0?{redirect_status:u}:{}}),$;p==="www"?($=await Q_(l,m,b,{host:w}),T=await h(l,m,"PATCH",`${b}/domains/${D("the domain",d)}`,S(w))):$=await e0(l,m,b,w,S(d));let R=p==="www"?[$,T]:[T,$];l.out.result({domains:R},()=>R.forEach(P=>pr(l,P)))}},i={name:`${t}:domains:redirect`,summary:`send a domain's visitors to another domain of the ${e}'s \u2014 the same path and query there \u2014 or, with --none, have it answer itself`,usage:`<host> (--to <host> [--status 301|302|307|308] | --none) [--${e} <name>]`,details:["It holds at once. A domain redirects to one that answers itself, and one others redirect to answers itself."],args:{min:1,max:1},flags:{...s,to:{type:"string",value:"host",description:`another domain of the ${e}'s`},status:{type:"string",value:"code",description:"301, 302, 307 or 308 (default: 308)"},none:{type:"boolean",description:"redirect nowhere: the domain answers itself"}},scope:"environment",async run(l){let d=l.args[0].trim().toLowerCase().replace(/\.$/,""),p=l.flags.to?.trim().toLowerCase().replace(/\.$/,"");if(p===void 0==(l.flags.none!==!0))throw g("name where it redirects (--to <host>), or --none");let u=Xu(l.flags.status);if(l.flags.none===!0&&u!==void 0)throw g("--status goes with --to");let m=await f(l),b=await n(l,m);await v(l,m,p?`redirect ${d} to ${p}`:`have ${d} answer itself`);let w=p?{redirect_to:p,...u!==void 0?{redirect_status:u}:{}}:{redirect_to:null},_=await h(l,m,"PATCH",`${b}/domains/${D("the domain",d)}`,w);l.out.result(_,()=>pr(l,_))}},o={name:`${t}:domains:remove`,summary:`stop a ${e} answering at a domain: at once, and another environment may add it`,usage:`<host> [--${e} <name>]`,args:{min:1,max:1},flags:s,scope:"environment",async run(l){let d=await f(l),p=await n(l,d);await v(l,d,`remove the domain ${l.args[0]}`),await h(l,d,"DELETE",`${p}/domains/${D("the domain",l.args[0].toLowerCase())}`),l.out.result({removed:l.args[0]},()=>l.out.line(`${l.args[0]} answers no more.`))}};return[a,r,i,o]}function Xu(e){if(e===void 0)return;let t=Number(e);if(![301,302,307,308].includes(t))throw g("a redirect's status is 301, 302, 307 or 308");return t}async function Q_(e,t,n,s){try{return await h(e,t,"POST",`${n}/domains`,s)}catch(a){if(!(a instanceof j&&a.code==="domain_exists"))throw a;let{domains:r}=await h(e,t,"GET",`${n}/domains`),i=r.find(o=>o.host===s.host);if(!i)throw a;return i}}async function e0(e,t,n,s,a){try{return await h(e,t,"POST",`${n}/domains`,{host:s,...a})}catch(r){if(!(r instanceof j&&r.code==="domain_exists"))throw r;return await h(e,t,"PATCH",`${n}/domains/${D("the domain",s)}`,a)}}function go(e,t,n,s){return{name:`${t}:previews:authorize`,summary:`build a fork's pull request's preview of a ${e}: its code runs with this environment's settings and secrets`,usage:`<pull request> [--${e} <name>]`,details:["A pull request from a fork waits for an admin of the environment (fork protection): look at what it changes first. The head shown is the one built; a push since asks again.","A person authorizes it, signed in with palbase login: an environment's token (PALBASE_TOKEN) cannot."],args:{min:1,max:1},flags:s,scope:"environment",async run(a){let r=Number(a.args[0].replace(/^#/,""));if(!Number.isInteger(r)||r<=0)throw g("the pull request is its number: 12, or #12");let i=await f(a),o=await n(a,i),{previews:l}=await h(a,i,"GET",`${o}/previews`),d=l.find(u=>u.pull_request===r&&u.state!=="closed");if(!d)throw new y("preview_not_found",`no open preview of pull request #${r}`,{hint:`palbase ${t}:previews lists them`});if(d.state!=="authorization_required")throw new y("preview_not_waiting",`#${r}'s preview waits for no authorization: it is ${d.state}`);await v(a,i,`build pull request #${r} at ${d.commit.slice(0,7)}, from a fork`,`Pull request #${r} is from a fork: its code at ${d.commit.slice(0,7)} runs with this environment's settings and secrets`);let p=await h(a,i,"POST",`${o}/previews/${r}/authorize`,{commit:d.commit});a.out.result(p,()=>a.out.line(`#${r} authorized at ${d.commit.slice(0,7)}: its preview is being built (palbase ${t}:previews).`))}}}function fo(e,t,n){t.length===0&&e.out.line(n);for(let s of t){let a=s.state==="authorization_required"?"waits for authorization (previews:authorize)":s.state==="idle"?"idle: no push for 3 days (previews:open opens it again)":s.state==="refused"?`refused: ${s.reason??""}`:s.state;e.out.line(`#${s.pull_request} ${a} ${s.commit.slice(0,7)}${s.fork?" fork":""} ${s.url}${s.machine?` (${s.machine})`:""}`)}}function Ce(e){if(!X_.test(e))throw g(`${JSON.stringify(e)} is not a site's name: lowercase letters, digits and dashes, starting with a letter`);return D("the site",e)}var Qu={repo:{type:"string",value:"owner/name",description:"build it from this GitHub repository on every push (default with --branch: this checkout's origin)"},branch:{type:"string",value:"branch",description:"the branch whose pushes are built"},path:{type:"string",value:"dir",description:"the site's directory in the repository (default: this directory's place in it)"},"install-command":{type:"string",value:"command",description:"what installs its packages (default: from its lockfile \u2014 pnpm, yarn, npm, bun)"},"build-command":{type:"string",value:"command",description:"what builds it (default: its package.json's build script)"},output:{type:"string",value:"dir",description:"the folder the build writes (default: what its builder writes \u2014 dist, build, out, \u2026)"},"build-env":{type:"string",multiple:!0,value:"K=V",description:"a setting the build runs with (repeat it): what its pages are sent (VITE_*), never a secret"}};async function ec(e,t){let n={};if(e.flags.repo!==void 0||e.flags.branch!==void 0||t){let r=await Us(e.io,e.io.cwd),i=e.flags.repo??r?.repository,o=e.flags.branch??r?.branch;if(!i)throw g("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!o)throw g("which branch? none is checked out here","pass --branch <branch>");n.source={repository:i,branch:o,path:e.flags.path??(e.flags.repo===void 0?r?.path??"":"")}}let s={};e.flags["install-command"]!==void 0&&(s.install_command=e.flags["install-command"]),e.flags["build-command"]!==void 0&&(s.command=e.flags["build-command"]),e.flags.output!==void 0&&(s.output_dir=e.flags.output);let a=e.flags["build-env"];if(a){let r={};for(let i of a){let o=i.indexOf("=");if(o<=0)throw g(`a setting is K=V, not ${JSON.stringify(i)}`);r[i.slice(0,o)]=i.slice(o+1)}s.env=r}return Object.keys(s).length>0&&(n.build=s),n}function ta(e){return e<1024?`${e} B`:e<1<<20?`${(e/1024).toFixed(1)} KiB`:`${(e/(1<<20)).toFixed(1)} MiB`}async function t0(e){let t=await Vu(e),n=[],s=async r=>{let i=await B_(r,{withFileTypes:!0});for(let o of i){if(o.name==="node_modules"||o.name.startsWith(".")&&!(o.name===".well-known"&&r===t))continue;let l=W_(r,o.name),d=await z_(l),p=l;if(d.isSymbolicLink()&&(p=await Vu(l),p!==t&&!p.startsWith(t+Yu)))throw new y("unsafe_path",`${Hu(t,l)} links outside ${e}`);let u=d.isSymbolicLink()?await F_(p):d;if(u.isDirectory()){await s(l);continue}if(!u.isFile())continue;let m="/"+Hu(t,l).split(Yu).join("/");if(/[\u0000-\u001f\u007f?#\\]/.test(m))throw new y("invalid_path",`${m} has a character a site's path cannot carry (?, #, \\ or a control character): rename it`);if(m.length>1024)throw new y("invalid_path",`${m.slice(0,80)}\u2026 is longer than a site's path may be (1024 bytes)`);if(u.size>H_)throw new y("file_too_large",`${m} is ${ta(u.size)}: a site's file is 25 MiB at most (keep large media in storage)`);if(n.push({path:m,file:p,size:u.size,digest:""}),n.length>ho)throw new y("too_many_files",`${e} holds more than ${ho} files: a site holds ${ho} at most`)}};await s(t),n.sort((r,i)=>r.path<i.path?-1:r.path>i.path?1:0);let a=n.reduce((r,i)=>r+i.size,0);if(a>Y_)throw new y("release_too_large",`${e} holds ${ta(a)}: a release is 1 GiB at most`);for(let r of n)r.digest=await n0(r.file);return n}function n0(e){return new Promise((t,n)=>{let s=J_("sha256");G_(e).on("data",a=>s.update(a)).on("error",n).on("end",()=>t(s.digest("hex")))})}function s0(e){let t=e.filter(n=>/\.html?$/i.test(n.path));return t.length===1&&t[0].path==="/index.html"}async function a0(e,t,n){try{return await h(e,t,"GET",`/sites/${Ce(n)}`)}catch(s){if(s instanceof j&&s.code==="site_not_found")return null;throw s}}async function Zu(e,t,n,s,a,r){let i=0,o=0,l=async()=>{for(;o<a.length;){let d=a[o++],p=r.get(d);if(!p)throw new y("internal",`the release asked for ${d}, which no file here is`);let u=await U_(p.file);await h(e,t,"PUT",`/sites/${Ce(n)}/releases/${D("the release",s)}/files/${d}`,new wn(u,"application/octet-stream")),i+=p.size}};return await Promise.all(Array.from({length:Math.min(Z_,a.length)},l)),i}var r0={name:"hosting:deploy",summary:"deploy a folder as a static site: only the files that changed are sent, and the site serves them at once",usage:"<folder> [--site <name>] [--spa]",details:["The folder is what your build wrote (dist, build, out, public): every file in it is served, at its path from the folder's root.","The site is opened on its first deploy; --spa then answers a path no file answers with /index.html (a single-page app).","A folder of one page, index.html, is taken for a single-page app when the site is opened."],args:{min:1,max:1},flags:{site:{type:"string",value:"name",description:"the site (default: web, which answers at the environment's ref)"},spa:{type:"boolean",description:"when the site is opened: answer every path no file answers with /index.html"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.site??"web";Ce(n);let s=V_(e.io.cwd,e.args[0]),a=await t0(s).catch(w=>{throw w instanceof y?w:new y("no_folder",`${e.args[0]}: ${w instanceof Error?w.message:String(w)}`)});if(a.length===0)throw new y("empty_folder",`${e.args[0]} holds no file to serve`);a.some(w=>w.path==="/index.html")||e.out.note(` ${e.args[0]} has no index.html: the site's root answers 404.`);let r=a.reduce((w,_)=>w+_.size,0);await v(e,t,`deploy ${a.length} files (${ta(r)}) to the site ${n}`);let i=await a0(e,t,n);if(!i){let w=e.flags.spa===!0||s0(a);i=await h(e,t,"POST","/sites",{name:n,spa:w}),e.out.note(` opened the site ${n}${w?" (a single-page app: every route is its index.html)":""}`)}let o={},l=new Map;for(let w of a)o[w.path]=w.digest,l.set(w.digest,w);let d=await h(e,t,"POST",`/sites/${Ce(n)}/releases`,{files:o}),p=d.missing??[];e.out.note(` release #${d.number}: ${a.length} files, ${p.length} to send${p.length<l.size?` (${l.size-p.length} kept from before)`:""}`);let u=await Zu(e,t,n,d.id,p,l),m;for(let w=0;w<3&&!m;w++)try{m=await h(e,t,"POST",`/sites/${Ce(n)}/releases/${D("the release",d.id)}/finish`)}catch(_){let T=_ instanceof j&&_.code==="files_missing"?_.body?.missing??[]:[];if(T.length===0)throw _;u+=await Zu(e,t,n,d.id,T,l)}if(!m)throw new y("release_unfinished",`the release #${d.number} could not be finished`,{hint:"deploy again"});i=await h(e,t,"GET",`/sites/${Ce(n)}`);let b={site:i.name,url:i.url,urls:i.urls,release:m,sent_bytes:u};e.out.result(b,()=>{e.out.line(`Deployed release #${m.number} of ${i.name} (${a.length} files, ${ta(u)} sent).`);for(let w of i.urls)e.out.line(` ${w}`)})}},i0={name:"hosting:sites:list",summary:"the project's static sites, each with the environment it is bound to: where each answers and the release it serves",scope:"environment",async run(e){let t=await f(e),[{sites:n},s]=await Promise.all([h(e,t,"GET","/sites"),zs(e.studio,t)]);e.out.result({sites:n},()=>{n.length===0&&e.out.line("No site yet: palbase hosting:deploy <folder> opens one.");for(let a of n){let r=a.taken_down?`taken down: ${a.taken_down.reason}`:a.release?`release #${a.release.number}`:"nothing deployed";e.out.line(`${a.name} ${Yn(s,a.environment)} ${a.url} ${r}${a.spa?" (single-page app)":""}`)}})}},o0={name:"hosting:sites:create",summary:"open a static site \u2014 built from GitHub on every push with --repo/--branch, or deployed from a folder (hosting:deploy opens one too)",usage:"[name] [--spa] [--repo <owner/name> --branch <branch> --path <dir>] [--build-command \u2026] [--output <dir>] [--build-env K=V]\u2026 [--previews [--preview-forks]]",details:["With --branch (and --repo, or in a checkout of a GitHub repository), its branch's head is built at once and on every push: the folder its build writes is served.","With --previews, each pull request against the branch is built too and answers at <name>-pr<n>-<ref> until it closes; the pull request is told where.","The environment needs its GitHub link first: palbase github:connect."],args:{min:0,max:1},flags:{spa:{type:"boolean",description:"a single-page app: every path no file answers is its /index.html"},...Qu,previews:ea.previews,"preview-forks":ea["preview-forks"]},scope:"environment",async run(e){let t=await f(e),n=e.args[0]??"web";Ce(n);let{source:s,build:a}=await ec(e,!1);await v(e,t,`open the site ${n}${s?`, built from ${s.repository}@${s.branch}`:""}`);let r={};na(e,r);let i=await h(e,t,"POST","/sites",{name:n,spa:e.flags.spa===!0,...s?{source:s}:{},...a?{build:a}:{},...r});e.out.result(i,()=>e.out.line(i.source?`Opened ${i.name}: ${i.url} \u2014 its first build is on its way (palbase hosting:builds --site ${i.name}).`:`Opened ${i.name}: ${i.url} (nothing deployed yet: palbase hosting:deploy <folder> --site ${i.name}).`))}},l0={name:"hosting:sites:update",summary:"change a site: whether it is a single-page app, where it is built from, what its build runs",usage:"<name> [--spa | --no-spa] [--repo \u2026 --branch \u2026 --path \u2026] [--no-source] [--build-command \u2026] [--output \u2026] [--build-env K=V]\u2026 [--previews | --no-previews] [--preview-forks | --no-preview-forks]",args:{min:1,max:1},flags:{spa:{type:"boolean",description:"a single-page app: every path no file answers is its /index.html"},"no-spa":{type:"boolean",description:"not a single-page app: a path no file answers is 404"},...Qu,"no-source":{type:"boolean",description:"build it from no repository any more: deploy folders alone"},...ea},scope:"environment",async run(e){let t=await f(e),n=e.args[0],s={};e.flags.spa===!0&&(s.spa=!0),e.flags["no-spa"]===!0&&(s.spa=!1);let{source:a,build:r}=await ec(e,!1);if(a&&(s.source=a),e.flags["no-source"]===!0&&(s.source={repository:""}),r&&(s.build=r),na(e,s),Object.keys(s).length===0)throw g("nothing to change: give a flag","palbase help hosting:sites:update");await v(e,t,`change the site ${n}`);let i=await h(e,t,"PATCH",`/sites/${Ce(n)}`,s);e.out.result(i,()=>e.out.line(`${i.name}: ${i.url}${i.spa?" (single-page app)":""}${i.source?` \u2014 built from ${i.source.repository}@${i.source.branch}`:""}`))}},p0={name:"hosting:sites:delete",summary:"delete a site: its addresses serve nothing from now on",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=e.args[0];await v(e,t,`delete the site ${n} \u2014 its addresses serve nothing from now on`),await h(e,t,"DELETE",`/sites/${Ce(n)}`),e.out.result({deleted:n},()=>e.out.line(`Deleted ${n}.`))}},d0={name:"hosting:releases",summary:"a site's releases, newest first: the ten newest are kept to return to",usage:"[--site <name>]",flags:{site:{type:"string",value:"name",description:"the site (default: web)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.site??"web",{releases:s}=await h(e,t,"GET",`/sites/${Ce(n)}/releases`);e.out.result({releases:s},()=>{for(let a of s)e.out.line(`#${a.number} ${a.id} ${a.state}${a.serving?" serving":""} ${a.files} files ${ta(a.bytes)} ${a.created_at}${a.commit?` ${a.commit.slice(0,7)}`:""}`)})}},u0={name:"hosting:rollback",summary:"serve an earlier release of a site again, at once (the one before the serving one, or a named one)",usage:"[--site <name>] [--to <release id | #number>]",flags:{site:{type:"string",value:"name",description:"the site (default: web)"},to:{type:"string",value:"release",description:"the release: its id, or its number (#3)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.site??"web",s=e.flags.to;if(s!==void 0&&/^#?\d+$/.test(s)){let r=Number(s.replace("#","")),{releases:i}=await h(e,t,"GET",`/sites/${Ce(n)}/releases`),o=i.find(l=>l.number===r);if(!o)throw new y("release_not_found",`${n} keeps no release #${r}`,{hint:`palbase hosting:releases --site ${n}`});s=o.id}await v(e,t,`serve ${s?`the release ${e.flags.to}`:"the release before the serving one"} of ${n}`);let a=await h(e,t,"POST",`/sites/${Ce(n)}/rollback`,s?{release:s}:{});e.out.result(a,()=>e.out.line(`${a.name} serves release #${a.release?.number}: ${a.url}`))}},c0={name:"hosting:builds",summary:"a site's newest builds (a site built from GitHub), or one with its log",usage:"[build] [--site <name>] [--wait]",args:{min:0,max:1},flags:{site:{type:"string",value:"name",description:"the site (default: web)"},wait:{type:"boolean",description:"with a build: follow it until it ends"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.site??"web",s=e.args[0];if(s===void 0){let{builds:r}=await h(e,t,"GET",`/sites/${Ce(n)}/builds`);e.out.result({builds:r},()=>{r.length===0&&e.out.line(`${n} has no build: it is built from GitHub with hosting:sites:create --repo \u2026 --branch \u2026.`);for(let i of r)e.out.line(`${i.id} ${i.commit.slice(0,7)} ${i.state}${i.reason?`: ${i.reason}`:""} ${i.message}`)});return}let a=await h(e,t,"GET",`/sites/${Ce(n)}/builds/${D("the build",s)}`);for(let r=0;e.flags.wait===!0&&(a.state==="queued"||a.state==="building")&&r<900;r++)await e.io.sleep(2e3),a=await h(e,t,"GET",`/sites/${Ce(n)}/builds/${D("the build",s)}`);if(e.out.result(a,()=>{e.out.line(`${a.id} ${a.commit.slice(0,7)} ${a.state}${a.reason?`: ${a.reason}`:""}`),a.log&&e.out.line(a.log)}),a.state==="failed")return 1}},h0={name:"hosting:build",summary:"build a site's branch head now and serve it, as a push does",usage:"[--site <name>]",flags:{site:{type:"string",value:"name",description:"the site (default: web)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.site??"web";await v(e,t,`build ${n} from the head of its branch`);let s=await h(e,t,"POST",`/sites/${Ce(n)}/builds`);e.out.result(s,()=>e.out.line(`${s.name}: a build of ${s.source?.branch??"its branch"}'s head is on its way (palbase hosting:builds --site ${s.name}).`))}},m0={name:"hosting:previews",summary:"a site's pull request previews, newest first: where each answers, and whether it is built",usage:"[--site <name>]",flags:{site:{type:"string",value:"name",description:"the site (default: web)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.site??"web",{previews:s}=await h(e,t,"GET",`/sites/${Ce(n)}/previews`);e.out.result({previews:s},()=>fo(e,s,`${n} has no preview: a site built from GitHub previews its pull requests with hosting:sites:update ${n} --previews.`))}},g0=mo("site","hosting",async e=>`/sites/${Ce(e.flags.site??"web")}`,{site:{type:"string",value:"name",description:"the site (default: web)"}}),f0=go("site","hosting",async e=>`/sites/${Ce(e.flags.site??"web")}`,{site:{type:"string",value:"name",description:"the site (default: web)"}}),tc=[r0,i0,o0,l0,p0,d0,u0,c0,h0,m0,f0,...g0];function sc(e){return`its last push (${A(e.commit.slice(0,7))}) did not roll out \u2014 ${A(sa(e.reason))}`}function y0(e){let t=`${e.running_version} serving`;if(e.version!==e.running_version){let s={waiting:"waiting to roll out",not_up:"not up",given_up:"given up on",migration:"held by its database migration",stopped:"not up (the machine is stopped)",failed:"not up (the machine cannot run)"}[e.state_reason_kind??""]??(e.state_reason?"not up":"rolling out");t+=`, ${e.version} ${s}`}return`${t}${e.build?` (build ${e.build.id}, ${e.build.commit.slice(0,7)})`:""}`}function sa(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t!=="").join(" \xB7 ")}function b0(e){let t=e.openapi_path?`, from ${e.openapi_path}`:"";switch(e.contract_state){case"refused":return`refused: ${(e.contract_error??"its app wrote none").split(/\r?\n/).filter(s=>s.trim()!=="").map(A).join(`
|
|
32
|
-
${" ".repeat(15)}`)}${t}`;case"none":return`none: its app serves none${t}`}return`${e.contract_digest?`sha256:${e.contract_digest.slice(0,12)}\u2026`:"none read"}${t}`}var w0=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/;async function z(e,t,n,s,a,r){return(await ye(e.studio,t.env_ref,n,s,a,r)).body}function te(e){if(!w0.test(e))throw g(`${JSON.stringify(e)} is not a name: lowercase letters, digits and dashes, starting with a letter`);return encodeURIComponent(e)}async function ce(e,t,n){if(n!==void 0)return n;let{machines:s}=await z(e,t,"GET","/machines?limit=100");if(s.length===1)return s[0].name;let a=await Us(e.io,e.io.cwd),r=a?.repository?s.filter(i=>i.source.repository.toLowerCase()===a.repository?.toLowerCase()&&(i.source.path??"")===a.path):[];if(r.length===1)return r[0].name;throw s.length===0?new y("no_machine","the environment has no machine yet",{hint:"make one with palbase machines:create"}):g("which machine? name it",`the environment's machines: ${s.map(i=>i.name).join(", ")}`)}var ac={name:"machines:sizes",summary:"the machine sizes, and which of them this environment may open now",scope:"environment",async run(e){let t=await f(e),{sizes:n}=await z(e,t,"GET","/machines/sizes");e.out.result({sizes:n},()=>e.out.table(n,[{header:"size",value:s=>s.name},{header:"cpu",value:s=>`${s.vcpu} vCPU`},{header:"memory",value:s=>`${s.memory_mib} MiB`},{header:"sleeps",value:s=>s.sleeps?"when idle":"never"},{header:"open",value:s=>s.available?"yes":`no \u2014 ${s.reason??""}`}]))}},rc={name:"databases:sizes",summary:"the database sizes, and which of them this environment may open now",scope:"environment",async run(e){let t=await f(e),{sizes:n}=await z(e,t,"GET","/databases/sizes");e.out.result({sizes:n},()=>e.out.table(n,[{header:"size",value:s=>s.name},{header:"cpu",value:s=>`${s.vcpu} vCPU`},{header:"memory",value:s=>`${s.memory_mib} MiB`},{header:"storage",value:s=>`${(s.storage_bytes/1e9).toFixed(0)} GB`},{header:"sleeps",value:s=>s.sleeps?`when idle${s.awake_hours_per_month?`, ${s.awake_hours_per_month} h awake a month`:""}`:"never"},{header:"open",value:s=>s.available?"yes":`no \u2014 ${s.reason??""}`}]))}},ic={name:"machines:list",summary:"the project's machines, each with the environment it is bound to: size, state, the version serving, address",details:["A project's machines are the project's: each is bound to one of its environments, whose settings, secrets and modules it takes, and the list is every environment's you reach. An environment's own token lists its environment's alone."],scope:"environment",async run(e){let t=await f(e),[{machines:n},s]=await Promise.all([z(e,t,"GET","/machines?limit=100"),zs(e.studio,t)]);e.out.result({machines:n},()=>{n.length===0&&e.out.line("No machine yet: palbase machines:create makes one from the code in this directory."),e.out.table(n,[{header:"name",value:a=>a.name},{header:"env",value:a=>`${Yn(s,a.environment)}${a.moving_to?` \u2192 ${Yn(s,a.moving_to)}`:""}`},{header:"size",value:a=>`${a.size}${a.replicas>1?` \xD7${a.replicas}`:""}`},{header:"state",value:a=>a.state},{header:"version",value:a=>a.running_version===a.version?`${a.version}`:`${a.running_version} \u2192 ${a.version}`},{header:"source",value:a=>`${a.source.repository}@${a.source.branch}${a.source.path?`/${a.source.path}`:""}`},{header:"url",value:a=>a.url}])})}},oc={name:"machines:move",summary:"bind a machine to another environment of the project: it starts there with that environment's settings, secrets and modules",usage:"<name> --to <env>",details:["The machine is taken out of the environment it leaves and starts in the new one at the version it serves, in a moment; its address names the new environment (<name>-<its ref>).","Its pull requests' previews are closed: a new push opens them in the new environment. The database it is given stays where it is kept, given to it across environments.","It needs the admin role in both environments. A machine with domains of its own does not move: remove them first (machines:domains:remove), add them again once it has moved."],args:{min:1,max:1},flags:{to:{type:"string",value:"env",description:"the environment of the project it moves to (its slug)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.to;if(typeof n!="string"||n==="")throw g("--to names the environment of the project it moves to");let s=(await Re(e.studio)).filter(i=>i.project_id===t.project_id),a=s.find(i=>i.slug===n||i.ref===n);if(!a)throw new y("no_such_environment",`the project has no environment ${JSON.stringify(n)}`,{hint:`its environments: ${s.map(i=>i.slug).join(", ")}`});let r=await z(e,t,"POST",`/machines/${te(e.args[0])}/move`,{environment:a.ref});e.out.result(r,()=>e.out.line(`${r.name} moves to ${a.slug}: it starts there in a moment (palbase machines:get ${r.name} -E ${a.slug}).`))}},lc={name:"machines:get",summary:"a machine in full: its source, size, environment, database and the build serving",usage:"[name]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),s=await z(e,t,"GET",`/machines/${te(n)}`);e.out.result(s,()=>{e.out.line(`${s.name} \u2014 ${s.state}${s.state_reason?` (${s.state_reason})`:""}`),e.out.line(` url ${s.url}`),e.out.line(` source ${s.source.repository} @ ${s.source.branch}${s.source.path?`, ${s.source.path}`:""}${s.source.context?` (context ${s.source.context})`:""}`),e.out.line(` size ${s.size} \xD7 ${s.replicas}, port ${s.port}${s.health_path?`, health ${s.health_path}`:""}`),e.out.line(` version ${y0(s)}`),s.failed_build&&e.out.line(` last push ${A(`${s.failed_build.commit.slice(0,7)} ${s.failed_build.state}: ${sa(s.failed_build.reason)}`)} (palbase machines:builds:log ${A(s.failed_build.id)} --machine ${s.name})`),e.out.line(` contract ${b0(s)}`),e.out.line(` database ${s.database?.name?`${s.database.name}${s.database.migrations?", its migrations run before each release":""}`:"none"}`),e.out.line(` secrets ${s.secrets?`the ${s.secrets} secrets`:"none"}`),e.out.line(` tests ${s.test_command?`${s.test_command}${s.test_users?.length?`, as ${s.test_users.join(", ")}`:""} \u2014 run on each build before it rolls out`:"none"}`),e.out.line(` env ${Object.keys(s.env).length===0?"none":Object.keys(s.env).sort().join(", ")}`)})}},pc={repo:{type:"string",value:"owner/name",description:"the GitHub repository (default: this checkout's origin)"},branch:{type:"string",value:"branch",description:"the branch whose pushes are built and rolled out (default: the one checked out)"},path:{type:"string",value:"dir",description:"the directory built, from the repository's root (default: this directory's place in it)"},context:{type:"string",value:"dir",description:'what the build is given above --path (a monorepo: ".")'},size:{type:"string",value:"size",description:"its size (palbase machines:sizes lists them)"},replicas:{type:"string",value:"n",description:"how many copies run, each on a node of its own"},port:{type:"string",value:"port",description:"the port it listens on (it also finds it in PORT)"},"always-on":{type:"boolean",description:"keep it awake: never put to sleep when idle (an environment on Pay as you go pays its every hour; on Free a shared machine sleeps when idle)"},"no-always-on":{type:"boolean",description:"let it sleep when idle again"},...ea,health:{type:"string",value:"path",description:"where it answers 2xx while well; a release that does not is not rolled out"},"openapi-path":{type:"string",value:"path",description:`where its app serves its OpenAPI contract, when it is not a Palbase backend (apps:sync makes its client from it); "" for a Palbase backend's own`},db:{type:"string",value:"database",description:'a database of the environment it is given (PALBASE_DB_URL); "" for none'},migrations:{type:"boolean",description:"run the database's migrations before each release (a Palbase backend's)"},secrets:{type:"string",value:"production|development",description:'the secrets it is started with, by name; "" for none'},var:{type:"string",multiple:!0,value:"K=V",description:"a setting it is started with (repeat it); secrets go in secrets:set"},"test-command":{type:"string",value:"command",description:'what each new build runs before it takes traffic, in its image, against the new version itself once its migration has run (bun test, npm test); a failure fails the build and the machine runs what it ran; "" for none'},"test-users":{type:"string",value:"names",description:'the test users each test run makes for its tests (api.signInAs), comma-separated; "" for none'}};function dc(e,t){e.flags["test-command"]!==void 0&&(t.test_command=e.flags["test-command"]),e.flags["test-users"]!==void 0&&(t.test_users=Wi(e.flags["test-users"]))}function uc(e){if(!e)return;let t={};for(let n of e){let s=n.indexOf("=");if(s<=0)throw g(`a setting is K=V, not ${JSON.stringify(n)}`);t[n.slice(0,s)]=n.slice(s+1)}return t}function kn(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw g(`--${t} is a whole number`);return n}var cc={name:"machines:create",summary:"make a machine from the code in this directory, built on every push to its branch",usage:"[name] [--size <size>] [--db <database> --migrations] [--repo --branch --path --context] \u2026",details:["Run in a checkout, it reads the repository from origin, the branch from HEAD and the directory from where you are; flags say otherwise.","The first build starts at once; --wait follows it until the machine serves, and prints its address.","The environment needs its GitHub link first: palbase github:connect."],args:{min:0,max:1},flags:{...pc,wait:{type:"boolean",description:"follow the first build until the machine serves"}},scope:"environment",async run(e){let t=await f(e),n=await Us(e.io,e.io.cwd),s=e.flags.repo??n?.repository,a=e.flags.branch??n?.branch;if(!s)throw g("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!a)throw g("which branch? none is checked out here","pass --branch <branch>");let r=e.flags.size;if(r===void 0){let{sizes:m}=await z(e,t,"GET","/machines/sizes");if(r=m.find(b=>b.available)?.name,!r)throw new y("no_size_open","no machine size is open to this environment",{hint:"palbase machines:sizes says why"})}let i=e.flags.path??n?.path??"",o={...e.args[0]?{name:e.args[0]}:{},source:{repository:s,branch:a,...i!==""?{path:i}:{},...e.flags.context?{context:e.flags.context}:{}},size:r},l=kn(e.flags.replicas,"replicas"),d=kn(e.flags.port,"port");l!==void 0&&(o.replicas=l),d!==void 0&&(o.port=d),e.flags["always-on"]===!0&&(o.always_on=!0),e.flags["no-always-on"]===!0&&(o.always_on=!1),na(e,o),e.flags.health!==void 0&&(o.health_path=e.flags.health),e.flags["openapi-path"]!==void 0&&(o.openapi_path=e.flags["openapi-path"]),e.flags.secrets!==void 0&&(o.secrets=e.flags.secrets);let p=uc(e.flags.var);if(p&&(o.env=p),e.flags.db!==void 0)o.database={name:e.flags.db,migrations:e.flags.migrations===!0};else if(e.flags.migrations===!0)throw g("--migrations goes with --db <database>");dc(e,o),await v(e,t,`make a machine from ${s}@${a}${i?`/${i}`:""} (${r})`);let u=await z(e,t,"POST","/machines",o);e.flags.wait===!0&&(u=await _0(e,t,u.name)),e.out.result(u,()=>e.out.line(`Made the machine ${u.name} (${u.size}) \u2014 ${u.state}; it answers at ${u.url}`))}},hc={name:"machines:update",summary:"change a machine: the change rolls out as a new version beside the one serving",usage:"[name] [--size \u2026] [--replicas \u2026] [--db \u2026] [--repo --branch --path --context] \u2026",args:{min:0,max:1},flags:pc,scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),s={};if(e.flags.repo!==void 0||e.flags.branch!==void 0||e.flags.path!==void 0||e.flags.context!==void 0){let o=await z(e,t,"GET",`/machines/${te(n)}`);s.source={repository:e.flags.repo??o.source.repository,branch:e.flags.branch??o.source.branch,path:e.flags.path??o.source.path??"",context:e.flags.context??o.source.context??""}}e.flags.size!==void 0&&(s.size=e.flags.size);let a=kn(e.flags.replicas,"replicas"),r=kn(e.flags.port,"port");if(a!==void 0&&(s.replicas=a),r!==void 0&&(s.port=r),e.flags["always-on"]===!0&&(s.always_on=!0),e.flags["no-always-on"]===!0&&(s.always_on=!1),na(e,s),e.flags.health!==void 0&&(s.health_path=e.flags.health),e.flags["openapi-path"]!==void 0&&(s.openapi_path=e.flags["openapi-path"]),e.flags.secrets!==void 0&&(s.secrets=e.flags.secrets),e.flags.var!==void 0)throw g("machines:update leaves the settings as they are: machines:env:set and machines:env:unset change them");if(e.flags.db!==void 0&&(s.database={name:e.flags.db,migrations:e.flags.migrations===!0}),dc(e,s),Object.keys(s).length===0)throw g("nothing to change: give a flag","palbase help machines:update");await v(e,t,`change the machine ${n}: ${Object.keys(s).join(", ")}`);let i=await z(e,t,"PATCH",`/machines/${te(n)}`,s);e.out.result(i,()=>e.out.line(`${i.name}: version ${i.version} rolls out beside ${i.running_version}.`))}},mc={name:"machines:env:list",summary:"what a machine is started with, and where each comes from (the platform, the machine, its secrets)",usage:"[name]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),s=await z(e,t,"GET",`/machines/${te(n)}`),a=s.secrets?await z(e,t,"GET",`/secrets/${D("the machine's secret set",s.secrets)}`).then(o=>(o.items??o.secrets??[]).map(l=>l.name),()=>[]):[],r=["PORT","PALBASE_URL","PALBASE_PROJECT_ID","PALBASE_REPLICAS","PALBASE_PLATFORM_SECRET","PALBASE_SECRET_KEY","PALBASE_WEBHOOK_SECRET",...s.database?.name?["PALBASE_DB_URL","PALBASE_DB_CONNECTIONS"]:[]],i=r.map(o=>({name:o,from:"platform",note:a.includes(o)||o in s.env?`in place of the ${o} set by hand`:""}));for(let o of Object.keys(s.env).sort())r.includes(o)||i.push({name:o,from:"machine",note:a.includes(o)?`shadows the secret ${o}`:""});for(let o of a.sort())r.includes(o)||o in s.env||i.push({name:o,from:`secrets (${s.secrets})`,note:""});e.out.result({machine:s.name,env:i},()=>e.out.table(i,[{header:"name",value:o=>o.name},{header:"from",value:o=>o.from},{header:"",value:o=>o.note}]))}};async function gc(e,t){let n=await f(e),s=await ce(e,n,e.flags.machine);for(let a=1;;a++){let r=await ye(e.studio,n.env_ref,"GET",`/machines/${te(s)}`),i={...r.body.env},o=t(i);if(a===1){if(r.body.secrets){let l=await z(e,n,"GET",`/secrets/${D("the machine's secret set",r.body.secrets)}`).catch(()=>({items:[]}));for(let d of Object.keys(i))(l.items??[]).some(p=>p.name===d)&&e.out.warn(`${d} in the machine's env shadows the secret of that name`)}await v(e,n,`${o.join(", ")} on the machine ${s}`)}try{let l=await z(e,n,"PATCH",`/machines/${te(s)}`,{env:i},r.etag?{"if-match":r.etag}:void 0);e.out.result({machine:l.name,env:Object.keys(l.env).sort()},()=>e.out.line(`${l.name}: version ${l.version} rolls out with it.`));return}catch(l){if(!(l instanceof j&&l.status===412)||a===3)throw l;e.out.note(`${s} changed meanwhile: making the change again on what it is now\u2026`)}}}var fc={name:"machines:env:set",summary:"set settings a machine is started with (not secrets: secrets:set keeps those)",usage:"K=V\u2026 [--machine <name>]",args:{min:1,max:50},flags:{machine:{type:"string",value:"name",description:"the machine (default: the only one, or this directory's)"}},scope:"environment",async run(e){let t=uc(e.args);await gc(e,n=>(Object.assign(n,t),Object.keys(t).map(s=>`set ${s}`)))}},yc={name:"machines:env:unset",summary:"take settings away from what a machine is started with",usage:"K\u2026 [--machine <name>]",args:{min:1,max:50},flags:{machine:{type:"string",value:"name",description:"the machine (default: the only one, or this directory's)"}},scope:"environment",async run(e){await gc(e,t=>{for(let n of e.args){if(!(n in t))throw new y("no_such_setting",`the machine is not started with ${n}`);delete t[n]}return e.args.map(n=>`unset ${n}`)})}},bc={name:"machines:builds",summary:"a machine's builds, newest first",usage:"[name]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),{builds:s}=await z(e,t,"GET",`/machines/${te(n)}/builds?limit=20`);e.out.result({builds:s},()=>e.out.table(s,[{header:"build",value:a=>a.id},{header:"commit",value:a=>a.commit.slice(0,7)},{header:"state",value:a=>`${a.state}${a.running?" (serving)":""}${a.reason?` \u2014 ${sa(a.reason)}`:""}`},{header:"message",value:a=>a.message.split(`
|
|
31
|
+
`))e.out.line(a)}})}},Ud={name:"notify:templates:set",summary:"override a template in a locale, from a file or stdin (email: {subject, html_body, text_body} as JSON)",usage:"<slug> --locale <locale> [--channel email|sms|whatsapp] [--file <path>]",details:['email: {"subject", "html_body", "text_body"}; sms: the text, or {"body"}; whatsapp: {"name", "language", "variables", "code_button"} of a template approved on your Meta account.',"notify:templates:get \u2026 --json > t.json gives a document to edit and set back. Handlebars: {{name}}, {{#if}}, {{#each}}."],args:{min:1,max:1},flags:{...Zi,file:{type:"string",value:"path",description:"the template (default: stdin)"}},scope:"environment",async run(e){let t=await f(e),n=Qs(e),s=Qi(e,e.args[0]),a=l_(n,await be(e,e.flags.file,"the template"));await v(e,t,`override the ${n} template ${e.args[0]} (${e.flags.locale})`);let r=await h(e,t,"PUT",s,a,C());e.out.result(r,()=>e.out.line(`The ${n} template ${e.args[0]} (${e.flags.locale}) is yours now${typeof r.subject=="string"?`: "${r.subject}"`:""}.`))}},zd={name:"notify:templates:delete",summary:"remove an override: the platform's default renders again (a WhatsApp mapping is forgotten)",usage:"<slug> --locale <locale> [--channel email|sms|whatsapp]",args:{min:1,max:1},flags:Zi,scope:"environment",async run(e){let t=await f(e),n=Qi(e,e.args[0]);await v(e,t,`remove the ${Qs(e)} template ${e.args[0]} (${e.flags.locale})`),await h(e,t,"DELETE",n,void 0,C()),e.out.result({deleted:{channel:Qs(e),slug:e.args[0],locale:e.flags.locale}},()=>e.out.line(`Removed the override of ${e.args[0]} (${e.flags.locale}).`))}};async function Xi(e,t){let n=[],s;do{let a=await h(e,t,"GET",`/notify/topics?limit=100${s?`&cursor=${k(s)}`:""}`);n.push(...a.topics),s=a.next_cursor}while(s);return n}var Bd={name:"notify:topics:list",summary:"the topics users follow, how many follow each, whether they follow it from the app",scope:"environment",async run(e){let t=await f(e),n=await Xi(e,t);e.out.result({topics:n},()=>{n.length===0&&e.out.line("No topic: palbase notify:topics:create <name> makes one."),e.out.table(n,[{header:"topic",value:s=>s.name},{header:"followers",value:s=>String(s.subscribers)},{header:"from the app",value:s=>s.self_subscribe?"yes":"no: the project adds them"}])})}},Fd={name:"notify:topics:create",summary:"make a topic users can follow; a push to it reaches its followers",usage:"<name> [--self-subscribe yes|no]",args:{min:1,max:1},flags:{"self-subscribe":{type:"string",value:"yes|no",description:"users follow it from the app (default no: the project adds them)"}},scope:"environment",async run(e){let t=await f(e),n=en(e.flags["self-subscribe"],"self-subscribe");await v(e,t,`make the topic ${e.args[0]}`);let s=await h(e,t,"POST","/notify/topics",{name:e.args[0],...n!==void 0?{self_subscribe:n}:{}},C());e.out.result(s,()=>e.out.line(`Made the topic ${s.name}${s.self_subscribe?", followed from the app":""}.`))}},Jd={name:"notify:topics:delete",summary:"delete a topic and who follows it",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e);await v(e,t,`delete the topic ${e.args[0]} and who follows it`),await h(e,t,"DELETE",`/notify/topics/${k(e.args[0])}`,void 0,C()),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the topic ${e.args[0]}.`))}},Wd={name:"notify:settings:get",summary:"the environment's message settings: the default locale, who email is from, where texts may go",scope:"environment",async run(e){let t=await f(e),{body:n}=await Ne(e,t,"/notify/settings");e.out.result(n,()=>Xn(e,n))}},Vd={name:"notify:settings:set",summary:'change message settings: key=value (from_email=\u2026, sms_countries=["+90","+44"], mx_check=true)',usage:"<key=value>\u2026",details:["The change is made on the revision read: one made beside it in the meantime is refused, not overwritten."],args:{min:1,max:20},scope:"environment",async run(e){let t=await f(e),n=Zt(e.args),{body:s,etag:a}=await Ne(e,t,"/notify/settings"),r=Qt(s,n),i=Dt(s,r);if(i.length===0)return ze(e,"the message settings",s);await v(e,t,`set the message settings ${i.join(", ")}`);let o=await h(e,t,"PUT","/notify/settings",r,{...Te(a),...C()});e.out.result({settings:o,changed:i},()=>{for(let l of i)e.out.line(`${l}: ${Ee(s[l])} \u2192 ${Ee(o[l])}`)})}},d_=new Set(["sms_countries","sms_blocked_countries"]);function u_(e){return{...e,sms_countries:e.sms_countries??[],sms_blocked_countries:e.sms_blocked_countries??[],mx_check:e.mx_check??!1}}var Hd={name:"notify",async read(e,t){let[n,s,a,r,i,o]=await Promise.all([h(e,t,"GET","/notify/settings"),h(e,t,"GET","/notify/providers"),h(e,t,"GET","/notify/templates/email"),h(e,t,"GET","/notify/templates/sms"),h(e,t,"GET","/notify/templates/whatsapp"),Xi(e,t)]),l={};for(let[u,m]of Object.entries(u_(n)))l[`settings.${u}`]=m;for(let u of s.providers)l[`providers.${u.channel}/${u.provider}`]={active:u.active,priority:u.priority,credentials:"set"};let d=a.templates.filter(u=>u.customized),p=await Promise.all(d.map(u=>h(e,t,"GET",`/notify/templates/email/${k(u.slug)}/${k(u.locale)}`)));for(let u of p)l[`templates.email/${u.slug}/${u.locale}`]={subject:u.subject,html_body:u.html_body,text_body:u.text_body};for(let u of r.templates.filter(m=>m.customized))l[`templates.sms/${u.slug}/${u.locale}`]={body:u.body};for(let u of i.templates)l[`templates.whatsapp/${u.slug}/${u.locale}`]={name:u.name,language:u.language,variables:u.variables,code_button:u.code_button};for(let u of o)l[`topics.${u.name}`]={self_subscribe:u.self_subscribe};return l},async copy(e,t,n,s){let a=pe(n,"settings.");if(a.length>0){let{body:o,etag:l}=await Ne(e,t,"/notify/settings"),d={...o};for(let p of a)d[p.name]=d_.has(p.name)&&Array.isArray(p.from)&&p.from.length===0?null:p.from;await V(s,`set the message settings ${a.map(p=>p.name).join(", ")}`,async()=>{await h(e,t,"PUT","/notify/settings",d,{...Te(l),...C()})})}for(let o of pe(n,"providers.")){let[l,d]=o.name.split("/");o.from===void 0?s.left(`the ${l} provider ${d}: only in the target, left as it is (it holds credentials)`):s.left(`the ${l} provider ${d}: credentials are not copied \u2014 set them with palbase notify:providers:set ${l} ${d} < credentials.json`)}for(let o of pe(n,"templates.")){let l=`/notify/templates/${o.name.split("/").map(k).join("/")}`;o.from===void 0?await V(s,`remove the template override ${o.name}`,async()=>{await h(e,t,"DELETE",l,void 0,C())}):await V(s,`override the template ${o.name}`,async()=>{await h(e,t,"PUT",l,o.from,C())})}let r=pe(n,"topics."),i=r.some(o=>o.from===void 0)?new Map((await Xi(e,t)).map(o=>[o.name,o.subscribers])):new Map;for(let o of r){let l=`/notify/topics/${k(o.name)}`,d=o.from?.self_subscribe;if(o.from===void 0){let p=i.get(o.name)??0;p>0?s.left(`the topic ${o.name}: only in the target, and ${p} users follow it \u2014 delete it with notify:topics:delete`):await V(s,`delete the topic ${o.name}`,async()=>{await h(e,t,"DELETE",l,void 0,C())})}else o.change==="only_in_from"?await V(s,`make the topic ${o.name}`,async()=>{await h(e,t,"POST","/notify/topics",{name:o.name,self_subscribe:d},C())}):await V(s,`set the topic ${o.name} ${d?"followed from the app":"followed by the project's adding"}`,async()=>{await h(e,t,"PATCH",l,{self_subscribe:d},C())})}}};var ts=["max_connections","max_events_per_second","max_joins_per_second","max_channels_per_connection"];function c_(e){if(e.kind==="owner")return"the user it names: everything";let t=[e.publish?"publish":"",e.state_read?"read state":"",e.state_write?"write state":""].filter(n=>n!=="");return`any signed-in user: subscribe${t.length>0?`, ${t.join(", ")}`:""}`}function eo(e){return Object.fromEntries(ts.map(t=>[t,e[t]??null]))}var Yd={name:"realtime:channels:get",summary:"the channel declaration, in the order patterns are matched: who may join each, publish, read and write its state",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET","/realtime/channels");e.out.result(n,()=>{n.channels.length===0&&e.out.line("No channel is declared: a channel no pattern matches belongs to no one."),e.out.table(n.channels,[{header:"pattern",value:s=>s.pattern},{header:"kind",value:s=>s.kind},{header:"who",value:s=>c_(s)}])})}},Xd={name:"realtime:channels:set",summary:'replace the channel declaration with a JSON file or stdin ({"channels": [\u2026]} or the list)',usage:"[--file <path>]",details:['Each channel: {"pattern": "room:{id}", "kind": "public", "publish": true, "state_read": true, "state_write": false}, or {"pattern": "user:{uid}", "kind": "owner"}.',"realtime:channels:get --json gives the document to edit. Open sockets are decided again within a heartbeat."],flags:{file:{type:"string",value:"path",description:"the declaration (default: stdin)"}},scope:"environment",async run(e){let t=await f(e),n=ue(await be(e,e.flags.file,"the channel declaration"),"the channel declaration"),s=Array.isArray(n)?n:n.channels;if(!Array.isArray(s))throw g('the declaration is {"channels": [\u2026]} or a list of channels');let a=await h(e,t,"GET","/realtime/channels");if(Me(a.channels,s))return ze(e,"the channel declaration",a);await v(e,t,`declare ${s.length} channel pattern(s) (now ${a.channels.length})`);let r=await h(e,t,"PUT","/realtime/channels",{channels:s});e.out.result(r,()=>e.out.line(r.channels.length===0?"No channel is declared now.":`Declared ${r.channels.length} channel pattern(s): ${r.channels.map(i=>i.pattern).join(", ")}.`))}},Zd={name:"realtime:limits:get",summary:"the limits the environment holds its clients to (null: the platform's), and the platform's",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET","/realtime/limits");e.out.result(n,()=>{let s=n.platform??{},a=Math.max(...ts.map(r=>r.length));for(let r of ts)e.out.line(`${r.padEnd(a)} ${n[r]===void 0||n[r]===null?"the platform's":Ee(n[r])}${s[r]!==void 0?` (platform ${s[r]===0?"no ceiling":Ee(s[r])})`:""}`)})}},Qd={name:"realtime:limits:set",summary:"change realtime limits: key=value (max_connections=500), null for the platform's",usage:"<key=value>\u2026",details:[`The keys: ${ts.join(", ")}. A value above the platform's has no effect beyond it.`],args:{min:1,max:4},scope:"environment",async run(e){let t=await f(e),n=Zt(e.args);for(let o of n)if(o.path.length!==1||!ts.includes(o.path[0]))throw g(`no limit ${JSON.stringify(o.path.join("."))}`,`the limits: ${ts.join(", ")}`);let s=eo(await h(e,t,"GET","/realtime/limits")),a=Qt(s,n),r=Dt(s,a);if(r.length===0)return ze(e,"the realtime limits",s);await v(e,t,`set the realtime limits ${r.join(", ")}`);let i=await h(e,t,"PUT","/realtime/limits",a);e.out.result({limits:i,changed:r},()=>{for(let o of r)e.out.line(`${o}: ${Ee(s[o]??"the platform's")} \u2192 ${Ee(i[o]??"the platform's")}`)})}},eu={name:"realtime",async read(e,t){let[n,s]=await Promise.all([h(e,t,"GET","/realtime/channels"),h(e,t,"GET","/realtime/limits")]),a={channels:n.channels};for(let[r,i]of Object.entries(eo(s)))a[`limits.${r}`]=i;return a},async copy(e,t,n,s){let a=n.find(i=>i.key==="channels");a&&await V(s,"declare the channels",async()=>{await h(e,t,"PUT","/realtime/channels",{channels:a.from??[]})});let r=pe(n,"limits.");if(r.length>0){let i=eo(await h(e,t,"GET","/realtime/limits"));for(let o of r)i[o.name]=o.from??null;await V(s,`set the realtime limits ${r.map(o=>o.name).join(", ")}`,async()=>{await h(e,t,"PUT","/realtime/limits",i)})}}},tu={name:"analytics:settings:get",summary:"how long analytics keeps events and console records, the share of performance samples kept, whether bodies are kept",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET","/analytics/settings");e.out.result(n,()=>Xn(e,n))}},nu={name:"analytics:settings:set",summary:"change analytics settings: key=value (retention_days=30, perf_sample_pct=10, console_bodies=false)",usage:"<key=value>\u2026",details:["A shorter retention removes what is older within minutes."],args:{min:1,max:4},scope:"environment",async run(e){let t=await f(e),n=Zt(e.args),s=await h(e,t,"GET","/analytics/settings"),a=Qt(s,n),r=Dt(s,a);if(r.length===0)return ze(e,"the analytics settings",s);await v(e,t,`set the analytics settings ${r.join(", ")}`);let i=await h(e,t,"PUT","/analytics/settings",a);e.out.result({settings:i,changed:r},()=>{for(let o of r)e.out.line(`${o}: ${Ee(s[o])} \u2192 ${Ee(i[o])}`)})}},su={name:"analytics",async read(e,t){let n=await h(e,t,"GET","/analytics/settings");return Object.fromEntries(Object.entries(n).map(([s,a])=>[`settings.${s}`,a]))},async copy(e,t,n,s){let a=pe(n,"settings.");if(a.length===0)return;let r=await h(e,t,"GET","/analytics/settings");for(let i of a)i.from!==void 0&&(r[i.name]=i.from);await V(s,`set the analytics settings ${a.map(i=>i.name).join(", ")}`,async()=>{await h(e,t,"PUT","/analytics/settings",r)})}};function h_(e){return{source:{repository:e.source.repository.toLowerCase(),branch:e.source.branch,path:e.source.path??"",context:e.source.context??""},size:e.size,replicas:e.replicas,port:e.port,health_path:e.health_path??"",env:e.env??{},secrets:e.secrets??"",database:e.database?{name:e.database.name,migrations:e.database.migrations===!0}:null,deploy_after_checks:e.deploy_after_checks===!0,deploy_checks:[...e.deploy_checks??[]].sort(),deploy_checks_app:e.deploy_checks_app??"github-actions"}}var au={name:"machines",async read(e,t){let{machines:n}=await h(e,t,"GET","/machines?limit=100");return Object.fromEntries(n.filter(s=>!s.preview_of).map(s=>[`machines.${s.name}`,h_(s)]))},async copy(e,t,n,s){for(let a of pe(n,"machines.")){if(a.change==="only_in_to"){s.left(`the machine ${a.name}: only the target has it \u2014 it serves on (palbase machines:delete ${a.name} takes it away)`);continue}let r=a.from;if(a.change==="only_in_from"){await V(s,`opened the machine ${a.name}, built from ${r.source.branch}'s head`,()=>h(e,t,"POST","/machines",{name:a.name,...r,database:r.database??void 0},C()));continue}let i=a.to,o=Object.fromEntries(Object.keys(r).filter(l=>!Me(r[l],i[l])).map(l=>[l,l==="database"&&r[l]===null?{name:""}:r[l]]));await V(s,`changed the machine ${a.name}: ${Object.keys(o).join(", ")} (a new version rolls out beside the one serving)`,()=>h(e,t,"PATCH",`/machines/${k(a.name)}`,o))}}};function m_(e){return{size:e.size,allow:[...e.allow].sort(),backup_days:e.backup_days}}async function g_(e,t,n,s){let a=await h(e,t,"POST","/databases",{name:n,...s},C());await e.state.keepDatabasePasswords(t.env_ref,a.name,{owner:a.credentials.owner.password,app:a.credentials.app.password})}var ru={name:"databases",async read(e,t){let{databases:n}=await h(e,t,"GET","/databases?limit=100");return Object.fromEntries(n.filter(s=>s.size!=="preview").map(s=>[`databases.${s.name}`,m_(s)]))},async copy(e,t,n,s){for(let a of pe(n,"databases.")){if(a.change==="only_in_to"){s.left(`the database ${a.name}: only the target has it \u2014 its data stays (palbase databases:delete ${a.name} takes it away)`);continue}let r=a.from;if(a.change==="only_in_from"){await V(s,`opened the database ${a.name} (${r.size}; its passwords kept on this computer \u2014 palbase db:copy brings its data)`,()=>g_(e,t,a.name,r));continue}let i=a.to,o=Object.fromEntries(["size","allow","backup_days"].filter(d=>!Me(r[d],i[d])).map(d=>[d,r[d]]));if(Object.keys(o).length===0)continue;let l=o.size===void 0?"":` (moving to ${o.size}, serving on)`;await V(s,`changed the database ${a.name}: ${Object.keys(o).join(", ")}${l}`,()=>h(e,t,"PATCH",`/databases/${k(a.name)}`,o))}}};var tt="/messaging/settings",f_=/^[A-Z][A-Z0-9_]{0,127}$/,no=["retention_days","push_preview","deleted_user_messages","search_by_meaning","event_text"];function ns(e,t){switch(e){case"retention_days":return t===null?"off: messages are kept for good":`${String(t)} days: older messages are removed`;case"push_preview":return t===!0?"on: a push says what the message says":"off: a push says only that a message came";case"deleted_user_messages":return t==="delete"?"delete: a deleted user's messages go with them":"keep: a deleted user's messages stay, their writer anonymous";case"search_by_meaning":return t===!0?"on: messages are found by what they mean too, each embedded by the AI module (billed as AI use)":"off: messages are found by their words alone";case"event_text":return t===!0?"on: messaging.message.created says what the message says":"off: messaging.message.created says who wrote to whom, not what (the backend reads it with the secret key)";case"hook":return t?iu(t):"none: anyone may reach anyone"}}function iu(e){return`${A(e.url)} (waited for ${e.timeout_ms} ms; when it does not answer, ${e.on_error==="allow"?"everyone is allowed":"no one is: the app is told to try again"})`}function y_(e,t){let n=[...no.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,r]of n)e.out.line(`${a.padEnd(s)} ${ns(a,r)}`)}function to(e,t){if(e!==void 0){if(e==="on")return!0;if(e==="off")return!1;throw g(`--${t} is on or off`)}}function b_(e){if(e===void 0)return;if(e==="off")return null;let t=Number(e);if(!/^[0-9]+$/.test(String(e))||t<1||t>36500)throw g("--retention-days is a whole number of days from 1 to 36500, or off (kept for good)");return t}var w_={name:"messaging:settings:get",summary:"how the environment runs its conversations: how long messages are kept, whether a push says what one says, what becomes of a deleted user's messages, whether they are found by what they mean, whether a message's event says what it says, the hook",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET",tt);e.out.result(n,()=>y_(e,n))}},v_={name:"messaging:settings:set",summary:"change how the environment runs its conversations: a setting left out is left as it is",usage:"[--retention-days <days>|off] [--push-preview on|off] [--deleted-user-messages keep|delete] [--search-by-meaning on|off] [--event-text on|off]",details:["A shorter retention removes the messages older than it, in every conversation. A deleted user's messages are kept or deleted as the setting is when the user is deleted.","Deleted, what of theirs had already gone from screens (seen once, its time up, vanish mode, taken back) stays its 14 days, sealed, for reports, then goes.","Search by meaning on: the app's search({ by: 'meaning' }) finds the messages nearest what a question means, no word of it needed. Each message's text (not a system message's, one seen a limited number of times, nor one of vanish mode) is embedded by the project's embedding model through the AI module and billed as the project's AI use; the messages written before are embedded in the background (seconds to minutes), a new one is found ~5 s after it is sent. Off: no message goes to a model, and the vectors are removed.","Event text on: messaging.message.created \u2014 told to the backend's webhooks and @On handlers that name it \u2014 carries the message's text (not a vanish-mode message's, one seen a limited number of times, nor one that goes after a time). The words leave the sealed store and stay on the event stream 7 days. Off: the backend reads the message with the secret key.","Only what changes is sent: a change made beside this one to another setting stays."],flags:{"retention-days":{type:"string",value:"days|off",description:"messages older than this many days are removed (1\u201336500); off: kept for good"},"push-preview":{type:"string",value:"on|off",description:"a push says what the message says (on), or only that one came (off)"},"deleted-user-messages":{type:"string",value:"keep|delete",description:"a deleted user's messages: kept, their writer anonymous, or deleted (what went from screens before stays its 14 days for reports)"},"search-by-meaning":{type:"string",value:"on|off",description:"messages are found by what they mean too (on: each embedded through the AI module, billed as AI use), or by their words alone (off)"},"event-text":{type:"string",value:"on|off",description:"messaging.message.created says what the message says (on), or who wrote to whom alone (off)"}},scope:"environment",async run(e){let t={},n=b_(e.flags["retention-days"]);n!==void 0&&(t.retention_days=n);let s=to(e.flags["push-preview"],"push-preview");s!==void 0&&(t.push_preview=s);let a=e.flags["deleted-user-messages"];if(a!==void 0){if(a!=="keep"&&a!=="delete")throw g("--deleted-user-messages is keep or delete");t.deleted_user_messages=a}let r=to(e.flags["search-by-meaning"],"search-by-meaning");r!==void 0&&(t.search_by_meaning=r);let i=to(e.flags["event-text"],"event-text");if(i!==void 0&&(t.event_text=i),Object.keys(t).length===0)throw g("nothing to change","pass --retention-days, --push-preview, --deleted-user-messages, --search-by-meaning or --event-text");let o=await f(e),l=await h(e,o,"GET",tt),d=no.filter(u=>u in t&&!Me(l[u],t[u]));if(d.length===0)return ze(e,"the messaging settings",l);await v(e,o,`set the messaging settings ${d.join(", ")}`);let p=await h(e,o,"PUT",tt,Object.fromEntries(d.map(u=>[u,t[u]])));e.out.result({settings:p,changed:d},()=>{for(let u of d)e.out.line(`${u}: ${ns(u,l[u])} \u2192 ${ns(u,p[u])}`)})}},ou={"secret-to":{type:"string",value:"NAME",description:"keep the new signing secret in the environment's secret NAME instead of printing it"},dev:{type:"boolean",description:"with --secret-to: the development secrets, not production"}};function lu(e){let t=e.flags["secret-to"];if(t!==void 0&&!f_.test(t))throw g(`--secret-to ${JSON.stringify(t)} is not a secret's name: capital letters, digits and _, a letter first`);if(e.flags.dev===!0&&t===void 0)throw g("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function pu(e,t,n,s,a){let{hook_secret:r,...i}=n;if(r===void 0){e.out.result({settings:i},()=>e.out.line(`${a}: ${ns("hook",i.hook)}.`));return}if(s!==void 0){let o=await h(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:r});e.out.result({settings:i,secret_to:{set:s.set,name:s.name,version:o.version}},()=>e.out.line(`${a}: ${ns("hook",i.hook)}; its signing secret is ${s.name} (${s.set}, v${o.version}) in ${q(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${ns("hook",i.hook)}.`),e.out.line(`signing secret (shown this once): ${r}`)})}var __={name:"messaging:hook:get",summary:"the hook asked whom one may reach: where it is, how long it is waited for, what is done when it does not answer (never its secret)",scope:"environment",async run(e){let t=await f(e),{hook:n}=await h(e,t,"GET",tt);e.out.result({hook:n},()=>e.out.line(n?iu(n):"No hook: anyone may reach anyone. palbase messaging:hook:set --url <url> sets one."))}},k_={name:"messaging:hook:set",summary:"set the hook asked whom one may reach, or change it; a new hook's signing secret is printed this once, or kept in a secret with --secret-to",usage:"[--url <url>] [--timeout-ms <ms>] [--on-error allow|deny] [--secret-to <NAME> [--dev]]",details:[`Before a direct conversation opens, people are added to a group, someone makes or opens an open group, a space's open groups are listed or one is joined, the hook is POSTed {"event": "messaging.can_message", "action": "direct" | "group_add" | "open_group" | "list_open" | "join", "from_user_id", "to_user_ids", "conversation_id", "space"}, signed as Standard Webhooks sign (webhook-id, webhook-timestamp, webhook-signature), and answers 200 {"allowed_user_ids": [\u2026]}: whom of to_user_ids from_user_id may reach \u2014 for open_group, list_open and join, to_user_ids is [from_user_id], and naming them lets them in. space is the conversation's (absent: none).`,"A new hook takes --url (an https URL on the public internet). Its signing secret is printed this once, or kept in the environment's secrets with --secret-to (production; --dev: development) and printed nowhere. A hook changed keeps its secret: palbase messaging:hook:secret:rotate makes a new one."],flags:{url:{type:"string",value:"url",description:"where the hook is asked"},"timeout-ms":{type:"string",value:"ms",description:"how long it is waited for: 100 to 5000 (a new hook: 2000)"},"on-error":{type:"string",value:"allow|deny",description:"when it does not answer: allow everyone, or deny and the app is told to try again (a new hook: deny)"},...ou},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw g("--url is where the hook is asked: an https URL");let n;if(e.flags["timeout-ms"]!==void 0&&(n=Number(e.flags["timeout-ms"]),!/^[0-9]+$/.test(String(e.flags["timeout-ms"]))||n<100||n>5e3))throw g("--timeout-ms is a whole number from 100 to 5000");let s=e.flags["on-error"];if(s!==void 0&&s!=="allow"&&s!=="deny")throw g("--on-error is allow or deny");if(t===void 0&&n===void 0&&s===void 0)throw g("nothing to change","pass --url, --timeout-ms or --on-error");let a=lu(e),r=await f(e),i=await h(e,r,"GET",tt),o=i.hook;if(!o&&t===void 0)throw g("the environment has no hook yet: --url names where it is asked");if(o&&a!==void 0)throw g("the hook has its signing secret, and a change keeps it: --secret-to goes with a new hook","palbase messaging:hook:secret:rotate --secret-to <NAME> makes a new secret and keeps it");let l={url:t??o.url},d=n??o?.timeout_ms;d!==void 0&&(l.timeout_ms=d);let p=s??o?.on_error;if(p!==void 0&&(l.on_error=p),o&&Me(o,{...o,...l}))return ze(e,"the hook",i);let u=o?["url","timeout_ms","on_error"].filter(b=>l[b]!==o[b]):[];await v(e,r,o?`change the messaging hook: ${u.join(", ")}`:`set the messaging hook ${l.url}${a?`, its secret kept in ${a.name} (${a.set})`:""}`);let m=await h(e,r,"PUT",tt,{hook:l});await pu(e,r,m,a,o?"Changed the hook":"Set the hook")}},S_={name:"messaging:hook:remove",summary:"remove the hook: anyone may reach anyone, and its signing secret is forgotten",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET",tt);if(!n.hook){e.out.result({settings:n,changed:[]},()=>e.out.line("Nothing to change: the environment has no hook."));return}await v(e,t,`remove the messaging hook ${n.hook.url}: anyone may reach anyone, and its signing secret is forgotten`);let s=await h(e,t,"PUT",tt,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may reach anyone."))}},$_={name:"messaging:hook:secret:rotate",summary:"make the hook's signing secret anew: printed this once, or kept in a secret with --secret-to; the old one signs nothing more",usage:"[--secret-to <NAME> [--dev]]",details:["The hook's calls are signed with the new secret alone from now: the endpoint verifies them with it (a machine reads a secret kept with --secret-to at its next start)."],flags:ou,scope:"environment",async run(e){let t=lu(e),n=await f(e);await v(e,n,`make the messaging hook's signing secret anew; the old one signs nothing more${t?`; the new one kept in ${t.name} (${t.set})`:""}`);let s=await h(e,n,"POST",`${tt}/hook-secret`);await pu(e,n,s,t,"Made the signing secret anew for the hook")}},du={name:"messaging",async read(e,t){let n=await h(e,t,"GET",tt),s={};for(let a of no)s[`settings.${a}`]=n[a];return n.hook&&(s.hook={url:n.hook.url,timeout_ms:n.hook.timeout_ms,on_error:n.hook.on_error}),s},async copy(e,t,n,s){let a=pe(n,"settings.");a.length>0&&await V(s,`set the messaging settings ${a.map(l=>l.name).join(", ")}`,async()=>{await h(e,t,"PUT",tt,Object.fromEntries(a.map(l=>[l.name,l.from])))});let r=n.find(l=>l.key==="hook");if(!r)return;if(r.from===void 0){await V(s,`remove the hook ${r.to.url}`,async()=>{await h(e,t,"PUT",tt,{hook:null})});return}let i=r.from,o;await V(s,`${r.change==="differs"?"change":"set"} the hook ${i.url}`,async()=>{o=(await h(e,t,"PUT",tt,{hook:i})).hook_secret}),o&&s.shown(`the hook ${i.url} signs with`,o)}},uu=[w_,v_,__,k_,S_,$_];var nt="/calls/settings",P_=/^[A-Z][A-Z0-9_]{0,127}$/,ao=["max_participants","calls_per_hour"];function ss(e,t){switch(e){case"max_participants":return`${String(t)}: a call holds at most this many, people and bots together`;case"calls_per_hour":return`${String(t)}: one person may start at most this many calls in an hour`;case"hook":return t?cu(t):"none: anyone may call anyone (blocks aside)"}}function cu(e){return`${A(e.url)} (waited for ${e.timeout_ms??2e3} ms; when it does not answer, ${e.on_error==="allow"?"everyone is allowed":"no one is: the call is refused"})${e.places?"; asked of places too":""}`}function A_(e,t){let n=[...ao.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,r]of n)e.out.line(`${a.padEnd(s)} ${ss(a,r)}`)}function so(e,t,n,s){if(e===void 0)return;let a=Number(e);if(!/^[0-9]+$/.test(String(e))||a<n||a>s)throw g(`--${t} is a whole number from ${n} to ${s}`);return a}var R_={name:"calls:settings:get",summary:"how the environment runs its calls: how many a call holds, how many calls a person may start in an hour, the hook",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET",nt);e.out.result(n,()=>A_(e,n))}},T_={name:"calls:settings:set",summary:"change how the environment runs its calls: a setting left out is left as it is",usage:"[--max-participants <n>] [--calls-per-hour <n>]",details:["A call holds at most --max-participants, people and the project's bots together, as the setting was when the call was made: a change holds for the calls made after it.","Every call's media, one to one or in a group, goes through the platform's media server: no device learns another's address.","A person who has started --calls-per-hour calls in the last hour is refused another (too_many_calls).","Only what changes is sent: a change made beside this one to another setting stays."],flags:{"max-participants":{type:"string",value:"n",description:"how many a call holds, people and bots together (2\u2013100)"},"calls-per-hour":{type:"string",value:"n",description:"how many calls one person may start in an hour (1\u20131000)"}},scope:"environment",async run(e){let t={},n=so(e.flags["max-participants"],"max-participants",2,100);n!==void 0&&(t.max_participants=n);let s=so(e.flags["calls-per-hour"],"calls-per-hour",1,1e3);if(s!==void 0&&(t.calls_per_hour=s),Object.keys(t).length===0)throw g("nothing to change","pass --max-participants or --calls-per-hour");let a=await f(e),r=await h(e,a,"GET",nt),i=ao.filter(l=>l in t&&!Me(r[l],t[l]));if(i.length===0)return ze(e,"the call settings",r);await v(e,a,`set the call settings ${i.join(", ")}`);let o=await h(e,a,"PUT",nt,Object.fromEntries(i.map(l=>[l,t[l]])));e.out.result({settings:o,changed:i},()=>{for(let l of i)e.out.line(`${l}: ${ss(l,r[l])} \u2192 ${ss(l,o[l])}`)})}},hu={"secret-to":{type:"string",value:"NAME",description:"keep the new signing secret in the environment's secret NAME instead of printing it"},dev:{type:"boolean",description:"with --secret-to: the development secrets, not production"}};function mu(e){let t=e.flags["secret-to"];if(t!==void 0&&!P_.test(t))throw g(`--secret-to ${JSON.stringify(t)} is not a secret's name: capital letters, digits and _, a letter first`);if(e.flags.dev===!0&&t===void 0)throw g("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function gu(e,t,n,s,a){let{hook_secret:r,...i}=n;if(r===void 0){e.out.result({settings:i},()=>e.out.line(`${a}: ${ss("hook",i.hook)}.`));return}if(s!==void 0){let o=await h(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:r});e.out.result({settings:i,secret_to:{set:s.set,name:s.name,version:o.version}},()=>e.out.line(`${a}: ${ss("hook",i.hook)}; its signing secret is ${s.name} (${s.set}, v${o.version}) in ${q(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${ss("hook",i.hook)}.`),e.out.line(`signing secret (shown this once): ${r}`)})}var E_={name:"calls:hook:get",summary:"the hook asked whom one may call: where it is, how long it is waited for, what is done when it does not answer (never its secret)",scope:"environment",async run(e){let t=await f(e),{hook:n}=await h(e,t,"GET",nt);e.out.result({hook:n},()=>e.out.line(n?cu(n):"No hook: anyone may call anyone (blocks aside). palbase calls:hook:set --url <url> sets one."))}},C_={name:"calls:hook:set",summary:"set the hook asked whom one may call, or change it; a new hook's signing secret is printed this once, or kept in a secret with --secret-to",usage:"[--url <url>] [--timeout-ms <ms>] [--on-error allow|deny] [--places on|off] [--secret-to <NAME> [--dev]]",details:['Before a call is made, or more people are asked into one, the hook is POSTed {"event": "calls.can_call", "action": "start" | "invite", "from_user_id", "to_user_ids", "video", "call_id", "conversation_id"}, signed as Standard Webhooks sign (webhook-id, webhook-timestamp, webhook-signature), and answers 200 {"allowed_user_ids": [\u2026]}: only those are called, and with none the call is refused.',`With --places on, the hook is asked of places too ({"action": "place", "place", "from_user_id", "to_user_ids": [that person]}): it says who may see and join the meeting held at a place of the app (a channel). Off (a new hook), places are not asked of it, and a place's meeting is seen only by the people asked into it.`,"A new hook takes --url (a URL on the public internet). Its signing secret is printed this once, or kept in the environment's secrets with --secret-to (production; --dev: development) and printed nowhere. A hook changed keeps its secret: palbase calls:hook:secret:rotate makes a new one."],flags:{url:{type:"string",value:"url",description:"where the hook is asked"},"timeout-ms":{type:"string",value:"ms",description:"how long it is waited for: 100 to 5000 (a new hook: 2000)"},"on-error":{type:"string",value:"allow|deny",description:"when it does not answer: allow everyone, or deny and the call is refused (a new hook: deny)"},places:{type:"string",value:"on|off",description:"the hook answers places too: who may see and join a channel's meeting (a new hook: off)"},...hu},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw g("--url is where the hook is asked: a URL");let n=so(e.flags["timeout-ms"],"timeout-ms",100,5e3),s=e.flags["on-error"];if(s!==void 0&&s!=="allow"&&s!=="deny")throw g("--on-error is allow or deny");let a=e.flags.places;if(a!==void 0&&a!=="on"&&a!=="off")throw g("--places is on or off");let r=a===void 0?void 0:a==="on";if(t===void 0&&n===void 0&&s===void 0&&r===void 0)throw g("nothing to change","pass --url, --timeout-ms, --on-error or --places");let i=mu(e),o=await f(e),l=await h(e,o,"GET",nt),d=l.hook;if(!d&&t===void 0)throw g("the environment has no hook yet: --url names where it is asked");if(d&&i!==void 0)throw g("the hook has its signing secret, and a change keeps it: --secret-to goes with a new hook","palbase calls:hook:secret:rotate --secret-to <NAME> makes a new secret and keeps it");let p={url:t??d.url},u=n??d?.timeout_ms;u!==void 0&&(p.timeout_ms=u);let m=s??d?.on_error;m!==void 0&&(p.on_error=m);let b=r??d?.places;if(b!==void 0&&(p.places=b),d&&Me(d,{...d,...p}))return ze(e,"the hook",l);let w=d?["url","timeout_ms","on_error","places"].filter(T=>(p[T]??!1)!==(d[T]??!1)):[];await v(e,o,d?`change the calls hook: ${w.join(", ")}`:`set the calls hook ${p.url}${i?`, its secret kept in ${i.name} (${i.set})`:""}`);let _=await h(e,o,"PUT",nt,{hook:p});await gu(e,o,_,i,d?"Changed the hook":"Set the hook")}},j_={name:"calls:hook:remove",summary:"remove the hook: anyone may call anyone (blocks aside), and its signing secret is forgotten",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET",nt);if(!n.hook){e.out.result({settings:n,changed:[]},()=>e.out.line("Nothing to change: the environment has no hook."));return}await v(e,t,`remove the calls hook ${n.hook.url}: anyone may call anyone, and its signing secret is forgotten`);let s=await h(e,t,"PUT",nt,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may call anyone (blocks aside)."))}},O_={name:"calls:hook:secret:rotate",summary:"make the hook's signing secret anew: printed this once, or kept in a secret with --secret-to; the old one signs nothing more",usage:"[--secret-to <NAME> [--dev]]",details:["The hook's calls are signed with the new secret alone from now: the endpoint verifies them with it (a machine reads a secret kept with --secret-to at its next start)."],flags:hu,scope:"environment",async run(e){let t=mu(e),n=await f(e);await v(e,n,`make the calls hook's signing secret anew; the old one signs nothing more${t?`; the new one kept in ${t.name} (${t.set})`:""}`);let s=await h(e,n,"POST",`${nt}/hook-secret`);await gu(e,n,s,t,"Made the signing secret anew for the hook")}},fu={name:"calls",async read(e,t){let n=await h(e,t,"GET",nt),s={};for(let a of ao)s[`settings.${a}`]=n[a];return n.hook&&(s.hook={url:n.hook.url,timeout_ms:n.hook.timeout_ms,on_error:n.hook.on_error}),s},async copy(e,t,n,s){let a=pe(n,"settings.");a.length>0&&await V(s,`set the call settings ${a.map(l=>l.name).join(", ")}`,async()=>{await h(e,t,"PUT",nt,Object.fromEntries(a.map(l=>[l.name,l.from])))});let r=n.find(l=>l.key==="hook");if(!r)return;if(r.from===void 0){await V(s,`remove the hook ${r.to.url}`,async()=>{await h(e,t,"PUT",nt,{hook:null})});return}let i=r.from,o;await V(s,`${r.change==="differs"?"change":"set"} the hook ${i.url}`,async()=>{o=(await h(e,t,"PUT",nt,{hook:i})).hook_secret}),o&&s.shown(`the hook ${i.url} signs with`,o)}},yu=[R_,T_,E_,C_,j_,O_];var M_=/^[a-z][a-z0-9-]{1,62}$/;function as(e){if(!M_.test(e))throw g(`${JSON.stringify(e)} is not a bucket's name: lowercase letters, digits and dashes, starting with a letter (2\u201363)`);return`/storage/buckets/${k(e)}`}function io(e){if(e==null)return"platform (5 GiB)";for(let[t,n]of[["GiB",2**30],["MiB",2**20],["KiB",2**10]])if(e>=n&&e%n===0)return`${e/n} ${t}`;return`${e} B`}function x_(e){if(e===""||e==="platform")return null;let t=/^(\d+(?:\.\d+)?)\s*(b|kb|kib|mb|mib|gb|gib)?$/i.exec(e.trim());if(!t)throw g(`--max-size ${JSON.stringify(e)} is not a size: 10MB, 512KiB, 1GB, a number of bytes, or platform`);let n=(t[2]??"b").toLowerCase(),s={b:1,kb:1e3,kib:2**10,mb:1e6,mib:2**20,gb:1e9,gib:2**30};return Math.round(Number(t[1])*s[n])}function ro(e){return{public:e.public,file_size_limit:e.file_size_limit??null,allowed_mime_types:e.allowed_mime_types??[],variants:e.variants??[]}}async function I_(e,t,n){try{return await h(e,t,"GET",as(n))}catch(s){if(s instanceof j&&s.status===404)return;throw s}}var bu={name:"storage:buckets:list",summary:"the environment's buckets: who may read each, the largest file and the types it takes",scope:"environment",async run(e){let t=await f(e),{buckets:n}=await h(e,t,"GET","/storage/buckets");e.out.result({buckets:n},()=>{n.length===0&&e.out.line("No bucket yet: palbase storage:buckets:set <name> makes one."),e.out.table(n,[{header:"bucket",value:s=>s.name},{header:"read by",value:s=>s.public?"anyone":"signed URLs, rules"},{header:"largest file",value:s=>io(s.file_size_limit)},{header:"types",value:s=>s.allowed_mime_types.length===0?"any":s.allowed_mime_types.join(", ")},{header:"renditions",value:s=>s.variants.map(a=>a.name).join(", ")}])})}},wu={name:"storage:buckets:get",summary:"a bucket's declaration in full, with its renditions",usage:"<bucket>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET",as(e.args[0]));e.out.result(n,()=>{e.out.line(n.name),e.out.line(` read by ${n.public?"anyone, at /storage/public/":"signed URLs and the rules"}`),e.out.line(` largest file ${io(n.file_size_limit)}`),e.out.line(` types ${n.allowed_mime_types.length===0?"any":n.allowed_mime_types.join(", ")}`);for(let s of n.variants)e.out.line(` rendition ${s.name}: ${s.width}\xD7${s.height} ${s.fit}, ${s.format}${s.quality?` q${s.quality}`:""}`)})}},vu={name:"storage:buckets:set",summary:"make a bucket, or change one: public or private, the largest file, the content types, its renditions",usage:"<bucket> [--public|--private] [--max-size <size>] [--types <a/b,c/*>] [--variants-file <path>]",details:["What is not given is kept as it is (a new bucket: private, the platform's size, any type, no rendition)."],args:{min:1,max:1},flags:{public:{type:"boolean",description:"anyone may read its files at /storage/public/"},private:{type:"boolean",description:"its files are read with signed URLs and the rules"},"max-size":{type:"string",value:"size",description:"the largest file: 10MB, 512KiB, 1GB, bytes, or platform"},types:{type:"string",value:"list",description:'the content types it takes, comma-separated (image/* a family); "" for any'},"variants-file":{type:"string",value:"path",description:"its renditions, a JSON list of {name, width, height, fit, format, quality}"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0];if(e.flags.public===!0&&e.flags.private===!0)throw g("--public and --private are one or the other");let s=await I_(e,t,n),a=ro(s??{name:n,public:!1,allowed_mime_types:[],variants:[]});if(e.flags.public===!0&&(a.public=!0),e.flags.private===!0&&(a.public=!1),e.flags["max-size"]!==void 0&&(a.file_size_limit=x_(e.flags["max-size"])),e.flags.types!==void 0&&(a.allowed_mime_types=re(e.flags.types)??[]),e.flags["variants-file"]!==void 0){let i=ue(await be(e,e.flags["variants-file"],"the renditions"),"the renditions file"),o=Array.isArray(i)?i:i.variants;if(!Array.isArray(o))throw g("the renditions file is a JSON list of {name, width, height, fit, format, quality}");a.variants=o}if(s&&Me(ro(s),a)){e.out.result(s,()=>e.out.line(`Nothing to change: ${n} already is so.`));return}await v(e,t,`${s?"change":"make"} the bucket ${n} (${a.public?"public":"private"})`);let r=await h(e,t,"PUT",as(n),a);e.out.result(r,()=>e.out.line(`${s?"Changed":"Made"} the bucket ${r.name}: ${r.public?"public":"private"}, files up to ${io(r.file_size_limit)}, ${r.allowed_mime_types.length===0?"any type":r.allowed_mime_types.join(", ")}.`))}},_u={name:"storage:buckets:delete",summary:"delete an empty bucket (one that still holds files is refused)",usage:"<bucket>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=as(e.args[0]);await v(e,t,`delete the bucket ${e.args[0]}`),await h(e,t,"DELETE",n),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the bucket ${e.args[0]}.`))}},ku={name:"storage",async read(e,t){let{buckets:n}=await h(e,t,"GET","/storage/buckets"),s={};for(let a of n){let r=ro(a);s[`buckets.${a.name}`]={...r,allowed_mime_types:[...r.allowed_mime_types].sort()}}return s},async copy(e,t,n,s){for(let a of pe(n,"buckets."))a.from===void 0?await V(s,`delete the bucket ${a.name}`,async()=>{await h(e,t,"DELETE",as(a.name))}):await V(s,`declare the bucket ${a.name}`,async()=>{await h(e,t,"PUT",as(a.name),a.from)})}};var rs=[$d,ku,Id,Hd,eu,su,du,fu],lr=[ru,au],Su={from:{type:"string",value:"env",description:"the environment compared from (slug or ref)"},to:{type:"string",value:"env",description:"the environment compared to (slug or ref)"},only:{type:"string",value:"modules",description:`only these, comma-separated: ${rs.map(e=>e.name).join(",")} (the default), and ${lr.map(e=>e.name).join(",")} when named`}};async function $u(e){if(e.global.env!==void 0)throw g("the two environments are named with --from and --to, not -E");let t=e.flags.from,n=e.flags.to;if(t===void 0||n===void 0)throw g("name both environments: --from <env> --to <env>");let s=await Re(e.studio),a;if(e.global.project!==void 0)a=_n(s,e.global.project);else{let l=await e.state.targetFor(e.io.cwd);if(!l)throw new y("no_target","which project? none is chosen for this directory",{hint:"pass -P <project>, or choose one here with palbase use"});a=s.filter(d=>d.project_id===l.target.project_id)}let r=l=>{let d=a.find(p=>p.slug===l||p.ref===l);if(!d)throw new y("no_such_environment",`the project has no environment ${JSON.stringify(l)}`,{hint:`its environments: ${a.map(p=>p.slug).join(", ")}`});return _e(d)},i=r(t),o=r(n);if(i.env_ref===o.env_ref)throw g("--from and --to name the same environment");return{from:i,to:o}}function Pu(e){let t=re(e.flags.only);if(t===void 0)return rs;let n=[...rs,...lr];for(let s of t)if(!n.some(a=>a.name===s))throw g(`no module ${JSON.stringify(s)}`,`the modules: ${n.map(a=>a.name).join(", ")}`);return n.filter(s=>t.includes(s.name))}function L_(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),s=[];for(let a of n){let r=a in e,i=a in t;r&&!i?s.push({key:a,change:"only_in_from",from:e[a]}):!r&&i?s.push({key:a,change:"only_in_to",to:t[a]}):Me(e[a],t[a])||s.push({key:a,change:"differs",from:e[a],to:t[a]})}return s}async function oo(e,t,n,s){let a=l=>Promise.all(t.map(d=>d.read(e,l))),[r,i]=await Promise.all([a(n),a(s)]),o=Object.fromEntries(t.map((l,d)=>[l.name,L_(r[d],i[d])]));return{from:n,to:s,modules:o,count:Object.values(o).reduce((l,d)=>l+d.length,0)}}function lo(e){return{from:{env:e.from.env_slug,ref:e.from.env_ref},to:{env:e.to.env_slug,ref:e.to.env_ref},equal:e.count===0,differences:e.count,modules:e.modules}}function or(e){let t=JSON.stringify(e)??"undefined";return t.length>140?`${t.slice(0,139)}\u2026`:t}function po(e,t){let n=t.from.env_slug,s=t.to.env_slug;for(let[r,i]of Object.entries(t.modules))if(i.length!==0){e.out.line(`${r} (${i.length})`);for(let o of i)o.change==="differs"?e.out.line(` ~ ${o.key}: ${n} ${or(o.from)} \xB7 ${s} ${or(o.to)}`):o.change==="only_in_from"?e.out.line(` - ${o.key}: only in ${n}: ${or(o.from)}`):e.out.line(` + ${o.key}: only in ${s}: ${or(o.to)}`)}let a=Object.keys(t.modules).join(", ");e.out.line(t.count===0?`${n} and ${s} have the same settings (${a}).`:`${t.count} difference(s) between ${n} and ${s} (${a}).`)}var D_={name:"config:diff",summary:"how two environments' module settings differ (auth, storage, flags, notify, realtime, analytics, messaging, calls; machines, databases when named)",usage:"--from <env> --to <env> [--only <modules>]",details:["- a key only in --from, + only in --to, ~ in both with other values. Ids, times and versions are not compared; a secret is compared as set or not, never by its value.","Exit code 0 when they are the same, 1 when they differ. --json gives each difference with both values."],flags:Su,scope:"environment",async run(e){let{from:t,to:n}=await $u(e),s=await oo(e,Pu(e),t,n);return e.out.result(lo(s),()=>po(e,s)),s.count===0?0:1}},q_={name:"config:copy",summary:"make one environment's module settings equal to another's (secrets excepted: their names are said)",usage:"--from <env> --to <env> [--only <modules>]",details:["It shows the differences, asks before changing a production environment (-y confirms), changes the target, and compares again.","A secret is never copied: a provider's credentials and a sign-in client's secret are listed by name for you to set. A new hook or OAuth client gets its own secret, printed this once.","What the target holds that its users depend on is not taken by a copy: a bucket with files, a role users hold, a topic users follow are left and said.","--only machines,databases copies what they are declared as \u2014 a machine's source, size, copies, settings, secrets' name, database; a database's size, who may connect, backups \u2014 never a database's data (palbase db:copy) nor a secret's value. A machine or database only the target has is left serving.","Exit code 0 when the two are the same afterwards, 1 when a difference remains."],flags:Su,scope:"environment",async run(e){let{from:t,to:n}=await $u(e);return uo(e,Pu(e),t,n)}};async function uo(e,t,n,s,a={}){let r=await oo(e,t,n,s);if(r.count===0)return e.out.result({...a,copied:[],left:[],shown_once:[],after:lo(r)},()=>e.out.line(`Nothing to copy: ${n.env_slug} and ${s.env_slug} have the same settings.`)),0;e.out.json||po(e,r);let i=t.filter(u=>r.modules[u.name].length>0).map(u=>u.name);await v(e,s,`make its ${i.join(", ")} settings equal to ${n.env_slug}'s (${r.count} difference(s))`);let o=[],l=[],d=[];e.out.json||e.out.line();for(let u of t){let m=r.modules[u.name];if(m.length===0)continue;let b={done(w){o.push(`${u.name}: ${w}`),e.out.json||e.out.line(`copied ${u.name}: ${w}`)},left(w){l.push(`${u.name}: ${w}`),e.out.json||e.out.line(`left ${u.name}: ${w}`)},shown(w,_){d.push({what:`${u.name}: ${w}`,value:_}),e.out.json||e.out.line(` ${u.name}: ${w} ${_} (shown this once)`)}};await u.copy(e,s,m,b)}let p=await oo(e,t,n,s);return e.out.result({...a,copied:o,left:l,shown_once:d,after:lo(p)},()=>{e.out.line(),e.out.line("Compared again:"),po(e,p)}),p.count===0?0:1}var Au=[od,ld,pd,dd,cd,ud,hd,md,gd,yd,bd,wd,vd,_d,kd,Sd,bu,wu,vu,_u,Td,Ed,Cd,jd,Md,xd,Od,Dd,qd,Nd,Kd,Gd,Ud,zd,Bd,Fd,Jd,Wd,Vd,Yd,Xd,Zd,Qd,tu,nu,...uu,...yu,D_,q_];async function co(e){return(await e.studio.get("/orgs")).organizations}async function gt(e,t){let n=await co(e);if(t===void 0){if(n.length===1)return n[0];throw g(n.length===0?"you are in no organization yet: make one with palbase orgs:create <name>":"which organization? pass --org <name>",`yours: ${n.map(a=>a.name).join(", ")}`)}let s=n.filter(a=>a.id===t||a.name.localeCompare(t,void 0,{sensitivity:"accent"})===0);if(s.length===0)throw new y("no_such_org",`no organization ${JSON.stringify(t)} among yours`,{hint:"palbase orgs:list shows them"});if(s.length>1)throw new y("ambiguous_org",`${JSON.stringify(t)} names more than one of your organizations`,{hint:"pass its id"});return s[0]}var Ru={name:"orgs:list",summary:"your organizations and your role in each",scope:"account",async run(e){let t=await co(e);e.out.result({organizations:t},()=>{t.length===0&&e.out.line("You are in no organization yet: palbase orgs:create <name> makes one."),e.out.table(t,[{header:"name",value:n=>n.name},{header:"role",value:n=>n.role},{header:"id",value:n=>n.id}])})}},Tu={name:"orgs:create",summary:"make an organization; you are its owner",usage:"<name>",details:["With an account token in PALBASE_TOKEN, the token's maker is its owner and the token its admin: one organization more the token reaches."],args:{min:1,max:1},scope:"account",async run(e){let t=await e.studio.post("/orgs",{name:e.args[0]});e.out.result(t,()=>e.out.line(`Made the organization ${K(t.name)} (${t.id}).`))}},Eu={name:"orgs:members:list",summary:"an organization's members, and the invitations still open (for its admins)",flags:{org:{type:"string",value:"org",description:"the organization (name or id); needed when you are in more than one"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),n=await e.studio.get(`/orgs/${t.id}/members`);e.out.result(n,()=>{e.out.table(n.members,[{header:"email",value:s=>s.email??""},{header:"role",value:s=>s.role},{header:"user",value:s=>s.user_id}]),n.invitations.length>0&&(e.out.line(),e.out.line("Invited:"),e.out.table(n.invitations,[{header:"email",value:s=>s.email},{header:"role",value:s=>s.role},{header:"invitation",value:s=>s.id}]))})}},Cu={name:"orgs:members:invite",summary:"invite someone to an organization by email; they accept in Studio",usage:"<email> [--role admin|member]",args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"},role:{type:"string",value:"role",description:"admin or member (default member)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw g("--role is admin or member");let s=await e.studio.post(`/orgs/${t.id}/invitations`,{email:e.args[0],role:n});e.out.result(s,()=>e.out.line(`Invited ${K(s.email)} to ${K(t.name)} as ${s.role}.`))}},ju={name:"orgs:members:remove",summary:"take a member (by email or user id) or an open invitation out of an organization",usage:"<email|user-id>",args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),n=e.args[0],s=await e.studio.get(`/orgs/${t.id}/members`),a=s.members.find(i=>i.user_id===n||i.email!==null&&i.email.toLowerCase()===n.toLowerCase());if(a){await e.studio.request("DELETE",`/orgs/${D("the organization's id",t.id)}/members/${D("the member's id",a.user_id)}`),e.out.result({removed:a},()=>e.out.line(`${K(a.email??a.user_id)} is no longer in ${K(t.name)}.`));return}let r=s.invitations.find(i=>i.id===n||i.email.toLowerCase()===n.toLowerCase());if(!r)throw new y("no_such_member",`${JSON.stringify(n)} is neither a member of ${t.name} nor invited to it`);await e.studio.request("DELETE",`/orgs/${D("the organization's id",t.id)}/invitations/${D("the invitation's id",r.id)}`),e.out.result({withdrawn:r},()=>e.out.line(`The invitation of ${K(r.email)} is withdrawn.`))}},Ou={name:"tokens:list",summary:"an organization's access tokens (PALBASE_TOKEN for CI and agents): name, role, when they end and were last used \u2014 never their values",flags:{org:{type:"string",value:"org",description:"the organization (name or id)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),{tokens:n}=await e.studio.get(`/orgs/${t.id}/tokens`);e.out.result({tokens:n},()=>{n.length===0?e.out.line(`${K(t.name)} has no access token yet: palbase tokens:create <name> makes one.`):e.out.table(n,[{header:"name",value:s=>K(s.name)},{header:"role",value:s=>s.role},{header:"token",value:s=>`pbo_\u2026${s.hint}`},{header:"ends",value:s=>s.expires_at.slice(0,10)},{header:"last used",value:s=>s.last_used_at?.slice(0,16).replace("T"," ")??"never"},{header:"id",value:s=>s.id}])})}},Mu={name:"orgs:audit",summary:"who changed what at an organization's environments, through Studio or the CLI, newest first \u2014 its admins'",usage:"[--org <org>] [--limit <n>]",details:["A module keeps a change made through Studio as Studio's key's: this says whose it was. What was sent is not kept."],flags:{org:{type:"string",value:"org",description:"the organization (name or id)"},limit:{type:"string",value:"n",description:"how many at most (default 50)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),n=e.flags.limit===void 0?50:Number(e.flags.limit);if(!Number.isInteger(n)||n<1||n>1e4)throw g("--limit is a whole number from 1 to 10000");let s=[],a=null;do{let r=new URLSearchParams({limit:String(Math.min(100,n-s.length)),...a?{before:a}:{}}),i=await e.studio.get(`/orgs/${t.id}/audit?${r}`);s.push(...i.entries),a=i.next_before}while(a&&s.length<n);e.out.result({entries:s},()=>{s.length===0?e.out.line(`Nothing changed at ${K(t.name)}'s environments yet.`):e.out.table(s,[{header:"when",value:r=>r.at.slice(0,16).replace("T"," ")},{header:"who",value:r=>K(r.actor_name??r.actor)},{header:"environment",value:r=>K(r.environment_ref)},{header:"what",value:r=>K(`${r.method} ${r.path}`)},{header:"answer",value:r=>String(r.status)}])})}},xu={name:"tokens:create",summary:"make an access token of an organization for CI or an agent; its value is shown this once",usage:"<name> [--role member|admin] [--days <n>]",details:["Give it to the CI as the secret PALBASE_TOKEN: the CLI acts with it in place of a sign-in. It reaches its organization's projects and environments at its role, and nothing of its people or tokens.","It ends after --days (default 90, at most 365), and goes when it is revoked or when the one who made it leaves the organization."],args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"},role:{type:"string",value:"role",description:"member (default) or admin: what it may change"},days:{type:"string",value:"n",description:"how many days it is good for (default 90)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw g("--role is member or admin");let s=e.flags.days===void 0?90:Number(e.flags.days);if(!Number.isInteger(s)||s<1||s>365)throw g("--days is a whole number from 1 to 365");let a=await e.studio.post(`/orgs/${t.id}/tokens`,{name:e.args[0],role:n,expires_in_days:s});e.out.result(a,()=>{e.out.line(`Made the access token ${K(a.name)} of ${K(t.name)} (${a.role}, until ${a.expires_at.slice(0,10)}).`),e.out.line(`token (shown this once \u2014 keep it as the CI's secret PALBASE_TOKEN): ${a.token}`)})}},Iu={name:"tokens:revoke",summary:"revoke an organization's access token (by its name or id): refused from its next request on",usage:"<name|id>",args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),{tokens:n}=await e.studio.get(`/orgs/${t.id}/tokens`),s=n.filter(i=>i.id===e.args[0]||i.name===e.args[0]);if(s.length===0)throw new y("no_such_token",`${K(t.name)} has no access token ${JSON.stringify(e.args[0])}`,{hint:"palbase tokens:list shows them"});if(s.length>1)throw new y("ambiguous_token",`${JSON.stringify(e.args[0])} names more than one token`,{hint:"pass its id"});let a=`/orgs/${D("the organization's id",t.id)}/tokens/${D("the token's id",s[0].id)}`,{endpoints:r}=await e.studio.get(`${a}/webhooks`);await e.studio.request("DELETE",a),e.out.result({revoked:s[0].id,kept_webhooks:r},()=>{if(e.out.line(`Revoked the access token ${K(s[0].name)} of ${K(t.name)}.`),r.length>0){e.out.line("These webhook endpoints it made stay, and keep receiving events (palbase webhooks:delete <id> -E <env> removes one):");for(let i of r)e.out.line(` ${A(i.url)} \u2014 ${A(i.environment_ref)} (${A(i.id)})`)}})}},Lu={name:"projects:list",summary:"every project of your organizations, with its environments",scope:"account",async run(e){let t=await Re(e.studio),n=await e.state.targetFor(e.io.cwd),s=(await e.studio.get("/projects")).projects,a=new Map(t.map(r=>[r.organization_id,r.org_name]));for(let r of await co(e))a.set(r.id,r.name);e.out.result({projects:s.map(r=>({...r,organization_name:a.get(r.organization_id)??null}))},()=>{s.length===0&&e.out.line("No project yet: palbase projects:create <name> makes one.");let r=s.flatMap(i=>i.environments.length===0?[{org:a.get(i.organization_id)??"",project:i.name,env:"(none)",ref:"",here:""}]:i.environments.map(o=>({org:a.get(i.organization_id)??"",project:i.name,env:o.slug,ref:o.ref,here:n?.target.env_ref===o.ref?"*":""})));e.out.table(r,[{header:"",value:i=>i.here},{header:"organization",value:i=>i.org},{header:"project",value:i=>i.project},{header:"env",value:i=>i.env},{header:"ref",value:i=>i.ref}])})}},Du={name:"projects:create",summary:"make a project with its first environment (main), and print its keys",usage:"<name> [--org <org>] [--env-name <name>]",details:["The first environment is the project's production one: its slug is always main.","Its secret key is printed this once; keys:create makes more."],args:{min:1,max:1},flags:{org:{type:"string",value:"org",description:"the organization (name or id)"},"env-name":{type:"string",value:"name",description:"what the first environment is called on screen (default Production)"}},scope:"account",async run(e){let t=await gt(e,e.flags.org),{project:n}=await e.studio.post(`/orgs/${t.id}/projects`,{name:e.args[0]}),s=await e.studio.post(`/projects/${n.id}/environments`,{name:e.flags["env-name"]??"Production"});e.out.result({project:n,environment:s.environment,keys:s.keys},()=>{e.out.line(`Made ${K(t.name)} \u203A ${K(n.name)} with its environment ${s.environment.slug} (ref ${s.environment.ref}).`),s.keys&&(e.out.line(`publishable key: ${s.keys.publishable.key}`),e.out.line(`secret key (shown this once): ${s.keys.secret.key}`)),e.out.line(`palbase use ${n.name}/${s.environment.slug} chooses it for this directory.`)})}},qu={name:"projects:delete",summary:"delete a project and every environment of it",usage:"<project> [-y]",details:["Its environments' data goes with them (the platform keeps it a week to bring back)."],args:{min:1,max:1},scope:"account",async run(e){let t=_n(await Re(e.studio),e.args[0]),n=t[0];if(e.out.note(`${n.org_name} \u203A ${n.project_name}: delete the project and its environments ${t.map(s=>s.slug).join(", ")}`),!e.global.yes){if(!e.interactive)throw new y("confirmation_needed","deleting a project is confirmed",{hint:"confirm with -y"});if((await e.io.prompt("Type the project's name to delete it: ")).trim()!==n.project_name)throw new y("cancelled","nothing was deleted")}await e.studio.request("DELETE",`/projects/${n.project_id}`),e.out.result({deleted:{project_id:n.project_id,environments:t.map(s=>s.ref)}},()=>e.out.line(`Deleted ${K(n.project_name)}.`))}},Nu={name:"envs:list",summary:"a project's environments (the project chosen here, or -P)",scope:"environment",async run(e){let t=await Nt(e);e.out.result({environments:t},()=>e.out.table(t,[{header:"slug",value:n=>n.slug},{header:"name",value:n=>n.name},{header:"ref",value:n=>n.ref},{header:"your role",value:n=>n.role}]))}},Ku={name:"envs:create",summary:"add an environment to a project (staging, a developer's own)",usage:"<slug> [--name <name>] [--from <env> [--with-cloud]]",details:["Each environment is a project of its own on the platform: its users, data, machines and keys are its own.","--from opens it with another environment's module settings (palbase config:copy: secrets are named, not copied); --with-cloud its machines and databases too \u2014 declared alike, built from the same branches, with no data (palbase db:copy brings it)."],args:{min:1,max:1},flags:{name:{type:"string",value:"name",description:"what it is called on screen (default: the slug)"},from:{type:"string",value:"env",description:"open it with this environment's settings (slug or ref)"},"with-cloud":{type:"boolean",description:"with --from: its machines and databases too (the new environment's GitHub link builds the machines)"}},scope:"environment",async run(e){let t=await N_(e),n=e.args[0],s=e.flags.from;if(e.flags["with-cloud"]===!0&&s===void 0)throw g("--with-cloud goes with --from <env>");let a=s===void 0?[]:(await Re(e.studio)).filter(d=>d.project_id===t.project_id),r=s===void 0?void 0:a.find(d=>d.slug===s||d.ref===s);if(s!==void 0&&!r)throw new y("no_such_environment",`the project has no environment ${JSON.stringify(s)}`,{hint:`its environments: ${a.map(d=>d.slug).join(", ")}`});let i=await e.studio.post(`/projects/${t.project_id}/environments`,{name:e.flags.name??n,slug:n}),o=()=>{e.out.line(`Made ${K(t.project_name)} \u203A ${i.environment.slug} (ref ${i.environment.ref}).`),i.keys&&(e.out.line(`publishable key: ${i.keys.publishable.key}`),e.out.line(`secret key (shown this once): ${i.keys.secret.key}`))};if(!r){e.out.result(i,o);return}e.out.json||o();let l=_e({...r,ref:i.environment.ref,slug:i.environment.slug,name:i.environment.name});return e.out.json||e.out.line(),uo(e,e.flags["with-cloud"]===!0?[...rs,...lr]:rs,_e(r),l,{made:i})}},Gu={name:"envs:delete",summary:"delete an environment of a project, with its data",usage:"<slug> [--delete-bound | --move-to <env>]",details:["A project's machines, databases and sites are the project's, each bound to one environment. What is bound to the environment deleted is deleted with it (--delete-bound), or its machines are moved to another environment of the project first (--move-to <slug>); with neither and something bound to it, a person at the terminal is asked, and anything else is refused with what is bound.","A database keeps its volume, and a site its files, where they were made: they do not move yet \u2014 an environment that keeps one is deleted with them, or kept."],args:{min:1,max:1},flags:{"delete-bound":{type:"boolean",description:"delete the machines, databases and sites bound to it with it"},"move-to":{type:"string",value:"env",description:"move its machines to this environment of the project (its slug) before it is deleted"}},scope:"environment",async run(e){let t=await Nt(e),n=t.find(l=>l.slug===e.args[0]||l.ref===e.args[0]);if(!n)throw new y("no_such_environment",`the project has no environment ${JSON.stringify(e.args[0])}`);let s=_e(n);if(e.out.note(`${q(s)}: delete the environment, its users, data, machines and databases`),!e.global.yes){if(!e.interactive)throw new y("confirmation_needed","deleting an environment is confirmed",{hint:"confirm with -y"});if((await e.io.prompt("Type the environment's slug to delete it: ")).trim()!==n.slug)throw new y("cancelled","nothing was deleted")}let a=e.flags["delete-bound"]===!0,r=typeof e.flags["move-to"]=="string"?e.flags["move-to"]:void 0;if(a&&r!==void 0)throw g("--delete-bound or --move-to: what is bound to it is deleted with it, or its machines are moved");let i=a?"?delete_bound=true":r!==void 0?`?move_to=${encodeURIComponent(r)}`:"";try{await e.studio.request("DELETE",`/environments/${n.ref}${i}`)}catch(l){if(!(l instanceof j)||l.code!=="environment_has_resources"||i!=="")throw l;let d=l.body?.data??{},p=[d.machines?.length?`machines ${d.machines.join(", ")}`:"",d.databases?.length?`databases ${d.databases.join(", ")}`:"",d.sites?.length?`sites ${d.sites.join(", ")}`:""].filter(b=>b!=="").join("; "),u=t.filter(b=>b.ref!==n.ref).map(b=>b.slug);if(!e.interactive||e.global.yes)throw new y("environment_has_resources",`bound to ${n.slug}: ${p}`,{hint:`delete them with it (--delete-bound), or move its machines first (--move-to ${u[0]??"<env>"})`});e.out.line(`Bound to ${n.slug}: ${p}.`);let m=(await e.io.prompt(`Delete them with it (delete), move its machines to another environment (${u.join(", ")}), or keep it (keep)? `)).trim();if(m==="delete")i="?delete_bound=true";else if(u.includes(m))i=`?move_to=${encodeURIComponent(m)}`;else throw new y("cancelled","nothing was deleted");await e.studio.request("DELETE",`/environments/${n.ref}${i}`)}let o=await e.state.targetFor(e.io.cwd);o?.target.env_ref===n.ref&&await e.state.clearTarget(o.dir),e.out.result({deleted:n.ref},()=>e.out.line(`Deleted ${q(s)}.`))}},Uu={name:"use",summary:"choose the environment this directory acts on (kept on this computer)",usage:"[<project>[/<env>] | <org>/<project>/<env>] [--clear]",details:["Commands run in this directory, or a directory under it, then act on that environment unless -P/-E say otherwise.","Nothing is written into the project: two checkouts of it can each act on their own environment.","With no argument and a person at the terminal, it lists your environments to pick from."],args:{min:0,max:1},flags:{clear:{type:"boolean",description:"forget the choice made for this directory"}},scope:"account",async run(e){if(e.flags.clear===!0){let n=await e.state.clearTarget(e.io.cwd);e.out.result({cleared:n},()=>e.out.line(n?"This directory acts on no environment now.":"No environment was chosen for this directory."));return}let t;if(e.args.length===0)t=await f(e);else{let n=await Re(e.studio);t=_e(K_(n,e.args[0]))}await e.state.setTarget(e.io.cwd,t),e.out.result({target:t,dir:e.io.cwd},()=>e.out.line(`This directory acts on ${q(t)}.`))}},zu={name:"status",summary:"the environment this directory acts on: who you are there, its machines and databases",scope:"environment",async run(e){let t=await f(e),n=await e.studio.get(`/environments/${t.env_ref}`),s=d=>ye(e.studio,t.env_ref,"GET",d).then(p=>p.body,p=>p instanceof j?null:Promise.reject(p)),[a,r]=await Promise.all([s("/machines?limit=100"),s("/databases?limit=100")]),i=a?.machines??[],o=r?.databases??[],l=await e.state.targetFor(e.io.cwd);e.out.result({target:t,role:n.role,address:`https://${t.env_ref}.${e.cloud.domain}`,machines:i,databases:o,chosen_for:l?.dir??null},()=>{e.out.line(q(t)),e.out.line(` ref ${t.env_ref} \xB7 your role ${n.role} \xB7 https://${t.env_ref}.${e.cloud.domain}`),l&&l.target.env_ref===t.env_ref&&e.out.line(` chosen for ${l.dir}`),e.out.line(` machines: ${i.length===0?"none":i.map(d=>`${d.name} (${d.size}, ${d.state})`).join(", ")}`),e.out.line(` databases: ${o.length===0?"none":o.map(d=>`${d.name} (${d.size}, ${d.state})`).join(", ")}`)})}},Bu={name:"open",summary:"open the environment in Studio (its overview, or a section: auth, storage, flags, \u2026)",usage:"[section]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=e.args[0]?`/${e.args[0].replace(/^\/+/,"")}`:"",s=`${e.cloud.studioWeb}/projects/${t.project_id}/environments/${t.env_ref}${n}`,a=e.interactive&&await e.io.openBrowser(s);e.out.result({url:s,opened:a},()=>e.out.line(a?`Opened ${s}`:s))}},Fu={name:"keys:list",summary:"the environment's API keys (never their values)",scope:"environment",async run(e){let t=await f(e),{keys:n}=await e.studio.get(`/environments/${t.env_ref}/keys`);e.out.result({keys:n},()=>e.out.table(n,[{header:"id",value:s=>s.id},{header:"kind",value:s=>s.kind},{header:"label",value:s=>s.label},{header:"ends",value:s=>s.hint?`\u2026${s.hint}`:""},{header:"state",value:s=>s.revoked_at?`revoked ${s.revoked_at}`:s.expires_at?`until ${s.expires_at}`:"active"},{header:"created",value:s=>s.created_at}]))}},Ju={name:"keys:create",summary:"make an API key of the environment; its value is shown this once",usage:"--kind publishable|secret [--label <label>]",flags:{kind:{type:"string",value:"kind",description:"publishable (ships in apps) or secret (servers only)"},label:{type:"string",value:"label",description:"what it is for, as Studio lists it"}},scope:"environment",async run(e){let t=e.flags.kind;if(t!=="publishable"&&t!=="secret")throw g("--kind is publishable or secret");let n=await f(e);await v(e,n,`make a ${t} key`);let s=await e.studio.post(`/environments/${n.env_ref}/keys`,{kind:t,label:e.flags.label??""});e.out.result(s,()=>{e.out.line(`${s.kind} key ${s.id}${s.kind==="secret"?" (shown this once)":""}:`),e.out.line(s.key)})}},Wu={name:"keys:revoke",summary:"revoke an API key of the environment; what holds it is refused from then on",usage:"<key-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=`/environments/${D("the environment's ref",t.env_ref)}/keys/${D("the key's id",e.args[0])}`;await v(e,t,`revoke the key ${e.args[0]}`),await e.studio.request("DELETE",n),e.out.result({revoked:e.args[0]},()=>e.out.line(`Revoked ${e.args[0]}.`))}};async function N_(e){return(await Nt(e))[0]}async function Nt(e){if(vn(e.io))return[await Oi(e)];let t=await Re(e.studio);if(e.global.project!==void 0)return _n(t,e.global.project);let n=await e.state.targetFor(e.io.cwd);if(!n)throw new y("no_target","no project is chosen for this directory",{hint:"pass -P <project>, or choose one here with palbase use"});let s=t.filter(a=>a.project_id===n.target.project_id);if(s.length===0)throw new y("no_such_project",`the project chosen here (${n.target.project_name}) is not among yours any more`,{hint:"palbase use another"});return s}function K_(e,t){let n=t.split("/");if(n.length>3||n.some(r=>r===""))throw g(`${JSON.stringify(t)} is not project, project/env or org/project/env`);let s=n.length===3?[{project:`${n[0]}/${n[1]}`,env:n[2]}]:n.length===2?[{project:n[0],env:n[1]},{project:t}]:[{project:t}],a;for(let r of s){let i;try{i=_n(e,r.project)}catch(o){a=o;continue}if(r.env!==void 0){let o=i.find(l=>l.slug===r.env||l.ref===r.env);if(o)return o;a=new y("no_such_environment",`${i[0].project_name} has no environment ${JSON.stringify(r.env)}`,{hint:`its environments: ${i.map(l=>l.slug).join(", ")}`});continue}if(i.length===1)return i[0];throw new y("which_environment",`${i[0].project_name} has more than one environment`,{hint:`name one: ${i.map(o=>`${o.project_name}/${o.slug}`).join(", ")}`})}throw a}import{createReadStream as G_,openAsBlob as U_}from"node:fs";import{lstat as z_,readdir as B_,realpath as Vu,stat as F_}from"node:fs/promises";import{createHash as J_}from"node:crypto";import{join as W_,relative as Hu,resolve as V_,sep as Yu}from"node:path";var ho=2e4,H_=25<<20,Y_=1<<30,X_=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/,Z_=6,ea={previews:{type:"boolean",description:"build each pull request against its branch into a preview of its own, in this environment with its settings \u2014 production's too"},"no-previews":{type:"boolean",description:"preview no pull request from now on"},"preview-forks":{type:"boolean",description:"preview a fork's pull requests without asking (fork protection off): anyone's code runs with this environment's settings and secrets \u2014 a person's to do, signed in with palbase login"},"no-preview-forks":{type:"boolean",description:"a fork's pull request waits for an admin to authorize each push (fork protection, the default): previews:authorize"}};function na(e,t){e.flags.previews===!0&&(t.previews=!0),e.flags["no-previews"]===!0&&(t.previews=!1),e.flags["preview-forks"]===!0&&(t.preview_forks=!0),e.flags["no-preview-forks"]===!0&&(t.preview_forks=!1)}function pr(e,t){if(e.out.line(`${t.host} ${t.state}${t.redirect_to?` \u2192 redirects to ${t.redirect_to} (${t.redirect_status??308})`:""}`),t.state!=="active"){e.out.line(` Add to ${t.host}'s DNS:`);for(let n of t.records){let s=n.type==="CNAME"&&t.apex?"ALIAS (or ANAME, or a flattened CNAME: the apex takes no CNAME)":n.type;e.out.line(` ${s} ${n.name} ${n.value}`)}for(let n of t.problems)e.out.line(` - ${n}`)}}function mo(e,t,n,s){let a={name:`${t}:domains`,summary:`a ${e}'s own domains: whether each answers, and what its DNS still needs`,usage:`[--${e} <name>]`,flags:s,scope:"environment",async run(l){let d=await f(l),{domains:p}=await h(l,d,"GET",`${await n(l,d)}/domains`);l.out.result({domains:p},()=>{p.length===0&&l.out.line(`No domain yet: palbase ${t}:domains:add <host> adds one.`);for(let u of p)pr(l,u)})}},r={name:`${t}:domains:add`,summary:`have a ${e} answer at a domain of your own too (www.example.com, or example.com \u2014 with its www)`,usage:`<host> [--${e} <name>] [--primary www|apex | --only] [--redirect-status 301|302|307|308]`,details:["It answers once its DNS points at the platform and says it is this environment's (the TXT record): both are printed.","At an apex (example.com) its www is added too, and one redirects to the other, as Vercel does: the apex to www.example.com unless --primary apex; --only adds the domain alone.","An apex takes an A record at the platform's address, which any DNS host has; a subdomain a CNAME. A domain is one environment's until it is removed there."],args:{min:1,max:1},flags:{...s,primary:{type:"string",value:"www|apex",description:"at an apex: the address visitors end up at, the other redirecting to it (default: www)"},only:{type:"boolean",description:"add the domain alone: no www, no redirect"},"redirect-status":{type:"string",value:"code",description:"the redirect's status: 301, 302, 307 or 308 (default: 308)"}},scope:"environment",async run(l){let d=l.args[0].trim().toLowerCase().replace(/\.$/,""),p=l.flags.primary??"www";if(p!=="www"&&p!=="apex")throw g("--primary is www or apex");if(l.flags.only===!0&&l.flags.primary!==void 0)throw g("--only adds the domain alone: no --primary");let u=Xu(l.flags["redirect-status"]),m=await f(l),b=await n(l,m),w=`www.${d}`,_=l.flags.only!==!0&&!d.startsWith("www.");await v(l,m,_?`add the domain ${d} \u2014 at an apex, with ${w}, ${p==="www"?`${d} redirecting to ${w}`:`${w} redirecting to ${d}`}`:`add the domain ${d}`);let T=await h(l,m,"POST",`${b}/domains`,{host:d});if(!_||!T.apex){l.out.result(T,()=>pr(l,T));return}let S=P=>({redirect_to:P,...u!==void 0?{redirect_status:u}:{}}),$;p==="www"?($=await Q_(l,m,b,{host:w}),T=await h(l,m,"PATCH",`${b}/domains/${D("the domain",d)}`,S(w))):$=await e0(l,m,b,w,S(d));let R=p==="www"?[$,T]:[T,$];l.out.result({domains:R},()=>R.forEach(P=>pr(l,P)))}},i={name:`${t}:domains:redirect`,summary:`send a domain's visitors to another domain of the ${e}'s \u2014 the same path and query there \u2014 or, with --none, have it answer itself`,usage:`<host> (--to <host> [--status 301|302|307|308] | --none) [--${e} <name>]`,details:["It holds at once. A domain redirects to one that answers itself, and one others redirect to answers itself."],args:{min:1,max:1},flags:{...s,to:{type:"string",value:"host",description:`another domain of the ${e}'s`},status:{type:"string",value:"code",description:"301, 302, 307 or 308 (default: 308)"},none:{type:"boolean",description:"redirect nowhere: the domain answers itself"}},scope:"environment",async run(l){let d=l.args[0].trim().toLowerCase().replace(/\.$/,""),p=l.flags.to?.trim().toLowerCase().replace(/\.$/,"");if(p===void 0==(l.flags.none!==!0))throw g("name where it redirects (--to <host>), or --none");let u=Xu(l.flags.status);if(l.flags.none===!0&&u!==void 0)throw g("--status goes with --to");let m=await f(l),b=await n(l,m);await v(l,m,p?`redirect ${d} to ${p}`:`have ${d} answer itself`);let w=p?{redirect_to:p,...u!==void 0?{redirect_status:u}:{}}:{redirect_to:null},_=await h(l,m,"PATCH",`${b}/domains/${D("the domain",d)}`,w);l.out.result(_,()=>pr(l,_))}},o={name:`${t}:domains:remove`,summary:`stop a ${e} answering at a domain: at once, and another environment may add it`,usage:`<host> [--${e} <name>]`,args:{min:1,max:1},flags:s,scope:"environment",async run(l){let d=await f(l),p=await n(l,d);await v(l,d,`remove the domain ${l.args[0]}`),await h(l,d,"DELETE",`${p}/domains/${D("the domain",l.args[0].toLowerCase())}`),l.out.result({removed:l.args[0]},()=>l.out.line(`${l.args[0]} answers no more.`))}};return[a,r,i,o]}function Xu(e){if(e===void 0)return;let t=Number(e);if(![301,302,307,308].includes(t))throw g("a redirect's status is 301, 302, 307 or 308");return t}async function Q_(e,t,n,s){try{return await h(e,t,"POST",`${n}/domains`,s)}catch(a){if(!(a instanceof j&&a.code==="domain_exists"))throw a;let{domains:r}=await h(e,t,"GET",`${n}/domains`),i=r.find(o=>o.host===s.host);if(!i)throw a;return i}}async function e0(e,t,n,s,a){try{return await h(e,t,"POST",`${n}/domains`,{host:s,...a})}catch(r){if(!(r instanceof j&&r.code==="domain_exists"))throw r;return await h(e,t,"PATCH",`${n}/domains/${D("the domain",s)}`,a)}}function go(e,t,n,s){return{name:`${t}:previews:authorize`,summary:`build a fork's pull request's preview of a ${e}: its code runs with this environment's settings and secrets`,usage:`<pull request> [--${e} <name>]`,details:["A pull request from a fork waits for an admin of the environment (fork protection): look at what it changes first. The head shown is the one built; a push since asks again.","A person authorizes it, signed in with palbase login: an environment's token (PALBASE_TOKEN) cannot."],args:{min:1,max:1},flags:s,scope:"environment",async run(a){let r=Number(a.args[0].replace(/^#/,""));if(!Number.isInteger(r)||r<=0)throw g("the pull request is its number: 12, or #12");let i=await f(a),o=await n(a,i),{previews:l}=await h(a,i,"GET",`${o}/previews`),d=l.find(u=>u.pull_request===r&&u.state!=="closed");if(!d)throw new y("preview_not_found",`no open preview of pull request #${r}`,{hint:`palbase ${t}:previews lists them`});if(d.state!=="authorization_required")throw new y("preview_not_waiting",`#${r}'s preview waits for no authorization: it is ${d.state}`);await v(a,i,`build pull request #${r} at ${d.commit.slice(0,7)}, from a fork`,`Pull request #${r} is from a fork: its code at ${d.commit.slice(0,7)} runs with this environment's settings and secrets`);let p=await h(a,i,"POST",`${o}/previews/${r}/authorize`,{commit:d.commit});a.out.result(p,()=>a.out.line(`#${r} authorized at ${d.commit.slice(0,7)}: its preview is being built (palbase ${t}:previews).`))}}}function fo(e,t,n){t.length===0&&e.out.line(n);for(let s of t){let a=s.state==="authorization_required"?"waits for authorization (previews:authorize)":s.state==="idle"?"idle: no push for 3 days (previews:open opens it again)":s.state==="refused"?`refused: ${s.reason??""}`:s.state;e.out.line(`#${s.pull_request} ${a} ${s.commit.slice(0,7)}${s.fork?" fork":""} ${s.url}${s.machine?` (${s.machine})`:""}`)}}function Ce(e){if(!X_.test(e))throw g(`${JSON.stringify(e)} is not a site's name: lowercase letters, digits and dashes, starting with a letter`);return D("the site",e)}var Qu={repo:{type:"string",value:"owner/name",description:"build it from this GitHub repository on every push (default with --branch: this checkout's origin)"},branch:{type:"string",value:"branch",description:"the branch whose pushes are built"},path:{type:"string",value:"dir",description:"the site's directory in the repository (default: this directory's place in it)"},"install-command":{type:"string",value:"command",description:"what installs its packages (default: from its lockfile \u2014 pnpm, yarn, npm, bun)"},"build-command":{type:"string",value:"command",description:"what builds it (default: its package.json's build script)"},output:{type:"string",value:"dir",description:"the folder the build writes (default: what its builder writes \u2014 dist, build, out, \u2026)"},"build-env":{type:"string",multiple:!0,value:"K=V",description:"a setting the build runs with (repeat it): what its pages are sent (VITE_*), never a secret"}};async function ec(e,t){let n={};if(e.flags.repo!==void 0||e.flags.branch!==void 0||t){let r=await Us(e.io,e.io.cwd),i=e.flags.repo??r?.repository,o=e.flags.branch??r?.branch;if(!i)throw g("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!o)throw g("which branch? none is checked out here","pass --branch <branch>");n.source={repository:i,branch:o,path:e.flags.path??(e.flags.repo===void 0?r?.path??"":"")}}let s={};e.flags["install-command"]!==void 0&&(s.install_command=e.flags["install-command"]),e.flags["build-command"]!==void 0&&(s.command=e.flags["build-command"]),e.flags.output!==void 0&&(s.output_dir=e.flags.output);let a=e.flags["build-env"];if(a){let r={};for(let i of a){let o=i.indexOf("=");if(o<=0)throw g(`a setting is K=V, not ${JSON.stringify(i)}`);r[i.slice(0,o)]=i.slice(o+1)}s.env=r}return Object.keys(s).length>0&&(n.build=s),n}function ta(e){return e<1024?`${e} B`:e<1<<20?`${(e/1024).toFixed(1)} KiB`:`${(e/(1<<20)).toFixed(1)} MiB`}async function t0(e){let t=await Vu(e),n=[],s=async r=>{let i=await B_(r,{withFileTypes:!0});for(let o of i){if(o.name==="node_modules"||o.name.startsWith(".")&&!(o.name===".well-known"&&r===t))continue;let l=W_(r,o.name),d=await z_(l),p=l;if(d.isSymbolicLink()&&(p=await Vu(l),p!==t&&!p.startsWith(t+Yu)))throw new y("unsafe_path",`${Hu(t,l)} links outside ${e}`);let u=d.isSymbolicLink()?await F_(p):d;if(u.isDirectory()){await s(l);continue}if(!u.isFile())continue;let m="/"+Hu(t,l).split(Yu).join("/");if(/[\u0000-\u001f\u007f?#\\]/.test(m))throw new y("invalid_path",`${m} has a character a site's path cannot carry (?, #, \\ or a control character): rename it`);if(m.length>1024)throw new y("invalid_path",`${m.slice(0,80)}\u2026 is longer than a site's path may be (1024 bytes)`);if(u.size>H_)throw new y("file_too_large",`${m} is ${ta(u.size)}: a site's file is 25 MiB at most (keep large media in storage)`);if(n.push({path:m,file:p,size:u.size,digest:""}),n.length>ho)throw new y("too_many_files",`${e} holds more than ${ho} files: a site holds ${ho} at most`)}};await s(t),n.sort((r,i)=>r.path<i.path?-1:r.path>i.path?1:0);let a=n.reduce((r,i)=>r+i.size,0);if(a>Y_)throw new y("release_too_large",`${e} holds ${ta(a)}: a release is 1 GiB at most`);for(let r of n)r.digest=await n0(r.file);return n}function n0(e){return new Promise((t,n)=>{let s=J_("sha256");G_(e).on("data",a=>s.update(a)).on("error",n).on("end",()=>t(s.digest("hex")))})}function s0(e){let t=e.filter(n=>/\.html?$/i.test(n.path));return t.length===1&&t[0].path==="/index.html"}async function a0(e,t,n){try{return await h(e,t,"GET",`/sites/${Ce(n)}`)}catch(s){if(s instanceof j&&s.code==="site_not_found")return null;throw s}}async function Zu(e,t,n,s,a,r){let i=0,o=0,l=async()=>{for(;o<a.length;){let d=a[o++],p=r.get(d);if(!p)throw new y("internal",`the release asked for ${d}, which no file here is`);let u=await U_(p.file);await h(e,t,"PUT",`/sites/${Ce(n)}/releases/${D("the release",s)}/files/${d}`,new wn(u,"application/octet-stream")),i+=p.size}};return await Promise.all(Array.from({length:Math.min(Z_,a.length)},l)),i}var r0={name:"hosting:deploy",summary:"deploy a folder as a static site: only the files that changed are sent, and the site serves them at once",usage:"<folder> [--site <name>] [--spa]",details:["The folder is what your build wrote (dist, build, out, public): every file in it is served, at its path from the folder's root.","The site is opened on its first deploy; --spa then answers a path no file answers with /index.html (a single-page app).","A folder of one page, index.html, is taken for a single-page app when the site is opened."],args:{min:1,max:1},flags:{site:{type:"string",value:"name",description:"the site (default: web, which answers at the environment's ref)"},spa:{type:"boolean",description:"when the site is opened: answer every path no file answers with /index.html"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.site??"web";Ce(n);let s=V_(e.io.cwd,e.args[0]),a=await t0(s).catch(w=>{throw w instanceof y?w:new y("no_folder",`${e.args[0]}: ${w instanceof Error?w.message:String(w)}`)});if(a.length===0)throw new y("empty_folder",`${e.args[0]} holds no file to serve`);a.some(w=>w.path==="/index.html")||e.out.note(` ${e.args[0]} has no index.html: the site's root answers 404.`);let r=a.reduce((w,_)=>w+_.size,0);await v(e,t,`deploy ${a.length} files (${ta(r)}) to the site ${n}`);let i=await a0(e,t,n);if(!i){let w=e.flags.spa===!0||s0(a);i=await h(e,t,"POST","/sites",{name:n,spa:w}),e.out.note(` opened the site ${n}${w?" (a single-page app: every route is its index.html)":""}`)}let o={},l=new Map;for(let w of a)o[w.path]=w.digest,l.set(w.digest,w);let d=await h(e,t,"POST",`/sites/${Ce(n)}/releases`,{files:o}),p=d.missing??[];e.out.note(` release #${d.number}: ${a.length} files, ${p.length} to send${p.length<l.size?` (${l.size-p.length} kept from before)`:""}`);let u=await Zu(e,t,n,d.id,p,l),m;for(let w=0;w<3&&!m;w++)try{m=await h(e,t,"POST",`/sites/${Ce(n)}/releases/${D("the release",d.id)}/finish`)}catch(_){let T=_ instanceof j&&_.code==="files_missing"?_.body?.missing??[]:[];if(T.length===0)throw _;u+=await Zu(e,t,n,d.id,T,l)}if(!m)throw new y("release_unfinished",`the release #${d.number} could not be finished`,{hint:"deploy again"});i=await h(e,t,"GET",`/sites/${Ce(n)}`);let b={site:i.name,url:i.url,urls:i.urls,release:m,sent_bytes:u};e.out.result(b,()=>{e.out.line(`Deployed release #${m.number} of ${i.name} (${a.length} files, ${ta(u)} sent).`);for(let w of i.urls)e.out.line(` ${w}`)})}},i0={name:"hosting:sites:list",summary:"the project's static sites, each with the environment it is bound to: where each answers and the release it serves",scope:"environment",async run(e){let t=await f(e),[{sites:n},s]=await Promise.all([h(e,t,"GET","/sites"),zs(e.studio,t)]);e.out.result({sites:n},()=>{n.length===0&&e.out.line("No site yet: palbase hosting:deploy <folder> opens one.");for(let a of n){let r=a.taken_down?`taken down: ${a.taken_down.reason}`:a.release?`release #${a.release.number}`:"nothing deployed";e.out.line(`${a.name} ${Yn(s,a.environment)} ${a.url} ${r}${a.spa?" (single-page app)":""}`)}})}},o0={name:"hosting:sites:create",summary:"open a static site \u2014 built from GitHub on every push with --repo/--branch, or deployed from a folder (hosting:deploy opens one too)",usage:"[name] [--spa] [--repo <owner/name> --branch <branch> --path <dir>] [--build-command \u2026] [--output <dir>] [--build-env K=V]\u2026 [--previews [--preview-forks]]",details:["With --branch (and --repo, or in a checkout of a GitHub repository), its branch's head is built at once and on every push: the folder its build writes is served.","With --previews, each pull request against the branch is built too and answers at <name>-pr<n>-<ref> until it closes; the pull request is told where.","The environment needs its GitHub link first: palbase github:connect."],args:{min:0,max:1},flags:{spa:{type:"boolean",description:"a single-page app: every path no file answers is its /index.html"},...Qu,previews:ea.previews,"preview-forks":ea["preview-forks"]},scope:"environment",async run(e){let t=await f(e),n=e.args[0]??"web";Ce(n);let{source:s,build:a}=await ec(e,!1);await v(e,t,`open the site ${n}${s?`, built from ${s.repository}@${s.branch}`:""}`);let r={};na(e,r);let i=await h(e,t,"POST","/sites",{name:n,spa:e.flags.spa===!0,...s?{source:s}:{},...a?{build:a}:{},...r});e.out.result(i,()=>e.out.line(i.source?`Opened ${i.name}: ${i.url} \u2014 its first build is on its way (palbase hosting:builds --site ${i.name}).`:`Opened ${i.name}: ${i.url} (nothing deployed yet: palbase hosting:deploy <folder> --site ${i.name}).`))}},l0={name:"hosting:sites:update",summary:"change a site: whether it is a single-page app, where it is built from, what its build runs",usage:"<name> [--spa | --no-spa] [--repo \u2026 --branch \u2026 --path \u2026] [--no-source] [--build-command \u2026] [--output \u2026] [--build-env K=V]\u2026 [--previews | --no-previews] [--preview-forks | --no-preview-forks]",args:{min:1,max:1},flags:{spa:{type:"boolean",description:"a single-page app: every path no file answers is its /index.html"},"no-spa":{type:"boolean",description:"not a single-page app: a path no file answers is 404"},...Qu,"no-source":{type:"boolean",description:"build it from no repository any more: deploy folders alone"},...ea},scope:"environment",async run(e){let t=await f(e),n=e.args[0],s={};e.flags.spa===!0&&(s.spa=!0),e.flags["no-spa"]===!0&&(s.spa=!1);let{source:a,build:r}=await ec(e,!1);if(a&&(s.source=a),e.flags["no-source"]===!0&&(s.source={repository:""}),r&&(s.build=r),na(e,s),Object.keys(s).length===0)throw g("nothing to change: give a flag","palbase help hosting:sites:update");await v(e,t,`change the site ${n}`);let i=await h(e,t,"PATCH",`/sites/${Ce(n)}`,s);e.out.result(i,()=>e.out.line(`${i.name}: ${i.url}${i.spa?" (single-page app)":""}${i.source?` \u2014 built from ${i.source.repository}@${i.source.branch}`:""}`))}},p0={name:"hosting:sites:delete",summary:"delete a site: its addresses serve nothing from now on",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=e.args[0];await v(e,t,`delete the site ${n} \u2014 its addresses serve nothing from now on`),await h(e,t,"DELETE",`/sites/${Ce(n)}`),e.out.result({deleted:n},()=>e.out.line(`Deleted ${n}.`))}},d0={name:"hosting:releases",summary:"a site's releases, newest first: the ten newest are kept to return to",usage:"[--site <name>]",flags:{site:{type:"string",value:"name",description:"the site (default: web)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.site??"web",{releases:s}=await h(e,t,"GET",`/sites/${Ce(n)}/releases`);e.out.result({releases:s},()=>{for(let a of s)e.out.line(`#${a.number} ${a.id} ${a.state}${a.serving?" serving":""} ${a.files} files ${ta(a.bytes)} ${a.created_at}${a.commit?` ${a.commit.slice(0,7)}`:""}`)})}},u0={name:"hosting:rollback",summary:"serve an earlier release of a site again, at once (the one before the serving one, or a named one)",usage:"[--site <name>] [--to <release id | #number>]",flags:{site:{type:"string",value:"name",description:"the site (default: web)"},to:{type:"string",value:"release",description:"the release: its id, or its number (#3)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.site??"web",s=e.flags.to;if(s!==void 0&&/^#?\d+$/.test(s)){let r=Number(s.replace("#","")),{releases:i}=await h(e,t,"GET",`/sites/${Ce(n)}/releases`),o=i.find(l=>l.number===r);if(!o)throw new y("release_not_found",`${n} keeps no release #${r}`,{hint:`palbase hosting:releases --site ${n}`});s=o.id}await v(e,t,`serve ${s?`the release ${e.flags.to}`:"the release before the serving one"} of ${n}`);let a=await h(e,t,"POST",`/sites/${Ce(n)}/rollback`,s?{release:s}:{});e.out.result(a,()=>e.out.line(`${a.name} serves release #${a.release?.number}: ${a.url}`))}},c0={name:"hosting:builds",summary:"a site's newest builds (a site built from GitHub), or one with its log",usage:"[build] [--site <name>] [--wait]",args:{min:0,max:1},flags:{site:{type:"string",value:"name",description:"the site (default: web)"},wait:{type:"boolean",description:"with a build: follow it until it ends"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.site??"web",s=e.args[0];if(s===void 0){let{builds:r}=await h(e,t,"GET",`/sites/${Ce(n)}/builds`);e.out.result({builds:r},()=>{r.length===0&&e.out.line(`${n} has no build: it is built from GitHub with hosting:sites:create --repo \u2026 --branch \u2026.`);for(let i of r)e.out.line(`${i.id} ${i.commit.slice(0,7)} ${i.state}${i.reason?`: ${i.reason}`:""} ${i.message}`)});return}let a=await h(e,t,"GET",`/sites/${Ce(n)}/builds/${D("the build",s)}`);for(let r=0;e.flags.wait===!0&&(a.state==="queued"||a.state==="building")&&r<900;r++)await e.io.sleep(2e3),a=await h(e,t,"GET",`/sites/${Ce(n)}/builds/${D("the build",s)}`);if(e.out.result(a,()=>{e.out.line(`${a.id} ${a.commit.slice(0,7)} ${a.state}${a.reason?`: ${a.reason}`:""}`),a.log&&e.out.line(a.log)}),a.state==="failed")return 1}},h0={name:"hosting:build",summary:"build a site's branch head now and serve it, as a push does",usage:"[--site <name>]",flags:{site:{type:"string",value:"name",description:"the site (default: web)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.site??"web";await v(e,t,`build ${n} from the head of its branch`);let s=await h(e,t,"POST",`/sites/${Ce(n)}/builds`);e.out.result(s,()=>e.out.line(`${s.name}: a build of ${s.source?.branch??"its branch"}'s head is on its way (palbase hosting:builds --site ${s.name}).`))}},m0={name:"hosting:previews",summary:"a site's pull request previews, newest first: where each answers, and whether it is built",usage:"[--site <name>]",flags:{site:{type:"string",value:"name",description:"the site (default: web)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.site??"web",{previews:s}=await h(e,t,"GET",`/sites/${Ce(n)}/previews`);e.out.result({previews:s},()=>fo(e,s,`${n} has no preview: a site built from GitHub previews its pull requests with hosting:sites:update ${n} --previews.`))}},g0=mo("site","hosting",async e=>`/sites/${Ce(e.flags.site??"web")}`,{site:{type:"string",value:"name",description:"the site (default: web)"}}),f0=go("site","hosting",async e=>`/sites/${Ce(e.flags.site??"web")}`,{site:{type:"string",value:"name",description:"the site (default: web)"}}),tc=[r0,i0,o0,l0,p0,d0,u0,c0,h0,m0,f0,...g0];function sc(e){return`its last push (${A(e.commit.slice(0,7))}) did not roll out \u2014 ${A(sa(e.reason))}`}function y0(e){let t=`${e.running_version} serving`;if(e.version!==e.running_version){let s={waiting:"waiting to roll out",not_up:"not up",given_up:"given up on",migration:"held by its database migration",stopped:"not up (the machine is stopped)",failed:"not up (the machine cannot run)"}[e.state_reason_kind??""]??(e.state_reason?"not up":"rolling out");t+=`, ${e.version} ${s}`}return`${t}${e.build?` (build ${e.build.id}, ${e.build.commit.slice(0,7)})`:""}`}function sa(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t!=="").join(" \xB7 ")}function b0(e){let t=e.openapi_path?`, from ${e.openapi_path}`:"";switch(e.contract_state){case"refused":return`refused: ${(e.contract_error??"its app wrote none").split(/\r?\n/).filter(s=>s.trim()!=="").map(A).join(`
|
|
32
|
+
${" ".repeat(15)}`)}${t}`;case"none":return`none: its app serves none${t}`}return`${e.contract_digest?`sha256:${e.contract_digest.slice(0,12)}\u2026`:"none read"}${t}`}var w0=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/;async function z(e,t,n,s,a,r){return(await ye(e.studio,t.env_ref,n,s,a,r)).body}function te(e){if(!w0.test(e))throw g(`${JSON.stringify(e)} is not a name: lowercase letters, digits and dashes, starting with a letter`);return encodeURIComponent(e)}async function ce(e,t,n){if(n!==void 0)return n;let{machines:s}=await z(e,t,"GET","/machines?limit=100");if(s.length===1)return s[0].name;let a=await Us(e.io,e.io.cwd),r=a?.repository?s.filter(i=>i.source.repository.toLowerCase()===a.repository?.toLowerCase()&&(i.source.path??"")===a.path):[];if(r.length===1)return r[0].name;throw s.length===0?new y("no_machine","the environment has no machine yet",{hint:"make one with palbase machines:create"}):g("which machine? name it",`the environment's machines: ${s.map(i=>i.name).join(", ")}`)}var ac={name:"machines:sizes",summary:"the machine sizes, and which of them this environment may open now",scope:"environment",async run(e){let t=await f(e),{sizes:n}=await z(e,t,"GET","/machines/sizes");e.out.result({sizes:n},()=>e.out.table(n,[{header:"size",value:s=>s.name},{header:"cpu",value:s=>`${s.vcpu} vCPU`},{header:"memory",value:s=>`${s.memory_mib} MiB`},{header:"sleeps",value:s=>s.sleeps?"when idle":"never"},{header:"open",value:s=>s.available?"yes":`no \u2014 ${s.reason??""}`}]))}},rc={name:"databases:sizes",summary:"the database sizes, and which of them this environment may open now",scope:"environment",async run(e){let t=await f(e),{sizes:n}=await z(e,t,"GET","/databases/sizes");e.out.result({sizes:n},()=>e.out.table(n,[{header:"size",value:s=>s.name},{header:"cpu",value:s=>`${s.vcpu} vCPU`},{header:"memory",value:s=>`${s.memory_mib} MiB`},{header:"storage",value:s=>`${(s.storage_bytes/1e9).toFixed(0)} GB`},{header:"sleeps",value:s=>s.sleeps?`when idle${s.awake_hours_per_month?`, ${s.awake_hours_per_month} h awake a month`:""}`:"never"},{header:"open",value:s=>s.available?"yes":`no \u2014 ${s.reason??""}`}]))}},ic={name:"machines:list",summary:"the project's machines, each with the environment it is bound to: size, state, the version serving, address",details:["A project's machines are the project's: each is bound to one of its environments, whose settings, secrets and modules it takes, and the list is every environment's you reach. An environment's own token lists its environment's alone."],scope:"environment",async run(e){let t=await f(e),[{machines:n},s]=await Promise.all([z(e,t,"GET","/machines?limit=100"),zs(e.studio,t)]);e.out.result({machines:n},()=>{n.length===0&&e.out.line("No machine yet: palbase machines:create makes one from the code in this directory."),e.out.table(n,[{header:"name",value:a=>a.name},{header:"env",value:a=>`${Yn(s,a.environment)}${a.moving_to?` \u2192 ${Yn(s,a.moving_to)}`:""}`},{header:"size",value:a=>`${a.size}${a.replicas>1?` \xD7${a.replicas}`:""}`},{header:"state",value:a=>a.state},{header:"version",value:a=>a.running_version===a.version?`${a.version}`:`${a.running_version} \u2192 ${a.version}`},{header:"source",value:a=>`${a.source.repository}@${a.source.branch}${a.source.path?`/${a.source.path}`:""}`},{header:"url",value:a=>a.url}])})}},oc={name:"machines:move",summary:"bind a machine to another environment of the project: it starts there with that environment's settings, secrets and modules",usage:"<name> --to <env>",details:["The machine is taken out of the environment it leaves and starts in the new one at the version it serves, in a moment; its address names the new environment (<name>-<its ref>).","Its pull requests' previews are closed: a new push opens them in the new environment. The database it is given stays where it is kept, given to it across environments.","It needs the admin role in both environments. A machine with domains of its own does not move: remove them first (machines:domains:remove), add them again once it has moved."],args:{min:1,max:1},flags:{to:{type:"string",value:"env",description:"the environment of the project it moves to (its slug)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.to;if(typeof n!="string"||n==="")throw g("--to names the environment of the project it moves to");let s=(await Re(e.studio)).filter(o=>o.project_id===t.project_id),a=s.find(o=>o.slug===n||o.ref===n);if(!a)throw new y("no_such_environment",`the project has no environment ${JSON.stringify(n)}`,{hint:`its environments: ${s.map(o=>o.slug).join(", ")}`});let r=e.args[0];await v(e,t,`move the machine ${r} out of this environment, into ${a.slug}`),await v(e,_e(a),`move the machine ${r} into this environment: it starts here with this environment's settings, secrets and modules`);let i=await z(e,t,"POST",`/machines/${te(r)}/move`,{environment:a.ref});e.out.result(i,()=>e.out.line(`${i.name} moves to ${a.slug}: it starts there in a moment (palbase machines:get ${i.name} -E ${a.slug}).`))}},lc={name:"machines:get",summary:"a machine in full: its source, size, environment, database and the build serving",usage:"[name]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),s=await z(e,t,"GET",`/machines/${te(n)}`);e.out.result(s,()=>{e.out.line(`${s.name} \u2014 ${s.state}${s.state_reason?` (${s.state_reason})`:""}`),e.out.line(` url ${s.url}`),e.out.line(` source ${s.source.repository} @ ${s.source.branch}${s.source.path?`, ${s.source.path}`:""}${s.source.context?` (context ${s.source.context})`:""}`),e.out.line(` size ${s.size} \xD7 ${s.replicas}, port ${s.port}${s.health_path?`, health ${s.health_path}`:""}`),e.out.line(` version ${y0(s)}`),s.failed_build&&e.out.line(` last push ${A(`${s.failed_build.commit.slice(0,7)} ${s.failed_build.state}: ${sa(s.failed_build.reason)}`)} (palbase machines:builds:log ${A(s.failed_build.id)} --machine ${s.name})`),e.out.line(` contract ${b0(s)}`),e.out.line(` database ${s.database?.name?`${s.database.name}${s.database.migrations?", its migrations run before each release":""}`:"none"}`),e.out.line(` secrets ${s.secrets?`the ${s.secrets} secrets`:"none"}`),e.out.line(` tests ${s.test_command?`${s.test_command}${s.test_users?.length?`, as ${s.test_users.join(", ")}`:""} \u2014 run on each build before it rolls out`:"none"}`),e.out.line(` env ${Object.keys(s.env).length===0?"none":Object.keys(s.env).sort().join(", ")}`)})}},pc={repo:{type:"string",value:"owner/name",description:"the GitHub repository (default: this checkout's origin)"},branch:{type:"string",value:"branch",description:"the branch whose pushes are built and rolled out (default: the one checked out)"},path:{type:"string",value:"dir",description:"the directory built, from the repository's root (default: this directory's place in it)"},context:{type:"string",value:"dir",description:'what the build is given above --path (a monorepo: ".")'},size:{type:"string",value:"size",description:"its size (palbase machines:sizes lists them)"},replicas:{type:"string",value:"n",description:"how many copies run, each on a node of its own"},port:{type:"string",value:"port",description:"the port it listens on (it also finds it in PORT)"},"always-on":{type:"boolean",description:"keep it awake: never put to sleep when idle (an environment on Pay as you go pays its every hour; on Free a shared machine sleeps when idle)"},"no-always-on":{type:"boolean",description:"let it sleep when idle again"},...ea,health:{type:"string",value:"path",description:"where it answers 2xx while well; a release that does not is not rolled out"},"openapi-path":{type:"string",value:"path",description:`where its app serves its OpenAPI contract, when it is not a Palbase backend (apps:sync makes its client from it); "" for a Palbase backend's own`},db:{type:"string",value:"database",description:'a database of the environment it is given (PALBASE_DB_URL); "" for none'},migrations:{type:"boolean",description:"run the database's migrations before each release (a Palbase backend's)"},secrets:{type:"string",value:"production|development",description:'the secrets it is started with, by name; "" for none'},var:{type:"string",multiple:!0,value:"K=V",description:"a setting it is started with (repeat it); secrets go in secrets:set"},"test-command":{type:"string",value:"command",description:'what each new build runs before it takes traffic, in its image, against the new version itself once its migration has run (bun test, npm test); a failure fails the build and the machine runs what it ran; "" for none'},"test-users":{type:"string",value:"names",description:'the test users each test run makes for its tests (api.signInAs), comma-separated; "" for none'}};function dc(e,t){e.flags["test-command"]!==void 0&&(t.test_command=e.flags["test-command"]),e.flags["test-users"]!==void 0&&(t.test_users=Wi(e.flags["test-users"]))}function uc(e){if(!e)return;let t={};for(let n of e){let s=n.indexOf("=");if(s<=0)throw g(`a setting is K=V, not ${JSON.stringify(n)}`);t[n.slice(0,s)]=n.slice(s+1)}return t}function kn(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw g(`--${t} is a whole number`);return n}var cc={name:"machines:create",summary:"make a machine from the code in this directory, built on every push to its branch",usage:"[name] [--size <size>] [--db <database> --migrations] [--repo --branch --path --context] \u2026",details:["Run in a checkout, it reads the repository from origin, the branch from HEAD and the directory from where you are; flags say otherwise.","The first build starts at once; --wait follows it until the machine serves, and prints its address.","The environment needs its GitHub link first: palbase github:connect."],args:{min:0,max:1},flags:{...pc,wait:{type:"boolean",description:"follow the first build until the machine serves"}},scope:"environment",async run(e){let t=await f(e),n=await Us(e.io,e.io.cwd),s=e.flags.repo??n?.repository,a=e.flags.branch??n?.branch;if(!s)throw g("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!a)throw g("which branch? none is checked out here","pass --branch <branch>");let r=e.flags.size;if(r===void 0){let{sizes:m}=await z(e,t,"GET","/machines/sizes");if(r=m.find(b=>b.available)?.name,!r)throw new y("no_size_open","no machine size is open to this environment",{hint:"palbase machines:sizes says why"})}let i=e.flags.path??n?.path??"",o={...e.args[0]?{name:e.args[0]}:{},source:{repository:s,branch:a,...i!==""?{path:i}:{},...e.flags.context?{context:e.flags.context}:{}},size:r},l=kn(e.flags.replicas,"replicas"),d=kn(e.flags.port,"port");l!==void 0&&(o.replicas=l),d!==void 0&&(o.port=d),e.flags["always-on"]===!0&&(o.always_on=!0),e.flags["no-always-on"]===!0&&(o.always_on=!1),na(e,o),e.flags.health!==void 0&&(o.health_path=e.flags.health),e.flags["openapi-path"]!==void 0&&(o.openapi_path=e.flags["openapi-path"]),e.flags.secrets!==void 0&&(o.secrets=e.flags.secrets);let p=uc(e.flags.var);if(p&&(o.env=p),e.flags.db!==void 0)o.database={name:e.flags.db,migrations:e.flags.migrations===!0};else if(e.flags.migrations===!0)throw g("--migrations goes with --db <database>");dc(e,o),await v(e,t,`make a machine from ${s}@${a}${i?`/${i}`:""} (${r})`);let u=await z(e,t,"POST","/machines",o);e.flags.wait===!0&&(u=await _0(e,t,u.name)),e.out.result(u,()=>e.out.line(`Made the machine ${u.name} (${u.size}) \u2014 ${u.state}; it answers at ${u.url}`))}},hc={name:"machines:update",summary:"change a machine: the change rolls out as a new version beside the one serving",usage:"[name] [--size \u2026] [--replicas \u2026] [--db \u2026] [--repo --branch --path --context] \u2026",args:{min:0,max:1},flags:pc,scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),s={};if(e.flags.repo!==void 0||e.flags.branch!==void 0||e.flags.path!==void 0||e.flags.context!==void 0){let o=await z(e,t,"GET",`/machines/${te(n)}`);s.source={repository:e.flags.repo??o.source.repository,branch:e.flags.branch??o.source.branch,path:e.flags.path??o.source.path??"",context:e.flags.context??o.source.context??""}}e.flags.size!==void 0&&(s.size=e.flags.size);let a=kn(e.flags.replicas,"replicas"),r=kn(e.flags.port,"port");if(a!==void 0&&(s.replicas=a),r!==void 0&&(s.port=r),e.flags["always-on"]===!0&&(s.always_on=!0),e.flags["no-always-on"]===!0&&(s.always_on=!1),na(e,s),e.flags.health!==void 0&&(s.health_path=e.flags.health),e.flags["openapi-path"]!==void 0&&(s.openapi_path=e.flags["openapi-path"]),e.flags.secrets!==void 0&&(s.secrets=e.flags.secrets),e.flags.var!==void 0)throw g("machines:update leaves the settings as they are: machines:env:set and machines:env:unset change them");if(e.flags.db!==void 0&&(s.database={name:e.flags.db,migrations:e.flags.migrations===!0}),dc(e,s),Object.keys(s).length===0)throw g("nothing to change: give a flag","palbase help machines:update");await v(e,t,`change the machine ${n}: ${Object.keys(s).join(", ")}`);let i=await z(e,t,"PATCH",`/machines/${te(n)}`,s);e.out.result(i,()=>e.out.line(`${i.name}: version ${i.version} rolls out beside ${i.running_version}.`))}},mc={name:"machines:env:list",summary:"what a machine is started with, and where each comes from (the platform, the machine, its secrets)",usage:"[name]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),s=await z(e,t,"GET",`/machines/${te(n)}`),a=s.secrets?await z(e,t,"GET",`/secrets/${D("the machine's secret set",s.secrets)}`).then(o=>(o.items??o.secrets??[]).map(l=>l.name),()=>[]):[],r=["PORT","PALBASE_URL","PALBASE_PROJECT_ID","PALBASE_REPLICAS","PALBASE_PLATFORM_SECRET","PALBASE_SECRET_KEY","PALBASE_WEBHOOK_SECRET",...s.database?.name?["PALBASE_DB_URL","PALBASE_DB_CONNECTIONS"]:[]],i=r.map(o=>({name:o,from:"platform",note:a.includes(o)||o in s.env?`in place of the ${o} set by hand`:""}));for(let o of Object.keys(s.env).sort())r.includes(o)||i.push({name:o,from:"machine",note:a.includes(o)?`shadows the secret ${o}`:""});for(let o of a.sort())r.includes(o)||o in s.env||i.push({name:o,from:`secrets (${s.secrets})`,note:""});e.out.result({machine:s.name,env:i},()=>e.out.table(i,[{header:"name",value:o=>o.name},{header:"from",value:o=>o.from},{header:"",value:o=>o.note}]))}};async function gc(e,t){let n=await f(e),s=await ce(e,n,e.flags.machine);for(let a=1;;a++){let r=await ye(e.studio,n.env_ref,"GET",`/machines/${te(s)}`),i={...r.body.env},o=t(i);if(a===1){if(r.body.secrets){let l=await z(e,n,"GET",`/secrets/${D("the machine's secret set",r.body.secrets)}`).catch(()=>({items:[]}));for(let d of Object.keys(i))(l.items??[]).some(p=>p.name===d)&&e.out.warn(`${d} in the machine's env shadows the secret of that name`)}await v(e,n,`${o.join(", ")} on the machine ${s}`)}try{let l=await z(e,n,"PATCH",`/machines/${te(s)}`,{env:i},r.etag?{"if-match":r.etag}:void 0);e.out.result({machine:l.name,env:Object.keys(l.env).sort()},()=>e.out.line(`${l.name}: version ${l.version} rolls out with it.`));return}catch(l){if(!(l instanceof j&&l.status===412)||a===3)throw l;e.out.note(`${s} changed meanwhile: making the change again on what it is now\u2026`)}}}var fc={name:"machines:env:set",summary:"set settings a machine is started with (not secrets: secrets:set keeps those)",usage:"K=V\u2026 [--machine <name>]",args:{min:1,max:50},flags:{machine:{type:"string",value:"name",description:"the machine (default: the only one, or this directory's)"}},scope:"environment",async run(e){let t=uc(e.args);await gc(e,n=>(Object.assign(n,t),Object.keys(t).map(s=>`set ${s}`)))}},yc={name:"machines:env:unset",summary:"take settings away from what a machine is started with",usage:"K\u2026 [--machine <name>]",args:{min:1,max:50},flags:{machine:{type:"string",value:"name",description:"the machine (default: the only one, or this directory's)"}},scope:"environment",async run(e){await gc(e,t=>{for(let n of e.args){if(!(n in t))throw new y("no_such_setting",`the machine is not started with ${n}`);delete t[n]}return e.args.map(n=>`unset ${n}`)})}},bc={name:"machines:builds",summary:"a machine's builds, newest first",usage:"[name]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),{builds:s}=await z(e,t,"GET",`/machines/${te(n)}/builds?limit=20`);e.out.result({builds:s},()=>e.out.table(s,[{header:"build",value:a=>a.id},{header:"commit",value:a=>a.commit.slice(0,7)},{header:"state",value:a=>`${a.state}${a.running?" (serving)":""}${a.reason?` \u2014 ${sa(a.reason)}`:""}`},{header:"message",value:a=>a.message.split(`
|
|
33
33
|
`)[0].slice(0,60)},{header:"created",value:a=>a.created_at}]))}},wc={name:"machines:previews",summary:"a machine's pull request previews, newest first: each a machine of its own while its pull request is open",usage:"[name]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),{previews:s}=await z(e,t,"GET",`/machines/${te(n)}/previews`);e.out.result({previews:s},()=>fo(e,s,`${n} has no preview: machines:update ${n} --previews previews its pull requests (in a preview environment).`))}},vc=mo("machine","machines",async(e,t)=>`/machines/${te(await ce(e,t,e.flags.machine))}`,{machine:{type:"string",value:"name",description:"the machine (default: the environment's only one)"}}),_c=go("machine","machines",async(e,t)=>`/machines/${te(await ce(e,t,e.flags.machine))}`,{machine:{type:"string",value:"name",description:"the machine (default: the environment's only one)"}}),kc={name:"machines:previews:open",summary:"open a machine's pull request preview again \u2014 one closed after 3 days with no push, or refused \u2014 at the pull request's head",usage:"<pull request> [--machine <name>]",details:["Its machine is made again and built at the pull request's head; a machine that runs its database's migrations has its preview given a new, empty database of its own, migrated by the preview's release.","A preview that is open goes on as it is, and its 3 days start again. A fork's, under fork protection, opens at a head an admin authorized (previews:authorize)."],args:{min:1,max:1},flags:{machine:{type:"string",value:"name",description:"the machine (default: the environment's only one)"}},scope:"environment",async run(e){let t=Number(e.args[0].replace(/^#/,""));if(!Number.isInteger(t)||t<=0)throw g("the pull request is its number: 12, or #12");let n=await f(e),s=await ce(e,n,e.flags.machine),a=await z(e,n,"POST",`/machines/${te(s)}/previews/${t}/open`);e.out.result(a,()=>e.out.line(`#${t}: its preview is being built at ${a.commit.slice(0,7)} (palbase machines:previews ${s}).`))}},Sc={name:"machines:builds:log",summary:"a build's log (the newest build's when none is named)",usage:"[build] [--machine <name>]",args:{min:0,max:1},flags:{machine:{type:"string",value:"name",description:"the machine (default: the only one, or this directory's)"}},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.flags.machine),s=e.args[0];if(!s){let{builds:i}=await z(e,t,"GET",`/machines/${te(n)}/builds?limit=1`);if(i.length===0)throw new y("no_build",`${n} has no build yet`);s=i[0].id}let a=await z(e,t,"GET",`/machines/${te(n)}/builds/${D("the build's id",s)}/log`),r=typeof a=="string"?a:JSON.stringify(a);e.out.result({build:s,log:r},()=>{for(let i of r.split(`
|
|
34
34
|
`))e.out.line(i)})}},$c={name:"machines:logs",summary:"a machine's log: the last hour, or since a time; -f follows what it writes next",usage:"[name] [-f] [--since <time>] [--lines <n>] [--search <text>]",details:["Besides the machine's own lines: its migration runs' (migration), and what a build printed while its tests ran against it (test) \u2014 the error it answered a test with, and that request's id: palbase machines:logs <name> --search <request_id>."],args:{min:0,max:1},flags:{follow:{type:"boolean",short:"f",description:"keep printing what the machine writes"},since:{type:"string",value:"time",description:"from when: an RFC 3339 time, or 10m, 2h, 1d ago"},lines:{type:"string",value:"n",description:"how many lines at most (default 200)"},search:{type:"string",value:"text",description:"only the lines that hold this text"}},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),s=kn(e.flags.lines,"lines")??200,a=e.flags.since?k0(e.flags.since,e.io.now()):void 0,r=e.flags.search,i=new Set,o=async d=>{let p=new URLSearchParams({lines:String(s),order:d,...a?{since:a}:{},...r?{q:r}:{}}),u=await z(e,t,"GET",`/machines/${te(n)}/logs?${p}`),m=u!==null&&typeof u=="object"?[u]:String(u??"").split(`
|
|
35
35
|
`).filter(b=>b.trim()!=="").map(b=>JSON.parse(b));return d==="desc"?m.reverse():m},l=d=>{for(let p of d)i.has(p.id)||(i.add(p.id),e.global.json?e.io.stdout(`${JSON.stringify(p)}
|
|
36
36
|
`):e.out.line(`${p.ts} ${p.pod?`[${p.pod.slice(-5)}] `:""}${p.source&&p.source!=="machine"?`(${p.source}) `:""}${p.line}`));d.length>0&&(a=d[d.length-1].ts)};for(l(await o("desc"));e.flags.follow===!0;)await e.io.sleep(2e3),l(await o("asc"))}},Pc={name:"machines:deploy",summary:"build the head of a machine's branch now and roll it out, as a push does",usage:"[name] [--wait]",details:["A push to the branch does this by itself; this is for the one GitHub did not deliver, or a build again.","The commit is the branch's head on GitHub: push first."],args:{min:0,max:1},flags:{wait:{type:"boolean",description:"follow the build until the machine serves it"}},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]);await v(e,t,`build and roll out ${n} from the head of its branch`);let s=await z(e,t,"POST",`/machines/${te(n)}/builds`);e.flags.wait===!0&&(s=await v0(e,t,n)),e.out.result(s,()=>e.out.line(e.flags.wait===!0?`${s.name} serves version ${s.running_version}${s.build?` (${s.build.commit.slice(0,7)})`:""}.`:`${s.name}: a build of ${s.source.branch}'s head is on its way (palbase machines:builds).`))}};async function v0(e,t,n){let s="";for(let a=0;a<900;a++){let r=await z(e,t,"GET",`/machines/${te(n)}`);if(!r.build_requested){let{builds:i}=await z(e,t,"GET",`/machines/${te(n)}/builds?limit=1`),o=i[0];if(!o)throw new y("build_failed",`${n} has no build${r.state_reason?`: ${r.state_reason}`:""}`,{hint:`palbase machines:get ${n}`});let l=`build ${o.id.slice(0,8)} (${o.commit.slice(0,7)}): ${o.state}${o.running?", serving":""}`;if(l!==s&&e.out.note(` ${l}`),s=l,o.state==="failed"||o.state==="cancelled"||o.state==="skipped")throw new y("build_failed",`the build ${o.state}${o.reason?`: ${o.reason}`:""}`,{hint:`palbase machines:builds:log ${o.id} --machine ${n}`});if(o.state==="succeeded"&&r.state==="failed")throw new y("build_failed",`${n}: ${r.state_reason??"failed"}`,{hint:`palbase machines:get ${n}`});if(o.running&&r.running_version===r.version)return r}await e.io.sleep(2e3)}throw new y("timeout",`${n} was not serving the build after 30 minutes`,{hint:`palbase machines:builds ${n}`})}var Ac={name:"machines:rollback",summary:"serve an earlier build again (the one before the serving one, or a named one)",usage:"[name] [--to <build>]",args:{min:0,max:1},flags:{to:{type:"string",value:"build",description:"the build to go back to (default: the last one that served before)"}},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),s=e.flags.to;if(!s){let{builds:r}=await z(e,t,"GET",`/machines/${te(n)}/builds?limit=50`),i=r.findIndex(l=>l.running),o=r.slice(i+1).find(l=>l.state==="succeeded");if(i<0||!o)throw new y("no_earlier_build",`${n} has no earlier build that succeeded`,{hint:"name one with --to (palbase machines:builds lists them)"});s=o.id}await v(e,t,`roll ${n} back to build ${s}`);let a=await z(e,t,"POST",`/machines/${te(n)}/rollback`,{build:s});e.out.result(a,()=>e.out.line(`${a.name} rolls back to build ${s} (version ${a.version}).`))}},Kt={machine:{type:"string",value:"name",description:"the machine (default: the only one, or this directory's)"}},wo=e=>e.replace(/[\u0000-\u001f\u007f-\u009f]/g," "),dr=(e,t,n="")=>`/machines/${te(e)}/crons/${D("the cron's name",t)}${n}`,vo=(e,t,n="")=>`/machines/${te(e)}/tasks/${D("the task's id",t)}${n}`,Rc={name:"machines:crons",summary:"the crons a machine runs on a schedule (its app's @Cron classes): when each is next due, on which zone's clocks, and how its last run went",usage:"[name]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),s=await z(e,t,"GET",`/machines/${te(n)}/crons`),a=s.crons??[];e.out.result(s,()=>e.out.table(a,[{header:"cron",value:r=>r.name},{header:"schedule",value:r=>r.schedule},{header:"zone",value:r=>r.time_zone},{header:"next",value:r=>r.paused?"paused":r.next_at??""},{header:"last run",value:r=>r.last_run?`${r.last_run.state} ${r.last_run.started_at??""}${r.last_run.manual?" (run now)":""}`:""}]))}},Tc={name:"machines:crons:runs",summary:"a cron's runs, newest first",usage:"<cron> [--machine <name>]",args:{min:1,max:1},flags:Kt,scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.flags.machine),s=await z(e,t,"GET",dr(n,e.args[0],"/runs")),a=s.runs??[];e.out.result(s,()=>e.out.table(a,[{header:"run",value:r=>r.id},{header:"state",value:r=>r.manual?`${r.state} (run now)`:r.state},{header:"attempt",value:r=>String(r.attempt)},{header:"started",value:r=>r.started_at??""},{header:"finished",value:r=>r.finished_at??""},{header:"reason",value:r=>wo(r.reason??"")}]))}},Ec={name:"machines:crons:run",summary:"run a cron now, apart from its schedule \u2014 the machine woken for it if asleep",usage:"<cron> [--machine <name>]",args:{min:1,max:1},flags:Kt,scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.flags.machine);await v(e,t,`run ${e.args[0]} of ${n} now`);let s=await z(e,t,"POST",dr(n,e.args[0],"/run"));e.out.result(s,()=>e.out.line(`${e.args[0]} runs now: run ${s.id}, ${s.state} for its first attempt (palbase machines:crons:runs ${e.args[0]} shows how it went).`))}},Cc={name:"machines:crons:pause",summary:"pause a cron: it is not run until resumed, whatever version of the machine comes up meanwhile",usage:"<cron> [--machine <name>]",args:{min:1,max:1},flags:Kt,scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.flags.machine);await v(e,t,`pause ${e.args[0]} of ${n}`);let s=await z(e,t,"POST",dr(n,e.args[0],"/pause"));e.out.result(s,()=>e.out.line(`${s.name} is paused: it is not run until palbase machines:crons:resume ${s.name}.`))}},jc={name:"machines:crons:resume",summary:"resume a paused cron: it is due at its next time from now \u2014 what it missed is not made up",usage:"<cron> [--machine <name>]",args:{min:1,max:1},flags:Kt,scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.flags.machine);await v(e,t,`resume ${e.args[0]} of ${n}`);let s=await z(e,t,"POST",dr(n,e.args[0],"/resume"));e.out.result(s,()=>e.out.line(`${s.name} is resumed: next due ${s.next_at??""} (${s.time_zone}).`))}},nc=["waiting","running","succeeded","failed","cancelled"],Oc={name:"machines:tasks",summary:"the tasks on a machine's queue (its app's @Task classes), newest first: of one state, one type, or all",usage:"[--machine <name>] [--state waiting|running|succeeded|failed|cancelled] [--task <type>] [--limit <n>]",args:{min:0,max:0},flags:{...Kt,state:{type:"string",value:"state",description:"only tasks in this state"},task:{type:"string",value:"type",description:"only tasks of this type"},limit:{type:"string",value:"n",description:"the most listed (50; 100 at most)"}},scope:"environment",async run(e){let t=e.flags.state;if(t!==void 0&&!nc.includes(t))throw g(`--state ${t} is not one: ${nc.join(", ")}`);let n=await f(e),s=await ce(e,n,e.flags.machine),a=new URLSearchParams;t&&a.set("state",t),e.flags.task&&a.set("task",e.flags.task),e.flags.limit&&a.set("limit",e.flags.limit);let r=await z(e,n,"GET",`/machines/${te(s)}/tasks${a.size>0?`?${a}`:""}`),i=r.tasks??[];e.out.result(r,()=>e.out.table(i,[{header:"task",value:o=>o.id},{header:"type",value:o=>o.task},{header:"state",value:o=>o.state},{header:"attempt",value:o=>`${o.attempt}/${o.retries+1}`},{header:"due",value:o=>o.state==="waiting"?o.run_at:o.finished_at??""},{header:"reason",value:o=>wo(o.reason??"")}]))}},Mc={name:"machines:tasks:types",summary:"the task types a machine's running version declares, and what each one's queue holds",usage:"[name]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),s=await z(e,t,"GET",`/machines/${te(n)}/task-types`),a=s.types??[];e.out.result(s,()=>e.out.table(a,[{header:"type",value:r=>r.name},{header:"at once",value:r=>String(r.concurrency)},{header:"retries",value:r=>String(r.retries)},{header:"timeout",value:r=>`${r.timeout} s`},{header:"waiting",value:r=>String(r.waiting)},{header:"running",value:r=>String(r.running)},{header:"failed",value:r=>String(r.failed)}]))}},xc={name:"machines:tasks:get",summary:"one task on a machine's queue, with what it carries",usage:"<task id> [--machine <name>]",args:{min:1,max:1},flags:Kt,scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.flags.machine),s=await z(e,t,"GET",vo(n,e.args[0]));e.out.result(s,()=>{e.out.line(`${s.id} (${s.task}): ${s.state}, attempt ${s.attempt} of ${s.retries+1}${s.reason?` \u2014 ${wo(s.reason)}`:""}`),e.out.line(s.payload===void 0?"payload: not kept \u2014 the task is over":`payload: ${JSON.stringify(s.payload)}`)})}},Ic={name:"machines:tasks:enqueue",summary:"put a task on a machine's queue, as its app's Tasks.enqueue does",usage:"<type> [--payload '<json>'] [--delay <seconds>] [--key <key>] [--machine <name>]",args:{min:1,max:1},flags:{...Kt,payload:{type:"string",value:"json",description:"what it carries: a JSON value (64 KiB at most)"},delay:{type:"string",value:"seconds",description:"due this many seconds from now (30 days at most)"},key:{type:"string",value:"key",description:"put once under this key (held until a day after the task is over)"}},scope:"environment",async run(e){let t=null;if(e.flags.payload!==void 0)try{t=JSON.parse(e.flags.payload)}catch{throw g("--payload is a JSON value",`like --payload '{"orderId":"o-1"}'`)}let n=e.flags.delay===void 0?void 0:Number(e.flags.delay);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw g("--delay is whole seconds");let s=await f(e),a=await ce(e,s,e.flags.machine);await v(e,s,`put a ${e.args[0]} task on ${a}'s queue`);let r=await z(e,s,"POST",`/machines/${te(a)}/tasks`,{task:e.args[0],payload:t,...n!==void 0?{delay:n}:{},...e.flags.key?{key:e.flags.key}:{}});e.out.result(r,()=>e.out.line(`${r.task} ${r.id}: ${r.state}, due ${r.run_at}.`))}},Lc={name:"machines:tasks:retry",summary:"put a task that failed back on the queue, due now, with as many attempts again as its type gives",usage:"<task id> [--machine <name>]",args:{min:1,max:1},flags:Kt,scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.flags.machine);await v(e,t,`try task ${e.args[0]} of ${n} again`);let s=await z(e,t,"POST",vo(n,e.args[0],"/retry"));e.out.result(s,()=>e.out.line(`${s.task} ${s.id} is back on the queue: ${s.state}, due now.`))}},Dc={name:"machines:tasks:cancel",summary:"take a task that is waiting off the queue: it is not run, nor tried again",usage:"<task id> [--machine <name>]",args:{min:1,max:1},flags:Kt,scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.flags.machine);await v(e,t,`cancel task ${e.args[0]} of ${n}`);let s=await z(e,t,"POST",vo(n,e.args[0],"/cancel"));e.out.result(s,()=>e.out.line(`${s.task} ${s.id} is cancelled: it is not run.`))}},qc={name:"machines:contract",summary:"the API a Palbase backend serves (its OpenAPI document), as the platform reads it from the machine",usage:"[name]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=await ce(e,t,e.args[0]),s=await z(e,t,"GET",`/machines/${te(n)}/openapi`);e.io.stdout(`${JSON.stringify(s,null,2)}
|
|
37
|
-
`)}},Nc={name:"machines:delete",summary:"delete a machine: it stops serving, its address answers nothing",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=e.args[0];if(!e.global.yes){if(!e.interactive)throw new y("confirmation_needed","deleting a machine is confirmed",{hint:"confirm with -y"});if((await e.io.prompt("Type the machine's name to delete it: ")).trim()!==n)throw new y("cancelled","nothing was deleted")}await z(e,t,"DELETE",`/machines/${te(n)}`),e.out.result({deleted:n},()=>e.out.line(`Deleted the machine ${n}.`))}};async function _0(e,t,n){e.out.note(`Following ${n}'s first build\u2026`);let s="";for(let a=0;a<900;a++){let r=await z(e,t,"GET",`/machines/${te(n)}`),i=`${r.state}${r.build?` (${r.build.commit.slice(0,7)})`:""}`;if(i!==s&&e.out.note(` ${i}${r.state_reason?` \u2014 ${r.state_reason}`:""}`),s=i,r.running_version>=1&&r.running_version===r.version&&(r.state==="awake"||r.state==="asleep"))return r;if(r.state==="failed")throw new y("build_failed",`${n}'s build failed${r.state_reason?`: ${r.state_reason}`:""}`,{hint:`palbase machines:builds:log --machine ${n}`});await e.io.sleep(2e3)}throw new y("timeout",`${n} was not serving after 30 minutes`,{hint:`palbase machines:get ${n}`})}function k0(e,t){let n=/^(\d+)([smhd])$/.exec(e);if(n)return new Date(t-Number(n[1])*{s:1e3,m:6e4,h:36e5,d:864e5}[n[2]]).toISOString();if(Number.isNaN(Date.parse(e)))throw g(`--since is a time (2026-10-08T12:00:00Z) or a duration ago (10m, 2h, 1d), not ${JSON.stringify(e)}`);return new Date(e).toISOString()}var Kc={name:"databases:list",summary:"the project's databases, each with the environment that keeps it: size, state, how full",details:["A project's databases are the project's: any machine of the project may be given one, whichever environment keeps it (machines:update --database)."],scope:"environment",async run(e){let t=await f(e),[{databases:n},s]=await Promise.all([z(e,t,"GET","/databases?limit=100"),zs(e.studio,t)]);e.out.result({databases:n},()=>{n.length===0&&e.out.line("No database yet: palbase databases:create makes one."),e.out.table(n,[{header:"name",value:a=>a.name},{header:"env",value:a=>Yn(s,a.environment)},{header:"size",value:a=>a.size},{header:"state",value:a=>`${a.state}${a.deleted_at?" (deleted)":""}`},{header:"used",value:a=>a.used_bytes!==void 0?`${(a.used_bytes/1e6).toFixed(1)} / ${(a.quota_bytes/1e6).toFixed(0)} MB`:""},{header:"host",value:a=>a.host}])})}},Gc={name:"databases:get",summary:"a database in full, with how to connect to it",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=await z(e,t,"GET",`/databases/${te(e.args[0])}`),s=await e.state.databasePasswords(t.env_ref,n.name);e.out.result({...n,passwords_on_this_computer:{owner:s.owner!==void 0,app:s.app!==void 0}},()=>{e.out.line(`${n.name} \u2014 ${n.size}, ${n.state}${n.state_reason?` (${n.state_reason})`:""}`),e.out.line(` host ${n.host}:${n.port} (pooled ${n.pooled_port})`),e.out.line(` allows ${n.allow.length===0?"anyone with the password":n.allow.join(", ")}`),e.out.line(` backups ${n.backup_days} days, any moment of them (databases:restore --to)`),n.used_bytes!==void 0&&e.out.line(` used ${(n.used_bytes/1e6).toFixed(1)} MB of ${(n.quota_bytes/1e6).toFixed(0)} MB`),n.awake_hours_limit&&e.out.line(` awake ${n.awake_hours??0} h this month; the environment's free databases ${n.environment_awake_hours??n.awake_hours??0} of ${n.awake_hours_limit} hours`),e.out.line(` passwords ${s.owner||s.app?`this computer holds ${[s.owner&&"owner",s.app&&"app"].filter(Boolean).join(" and ")}`:"none on this computer (databases:password:reset makes new ones)"}`)})}};function Uc(e){if(e!==void 0)return String(e).split(",").map(t=>t.trim()).filter(t=>t!=="")}var zc={name:"databases:create",summary:"open a database; its passwords are kept on this computer (the platform shows them once)",usage:"[name] [--size <size>] [--allow <ip/cidr,\u2026>] [--backup-days <n>] [--show-passwords]",args:{min:0,max:1},flags:{size:{type:"string",value:"size",description:"its size (palbase databases:sizes lists what is open)"},allow:{type:"string",value:"list",description:"who may connect, as addresses or CIDRs, comma-separated (default: anyone with the password)"},"backup-days":{type:"string",value:"n",description:"how many days of backups to keep, 1 to 35"},"show-passwords":{type:"boolean",description:"print the passwords too (they are kept on this computer either way)"}},scope:"environment",async run(e){let t=await f(e),n={};e.args[0]&&(n.name=e.args[0]),e.flags.size!==void 0&&(n.size=e.flags.size);let s=Uc(e.flags.allow);s&&(n.allow=s);let a=kn(e.flags["backup-days"],"backup-days");a!==void 0&&(n.backup_days=a),await v(e,t,`open a database ${e.args[0]??"main"}${n.size?` (${n.size})`:""}`);let r=await z(e,t,"POST","/databases",n);await e.state.keepDatabasePasswords(t.env_ref,r.name,{owner:r.credentials.owner.password,app:r.credentials.app.password});let i=e.flags["show-passwords"]===!0,{credentials:o,...l}=r;e.out.result(i?r:{...l,credentials:{owner:bo(o.owner),app:bo(o.app)}},()=>{e.out.line(`Opened the database ${r.name} (${r.size}) at ${r.host}.`),e.out.line("Its passwords are kept on this computer: palbase db:url and db:shell use them."),i&&(e.out.line(`owner: ${r.credentials.owner.password??""}`),e.out.line(`app: ${r.credentials.app.password??""}`))})}},yo="[YOUR-PASSWORD]";function bo(e){let{password:t,...n}=e,s={};for(let[a,r]of Object.entries(n))s[a]=typeof r=="string"?S0(r,t):r;return s}function S0(e,t){let n=e.replace(/(postgres(?:ql)?:\/\/[^:/@\s'"]+:)[^@\s'"]*(@)/gi,`$1${yo}$2`).replace(/([?&;]password=)[^&;\s'"]*/gi,`$1${yo}`);if(t)for(let s of new Set([t,encodeURIComponent(t),new URLSearchParams({p:t}).toString().slice(2)]))n=n.split(s).join(yo);return n}var Bc={name:"databases:update",summary:"change a database's size, who may connect to it, or how long its backups are kept",usage:'<name> [--size <size>] [--allow <list>|""] [--backup-days <n>] [--wait]',details:["A new size is taken at once and the database moves to it serving on (palbase databases:sizes lists them): its sessions on the direct port end once, when its primary moves, and new logins wait a few seconds then."],args:{min:1,max:1},flags:{size:{type:"string",value:"size",description:"the size to move it to"},allow:{type:"string",value:"list",description:'who may connect (comma-separated addresses or CIDRs); "" for anyone with the password'},"backup-days":{type:"string",value:"n",description:"how many days of backups to keep, 1 to 35"},wait:{type:"boolean",description:"with --size: follow the move until it serves at the new size"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0],s={},a=e.flags.size;if(a!==void 0){if(a==="")throw g("--size is one of palbase databases:sizes");s.size=a}let r=Uc(e.flags.allow);r&&(s.allow=r);let i=kn(e.flags["backup-days"],"backup-days");if(i!==void 0&&(s.backup_days=i),Object.keys(s).length===0)throw g("nothing to change: --size, --allow or --backup-days");await v(e,t,`change the database ${n}: ${Object.keys(s).join(", ")}`);let o=await z(e,t,"PATCH",`/databases/${te(n)}`,s);a!==void 0&&e.flags.wait===!0&&(o=await $0(e,t,n,a)),e.out.result(o,()=>{a!==void 0&&e.out.line(o.state==="resizing"?`${o.name} is moving to ${a}, serving on: its sessions on the direct port end once, when its primary moves (palbase databases:get ${o.name} follows it).`:`${o.name} serves at ${o.size} (${o.state}).`),(r||i!==void 0)&&e.out.line(`${o.name}: allows ${o.allow.length===0?"anyone with the password":o.allow.join(", ")}; backups ${o.backup_days} days.`)})}};async function $0(e,t,n,s){e.out.note(`Following ${n}'s move to ${s}\u2026`);let a="";for(let r=0;r<900;r++){let i=await z(e,t,"GET",`/databases/${te(n)}`),o=`${i.state}${i.state_reason?` \u2014 ${i.state_reason}`:""}`;if(o!==a&&e.out.note(` ${o}`),a=o,i.size===s&&i.state!=="resizing"&&i.state!=="starting"){if(i.state==="failed")throw new y("resize_failed",`${n} did not come up at ${s}${i.state_reason?`: ${i.state_reason}`:""}`,{hint:`palbase databases:get ${n}`});return i}if(i.size!==s)throw new y("resize_changed",`${n} is asked for ${i.size} now, not ${s}: another change came`,{hint:`palbase databases:get ${n}`});await e.io.sleep(2e3)}throw new y("timeout",`${n} was still moving to ${s} after 30 minutes; it serves on meanwhile`,{hint:`palbase databases:get ${n}`})}var Fc={name:"databases:password:reset",summary:"make a database role's password new; it is kept on this computer, the old one stops working",usage:"<name> --role owner|app [--show-password]",details:["The app role's new password reaches the machines given the database as they roll out with it; they keep serving."],args:{min:1,max:1},flags:{role:{type:"string",value:"role",description:"owner (migrations, the console) or app (what the machines use)"},"show-password":{type:"boolean",description:"print it too"}},scope:"environment",async run(e){let t=e.flags.role;if(t!=="owner"&&t!=="app")throw g("--role is owner or app");let n=await f(e);await v(e,n,`make the ${t} password of ${e.args[0]} new`);let a=(await z(e,n,"POST",`/databases/${te(e.args[0])}/password`,{role:t}))[t];if(!a?.password)throw new y("no_password","the platform answered no password");await e.state.keepDatabasePasswords(n.env_ref,e.args[0],{[t]:a.password}),await P0(e,n,e.args[0]),e.out.result(e.flags["show-password"]===!0?a:bo(a),()=>{e.out.line(`The ${t} password of ${e.args[0]} is new and kept on this computer.`),e.flags["show-password"]===!0&&e.out.line(a.password??"")})}};async function P0(e,t,n){for(let s=0;s<60;s++){if((await z(e,t,"GET",`/databases/${te(n)}`)).password_changing!==!0)return;s===0&&e.out.note(`Waiting for ${n} to take the new password\u2026`),await e.io.sleep(1e3)}throw new y("timeout",`${n} had not taken the new password after a minute; it is kept here and works once it has`,{hint:`palbase databases:get ${n}`})}var Jc={name:"databases:restore",summary:"bring a database back to a moment of its backups",usage:"<name> --to <time>",args:{min:1,max:1},flags:{to:{type:"string",value:"time",description:"the moment, as an RFC 3339 time (2026-10-08T12:00:00Z)"}},scope:"environment",async run(e){let t=e.flags.to;if(!t||Number.isNaN(Date.parse(t)))throw g("--to is the moment to go back to, as an RFC 3339 time");let n=await f(e);await v(e,n,`bring ${e.args[0]} back to ${t} (what was written since goes)`);let s=await z(e,n,"POST",`/databases/${te(e.args[0])}/restore`,{to:new Date(t).toISOString()});e.out.result(s,()=>e.out.line(`${s.name} is being brought back to ${t} \u2014 ${s.state}.`))}};function _o(e,t,n,s,a,r,i=!1){return{name:e,summary:t,usage:"<name>",args:{min:1,max:1},scope:"environment",async run(o){let l=await f(o),d=o.args[0];if(n==="DELETE"||s==="/purge"){if(!o.global.yes){if(!o.interactive)throw new y("confirmation_needed",`${a(d)} is confirmed`,{hint:"confirm with -y"});if((await o.io.prompt("Type the database's name to go ahead: ")).trim()!==d)throw new y("cancelled","nothing was changed")}}else await v(o,l,a(d));await z(o,l,n,`/databases/${te(d)}${s}`),i&&await o.state.forgetDatabase(l.env_ref,d),o.out.result({database:d,done:e},()=>o.out.line(r(d)))}}}var Wc=_o("databases:delete","delete a database (the platform keeps it 7 days to take back)","DELETE","",e=>`deleting the database ${e}`,e=>`Deleted ${e}; databases:undelete takes it back within 7 days.`),Vc=_o("databases:undelete","take back a database deleted in the last 7 days","POST","/undelete",e=>`take back the database ${e}`,e=>`${e} is back.`),Hc=_o("databases:purge","delete a deleted database for good, now","POST","/purge",e=>`purging the database ${e} for good`,e=>`${e} is purged.`,!0),Yc={name:"github:connect",summary:"link the environment to GitHub: Palbase Cloud's GitHub app on the account whose repositories machines are built from",usage:"[--device | --github-token-stdin | --from <env> [--repo <owner/name>\u2026]] [--installation <account|id>] [--all-envs]",details:["Opens GitHub; back from it, the page shows the account and you link it by writing the environment's ref.","--from <env>: the installation another environment of the organization linked (its slug in this project, or its ref), linked here too with no GitHub sign-in \u2014 a program that opens a project for each product (an admin, or an admin access token). The environment reaches what the GitHub user who linked it there can push to.","--repo <owner/name> (given again for more): with --from, the environment reaches those repositories of the installation alone, never one it reaches later \u2014 a product's environment builds nothing of another product's.","--device: no browser here \u2014 GitHub's device flow (a code you enter at github.com/login/device on any device); the GitHub token stays in memory.","--all-envs links every environment of the project the same way."],flags:{device:{type:"boolean",description:"GitHub's device flow, for a computer with no browser (a server, an agent)"},"github-token-stdin":{type:"boolean",description:"a GitHub user's token from stdin (CI): the installations it reaches, no browser and no code"},installation:{type:"string",value:"account|id",description:"which installation to link, when the GitHub user reaches more than one (--device)"},"all-envs":{type:"boolean",description:"link every environment of the project"},from:{type:"string",value:"env",description:"another environment of the organization whose linked installation this one shares (its slug in this project, or its ref): no GitHub sign-in"},repo:{type:"string",multiple:!0,value:"owner/name",description:"with --from: the repositories it reaches of the installation, and no other (given again for more)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags["all-envs"]===!0?(await Nt(e)).map($e):[t],s=e.flags.repo;if(typeof e.flags.from=="string"){if(e.flags.device===!0||e.flags["github-token-stdin"]===!0)throw g("--from links what another environment linked: no GitHub sign-in goes with it");for(let d of s??[])if(!/^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100}$/.test(d))throw g(`--repo names a repository as owner/name: ${JSON.stringify(d)} is none`);await A0(e,t,n,e.flags.from,s);return}if(s!==void 0)throw g("--repo goes with --from: it narrows what a shared installation reaches");let a=await z(e,t,"POST","/machines/github/connect"),r=e.flags["github-token-stdin"]===!0;if(!r&&e.flags.device!==!0&&e.interactive&&n.length===1){let d=await e.io.openBrowser(a.url);e.out.result({url:a.url,expires_at:a.expires_at,ref:t.env_ref},()=>e.out.line(d?`Opened GitHub. When it asks, link the environment ${t.env_ref}.`:`Open ${a.url} (good until ${a.expires_at}) and link the environment ${t.env_ref}.`));return}let i=r?await xe(e,"a GitHub user's token"):await R0(e,a.client_id),o=await T0(e,i),l=[];for(let d of n){await v(e,d,`link the GitHub account ${o.account}`);let p=await z(e,d,"POST","/machines/github/installations",{installation_id:o.id,user_token:i});l.push({ref:d.env_ref,account:p.account})}e.out.result({linked:l},()=>{for(let d of l)e.out.line(`Linked ${d.account} to ${d.ref}.`)})}};async function A0(e,t,n,s,a){let r=await Re(e.studio),i=r.find(u=>u.ref===s)??r.find(u=>u.project_id===t.project_id&&u.slug===s);if(!i||i.organization_id!==t.org_id)throw new y("no_such_environment",`no environment ${JSON.stringify(s)} of ${t.org_name} besides this one`,{hint:"name it by its slug in this project, or by its ref (palbase projects:list)"});let o=(await z(e,$e(i),"GET","/machines/github/installations")).installations,l=e.flags.installation,d=l!==void 0?o.filter(u=>String(u.installation_id)===l||u.account.toLowerCase()===l.toLowerCase()):o;if(d.length===0)throw new y("no_installation",`${i.slug} (${i.ref}) links no GitHub account${l!==void 0?` ${JSON.stringify(l)}`:""}`,{hint:"link it there first: palbase github:connect -E <env>"});if(d.length>1)throw g("which installation? --installation <account|id>",`${i.slug} links ${d.map(u=>u.account).join(", ")}`);let p=[];for(let u of n){if(u.env_ref===i.ref)continue;await v(e,u,`link the GitHub account ${d[0].account}${a?` for ${a.join(", ")} alone`:""}, as ${i.slug} (${i.ref}) links it`);let m=await e.studio.post(`/environments/${D("the environment's ref",u.env_ref)}/github/installations`,{installation_id:d[0].installation_id,from:i.ref,...a?{repositories:a}:{}});p.push({ref:u.env_ref,account:m.account})}e.out.result({linked:p},()=>{for(let u of p)e.out.line(`Linked ${u.account} to ${u.ref}, as ${i.slug} (${i.ref}) links it.`)})}async function R0(e,t){let n=o=>({method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(o)}),s=await e.io.fetch("https://github.com/login/device/code",n({client_id:t}));if(!s.ok)throw new y("github_unavailable",`GitHub did not start the sign-in: ${s.status}`);let a=await s.json();e.out.note(""),e.out.note(` Enter this code at ${a.verification_uri}: ${a.user_code}`),e.out.note("");let r=Math.max(1,a.interval??5),i=e.io.now()+(a.expires_in??900)*1e3;for(;e.io.now()<i;){await e.io.sleep(r*1e3);let o;try{o=await e.io.fetch("https://github.com/login/oauth/access_token",n({client_id:t,device_code:a.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}))}catch{continue}if(o.status>=500||o.status===429)continue;let l=await o.json().catch(()=>({}));if(l.access_token)return l.access_token;if(l.error!=="authorization_pending"){if(l.error==="slow_down"){r+=5;continue}if(l.error==="expired_token")break;throw l.error==="access_denied"?new y("access_denied","the sign-in was denied on GitHub"):new y("github_denied",`GitHub's sign-in ended: ${l.error??o.status}`)}}throw new y("expired_code","GitHub's code expired before it was entered",{hint:"run the command again"})}async function T0(e,t){let n=await e.io.fetch("https://api.github.com/user/installations?per_page=100",{headers:{authorization:`Bearer ${t}`,accept:"application/vnd.github+json","x-github-api-version":"2022-11-28"}});if(!n.ok)throw new y("github_unavailable",`GitHub did not list your installations: ${n.status}`);let s=(await n.json()).installations.map(r=>({id:r.id,account:r.account.login}));if(s.length===0)throw new y("no_installation","Palbase Cloud is installed on no GitHub account you reach",{hint:"install it (palbase github:connect, in a browser) or have the account's owner install it"});let a=e.flags.installation;if(a!==void 0){let r=s.find(i=>String(i.id)===a||i.account.toLowerCase()===a.toLowerCase());if(!r)throw new y("no_such_installation",`you reach no installation ${JSON.stringify(a)}: ${s.map(i=>i.account).join(", ")}`);return r}if(s.length===1)return s[0];if(!e.interactive)throw g("which installation? --installation <account>",`yours: ${s.map(r=>r.account).join(", ")}`);for(s.forEach((r,i)=>e.out.note(` ${i+1}) ${r.account}`));;){let r=Number((await e.io.prompt(`Which account? [1-${s.length}] `)).trim());if(Number.isInteger(r)&&r>=1&&r<=s.length)return s[r-1]}}var Xc={name:"github:list",summary:"the GitHub accounts linked to the environment, and who linked each",scope:"environment",async run(e){let t=await f(e),{installations:n}=await z(e,t,"GET","/machines/github/installations");e.out.result({installations:n},()=>{n.length===0&&e.out.line("No GitHub account is linked: palbase github:connect links one."),e.out.table(n,[{header:"account",value:s=>s.account},{header:"installation",value:s=>String(s.installation_id)},{header:"linked by",value:s=>s.linked_by}])})}},Zc={name:"github:repos",summary:"the repositories machines of the environment may be built from",scope:"environment",async run(e){let t=await f(e),{repositories:n}=await z(e,t,"GET","/machines/github/repositories");e.out.result({repositories:n},()=>e.out.table(n,[{header:"repository",value:s=>s.repository},{header:"default branch",value:s=>s.default_branch},{header:"",value:s=>s.private?"private":""}]))}},Qc={name:"github:disconnect",summary:"unlink a GitHub account from the environment; its repositories are no longer built",usage:"<account|installation-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),{installations:n}=await z(e,t,"GET","/machines/github/installations"),s=n.find(a=>String(a.installation_id)===e.args[0]||a.account.toLowerCase()===e.args[0].toLowerCase());if(!s)throw new y("no_such_installation",`no linked GitHub account ${JSON.stringify(e.args[0])}`);await v(e,t,`unlink the GitHub account ${s.account}`),await z(e,t,"DELETE",`/machines/github/installations/${s.installation_id}`),e.out.result({unlinked:s},()=>e.out.line(`Unlinked ${s.account}.`))}};var Ie=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0;function Gt(e,t,n){let s=Ie(Ie(Ie(e)?.components)?.schemas)??{},a=(p,u)=>{let m=new Set,b=(_,T,S)=>{let $=Ie(_);if(!$)return;if(typeof $.$ref=="string"){if(S.has($.$ref)||!$.$ref.startsWith("#/components/schemas/"))return;b(s[$.$ref.slice(21)],T,new Set(S).add($.$ref));return}if($[Ya]===!0){m.add(T);return}for(let P of["anyOf","oneOf","allOf"]){let L=$[P];if(Array.isArray(L))for(let U of L)b(U,T,S)}let R=Ie($.properties);if(R)for(let[P,L]of Object.entries(R))b(L,`${T}/${er(P)}`,S);Ie($.items)&&b($.items,`${T}/*`,S);for(let P of["additionalProperties","patternProperties","prefixItems"])if($[P]!==void 0&&w($[P],new Set(S)))throw new Error(`${n}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},w=(_,T)=>{if(Array.isArray(_))return _.some($=>w($,T));let S=Ie(_);return S?S[Ya]===!0?!0:typeof S.$ref=="string"&&!T.has(S.$ref)&&S.$ref.startsWith("#/components/schemas/")?(T.add(S.$ref),w(s[S.$ref.slice(21)],T)):Object.values(S).some($=>typeof $=="object"&&$!==null&&w($,T)):!1};return b(p,u,new Set),[...m]},r=p=>Ie(Ie(Ie(p)?.["application/json"])?.schema),i=[];i.push(...a(r(Ie(t.requestBody)?.content),"/body"));for(let p of Array.isArray(t.parameters)?t.parameters:[]){let u=Ie(p);if(!u)continue;let m=a(u.schema,`/query/${er(String(u.name))}`);if(m.length!==0){if(u.in!=="query")throw new Error(`${n}: ${String(u.in)} parameter ${String(u.name)} is marked encrypted \u2014 a body's or a query's field is`);if(m.some(b=>b.split("/").length!==3))throw new Error(`${n}: an encrypted query field is one of the query's own names`);i.push(...m)}}let o=Ie(t.responses)??{},l=Object.keys(o).filter(p=>/^2\d\d$/.test(p)).sort((p,u)=>p==="200"?-1:u==="200"?1:p.localeCompare(u)),d=l.length>0?a(r(Ie(o[l[0]])?.content),"/response"):[];if(i.length+d.length!==0){if(t["x-palbase-sse"]!==void 0&&d.length>0)throw new Error(`${n}: a streamed answer carries no encrypted field`);if(t["x-palbase-upload"]!==void 0)throw new Error(`${n}: an upload goes through storage, which seals nothing \u2014 it carries no encrypted field`);return{request:i,response:d}}}function eh(e){return JSON.stringify(e??null).includes(`"${Ya}":true`)}async function th(e){let t=`${e.method.toUpperCase()} ${e.path}`,n=Ie(Ie(Ie(Ie(e.contract)?.paths)?.[e.path])?.[e.method.toLowerCase()]),s=n?Gt(e.contract,n,t):void 0;if(!s)return{body:e.body,query:e.query,open:async o=>o};let{key:a,header:r}=await Vp(e.key.kid,Pt(e.key.publicKey),Za(e.projectId,e.method,e.path,e.params??[])),i=(o,l)=>o==null?o:Qn(o,l,s.request,(d,p)=>Hs(a,d,p));return{header:r,body:await i(e.body,"/body"),query:await i(e.query,"/query"),open:o=>o===void 0?Promise.resolve(o):Qn(o,"/response",s.response,async(l,d)=>{if(!Ys(d))throw new _e("unopenable",`${t}: ${l} came plain where the contract says it is encrypted`);return Qa(a,l,d)})}}var nh=["GET","POST","PUT","PATCH","DELETE"];function E0(e,t,n){let s=n.split("/").filter(Boolean);for(let[a,r]of Object.entries(e.paths??{})){let i=r?.[t.toLowerCase()];if(typeof i!="object"||i===null)continue;let o=a.split("/").filter(Boolean);if(o.length!==s.length)continue;let l=[],d=!0;for(let p=0;p<s.length&&d;p++)/^\{[^/{}]+\}$/.test(o[p])?l.push(decodeURIComponent(s[p])):d=o[p]===s[p];if(d)return{template:a,params:l,op:i}}}var sh={name:"machines:call",summary:"call a route of a machine's backend as its apps do: the fields its contract marks encrypted sealed, its answer's opened",usage:"<machine> <METHOD> <path> [--data <json>] [--token <access token>]",details:[`palbase machines:call api POST /patients --data '{"name":"Ada","tc":"10000000146"}'`,"The route is found in the machine's contract; a field it marks encrypted (palbase/backend's encrypted() and encrypt()) goes sealed to the project's key in use and comes back opened, as the app's generated client does.","--token is a user's access token, for a route that takes one; without it the call is nobody's."],args:{min:3,max:3},flags:{data:{type:"string",value:"json",description:"the request's body, as JSON"},token:{type:"string",value:"token",description:"a user's access token: the call is theirs"}},scope:"environment",async run(e){let t=await f(e),[n,s,a]=e.args,r=s.toUpperCase();if(!nh.includes(r))throw g(`${s} is not a method a route answers`,`one of ${nh.join(", ")}`);if(!a.startsWith("/"))throw g(`${a}: the route's path starts with /`,"palbase machines:call api GET /patients/p1");let i;if(e.flags.data!==void 0)try{i=JSON.parse(e.flags.data)}catch{throw g("--data is JSON",`--data '{"name":"x"}'`)}let o=D("the machine's name",n),{body:l}=await ye(e.studio,t.env_ref,"GET",`/machines/${o}`),{body:d}=await ye(e.studio,t.env_ref,"GET",`/machines/${o}/openapi`),p=new URL(l.url),u=new URL(a,p);if(u.origin!==p.origin||u.pathname.startsWith("//"))throw g(`${a} is not a path of ${n}`,"palbase machines:call api GET /patients/p1");let m=E0(d,r,u.pathname);if(!m)throw new y("route_not_found",`${n}'s contract has no ${r} ${u.pathname}`,{hint:`palbase machines:contract ${n} lists its routes`});let b=u.search===""?void 0:Object.fromEntries(u.searchParams),w,_="";if(Gt(d,m.op,`${r} ${m.template}`)){_=(await e.studio.get(`/environments/${t.env_ref}`)).platform_id;let{body:F}=await ye(e.studio,t.env_ref,"GET","/secrets/transit"),x=F.keys.find(J=>J.id===F.current);if(!x)throw new y("no_transit_key","the project has no transit key in use: palbase transit:list says what there is");w={kid:x.id,publicKey:x.public_key}}let T=w?await th({contract:d,method:r,path:m.template,params:m.params,body:i,query:b,projectId:_,key:w}):{body:i,query:b,header:void 0,open:async U=>U},S=new URL(p.origin);S.pathname=u.pathname;for(let[U,F]of Object.entries(T.query??{}))S.searchParams.set(U,typeof F=="string"?F:JSON.stringify(F));let $={accept:"application/json"};T.body!==void 0&&($["content-type"]="application/json"),e.flags.token&&($.authorization=`Bearer ${e.flags.token}`),T.header&&($[ut]=T.header);let R=await e.io.fetch(S.href,{method:r,headers:$,body:T.body===void 0?void 0:JSON.stringify(T.body),redirect:"manual"}),P=await R.text(),L=P;if(P!=="")try{L=JSON.parse(P)}catch{}return R.ok&&typeof L=="object"&&(L=await T.open(L)),e.out.result({status:R.status,encrypted:w!==void 0,answer:L},()=>{e.out.line(`${R.status} ${r} ${u.pathname}${w?` (its encrypted fields sealed to ${w.kid}, the answer's opened)`:""}`),P!==""&&e.out.line(typeof L=="string"?L:JSON.stringify(L,null,2))}),R.ok?0:1}};import{createHash as Sm}from"node:crypto";import{lstat as s$,mkdir as a$,mkdtemp as r$,readdir as Ko,readFile as ua,rm as $m,rmdir as i$,writeFile as o$}from"node:fs/promises";import{tmpdir as l$}from"node:os";import{dirname as p$,join as rt,relative as Or,resolve as vm,sep as jr}from"node:path";function O0(e){return e.replace(/\s+/g," ").trim()}var TD=String.raw`
|
|
37
|
+
`)}},Nc={name:"machines:delete",summary:"delete a machine: it stops serving, its address answers nothing",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=e.args[0];if(!e.global.yes){if(!e.interactive)throw new y("confirmation_needed","deleting a machine is confirmed",{hint:"confirm with -y"});if((await e.io.prompt("Type the machine's name to delete it: ")).trim()!==n)throw new y("cancelled","nothing was deleted")}await z(e,t,"DELETE",`/machines/${te(n)}`),e.out.result({deleted:n},()=>e.out.line(`Deleted the machine ${n}.`))}};async function _0(e,t,n){e.out.note(`Following ${n}'s first build\u2026`);let s="";for(let a=0;a<900;a++){let r=await z(e,t,"GET",`/machines/${te(n)}`),i=`${r.state}${r.build?` (${r.build.commit.slice(0,7)})`:""}`;if(i!==s&&e.out.note(` ${i}${r.state_reason?` \u2014 ${r.state_reason}`:""}`),s=i,r.running_version>=1&&r.running_version===r.version&&(r.state==="awake"||r.state==="asleep"))return r;if(r.state==="failed")throw new y("build_failed",`${n}'s build failed${r.state_reason?`: ${r.state_reason}`:""}`,{hint:`palbase machines:builds:log --machine ${n}`});await e.io.sleep(2e3)}throw new y("timeout",`${n} was not serving after 30 minutes`,{hint:`palbase machines:get ${n}`})}function k0(e,t){let n=/^(\d+)([smhd])$/.exec(e);if(n)return new Date(t-Number(n[1])*{s:1e3,m:6e4,h:36e5,d:864e5}[n[2]]).toISOString();if(Number.isNaN(Date.parse(e)))throw g(`--since is a time (2026-10-08T12:00:00Z) or a duration ago (10m, 2h, 1d), not ${JSON.stringify(e)}`);return new Date(e).toISOString()}var Kc={name:"databases:list",summary:"the project's databases, each with the environment that keeps it: size, state, how full",details:["A project's databases are the project's: any machine of the project may be given one, whichever environment keeps it (machines:update --database)."],scope:"environment",async run(e){let t=await f(e),[{databases:n},s]=await Promise.all([z(e,t,"GET","/databases?limit=100"),zs(e.studio,t)]);e.out.result({databases:n},()=>{n.length===0&&e.out.line("No database yet: palbase databases:create makes one."),e.out.table(n,[{header:"name",value:a=>a.name},{header:"env",value:a=>Yn(s,a.environment)},{header:"size",value:a=>a.size},{header:"state",value:a=>`${a.state}${a.deleted_at?" (deleted)":""}`},{header:"used",value:a=>a.used_bytes!==void 0?`${(a.used_bytes/1e6).toFixed(1)} / ${(a.quota_bytes/1e6).toFixed(0)} MB`:""},{header:"host",value:a=>a.host}])})}},Gc={name:"databases:get",summary:"a database in full, with how to connect to it",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=await z(e,t,"GET",`/databases/${te(e.args[0])}`),s=await e.state.databasePasswords(t.env_ref,n.name);e.out.result({...n,passwords_on_this_computer:{owner:s.owner!==void 0,app:s.app!==void 0}},()=>{e.out.line(`${n.name} \u2014 ${n.size}, ${n.state}${n.state_reason?` (${n.state_reason})`:""}`),e.out.line(` host ${n.host}:${n.port} (pooled ${n.pooled_port})`),e.out.line(` allows ${n.allow.length===0?"anyone with the password":n.allow.join(", ")}`),e.out.line(` backups ${n.backup_days} days, any moment of them (databases:restore --to)`),n.used_bytes!==void 0&&e.out.line(` used ${(n.used_bytes/1e6).toFixed(1)} MB of ${(n.quota_bytes/1e6).toFixed(0)} MB`),n.awake_hours_limit&&e.out.line(` awake ${n.awake_hours??0} h this month; the environment's free databases ${n.environment_awake_hours??n.awake_hours??0} of ${n.awake_hours_limit} hours`),e.out.line(` passwords ${s.owner||s.app?`this computer holds ${[s.owner&&"owner",s.app&&"app"].filter(Boolean).join(" and ")}`:"none on this computer (databases:password:reset makes new ones)"}`)})}};function Uc(e){if(e!==void 0)return String(e).split(",").map(t=>t.trim()).filter(t=>t!=="")}var zc={name:"databases:create",summary:"open a database; its passwords are kept on this computer (the platform shows them once)",usage:"[name] [--size <size>] [--allow <ip/cidr,\u2026>] [--backup-days <n>] [--show-passwords]",args:{min:0,max:1},flags:{size:{type:"string",value:"size",description:"its size (palbase databases:sizes lists what is open)"},allow:{type:"string",value:"list",description:"who may connect, as addresses or CIDRs, comma-separated (default: anyone with the password)"},"backup-days":{type:"string",value:"n",description:"how many days of backups to keep, 1 to 35"},"show-passwords":{type:"boolean",description:"print the passwords too (they are kept on this computer either way)"}},scope:"environment",async run(e){let t=await f(e),n={};e.args[0]&&(n.name=e.args[0]),e.flags.size!==void 0&&(n.size=e.flags.size);let s=Uc(e.flags.allow);s&&(n.allow=s);let a=kn(e.flags["backup-days"],"backup-days");a!==void 0&&(n.backup_days=a),await v(e,t,`open a database ${e.args[0]??"main"}${n.size?` (${n.size})`:""}`);let r=await z(e,t,"POST","/databases",n);await e.state.keepDatabasePasswords(t.env_ref,r.name,{owner:r.credentials.owner.password,app:r.credentials.app.password});let i=e.flags["show-passwords"]===!0,{credentials:o,...l}=r;e.out.result(i?r:{...l,credentials:{owner:bo(o.owner),app:bo(o.app)}},()=>{e.out.line(`Opened the database ${r.name} (${r.size}) at ${r.host}.`),e.out.line("Its passwords are kept on this computer: palbase db:url and db:shell use them."),i&&(e.out.line(`owner: ${r.credentials.owner.password??""}`),e.out.line(`app: ${r.credentials.app.password??""}`))})}},yo="[YOUR-PASSWORD]";function bo(e){let{password:t,...n}=e,s={};for(let[a,r]of Object.entries(n))s[a]=typeof r=="string"?S0(r,t):r;return s}function S0(e,t){let n=e.replace(/(postgres(?:ql)?:\/\/[^:/@\s'"]+:)[^@\s'"]*(@)/gi,`$1${yo}$2`).replace(/([?&;]password=)[^&;\s'"]*/gi,`$1${yo}`);if(t)for(let s of new Set([t,encodeURIComponent(t),new URLSearchParams({p:t}).toString().slice(2)]))n=n.split(s).join(yo);return n}var Bc={name:"databases:update",summary:"change a database's size, who may connect to it, or how long its backups are kept",usage:'<name> [--size <size>] [--allow <list>|""] [--backup-days <n>] [--wait]',details:["A new size is taken at once and the database moves to it serving on (palbase databases:sizes lists them): its sessions on the direct port end once, when its primary moves, and new logins wait a few seconds then."],args:{min:1,max:1},flags:{size:{type:"string",value:"size",description:"the size to move it to"},allow:{type:"string",value:"list",description:'who may connect (comma-separated addresses or CIDRs); "" for anyone with the password'},"backup-days":{type:"string",value:"n",description:"how many days of backups to keep, 1 to 35"},wait:{type:"boolean",description:"with --size: follow the move until it serves at the new size"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0],s={},a=e.flags.size;if(a!==void 0){if(a==="")throw g("--size is one of palbase databases:sizes");s.size=a}let r=Uc(e.flags.allow);r&&(s.allow=r);let i=kn(e.flags["backup-days"],"backup-days");if(i!==void 0&&(s.backup_days=i),Object.keys(s).length===0)throw g("nothing to change: --size, --allow or --backup-days");await v(e,t,`change the database ${n}: ${Object.keys(s).join(", ")}`);let o=await z(e,t,"PATCH",`/databases/${te(n)}`,s);a!==void 0&&e.flags.wait===!0&&(o=await $0(e,t,n,a)),e.out.result(o,()=>{a!==void 0&&e.out.line(o.state==="resizing"?`${o.name} is moving to ${a}, serving on: its sessions on the direct port end once, when its primary moves (palbase databases:get ${o.name} follows it).`:`${o.name} serves at ${o.size} (${o.state}).`),(r||i!==void 0)&&e.out.line(`${o.name}: allows ${o.allow.length===0?"anyone with the password":o.allow.join(", ")}; backups ${o.backup_days} days.`)})}};async function $0(e,t,n,s){e.out.note(`Following ${n}'s move to ${s}\u2026`);let a="";for(let r=0;r<900;r++){let i=await z(e,t,"GET",`/databases/${te(n)}`),o=`${i.state}${i.state_reason?` \u2014 ${i.state_reason}`:""}`;if(o!==a&&e.out.note(` ${o}`),a=o,i.size===s&&i.state!=="resizing"&&i.state!=="starting"){if(i.state==="failed")throw new y("resize_failed",`${n} did not come up at ${s}${i.state_reason?`: ${i.state_reason}`:""}`,{hint:`palbase databases:get ${n}`});return i}if(i.size!==s)throw new y("resize_changed",`${n} is asked for ${i.size} now, not ${s}: another change came`,{hint:`palbase databases:get ${n}`});await e.io.sleep(2e3)}throw new y("timeout",`${n} was still moving to ${s} after 30 minutes; it serves on meanwhile`,{hint:`palbase databases:get ${n}`})}var Fc={name:"databases:password:reset",summary:"make a database role's password new; it is kept on this computer, the old one stops working",usage:"<name> --role owner|app [--show-password]",details:["The app role's new password reaches the machines given the database as they roll out with it; they keep serving."],args:{min:1,max:1},flags:{role:{type:"string",value:"role",description:"owner (migrations, the console) or app (what the machines use)"},"show-password":{type:"boolean",description:"print it too"}},scope:"environment",async run(e){let t=e.flags.role;if(t!=="owner"&&t!=="app")throw g("--role is owner or app");let n=await f(e);await v(e,n,`make the ${t} password of ${e.args[0]} new`);let a=(await z(e,n,"POST",`/databases/${te(e.args[0])}/password`,{role:t}))[t];if(!a?.password)throw new y("no_password","the platform answered no password");await e.state.keepDatabasePasswords(n.env_ref,e.args[0],{[t]:a.password}),await P0(e,n,e.args[0]),e.out.result(e.flags["show-password"]===!0?a:bo(a),()=>{e.out.line(`The ${t} password of ${e.args[0]} is new and kept on this computer.`),e.flags["show-password"]===!0&&e.out.line(a.password??"")})}};async function P0(e,t,n){for(let s=0;s<60;s++){if((await z(e,t,"GET",`/databases/${te(n)}`)).password_changing!==!0)return;s===0&&e.out.note(`Waiting for ${n} to take the new password\u2026`),await e.io.sleep(1e3)}throw new y("timeout",`${n} had not taken the new password after a minute; it is kept here and works once it has`,{hint:`palbase databases:get ${n}`})}var Jc={name:"databases:restore",summary:"bring a database back to a moment of its backups",usage:"<name> --to <time>",args:{min:1,max:1},flags:{to:{type:"string",value:"time",description:"the moment, as an RFC 3339 time (2026-10-08T12:00:00Z)"}},scope:"environment",async run(e){let t=e.flags.to;if(!t||Number.isNaN(Date.parse(t)))throw g("--to is the moment to go back to, as an RFC 3339 time");let n=await f(e);await v(e,n,`bring ${e.args[0]} back to ${t} (what was written since goes)`);let s=await z(e,n,"POST",`/databases/${te(e.args[0])}/restore`,{to:new Date(t).toISOString()});e.out.result(s,()=>e.out.line(`${s.name} is being brought back to ${t} \u2014 ${s.state}.`))}};function _o(e,t,n,s,a,r,i=!1){return{name:e,summary:t,usage:"<name>",args:{min:1,max:1},scope:"environment",async run(o){let l=await f(o),d=o.args[0];if(n==="DELETE"||s==="/purge"){if(!o.global.yes){if(!o.interactive)throw new y("confirmation_needed",`${a(d)} is confirmed`,{hint:"confirm with -y"});if((await o.io.prompt("Type the database's name to go ahead: ")).trim()!==d)throw new y("cancelled","nothing was changed")}}else await v(o,l,a(d));await z(o,l,n,`/databases/${te(d)}${s}`),i&&await o.state.forgetDatabase(l.env_ref,d),o.out.result({database:d,done:e},()=>o.out.line(r(d)))}}}var Wc=_o("databases:delete","delete a database (the platform keeps it 7 days to take back)","DELETE","",e=>`deleting the database ${e}`,e=>`Deleted ${e}; databases:undelete takes it back within 7 days.`),Vc=_o("databases:undelete","take back a database deleted in the last 7 days","POST","/undelete",e=>`take back the database ${e}`,e=>`${e} is back.`),Hc=_o("databases:purge","delete a deleted database for good, now","POST","/purge",e=>`purging the database ${e} for good`,e=>`${e} is purged.`,!0),Yc={name:"github:connect",summary:"link the environment to GitHub: Palbase Cloud's GitHub app on the account whose repositories machines are built from",usage:"[--device | --github-token-stdin | --from <env> [--repo <owner/name>\u2026]] [--installation <account|id>] [--all-envs]",details:["Opens GitHub; back from it, the page shows the account and you link it by writing the environment's ref.","--from <env>: the installation another environment of the organization linked (its slug in this project, or its ref), linked here too with no GitHub sign-in \u2014 a program that opens a project for each product (an admin, or an admin access token). The environment reaches what the GitHub user who linked it there can push to.","--repo <owner/name> (given again for more): with --from, the environment reaches those repositories of the installation alone, never one it reaches later \u2014 a product's environment builds nothing of another product's.","--device: no browser here \u2014 GitHub's device flow (a code you enter at github.com/login/device on any device); the GitHub token stays in memory.","--all-envs links every environment of the project the same way."],flags:{device:{type:"boolean",description:"GitHub's device flow, for a computer with no browser (a server, an agent)"},"github-token-stdin":{type:"boolean",description:"a GitHub user's token from stdin (CI): the installations it reaches, no browser and no code"},installation:{type:"string",value:"account|id",description:"which installation to link, when the GitHub user reaches more than one (--device)"},"all-envs":{type:"boolean",description:"link every environment of the project"},from:{type:"string",value:"env",description:"another environment of the organization whose linked installation this one shares (its slug in this project, or its ref): no GitHub sign-in"},repo:{type:"string",multiple:!0,value:"owner/name",description:"with --from: the repositories it reaches of the installation, and no other (given again for more)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags["all-envs"]===!0?(await Nt(e)).map(_e):[t],s=e.flags.repo;if(typeof e.flags.from=="string"){if(e.flags.device===!0||e.flags["github-token-stdin"]===!0)throw g("--from links what another environment linked: no GitHub sign-in goes with it");for(let d of s??[])if(!/^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100}$/.test(d))throw g(`--repo names a repository as owner/name: ${JSON.stringify(d)} is none`);await A0(e,t,n,e.flags.from,s);return}if(s!==void 0)throw g("--repo goes with --from: it narrows what a shared installation reaches");let a=await z(e,t,"POST","/machines/github/connect"),r=e.flags["github-token-stdin"]===!0;if(!r&&e.flags.device!==!0&&e.interactive&&n.length===1){let d=await e.io.openBrowser(a.url);e.out.result({url:a.url,expires_at:a.expires_at,ref:t.env_ref},()=>e.out.line(d?`Opened GitHub. When it asks, link the environment ${t.env_ref}.`:`Open ${a.url} (good until ${a.expires_at}) and link the environment ${t.env_ref}.`));return}let i=r?await xe(e,"a GitHub user's token"):await R0(e,a.client_id),o=await T0(e,i),l=[];for(let d of n){await v(e,d,`link the GitHub account ${o.account}`);let p=await z(e,d,"POST","/machines/github/installations",{installation_id:o.id,user_token:i});l.push({ref:d.env_ref,account:p.account})}e.out.result({linked:l},()=>{for(let d of l)e.out.line(`Linked ${d.account} to ${d.ref}.`)})}};async function A0(e,t,n,s,a){let r=await Re(e.studio),i=r.find(u=>u.ref===s)??r.find(u=>u.project_id===t.project_id&&u.slug===s);if(!i||i.organization_id!==t.org_id)throw new y("no_such_environment",`no environment ${JSON.stringify(s)} of ${t.org_name} besides this one`,{hint:"name it by its slug in this project, or by its ref (palbase projects:list)"});let o=(await z(e,_e(i),"GET","/machines/github/installations")).installations,l=e.flags.installation,d=l!==void 0?o.filter(u=>String(u.installation_id)===l||u.account.toLowerCase()===l.toLowerCase()):o;if(d.length===0)throw new y("no_installation",`${i.slug} (${i.ref}) links no GitHub account${l!==void 0?` ${JSON.stringify(l)}`:""}`,{hint:"link it there first: palbase github:connect -E <env>"});if(d.length>1)throw g("which installation? --installation <account|id>",`${i.slug} links ${d.map(u=>u.account).join(", ")}`);let p=[];for(let u of n){if(u.env_ref===i.ref)continue;await v(e,u,`link the GitHub account ${d[0].account}${a?` for ${a.join(", ")} alone`:""}, as ${i.slug} (${i.ref}) links it`);let m=await e.studio.post(`/environments/${D("the environment's ref",u.env_ref)}/github/installations`,{installation_id:d[0].installation_id,from:i.ref,...a?{repositories:a}:{}});p.push({ref:u.env_ref,account:m.account})}e.out.result({linked:p},()=>{for(let u of p)e.out.line(`Linked ${u.account} to ${u.ref}, as ${i.slug} (${i.ref}) links it.`)})}async function R0(e,t){let n=o=>({method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(o)}),s=await e.io.fetch("https://github.com/login/device/code",n({client_id:t}));if(!s.ok)throw new y("github_unavailable",`GitHub did not start the sign-in: ${s.status}`);let a=await s.json();e.out.note(""),e.out.note(` Enter this code at ${a.verification_uri}: ${a.user_code}`),e.out.note("");let r=Math.max(1,a.interval??5),i=e.io.now()+(a.expires_in??900)*1e3;for(;e.io.now()<i;){await e.io.sleep(r*1e3);let o;try{o=await e.io.fetch("https://github.com/login/oauth/access_token",n({client_id:t,device_code:a.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}))}catch{continue}if(o.status>=500||o.status===429)continue;let l=await o.json().catch(()=>({}));if(l.access_token)return l.access_token;if(l.error!=="authorization_pending"){if(l.error==="slow_down"){r+=5;continue}if(l.error==="expired_token")break;throw l.error==="access_denied"?new y("access_denied","the sign-in was denied on GitHub"):new y("github_denied",`GitHub's sign-in ended: ${l.error??o.status}`)}}throw new y("expired_code","GitHub's code expired before it was entered",{hint:"run the command again"})}async function T0(e,t){let n=await e.io.fetch("https://api.github.com/user/installations?per_page=100",{headers:{authorization:`Bearer ${t}`,accept:"application/vnd.github+json","x-github-api-version":"2022-11-28"}});if(!n.ok)throw new y("github_unavailable",`GitHub did not list your installations: ${n.status}`);let s=(await n.json()).installations.map(r=>({id:r.id,account:r.account.login}));if(s.length===0)throw new y("no_installation","Palbase Cloud is installed on no GitHub account you reach",{hint:"install it (palbase github:connect, in a browser) or have the account's owner install it"});let a=e.flags.installation;if(a!==void 0){let r=s.find(i=>String(i.id)===a||i.account.toLowerCase()===a.toLowerCase());if(!r)throw new y("no_such_installation",`you reach no installation ${JSON.stringify(a)}: ${s.map(i=>i.account).join(", ")}`);return r}if(s.length===1)return s[0];if(!e.interactive)throw g("which installation? --installation <account>",`yours: ${s.map(r=>r.account).join(", ")}`);for(s.forEach((r,i)=>e.out.note(` ${i+1}) ${r.account}`));;){let r=Number((await e.io.prompt(`Which account? [1-${s.length}] `)).trim());if(Number.isInteger(r)&&r>=1&&r<=s.length)return s[r-1]}}var Xc={name:"github:list",summary:"the GitHub accounts linked to the environment, and who linked each",scope:"environment",async run(e){let t=await f(e),{installations:n}=await z(e,t,"GET","/machines/github/installations");e.out.result({installations:n},()=>{n.length===0&&e.out.line("No GitHub account is linked: palbase github:connect links one."),e.out.table(n,[{header:"account",value:s=>s.account},{header:"installation",value:s=>String(s.installation_id)},{header:"linked by",value:s=>s.linked_by}])})}},Zc={name:"github:repos",summary:"the repositories machines of the environment may be built from",scope:"environment",async run(e){let t=await f(e),{repositories:n}=await z(e,t,"GET","/machines/github/repositories");e.out.result({repositories:n},()=>e.out.table(n,[{header:"repository",value:s=>s.repository},{header:"default branch",value:s=>s.default_branch},{header:"",value:s=>s.private?"private":""}]))}},Qc={name:"github:disconnect",summary:"unlink a GitHub account from the environment; its repositories are no longer built",usage:"<account|installation-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),{installations:n}=await z(e,t,"GET","/machines/github/installations"),s=n.find(a=>String(a.installation_id)===e.args[0]||a.account.toLowerCase()===e.args[0].toLowerCase());if(!s)throw new y("no_such_installation",`no linked GitHub account ${JSON.stringify(e.args[0])}`);await v(e,t,`unlink the GitHub account ${s.account}`),await z(e,t,"DELETE",`/machines/github/installations/${s.installation_id}`),e.out.result({unlinked:s},()=>e.out.line(`Unlinked ${s.account}.`))}};var Ie=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0;function Gt(e,t,n){let s=Ie(Ie(Ie(e)?.components)?.schemas)??{},a=(p,u)=>{let m=new Set,b=(_,T,S)=>{let $=Ie(_);if(!$)return;if(typeof $.$ref=="string"){if(S.has($.$ref)||!$.$ref.startsWith("#/components/schemas/"))return;b(s[$.$ref.slice(21)],T,new Set(S).add($.$ref));return}if($[Ya]===!0){m.add(T);return}for(let P of["anyOf","oneOf","allOf"]){let L=$[P];if(Array.isArray(L))for(let U of L)b(U,T,S)}let R=Ie($.properties);if(R)for(let[P,L]of Object.entries(R))b(L,`${T}/${er(P)}`,S);Ie($.items)&&b($.items,`${T}/*`,S);for(let P of["additionalProperties","patternProperties","prefixItems"])if($[P]!==void 0&&w($[P],new Set(S)))throw new Error(`${n}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},w=(_,T)=>{if(Array.isArray(_))return _.some($=>w($,T));let S=Ie(_);return S?S[Ya]===!0?!0:typeof S.$ref=="string"&&!T.has(S.$ref)&&S.$ref.startsWith("#/components/schemas/")?(T.add(S.$ref),w(s[S.$ref.slice(21)],T)):Object.values(S).some($=>typeof $=="object"&&$!==null&&w($,T)):!1};return b(p,u,new Set),[...m]},r=p=>Ie(Ie(Ie(p)?.["application/json"])?.schema),i=[];i.push(...a(r(Ie(t.requestBody)?.content),"/body"));for(let p of Array.isArray(t.parameters)?t.parameters:[]){let u=Ie(p);if(!u)continue;let m=a(u.schema,`/query/${er(String(u.name))}`);if(m.length!==0){if(u.in!=="query")throw new Error(`${n}: ${String(u.in)} parameter ${String(u.name)} is marked encrypted \u2014 a body's or a query's field is`);if(m.some(b=>b.split("/").length!==3))throw new Error(`${n}: an encrypted query field is one of the query's own names`);i.push(...m)}}let o=Ie(t.responses)??{},l=Object.keys(o).filter(p=>/^2\d\d$/.test(p)).sort((p,u)=>p==="200"?-1:u==="200"?1:p.localeCompare(u)),d=l.length>0?a(r(Ie(o[l[0]])?.content),"/response"):[];if(i.length+d.length!==0){if(t["x-palbase-sse"]!==void 0&&d.length>0)throw new Error(`${n}: a streamed answer carries no encrypted field`);if(t["x-palbase-upload"]!==void 0)throw new Error(`${n}: an upload goes through storage, which seals nothing \u2014 it carries no encrypted field`);return{request:i,response:d}}}function eh(e){return JSON.stringify(e??null).includes(`"${Ya}":true`)}async function th(e){let t=`${e.method.toUpperCase()} ${e.path}`,n=Ie(Ie(Ie(Ie(e.contract)?.paths)?.[e.path])?.[e.method.toLowerCase()]),s=n?Gt(e.contract,n,t):void 0;if(!s)return{body:e.body,query:e.query,open:async o=>o};let{key:a,header:r}=await Vp(e.key.kid,Pt(e.key.publicKey),Za(e.projectId,e.method,e.path,e.params??[])),i=(o,l)=>o==null?o:Qn(o,l,s.request,(d,p)=>Hs(a,d,p));return{header:r,body:await i(e.body,"/body"),query:await i(e.query,"/query"),open:o=>o===void 0?Promise.resolve(o):Qn(o,"/response",s.response,async(l,d)=>{if(!Ys(d))throw new ke("unopenable",`${t}: ${l} came plain where the contract says it is encrypted`);return Qa(a,l,d)})}}var nh=["GET","POST","PUT","PATCH","DELETE"];function E0(e,t,n){let s=n.split("/").filter(Boolean);for(let[a,r]of Object.entries(e.paths??{})){let i=r?.[t.toLowerCase()];if(typeof i!="object"||i===null)continue;let o=a.split("/").filter(Boolean);if(o.length!==s.length)continue;let l=[],d=!0;for(let p=0;p<s.length&&d;p++)/^\{[^/{}]+\}$/.test(o[p])?l.push(decodeURIComponent(s[p])):d=o[p]===s[p];if(d)return{template:a,params:l,op:i}}}var sh={name:"machines:call",summary:"call a route of a machine's backend as its apps do: the fields its contract marks encrypted sealed, its answer's opened",usage:"<machine> <METHOD> <path> [--data <json>] [--token <access token>]",details:[`palbase machines:call api POST /patients --data '{"name":"Ada","tc":"10000000146"}'`,"The route is found in the machine's contract; a field it marks encrypted (palbase/backend's encrypted() and encrypt()) goes sealed to the project's key in use and comes back opened, as the app's generated client does.","--token is a user's access token, for a route that takes one; without it the call is nobody's."],args:{min:3,max:3},flags:{data:{type:"string",value:"json",description:"the request's body, as JSON"},token:{type:"string",value:"token",description:"a user's access token: the call is theirs"}},scope:"environment",async run(e){let t=await f(e),[n,s,a]=e.args,r=s.toUpperCase();if(!nh.includes(r))throw g(`${s} is not a method a route answers`,`one of ${nh.join(", ")}`);if(!a.startsWith("/"))throw g(`${a}: the route's path starts with /`,"palbase machines:call api GET /patients/p1");let i;if(e.flags.data!==void 0)try{i=JSON.parse(e.flags.data)}catch{throw g("--data is JSON",`--data '{"name":"x"}'`)}let o=D("the machine's name",n),{body:l}=await ye(e.studio,t.env_ref,"GET",`/machines/${o}`),{body:d}=await ye(e.studio,t.env_ref,"GET",`/machines/${o}/openapi`),p=new URL(l.url),u=new URL(a,p);if(u.origin!==p.origin||u.pathname.startsWith("//"))throw g(`${a} is not a path of ${n}`,"palbase machines:call api GET /patients/p1");let m=E0(d,r,u.pathname);if(!m)throw new y("route_not_found",`${n}'s contract has no ${r} ${u.pathname}`,{hint:`palbase machines:contract ${n} lists its routes`});let b=u.search===""?void 0:Object.fromEntries(u.searchParams),w,_="";if(Gt(d,m.op,`${r} ${m.template}`)){_=(await e.studio.get(`/environments/${t.env_ref}`)).platform_id;let{body:F}=await ye(e.studio,t.env_ref,"GET","/secrets/transit"),x=F.keys.find(J=>J.id===F.current);if(!x)throw new y("no_transit_key","the project has no transit key in use: palbase transit:list says what there is");w={kid:x.id,publicKey:x.public_key}}let T=w?await th({contract:d,method:r,path:m.template,params:m.params,body:i,query:b,projectId:_,key:w}):{body:i,query:b,header:void 0,open:async U=>U},S=new URL(p.origin);S.pathname=u.pathname;for(let[U,F]of Object.entries(T.query??{}))S.searchParams.set(U,typeof F=="string"?F:JSON.stringify(F));let $={accept:"application/json"};T.body!==void 0&&($["content-type"]="application/json"),e.flags.token&&($.authorization=`Bearer ${e.flags.token}`),T.header&&($[ut]=T.header);let R=await e.io.fetch(S.href,{method:r,headers:$,body:T.body===void 0?void 0:JSON.stringify(T.body),redirect:"manual"}),P=await R.text(),L=P;if(P!=="")try{L=JSON.parse(P)}catch{}return R.ok&&typeof L=="object"&&(L=await T.open(L)),e.out.result({status:R.status,encrypted:w!==void 0,answer:L},()=>{e.out.line(`${R.status} ${r} ${u.pathname}${w?` (its encrypted fields sealed to ${w.kid}, the answer's opened)`:""}`),P!==""&&e.out.line(typeof L=="string"?L:JSON.stringify(L,null,2))}),R.ok?0:1}};import{createHash as Sm}from"node:crypto";import{lstat as s$,mkdir as a$,mkdtemp as r$,readdir as Ko,readFile as ua,rm as $m,rmdir as i$,writeFile as o$}from"node:fs/promises";import{tmpdir as l$}from"node:os";import{dirname as p$,join as rt,relative as Or,resolve as vm,sep as jr}from"node:path";function O0(e){return e.replace(/\s+/g," ").trim()}var TD=String.raw`
|
|
38
38
|
import Foundation
|
|
39
39
|
|
|
40
40
|
/// Any JSON value: what a contract leaves open.
|
|
@@ -553,28 +553,28 @@ public typealias JSONValue = JsonElement
|
|
|
553
553
|
// MARK: - Gateways (@Gateway)
|
|
554
554
|
|
|
555
555
|
`;for(let d of a)o+=gS(d,i)+`
|
|
556
|
-
`}return o}function Rk(e){if(!e.transit)throw new Error("the contract marks encrypted fields: the client needs the project's id and signing key (palbase apps:sync gives them)");return", transit: PBTransitConfig(projectID: "+Le(e.transit.projectId)+", signer: "+Le(e.transit.signer)+")"}var Tk=new Set("associatedtype borrowing class consuming deinit enum extension fileprivate func import init inout internal let operator precedencegroup private protocol public rethrows static struct subscript typealias var break case catch continue default defer do else fallthrough for guard if in repeat return throw switch where while as await false is nil self super throws true try".split(" "));function Ek(e){if(!/^[a-z][A-Za-z0-9]*$/.test(e.client)||Tk.has(e.client))throw new Error(`client ${JSON.stringify(e.client)} is not a lowerCamel Swift identifier`);for(let t of e.header)if(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/.test(t))throw new Error(`header line ${JSON.stringify(t)} would end its comment, or read as other than it is`)}function hr(e,t){let n=Ro.get(t);if(n!==void 0)throw new Error(`${e} declares the type ${t}, which in the app would stand in for ${n}'s ${t}: rename it in the backend`)}function Ck(e,t,n,s){hr(`client ${JSON.stringify(t)}`,n),s.set(de(n),`client ${JSON.stringify(t)}`);for(let a of e){let r=yr(a.operationID);for(let i=1;i<r.length;i++){let o=`operation ${JSON.stringify(a.operationID)}, in namespace ${JSON.stringify(r.slice(0,i).join("."))},`,l=Co(r.slice(0,i),n);hr(o,l),s.has(de(l))||s.set(de(l),`namespace ${JSON.stringify(r.slice(0,i).join("."))}`)}}}function jk(e){let t='"';for(let n of e){let s=n.codePointAt(0);if(s>=55296&&s<=57343)throw new Error(`machine ${JSON.stringify(e)} is not a Swift string`);n==='"'||n==="\\"?t+="\\"+n:s>=32&&s<127?t+=n:t+="\\u{"+s.toString(16)+"}"}return t+'"'}var Ok=new Intl.Segmenter("en",{granularity:"grapheme"});function bt(e){return Array.from(Ok.segment(e),t=>t.segment)}function de(e){return e.normalize("NFC")}function ke(e,t){return de(e)===de(t)}function Et(e,t){let n=Array.from(de(e)),s=Array.from(de(t));for(let a=0;a<n.length&&a<s.length;a++){let r=n[a].codePointAt(0)-s[a].codePointAt(0);if(r!==0)return r}return n.length-s.length}var Gh=e=>[...e].sort(Et);function Tn(e,t,n){let s=[],a="";for(let r of bt(e))ke(r,t)?((!n||a!=="")&&s.push(a),a=""):a+=r;return(!n||a!=="")&&s.push(a),s}function ps(e,t,n){let s=bt(e),a=bt(t),r="";for(let i=0;i<s.length;)i+a.length<=s.length&&a.every((o,l)=>ke(s[i+l],o))?(r+=n,i+=a.length):r+=s[i++];return r}var xh=new WeakMap;function jo(e){let t=xh.get(e);if(t===void 0){t=new Map;for(let n of Object.keys(e))e[n]!==void 0&&(t.delete(de(n)),t.set(de(n),[n,e[n]]));xh.set(e,t)}return t}var N=(e,t)=>jo(e).get(de(t))?.[1],rn=(e,t)=>jo(e).has(de(t)),Ct=e=>[...jo(e).values()],Oo=e=>Ct(e).map(([t])=>t);function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ft(e){return Array.isArray(e)?e:void 0}function Ae(e){return typeof e=="string"?e:void 0}function fr(e){if(typeof e=="boolean")return e;if(e===1)return!0;if(e===0)return!1}function Mk(e){if(typeof e=="number")return e;if(typeof e=="boolean")return e?1:0}var Rn=(e,t=!1)=>({kind:e,nullable:t,props:[],enumVals:[]}),Uh=2n**63n-1n,zh=-(2n**63n);function xk(e){return Number.isNaN(e)?0n:e>=2**63?Uh:e<=-(2**63)?zh:BigInt(Math.trunc(e))}function Ik(e,t=new At){let n=H(e);if(n===void 0)throw new Error("openapi.json is not valid JSON: root is not an object");let s=H(N(n,"paths"));if(s===void 0)throw new Error("openapi.json has no `paths`");let a=[];for(let[r,i]of Ct(s)){let o=H(i);if(o!==void 0)for(let[l,d]of Ct(o)){let p=H(d);if(p===void 0)continue;let u=Ae(N(p,"operationId"))??"";if(u==="")continue;let m={where:`operation ${JSON.stringify(u)}`,budget:t,through:u.length,path:new Set};a.push({operationID:u,method:l.toUpperCase(),path:r,pathParams:Gk(r),input:Nk(p,m),output:Uk(p,m),headers:Lh(p,"header",m),query:Lh(p,"query",m),errors:Lk(p,m),upload:Dk(p),sse:rn(p,"x-palbase-sse"),idempotent:Kk(p),attests:N(p,"x-palbase-attest")===!0,...pS(Gt(e,p,`${l.toUpperCase()} ${r}`))})}}return a.sort((r,i)=>Et(r.operationID,i.operationID)),a}function Lk(e,t){let n=H(N(e,"x-palbase-errors"));if(n===void 0)return[];let s=H(N(e,"responses")),a=[];for(let[r,i]of Ct(n)){let o=H(i);if(o===void 0)continue;let l=Mk(N(o,"status"))??0,d=Ae(N(o,"code"))??"",p=Ae(N(o,"description"))??"",u=fr(N(o,"hasData"))??!1;if(d===""||l===0)continue;let m={name:r,code:d,status:xk(l),description:p};u&&(m.data=qk(s,m.status,d,{...t,through:t.through+r.length})),a.push(m)}return a.sort((r,i)=>Et(r.name,i.name)),a}function Dk(e){let t=H(N(e,"x-palbase-upload"));if(t===void 0||Ct(t).length===0)return;let n=Ae(N(t,"bucket"))??"",s=Ae(N(t,"pathTemplate"))??"";if(!(n===""||s===""))return{bucket:n,pathTemplate:s}}function qk(e,t,n,s){if(e===void 0)return;let a=H(N(e,t.toString()));if(a===void 0)return;let r=H(N(a,"content"));if(r===void 0)return;let i=H(N(r,"application/json"));if(i===void 0)return;let o=H(N(i,"schema"));if(o===void 0)return;let l=ft(N(o,"oneOf"));if(l!==void 0){for(let d of l){let p=H(d);if(p===void 0)continue;let u=H(N(p,"properties")),m=u===void 0?void 0:H(N(u,"error"));if(m===void 0)continue;let b=Ae(N(m,"const"));if(b!==void 0&&ke(b,n))return Ih(p,s)}return}return Ih(o,s)}function Ih(e,t){let n=H(N(e,"properties"));if(n===void 0)return;let s=H(N(n,"data"));if(s!==void 0)return on(s,s,t)}function Nk(e,t){let n=H(N(e,"requestBody"));if(n!==void 0)return Fh(N(n,"content"),t)}var Bh=e=>de(e).toLowerCase()==="idempotency-key";function Kk(e){return(ft(N(e,"parameters"))??[]).some(t=>{let n=H(t);return n!==void 0&&ke(Ae(N(n,"in"))??"","header")&&Bh(Ae(N(n,"name"))??"")})}function Lh(e,t,n){let s=ft(N(e,"parameters"));if(s===void 0||s.length===0)return;let a=[];for(let r of s){let i=H(r);if(i===void 0||!ke(Ae(N(i,"in"))??"",t))continue;let o=Ae(N(i,"name"))??"";if(o===""||t==="header"&&Bh(o))continue;let l=fr(N(i,"required"))??!1,d=H(N(i,"schema"));a.push({name:o,schema:d===void 0?Rn("string"):on(d,d,{...n,through:n.through+o.length}),required:l})}if(a.length!==0)return a.sort((r,i)=>Et(r.name,i.name)),{kind:"object",nullable:!1,props:a,enumVals:[]}}function Gk(e){let t=[],n=e;for(;;){let s=n.indexOf("{");if(s<0)break;let a=n.indexOf("}",s);if(a<0)break;let r=n.slice(s+1,a);r!==""&&t.push(r),n=n.slice(a+1)}return t}function Uk(e,t){let n=H(N(e,"responses"));if(n===void 0)return;let s=Oo(n).filter(a=>ke(bt(a)[0]??"","2")&&!ke(a,"200")&&!ke(a,"201"));for(let a of["200","201",...Gh(s)]){let r=H(N(n,a));if(r===void 0)continue;let i=Fh(N(r,"content"),t);if(i!==void 0)return i}}function Fh(e,t){let n=H(e);if(n===void 0)return;let s=H(N(n,"application/json"));if(s===void 0)return;let a=H(N(s,"schema"));if(a!==void 0&&!rn(a,"$ref"))return on(a,a,t)}function on(e,t,n,s=0,a=n.through){let r=e,i=Fk(r,t);if(i!==void 0&&s<16){if(n.path.has(i))throw new Error(`${n.where}: the $ref ${JSON.stringify(Ae(N(r,"$ref")))} points back into a schema it is part of, a recursive schema, which no Swift type is written for: refused`);r=i}else if(rn(r,"$ref"))return Rn("any");let o=H(N(r,"properties")),l=(o===void 0?0:Dh(Oo(o)))+Dh(ft(N(r,"enum"))??[]);n.budget.charge(n.where,s,a,l),n.path.add(r);try{return zk(r,t,n,s,a)}finally{n.path.delete(r)}}var Dh=e=>e.reduce((t,n)=>t+(Ae(n)?.length??0),0);function zk(e,t,n,s,a){let r=fr(N(e,"nullable"))??!1,i=ft(N(e,"type"));if(i!==void 0)for(let p of i)Ae(p)==="null"&&(r=!0);let o=ft(N(e,"anyOf"))??ft(N(e,"oneOf"));if(o!==void 0){let p=o.map(H).filter(m=>m!==void 0),u=p.filter(m=>!Bk(m));if(p.length===o.length&&u.length===1&&p.length>u.length){let m=on(u[0],t,n,s+1,a);return m.nullable=!0,m}}let l=ft(N(e,"enum"));if(l!==void 0){let p=[],u=!0;for(let m of l){let b=Ae(m);if(b===void 0){u=!1;break}p.push(b)}if(u&&p.length>0)return{kind:"enum",nullable:r,props:[],enumVals:p}}let d=Ae(N(e,"type"))??"";if(d===""&&i!==void 0)for(let p of i){let u=Ae(p);u!==void 0&&(u==="null"?r=!0:d===""&&(d=u))}switch(d){case"string":case"number":case"integer":case"boolean":return Rn(d,r);case"array":{let p=H(N(e,"items"));return{kind:"array",nullable:r,props:[],elem:p===void 0?Rn("any"):on(p,t,n,s+1,a),enumVals:[]}}case"object":return qh(e,r,t,n,s,a);default:return rn(e,"properties")||rn(e,"additionalProperties")?qh(e,r,t,n,s,a):Rn("any",r)}}function qh(e,t,n,s,a,r){let i=H(N(e,"properties"))??{},o=N(e,"additionalProperties"),l,d=H(o);if(d!==void 0?l=on(d,n,s,a+1,r):(fr(o)===!0||Ct(i).length===0&&!rn(e,"additionalProperties"))&&(l=Rn("any")),l!==void 0)return{kind:Ct(i).length===0?"map":"mixedObject",nullable:t,props:[],elem:l,enumVals:[]};let p=new Set;for(let m of ft(N(e,"required"))??[]){let b=Ae(m);b!==void 0&&p.add(de(b))}let u=[];for(let m of Gh(Oo(i))){let b=H(N(i,m));u.push({name:m,schema:b===void 0?Rn("any"):on(b,n,s,a+1,r+m.length),required:p.has(de(m))})}return{kind:"object",nullable:t,props:u,enumVals:[]}}function Bk(e){let t=N(e,"type");if(typeof t=="string")return t==="null";let n=ft(t);if(n!==void 0){let s=n.filter(a=>typeof a=="string");return s.length===1&&s[0]==="null"}return!1}function Fk(e,t){let n=Ae(N(e,"$ref"));if(n===void 0)return;let s=bt(n);if(!ke(s[0]??"","#")||!ke(s[1]??"","/"))return;let a=t;for(let r of Tn(s.slice(2).join(""),"/",!0)){let i=ps(ps(r,"~1","/"),"~0","~"),o=H(a),l=ft(a),d=Qk(i);if(o!==void 0&&rn(o,i))a=N(o,i);else if(l!==void 0&&d!==void 0&&d>=0n&&d<BigInt(l.length))a=l[Number(d)];else return}return H(a)}function Jk(e,t=new At){let n=H(e);if(n===void 0)throw new Error("openapi.json is not valid JSON: root is not an object");let s=H(N(n,"x-palbase-gateways"));if(s===void 0)return[];let a=[];for(let[r,i]of Ct(s)){let o=H(i),l=o===void 0?void 0:Ae(N(o,"pattern"));if(o===void 0||l===void 0||l===""||!Wk(r))continue;let d={where:Jh(r,l),budget:t,through:r.length,path:new Set},p=N(o,"durable");a.push({name:r,pattern:l,params:Hk(l),durable:typeof p=="number"&&p>0,chat:N(o,"chat")===!0,events:Yk(N(o,"events"),n,d),messages:Xk(N(o,"messages"),n,d)})}return a.sort((r,i)=>Et(r.name,i.name)),a}var Jh=(e,t)=>`gateway ${e} (${JSON.stringify(t)})`;function Wk(e){return/^(?:[A-Za-z][A-Za-z0-9_]*|_[A-Za-z0-9_]+)$/.test(e)&&!Vk.has(e)&&!Ro.has(e)}var Vk=new Set([..."associatedtype borrowing class consuming deinit enum extension fileprivate func import init inout internal let operator precedencegroup private protocol public rethrows static struct subscript typealias var break case catch continue default defer do else fallthrough for guard if in repeat return throw switch where while as async await false is nil self super throws true try any Any Self Type Protocol".split(" "),..."Swift Foundation Palbase Palbe _Concurrency _StringProcessing".split(" "),..."String Int Double Bool Data UUID Error Never Void Optional Array Dictionary Sendable Codable Encodable Decodable Encoder Decoder CodingKey CodingKeys JSONDecoder JSONEncoder AsyncThrowingStream".split(" "),..."PalbaseClient JSONValue PalBackendClient PBBackend PBGateway PBChatGateway PBChat PBChatModel PBGatewayError GatewayHandle GatewayTransport PBError BackendError PBRequest PBMethod PBPathSegment PBEndpoint PBVoidEndpoint PBSseEndpoint PBUploadEndpoint PBFileSource BackendUploadProgress PBWireValue PBEncryption PBTransitConfig Nullable AnyCodableValue".split(" ")]);function Wh(e){let t=bt(e);return t.length>2&&ke(t[0],"{")&&ke(t[t.length-1],"}")?t.slice(1,-1).join(""):void 0}function Hk(e){return Tn(e,":",!1).flatMap(t=>Wh(t)??[])}function Eo(e,t,n,s){let a=Zk(e,t)??e;return on(a,a,{...n,through:n.through+s.length})}function Yk(e,t,n){let s=H(e);if(s===void 0)return[];let a=[];for(let[r,i]of Ct(s)){let o=H(i);o!==void 0&&a.push({name:r,schema:Eo(o,t,n,r)})}return a.sort((r,i)=>Et(r.name,i.name)),a}function Xk(e,t,n){let s=H(e);if(s===void 0)return[];let a=[];for(let[r,i]of Ct(s)){let o=H(i),l=o===void 0?void 0:H(N(o,"payload"));if(o===void 0||l===void 0)continue;let d={name:r,schema:Eo(l,t,n,r)},p=H(N(o,"reply"));p!==void 0&&(d.reply=Eo(p,t,n,r)),a.push(d)}return a.sort((r,i)=>Et(r.name,i.name)),a}function Zk(e,t){let n=Ae(N(e,"$ref"));if(n===void 0)return;let s=bt(n);if(!ke(s[0]??"","#")||!ke(s[1]??"","/"))return;let a=t;for(let r of Tn(s.slice(2).join(""),"/",!0)){let i=ps(ps(r,"~1","/"),"~0","~"),o=H(a);if(o===void 0||!rn(o,i))return;a=N(o,i)}return H(a)}function Qk(e){if(!/^[+-]?[0-9]+$/.test(e))return;let t=BigInt(e);return t>Uh||t<zh?void 0:t}function Le(e){let t='"';for(let n of e){let s=n.codePointAt(0);if(n==='"')t+='\\"';else if(n==="\\")t+="\\\\";else if(n===`
|
|
557
|
-
`)t+="\\n";else if(n==="\r")t+="\\r";else if(n===" ")t+="\\t";else{if(s>=55296&&s<=57343)throw new Error(`${JSON.stringify(e)} is not a Swift string: it carries a lone surrogate`);s<32||s>=127&&s<=159||s===8232||s===8233||eS.has(s)?t+="\\u{"+s.toString(16)+"}":t+=n}}return t+'"'}var eS=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),yr=e=>Tn(e,".",!0),yt=e=>Vh(e,!0);function se(e){let t=Vh(e,!1);if(sS.has(t))throw new Error(`the name ${JSON.stringify(e)} becomes the Swift keyword ${t}, which the client does not put in backticks and Swift takes as no name: rename it in the backend`);return rS(t)}var us=e=>yr(e).map(yt).join(""),br=e=>us(e)+"Request",ds=e=>us(e)+"Response",wr=e=>us(e)+"Error",Mo=e=>us(e)+"Headers",la=e=>us(e)+"Query";function tS(e){let t=(n,s)=>Et(e,n)>=0&&Et(e,s)<=0;return t("a","z")||t("A","Z")||t("0","9")}function Vh(e,t){let n=[],s=[];for(let i of bt(e))tS(i)?s.push(i):s.length>0&&(n.push(s),s=[]);if(s.length>0&&n.push(s),n.length===0)return t?"Op":"op";let a="";n.forEach((i,o)=>{a+=(o===0&&!t?i[0].toLowerCase():i[0].toUpperCase())+i.slice(1).join("")});let r=a.codePointAt(0);if(r>=48&&r<=57&&(a="_"+a),!/^[A-Za-z0-9_]+$/.test(a))throw new Error(`the name ${JSON.stringify(e)} becomes ${JSON.stringify(a)} in Swift, which is more than A-Z, a-z, 0-9 and _: rename it in the backend`);return a}var nS=new Set(["class","struct","enum","func","let","var","return","if","else","for","while","switch","case","default","import","public","private","internal","protocol","extension","self","init","deinit","in","where","as","is","try","throw","throws","async","await","nil","true","false","guard","defer","do","catch","repeat","operator","associatedtype","any"]),sS=new Set(["break","continue","fallthrough","fileprivate","inout","precedencegroup","rethrows","static","subscript","super","typealias"]),aS=new Set(["Any","Self","Type","Protocol"]);function rS(e){return nS.has(de(e))?"`"+e+"`":e}var Tt=e=>ps(e,"`","");function Nh(e,t){if(
|
|
558
|
-
`)}function Hh(e){let t=[];for(let n of e){let s=/^public (?:nonisolated )?(?:struct|enum|typealias) ([A-Za-z0-9_]+)/.exec(n);s!==null&&t.push(s[1])}return t}var vr=e=>us(e)+"Endpoint";function Yh(e){let t=[];for(let n of Tn(e,"/",!1)){if(n==="")continue;let s=bt(n);if(s.length>=2&&
|
|
556
|
+
`}return o}function Rk(e){if(!e.transit)throw new Error("the contract marks encrypted fields: the client needs the project's id and signing key (palbase apps:sync gives them)");return", transit: PBTransitConfig(projectID: "+Le(e.transit.projectId)+", signer: "+Le(e.transit.signer)+")"}var Tk=new Set("associatedtype borrowing class consuming deinit enum extension fileprivate func import init inout internal let operator precedencegroup private protocol public rethrows static struct subscript typealias var break case catch continue default defer do else fallthrough for guard if in repeat return throw switch where while as await false is nil self super throws true try".split(" "));function Ek(e){if(!/^[a-z][A-Za-z0-9]*$/.test(e.client)||Tk.has(e.client))throw new Error(`client ${JSON.stringify(e.client)} is not a lowerCamel Swift identifier`);for(let t of e.header)if(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/.test(t))throw new Error(`header line ${JSON.stringify(t)} would end its comment, or read as other than it is`)}function hr(e,t){let n=Ro.get(t);if(n!==void 0)throw new Error(`${e} declares the type ${t}, which in the app would stand in for ${n}'s ${t}: rename it in the backend`)}function Ck(e,t,n,s){hr(`client ${JSON.stringify(t)}`,n),s.set(de(n),`client ${JSON.stringify(t)}`);for(let a of e){let r=yr(a.operationID);for(let i=1;i<r.length;i++){let o=`operation ${JSON.stringify(a.operationID)}, in namespace ${JSON.stringify(r.slice(0,i).join("."))},`,l=Co(r.slice(0,i),n);hr(o,l),s.has(de(l))||s.set(de(l),`namespace ${JSON.stringify(r.slice(0,i).join("."))}`)}}}function jk(e){let t='"';for(let n of e){let s=n.codePointAt(0);if(s>=55296&&s<=57343)throw new Error(`machine ${JSON.stringify(e)} is not a Swift string`);n==='"'||n==="\\"?t+="\\"+n:s>=32&&s<127?t+=n:t+="\\u{"+s.toString(16)+"}"}return t+'"'}var Ok=new Intl.Segmenter("en",{granularity:"grapheme"});function bt(e){return Array.from(Ok.segment(e),t=>t.segment)}function de(e){return e.normalize("NFC")}function Se(e,t){return de(e)===de(t)}function Et(e,t){let n=Array.from(de(e)),s=Array.from(de(t));for(let a=0;a<n.length&&a<s.length;a++){let r=n[a].codePointAt(0)-s[a].codePointAt(0);if(r!==0)return r}return n.length-s.length}var Gh=e=>[...e].sort(Et);function Tn(e,t,n){let s=[],a="";for(let r of bt(e))Se(r,t)?((!n||a!=="")&&s.push(a),a=""):a+=r;return(!n||a!=="")&&s.push(a),s}function ps(e,t,n){let s=bt(e),a=bt(t),r="";for(let i=0;i<s.length;)i+a.length<=s.length&&a.every((o,l)=>Se(s[i+l],o))?(r+=n,i+=a.length):r+=s[i++];return r}var xh=new WeakMap;function jo(e){let t=xh.get(e);if(t===void 0){t=new Map;for(let n of Object.keys(e))e[n]!==void 0&&(t.delete(de(n)),t.set(de(n),[n,e[n]]));xh.set(e,t)}return t}var N=(e,t)=>jo(e).get(de(t))?.[1],rn=(e,t)=>jo(e).has(de(t)),Ct=e=>[...jo(e).values()],Oo=e=>Ct(e).map(([t])=>t);function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ft(e){return Array.isArray(e)?e:void 0}function Ae(e){return typeof e=="string"?e:void 0}function fr(e){if(typeof e=="boolean")return e;if(e===1)return!0;if(e===0)return!1}function Mk(e){if(typeof e=="number")return e;if(typeof e=="boolean")return e?1:0}var Rn=(e,t=!1)=>({kind:e,nullable:t,props:[],enumVals:[]}),Uh=2n**63n-1n,zh=-(2n**63n);function xk(e){return Number.isNaN(e)?0n:e>=2**63?Uh:e<=-(2**63)?zh:BigInt(Math.trunc(e))}function Ik(e,t=new At){let n=H(e);if(n===void 0)throw new Error("openapi.json is not valid JSON: root is not an object");let s=H(N(n,"paths"));if(s===void 0)throw new Error("openapi.json has no `paths`");let a=[];for(let[r,i]of Ct(s)){let o=H(i);if(o!==void 0)for(let[l,d]of Ct(o)){let p=H(d);if(p===void 0)continue;let u=Ae(N(p,"operationId"))??"";if(u==="")continue;let m={where:`operation ${JSON.stringify(u)}`,budget:t,through:u.length,path:new Set};a.push({operationID:u,method:l.toUpperCase(),path:r,pathParams:Gk(r),input:Nk(p,m),output:Uk(p,m),headers:Lh(p,"header",m),query:Lh(p,"query",m),errors:Lk(p,m),upload:Dk(p),sse:rn(p,"x-palbase-sse"),idempotent:Kk(p),attests:N(p,"x-palbase-attest")===!0,...pS(Gt(e,p,`${l.toUpperCase()} ${r}`))})}}return a.sort((r,i)=>Et(r.operationID,i.operationID)),a}function Lk(e,t){let n=H(N(e,"x-palbase-errors"));if(n===void 0)return[];let s=H(N(e,"responses")),a=[];for(let[r,i]of Ct(n)){let o=H(i);if(o===void 0)continue;let l=Mk(N(o,"status"))??0,d=Ae(N(o,"code"))??"",p=Ae(N(o,"description"))??"",u=fr(N(o,"hasData"))??!1;if(d===""||l===0)continue;let m={name:r,code:d,status:xk(l),description:p};u&&(m.data=qk(s,m.status,d,{...t,through:t.through+r.length})),a.push(m)}return a.sort((r,i)=>Et(r.name,i.name)),a}function Dk(e){let t=H(N(e,"x-palbase-upload"));if(t===void 0||Ct(t).length===0)return;let n=Ae(N(t,"bucket"))??"",s=Ae(N(t,"pathTemplate"))??"";if(!(n===""||s===""))return{bucket:n,pathTemplate:s}}function qk(e,t,n,s){if(e===void 0)return;let a=H(N(e,t.toString()));if(a===void 0)return;let r=H(N(a,"content"));if(r===void 0)return;let i=H(N(r,"application/json"));if(i===void 0)return;let o=H(N(i,"schema"));if(o===void 0)return;let l=ft(N(o,"oneOf"));if(l!==void 0){for(let d of l){let p=H(d);if(p===void 0)continue;let u=H(N(p,"properties")),m=u===void 0?void 0:H(N(u,"error"));if(m===void 0)continue;let b=Ae(N(m,"const"));if(b!==void 0&&Se(b,n))return Ih(p,s)}return}return Ih(o,s)}function Ih(e,t){let n=H(N(e,"properties"));if(n===void 0)return;let s=H(N(n,"data"));if(s!==void 0)return on(s,s,t)}function Nk(e,t){let n=H(N(e,"requestBody"));if(n!==void 0)return Fh(N(n,"content"),t)}var Bh=e=>de(e).toLowerCase()==="idempotency-key";function Kk(e){return(ft(N(e,"parameters"))??[]).some(t=>{let n=H(t);return n!==void 0&&Se(Ae(N(n,"in"))??"","header")&&Bh(Ae(N(n,"name"))??"")})}function Lh(e,t,n){let s=ft(N(e,"parameters"));if(s===void 0||s.length===0)return;let a=[];for(let r of s){let i=H(r);if(i===void 0||!Se(Ae(N(i,"in"))??"",t))continue;let o=Ae(N(i,"name"))??"";if(o===""||t==="header"&&Bh(o))continue;let l=fr(N(i,"required"))??!1,d=H(N(i,"schema"));a.push({name:o,schema:d===void 0?Rn("string"):on(d,d,{...n,through:n.through+o.length}),required:l})}if(a.length!==0)return a.sort((r,i)=>Et(r.name,i.name)),{kind:"object",nullable:!1,props:a,enumVals:[]}}function Gk(e){let t=[],n=e;for(;;){let s=n.indexOf("{");if(s<0)break;let a=n.indexOf("}",s);if(a<0)break;let r=n.slice(s+1,a);r!==""&&t.push(r),n=n.slice(a+1)}return t}function Uk(e,t){let n=H(N(e,"responses"));if(n===void 0)return;let s=Oo(n).filter(a=>Se(bt(a)[0]??"","2")&&!Se(a,"200")&&!Se(a,"201"));for(let a of["200","201",...Gh(s)]){let r=H(N(n,a));if(r===void 0)continue;let i=Fh(N(r,"content"),t);if(i!==void 0)return i}}function Fh(e,t){let n=H(e);if(n===void 0)return;let s=H(N(n,"application/json"));if(s===void 0)return;let a=H(N(s,"schema"));if(a!==void 0&&!rn(a,"$ref"))return on(a,a,t)}function on(e,t,n,s=0,a=n.through){let r=e,i=Fk(r,t);if(i!==void 0&&s<16){if(n.path.has(i))throw new Error(`${n.where}: the $ref ${JSON.stringify(Ae(N(r,"$ref")))} points back into a schema it is part of, a recursive schema, which no Swift type is written for: refused`);r=i}else if(rn(r,"$ref"))return Rn("any");let o=H(N(r,"properties")),l=(o===void 0?0:Dh(Oo(o)))+Dh(ft(N(r,"enum"))??[]);n.budget.charge(n.where,s,a,l),n.path.add(r);try{return zk(r,t,n,s,a)}finally{n.path.delete(r)}}var Dh=e=>e.reduce((t,n)=>t+(Ae(n)?.length??0),0);function zk(e,t,n,s,a){let r=fr(N(e,"nullable"))??!1,i=ft(N(e,"type"));if(i!==void 0)for(let p of i)Ae(p)==="null"&&(r=!0);let o=ft(N(e,"anyOf"))??ft(N(e,"oneOf"));if(o!==void 0){let p=o.map(H).filter(m=>m!==void 0),u=p.filter(m=>!Bk(m));if(p.length===o.length&&u.length===1&&p.length>u.length){let m=on(u[0],t,n,s+1,a);return m.nullable=!0,m}}let l=ft(N(e,"enum"));if(l!==void 0){let p=[],u=!0;for(let m of l){let b=Ae(m);if(b===void 0){u=!1;break}p.push(b)}if(u&&p.length>0)return{kind:"enum",nullable:r,props:[],enumVals:p}}let d=Ae(N(e,"type"))??"";if(d===""&&i!==void 0)for(let p of i){let u=Ae(p);u!==void 0&&(u==="null"?r=!0:d===""&&(d=u))}switch(d){case"string":case"number":case"integer":case"boolean":return Rn(d,r);case"array":{let p=H(N(e,"items"));return{kind:"array",nullable:r,props:[],elem:p===void 0?Rn("any"):on(p,t,n,s+1,a),enumVals:[]}}case"object":return qh(e,r,t,n,s,a);default:return rn(e,"properties")||rn(e,"additionalProperties")?qh(e,r,t,n,s,a):Rn("any",r)}}function qh(e,t,n,s,a,r){let i=H(N(e,"properties"))??{},o=N(e,"additionalProperties"),l,d=H(o);if(d!==void 0?l=on(d,n,s,a+1,r):(fr(o)===!0||Ct(i).length===0&&!rn(e,"additionalProperties"))&&(l=Rn("any")),l!==void 0)return{kind:Ct(i).length===0?"map":"mixedObject",nullable:t,props:[],elem:l,enumVals:[]};let p=new Set;for(let m of ft(N(e,"required"))??[]){let b=Ae(m);b!==void 0&&p.add(de(b))}let u=[];for(let m of Gh(Oo(i))){let b=H(N(i,m));u.push({name:m,schema:b===void 0?Rn("any"):on(b,n,s,a+1,r+m.length),required:p.has(de(m))})}return{kind:"object",nullable:t,props:u,enumVals:[]}}function Bk(e){let t=N(e,"type");if(typeof t=="string")return t==="null";let n=ft(t);if(n!==void 0){let s=n.filter(a=>typeof a=="string");return s.length===1&&s[0]==="null"}return!1}function Fk(e,t){let n=Ae(N(e,"$ref"));if(n===void 0)return;let s=bt(n);if(!Se(s[0]??"","#")||!Se(s[1]??"","/"))return;let a=t;for(let r of Tn(s.slice(2).join(""),"/",!0)){let i=ps(ps(r,"~1","/"),"~0","~"),o=H(a),l=ft(a),d=Qk(i);if(o!==void 0&&rn(o,i))a=N(o,i);else if(l!==void 0&&d!==void 0&&d>=0n&&d<BigInt(l.length))a=l[Number(d)];else return}return H(a)}function Jk(e,t=new At){let n=H(e);if(n===void 0)throw new Error("openapi.json is not valid JSON: root is not an object");let s=H(N(n,"x-palbase-gateways"));if(s===void 0)return[];let a=[];for(let[r,i]of Ct(s)){let o=H(i),l=o===void 0?void 0:Ae(N(o,"pattern"));if(o===void 0||l===void 0||l===""||!Wk(r))continue;let d={where:Jh(r,l),budget:t,through:r.length,path:new Set},p=N(o,"durable");a.push({name:r,pattern:l,params:Hk(l),durable:typeof p=="number"&&p>0,chat:N(o,"chat")===!0,events:Yk(N(o,"events"),n,d),messages:Xk(N(o,"messages"),n,d)})}return a.sort((r,i)=>Et(r.name,i.name)),a}var Jh=(e,t)=>`gateway ${e} (${JSON.stringify(t)})`;function Wk(e){return/^(?:[A-Za-z][A-Za-z0-9_]*|_[A-Za-z0-9_]+)$/.test(e)&&!Vk.has(e)&&!Ro.has(e)}var Vk=new Set([..."associatedtype borrowing class consuming deinit enum extension fileprivate func import init inout internal let operator precedencegroup private protocol public rethrows static struct subscript typealias var break case catch continue default defer do else fallthrough for guard if in repeat return throw switch where while as async await false is nil self super throws true try any Any Self Type Protocol".split(" "),..."Swift Foundation Palbase Palbe _Concurrency _StringProcessing".split(" "),..."String Int Double Bool Data UUID Error Never Void Optional Array Dictionary Sendable Codable Encodable Decodable Encoder Decoder CodingKey CodingKeys JSONDecoder JSONEncoder AsyncThrowingStream".split(" "),..."PalbaseClient JSONValue PalBackendClient PBBackend PBGateway PBChatGateway PBChat PBChatModel PBGatewayError GatewayHandle GatewayTransport PBError BackendError PBRequest PBMethod PBPathSegment PBEndpoint PBVoidEndpoint PBSseEndpoint PBUploadEndpoint PBFileSource BackendUploadProgress PBWireValue PBEncryption PBTransitConfig Nullable AnyCodableValue".split(" ")]);function Wh(e){let t=bt(e);return t.length>2&&Se(t[0],"{")&&Se(t[t.length-1],"}")?t.slice(1,-1).join(""):void 0}function Hk(e){return Tn(e,":",!1).flatMap(t=>Wh(t)??[])}function Eo(e,t,n,s){let a=Zk(e,t)??e;return on(a,a,{...n,through:n.through+s.length})}function Yk(e,t,n){let s=H(e);if(s===void 0)return[];let a=[];for(let[r,i]of Ct(s)){let o=H(i);o!==void 0&&a.push({name:r,schema:Eo(o,t,n,r)})}return a.sort((r,i)=>Et(r.name,i.name)),a}function Xk(e,t,n){let s=H(e);if(s===void 0)return[];let a=[];for(let[r,i]of Ct(s)){let o=H(i),l=o===void 0?void 0:H(N(o,"payload"));if(o===void 0||l===void 0)continue;let d={name:r,schema:Eo(l,t,n,r)},p=H(N(o,"reply"));p!==void 0&&(d.reply=Eo(p,t,n,r)),a.push(d)}return a.sort((r,i)=>Et(r.name,i.name)),a}function Zk(e,t){let n=Ae(N(e,"$ref"));if(n===void 0)return;let s=bt(n);if(!Se(s[0]??"","#")||!Se(s[1]??"","/"))return;let a=t;for(let r of Tn(s.slice(2).join(""),"/",!0)){let i=ps(ps(r,"~1","/"),"~0","~"),o=H(a);if(o===void 0||!rn(o,i))return;a=N(o,i)}return H(a)}function Qk(e){if(!/^[+-]?[0-9]+$/.test(e))return;let t=BigInt(e);return t>Uh||t<zh?void 0:t}function Le(e){let t='"';for(let n of e){let s=n.codePointAt(0);if(n==='"')t+='\\"';else if(n==="\\")t+="\\\\";else if(n===`
|
|
557
|
+
`)t+="\\n";else if(n==="\r")t+="\\r";else if(n===" ")t+="\\t";else{if(s>=55296&&s<=57343)throw new Error(`${JSON.stringify(e)} is not a Swift string: it carries a lone surrogate`);s<32||s>=127&&s<=159||s===8232||s===8233||eS.has(s)?t+="\\u{"+s.toString(16)+"}":t+=n}}return t+'"'}var eS=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),yr=e=>Tn(e,".",!0),yt=e=>Vh(e,!0);function se(e){let t=Vh(e,!1);if(sS.has(t))throw new Error(`the name ${JSON.stringify(e)} becomes the Swift keyword ${t}, which the client does not put in backticks and Swift takes as no name: rename it in the backend`);return rS(t)}var us=e=>yr(e).map(yt).join(""),br=e=>us(e)+"Request",ds=e=>us(e)+"Response",wr=e=>us(e)+"Error",Mo=e=>us(e)+"Headers",la=e=>us(e)+"Query";function tS(e){let t=(n,s)=>Et(e,n)>=0&&Et(e,s)<=0;return t("a","z")||t("A","Z")||t("0","9")}function Vh(e,t){let n=[],s=[];for(let i of bt(e))tS(i)?s.push(i):s.length>0&&(n.push(s),s=[]);if(s.length>0&&n.push(s),n.length===0)return t?"Op":"op";let a="";n.forEach((i,o)=>{a+=(o===0&&!t?i[0].toLowerCase():i[0].toUpperCase())+i.slice(1).join("")});let r=a.codePointAt(0);if(r>=48&&r<=57&&(a="_"+a),!/^[A-Za-z0-9_]+$/.test(a))throw new Error(`the name ${JSON.stringify(e)} becomes ${JSON.stringify(a)} in Swift, which is more than A-Z, a-z, 0-9 and _: rename it in the backend`);return a}var nS=new Set(["class","struct","enum","func","let","var","return","if","else","for","while","switch","case","default","import","public","private","internal","protocol","extension","self","init","deinit","in","where","as","is","try","throw","throws","async","await","nil","true","false","guard","defer","do","catch","repeat","operator","associatedtype","any"]),sS=new Set(["break","continue","fallthrough","fileprivate","inout","precedencegroup","rethrows","static","subscript","super","typealias"]),aS=new Set(["Any","Self","Type","Protocol"]);function rS(e){return nS.has(de(e))?"`"+e+"`":e}var Tt=e=>ps(e,"`","");function Nh(e,t){if(Se(e,t))return!0;let n=bt(t);if(!n.some(l=>Se(l,"_")))return!1;let s=0;for(;s<n.length&&Se(n[s],"_");)s++;let a=0;for(;a<n.length-s&&Se(n[n.length-1-a],"_");)a++;let r=n.slice(s,n.length-a).join("");if(r==="")return!1;let i=n.slice(0,s).join(""),o=Tn(r,"_",!1);for(let l=0;l<o.length;l++){if(o[l]==="")return!1;if(l===0)i+=o[l].toLowerCase();else{let d=bt(o[l]);i+=d[0].toUpperCase()+d.slice(1).join("").toLowerCase()}}return i+=n.slice(n.length-a).join(""),Se(i,e)}var E=e=>" ".repeat(e);function Rt(e,t){for(let n of t)e.push(n)}function iS(e,t){let n=[];for(let s of e){let a=n.length,r=!1;if(s.input!==void 0&&(Rt(n,ls(br(s.operationID),s.input,!0)),r=!0),s.output!==void 0?(r&&n.push(""),Rt(n,ls(ds(s.operationID),s.output)),r=!0):s.upload!==void 0&&(r&&n.push(""),n.push("public nonisolated struct "+ds(s.operationID)+": Codable, Sendable {"),n.push("}"),r=!0),s.headers!==void 0){for(let i of s.headers.props)if(!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(i.name))throw new Error(`operation ${JSON.stringify(s.operationID)}: the header ${JSON.stringify(i.name)} is no HTTP field name (RFC 9110's token): rename it in the backend`);r&&n.push(""),Rt(n,uS(Mo(s.operationID),s.headers)),r=!0}s.query!==void 0&&(r&&n.push(""),Rt(n,_r(la(s.operationID),s.query.props,0)),r=!0),r&&n.push(""),Rt(n,cS(wr(s.operationID),s.errors)),n.push(""),Rt(n,oS(s)),n.push("");for(let i of Hh(n.slice(a)))hr(`operation ${JSON.stringify(s.operationID)}`,i),t.has(de(i))||t.set(de(i),`operation ${JSON.stringify(s.operationID)}`)}return n.join(`
|
|
558
|
+
`)}function Hh(e){let t=[];for(let n of e){let s=/^public (?:nonisolated )?(?:struct|enum|typealias) ([A-Za-z0-9_]+)/.exec(n);s!==null&&t.push(s[1])}return t}var vr=e=>us(e)+"Endpoint";function Yh(e){let t=[];for(let n of Tn(e,"/",!1)){if(n==="")continue;let s=bt(n);if(s.length>=2&&Se(s[0],"{")&&Se(s[s.length-1],"}")){let a=s.slice(1,s.length-1).join("");if(a==="")continue;t.push(".param("+se(a)+")")}else t.push(Le(n))}return"["+t.join(", ")+"]"}function Xh(e){return e.path===""?"/"+ps(e.operationID,".","/"):e.path}function oS(e){if(e.upload!==void 0)return dS(e);let t=vr(e.operationID),n=[];e.sse?(n.push("public nonisolated struct "+t+": PBSseEndpoint {"),n.push(E(1)+"public typealias Element = "+ds(e.operationID))):e.output!==void 0?(n.push("public nonisolated struct "+t+": PBEndpoint {"),n.push(E(1)+"public typealias Response = "+ds(e.operationID))):n.push("public nonisolated struct "+t+": PBVoidEndpoint {"),n.push(E(1)+"public typealias Failure = "+wr(e.operationID));for(let r of e.pathParams)n.push(E(1)+"let "+se(r)+": String");e.input!==void 0&&n.push(E(1)+"let input: "+br(e.operationID)),e.query!==void 0&&n.push(E(1)+"let query: "+la(e.operationID)),e.headers!==void 0&&n.push(E(1)+"let headers: "+Mo(e.operationID));let s=e.method===""?"POST":e.method;if(!/^[a-z][a-z0-9]*$/.test(s.toLowerCase()))throw new Error(`operation ${JSON.stringify(e.operationID)}: the method ${JSON.stringify(s)} is not a Swift name`);let a=["."+s.toLowerCase(),Yh(Xh(e))];if(e.input!==void 0&&a.push("body: Palbe.PBWireValue(input)"),e.query!==void 0&&a.push("query: query"),e.headers!==void 0&&a.push("headers: headers.asHeaderDict()"),n.push(E(1)+"public var pbRequest: PBRequest { PBRequest("+a.join(", ")+") }"),e.idempotent&&!e.sse){if(e.pathParams.some(r=>Tt(se(r))==="idempotent"))throw new Error(`operation ${JSON.stringify(e.operationID)}: the path parameter idempotent is the name the endpoint says it may be sent again by: rename it in the backend`);n.push(E(1)+"public var idempotent: Bool { true }")}if(e.attests){if(e.pathParams.some(r=>Tt(se(r))==="attests"))throw new Error(`operation ${JSON.stringify(e.operationID)}: the path parameter attests is the name the endpoint says it proves the device by: rename it in the backend`);n.push(E(1)+"public var attests: Bool { true }")}if(e.encryption){if(e.pathParams.some(r=>Tt(se(r))==="encryption"))throw new Error(`operation ${JSON.stringify(e.operationID)}: the path parameter encryption is the name the endpoint says its encrypted fields by: rename it in the backend`);n.push(E(1)+"public var encryption: PBEncryption? { "+lS(e.encryption)+" }")}return n.push("}"),n}function lS(e){let t=n=>"["+n.map(Le).join(", ")+"]";return"PBEncryption(request: "+t(e.request)+", response: "+t(e.response)+")"}function pS(e){return e?{encryption:e}:{}}function dS(e){let t=[];t.push("public nonisolated struct "+vr(e.operationID)+": PBUploadEndpoint {"),t.push(E(1)+"public typealias Response = "+ds(e.operationID)),t.push(E(1)+"public typealias Failure = "+wr(e.operationID));for(let s of e.pathParams)t.push(E(1)+"let "+se(s)+": String");e.input!==void 0&&t.push(E(1)+"let input: "+br(e.operationID)),e.query!==void 0&&t.push(E(1)+"let query: "+la(e.operationID));let n=[".post",Yh(Xh(e))];return e.input!==void 0&&n.push("body: Palbe.PBWireValue(input)"),e.query!==void 0&&n.push("query: query"),t.push(E(1)+"public var authorizeRequest: PBRequest { PBRequest("+n.join(", ")+") }"),t.push("}"),t}function ls(e,t,n=!1,s=0){if(t.kind==="object")return _r(e,t.props,s,n);let[a,r]=t.kind==="enum"?["String",[]]:gr(t,e,s,n),i=[...r];return i.length>0&&i.push(""),i.push(E(s)+"public typealias "+e+" = "+a+(t.nullable?"?":"")),i}function uS(e,t){let n=_r(e,t.props,0);n[n.length-1].trim()==="}"&&n.pop(),n.push(E(1)+"public func asHeaderDict() -> [String: String] {"),n.push(E(2)+"var out: [String: String] = [:]");for(let s of t.props){let a=se(s.name),r=Le(s.name),i=s.schema.kind==="enum";!s.required||s.schema.nullable?n.push(E(2)+"if let v = "+a+" { out["+r+"] = "+(i?"v.rawValue":"v")+" }"):n.push(E(2)+"out["+r+"] = "+a+(i?".rawValue":""))}return n.push(E(2)+"return out"),n.push(E(1)+"}"),n.push("}"),n}function cS(e,t){let n=["public nonisolated enum "+e+": PBError {"],s=1,a=new Map([["other","the other(BackendError) fallback"]]),r=[];for(let i of t){let o=Tt(se(i.name)),l=a.get(de(o));if(l!==void 0){n.push(E(s)+"#error("+Le("palbase: "+e+" declares error "+i.name+" ("+i.code+"), which maps to the same Swift case `"+o+"` as "+l+". Rename one of the errors in the backend and regenerate the client.")+")");continue}a.set(de(o),i.name+" ("+i.code+")"),r.push(i)}for(let i of r)i.data!==void 0&&Rt(n,ls(yt(i.name)+"Data",i.data,!1,s));for(let i of r)n.push(E(s)+"case "+se(i.name)+(i.data!==void 0?"("+yt(i.name)+"Data)":""));if(n.push(E(s)+"case other(BackendError)"),r.length===0)return n.push(E(s)+"public nonisolated init(_ backend: BackendError) { self = .other(backend) }"),n.push("}"),n;n.push(E(s)+"public nonisolated init(_ backend: BackendError) {"),n.push(E(s+1)+"guard let f = backend.failure else { self = .other(backend); return }"),n.push(E(s+1)+"switch f.code {");for(let i of r){let o=se(i.name);i.data!==void 0?(n.push(E(s+1)+"case "+Le(i.code)+":"),n.push(E(s+2)+"if let data = f.decodeData("+yt(i.name)+"Data.self) { self = ."+o+"(data) } else { self = .other(backend) }")):n.push(E(s+1)+"case "+Le(i.code)+": self = ."+o)}return n.push(E(s+1)+"default: self = .other(backend)"),n.push(E(s+1)+"}"),n.push(E(s)+"}"),n.push("}"),n}function _r(e,t,n,s=!1){let a=[E(n)+"public nonisolated struct "+e+": Codable, Sendable {"],r=n+1,i=[],o=new mr,l=new Map;for(let p of t){let u=se(p.name),m=l.get(de(u));if(m!==void 0){a.push(E(r)+"#error("+Le("palbase: "+e+" has colliding Swift property `"+Tt(u)+"` for wire keys "+m+" and "+p.name+". This schema is unsupported; use distinct property names and regenerate the client.")+")");continue}l.set(de(u),p.name);let b=!p.required||p.schema.nullable,[w,_]=gr(p.schema,p.name,r,s,o);s&&!p.required&&p.schema.nullable&&(w="Nullable<"+w+">"),Rt(a,_),i.push({ident:u,key:p.name,typ:w,optional:b,required:p.required})}for(let p of i)a.push(E(r)+"public let "+p.ident+": "+p.typ+(p.optional?"?":""));let d=i.map(p=>p.ident+": "+p.typ+(p.optional?"? = nil":""));a.push(E(r)+"public init("+d.join(", ")+") {");for(let p of i)a.push(E(r+1)+"self."+p.ident+" = "+p.ident);if(a.push(E(r)+"}"),s){a.push(E(r)+"public func encode(to encoder: any Swift.Encoder) throws {"),a.push(E(r+1)+(i.length===0?"let":"var")+" fields: [Swift.String: Palbe.PBWireValue] = [:]");for(let p of i){let u="fields["+Le(p.key)+"] = Palbe.PBWireValue(";p.required?a.push(E(r+1)+u+"self."+p.ident+")"):a.push(E(r+1)+"if let value = self."+p.ident+" { "+u+"value) }")}a.push(E(r+1)+"var container = encoder.singleValueContainer()"),a.push(E(r+1)+"try container.encode(fields)"),a.push(E(r)+"}")}if(i.some(p=>!Nh(Tt(p.ident),p.key))){a.push(E(r)+"enum CodingKeys: String, CodingKey {");for(let p of i)Nh(Tt(p.ident),p.key)?a.push(E(r+1)+"case "+p.ident):a.push(E(r+1)+"case "+p.ident+" = "+Le(p.key));a.push(E(r)+"}")}return a.push(E(n)+"}"),a}var mr=class{used=new Set(["Swift","Palbe","Foundation","String","Int","Double","Bool","Encoder","Decoder","Encodable","Decodable","Codable","Sendable","CodingKey","CodingKeys","AnyCodableValue","Nullable","PBWireValue"]);allocate(t){let n=t;for(let s=2;this.used.has(de(n));s++)n=t+s;return this.used.add(de(n)),n}};function gr(e,t,n,s=!1,a=new mr){switch(e.kind){case"string":return["String",[]];case"number":return["Double",[]];case"integer":return["Int",[]];case"boolean":return["Bool",[]];case"any":return["AnyCodableValue",[]];case"enum":{let r=a.allocate(yt(t)+"Value"),i=[E(n)+"public nonisolated enum "+r+": String, Codable, Sendable {"];for(let o of e.enumVals)i.push(E(n+1)+"case "+se(o)+" = "+Le(o));return i.push(E(n)+"}"),[r,i]}case"array":{let r=e.elem,[i,o]=gr(r,t+"Item",n,s,a);return["["+i+(r.nullable?"?":"")+"]",o]}case"map":{let r=e.elem,[i,o]=gr(r,t+"Value",n,s,a);return["[String: "+i+(r.nullable?"?":"")+"]",o]}case"mixedObject":return["AnyCodableValue",[E(n)+"#error("+Le("palbase: "+t+" combines declared properties with additionalProperties. This mixed object schema is unsupported; use a separate typed map field and regenerate the client.")+")"]];case"object":{if(aS.has(yt(t)))throw new Error(`the name ${JSON.stringify(t)} becomes the type ${yt(t)}, a name Swift gives no type of a program's: rename it in the backend`);let r=a.allocate(yt(t));return[r,_r(r,e.props,n,s)]}default:return["AnyCodableValue",[]]}}function hS(e,t){let n={path:[],children:new Map,methods:[]};for(let r of e){let i=yr(r.operationID),o=n;for(let l of i.slice(0,Math.max(i.length-1,0))){let d=o.children.get(de(l));d===void 0&&(d=[l,{path:[...o.path,l],children:new Map,methods:[]}],o.children.set(de(l),d)),o=d[1]}o.methods.push(r)}let s=[],a=[n];for(;a.length>0;){let r=a.shift();s.push(r),a.push(...Zh(r).map(([,i])=>i))}return s.map(r=>mS(r,t)+`
|
|
559
559
|
`).join("")}var Zh=e=>[...e.children.values()].sort((t,n)=>Et(t[0],n[0]));function Co(e,t){return e.length===0?t:"PB"+e.map(yt).join("")+"Namespace"}function mS(e,t){let n=e.path.length===0,s=[];n?s.push("public extension "+t+" {"):(s.push("public nonisolated struct "+Co(e.path,t)+": Sendable {"),s.push(" let _pb: PalBackendClient"));let a=n?"":"public ",r="_pb";for(let[,i]of Zh(e)){let o=Co(i.path,t);s.push(E(1)+a+"nonisolated var "+se(i.path[i.path.length-1])+": "+o+" { "+o+"(_pb: "+r+") }")}for(let i of e.methods){let o=yr(i.operationID);if(o.length===0)throw new Error(`operationId ${JSON.stringify(i.operationID)} names no method`);let l=se(o[o.length-1]),d=br(i.operationID),p=ds(i.operationID),u="throws("+wr(i.operationID)+")";if(i.upload!==void 0){Rt(s,fS(i,l,d,p,u,a,r));continue}let m=i.pathParams.map(_=>se(_)+": String");i.input!==void 0&&m.push("_ input: "+d),i.query!==void 0&&m.push("query: "+la(i.operationID)),i.headers!==void 0&&m.push("headers: "+Mo(i.operationID));let b=i.pathParams.map(_=>se(_)+": "+se(_));i.input!==void 0&&b.push("input: input"),i.query!==void 0&&b.push("query: query"),i.headers!==void 0&&b.push("headers: headers");let w=vr(i.operationID)+"("+b.join(", ")+")";i.sse?(s.push(E(1)+a+"func "+l+"("+m.join(", ")+") async throws -> AsyncThrowingStream<"+p+", Error> {"),s.push(E(2)+"return try await "+r+".stream("+w+")")):i.output!==void 0?(s.push(E(1)+"@discardableResult"),s.push(E(1)+a+"func "+l+"("+m.join(", ")+") async "+u+" -> "+p+" {"),s.push(E(2)+"return try await "+r+".call("+w+")")):(s.push(E(1)+a+"func "+l+"("+m.join(", ")+") async "+u+" {"),s.push(E(2)+"try await "+r+".call("+w+")")),s.push(E(1)+"}")}return s.push("}"),s.join(`
|
|
560
560
|
`)+`
|
|
561
561
|
`}var To=(e,t,n)=>e+yt(t)+n;function cr(e,t,n){let s=e.get(de(t));if(s!==void 0)throw new Error(`${s} and ${n} both become ${t} in Swift: rename one in the backend`);e.set(de(t),n)}function gS(e,t){let n=Jh(e.name,e.pattern),s=new Map([["topic","the gateway's topic"]]);for(let p of e.params){let u=Tt(se(p));if(cr(s,u,`${n}'s parameter ${JSON.stringify(p)}`),u==="self"||u==="init")throw new Error(`${n}'s parameter ${JSON.stringify(p)} becomes ${u} in Swift, which the gateway's initializer cannot set: rename it in the backend`)}for(let[p,u]of[["event",e.events],["message",e.messages]]){let m=new Map;for(let b of u)cr(m,Tt(se(b.name)),`${n}'s ${p} ${JSON.stringify(b.name)}`)}let a=[],r=(p,u)=>{for(let m of Hh(p))cr(t,m,u),hr(u,m);Rt(a,p),a.push("")},i=p=>To(e.name,p,"Event"),o=p=>To(e.name,p,"Message"),l=p=>p.reply===void 0?"JSONValue":To(e.name,p.name,"Reply");for(let p of e.events)r(ls(i(p.name),p.schema),`${n}'s event ${JSON.stringify(p.name)}`);for(let p of e.messages)r(ls(o(p.name),p.schema,!0),`${n}'s message ${JSON.stringify(p.name)}`),p.reply!==void 0&&r(ls(l(p),p.reply),`${n}'s ack of ${JSON.stringify(p.name)}`);cr(t,e.name,n),a.push("public nonisolated struct "+e.name+": "+(e.chat?"PBChatGateway":"PBGateway")+" {"),a.push(E(1)+"public static let pattern = "+Le(e.pattern)),a.push(E(1)+"public static let durable = "+String(e.durable));for(let p of e.params)a.push(E(1)+"public let "+se(p)+": String");if(e.params.length===0)a.push(E(1)+"public init() {}");else{a.push(E(1)+"public init("+e.params.map(p=>se(p)+": String").join(", ")+") {");for(let p of e.params)a.push(E(2)+"self."+Tt(se(p))+" = "+se(p));a.push(E(1)+"}")}a.push(E(1)+"public var topic: String {");let d="";for(let p of Tn(e.pattern,":",!1)){d!==""&&(d+=":");let u=Wh(p);d+=u!==void 0?"\\("+se(u)+")":Le(p).slice(1,-1)}a.push(E(2)+'return "'+d+'"'),a.push(E(1)+"}"),a.push(""),a.push(E(1)+"public enum Event: Sendable {");for(let p of e.events)a.push(E(2)+"case "+se(p.name)+"("+i(p.name)+")");if(e.events.length===0&&a.push(E(2)+"// this gateway declares no events"),a.push(E(1)+"}"),a.push(""),a.push(E(1)+"public static let eventNames: [String] = ["+e.events.map(p=>Le(p.name)).join(", ")+"]"),a.push(""),a.push(E(1)+"public static func decode(event: String, data: Data) throws -> Event? {"),e.events.length===0)a.push(E(2)+"_ = (event, data)"),a.push(E(2)+"return nil");else{a.push(E(2)+"switch event {");for(let p of e.events)a.push(E(2)+"case "+Le(p.name)+":"),a.push(E(3)+"return ."+se(p.name)+"(try JSONDecoder.palbaseDefault.decode("+i(p.name)+".self, from: data))");a.push(E(2)+"default:"),a.push(E(3)+"return nil"),a.push(E(2)+"}")}a.push(E(1)+"}"),a.push(""),a.push(E(1)+"public enum Send: Sendable {");for(let p of e.messages)a.push(E(2)+"case "+se(p.name)+"("+o(p.name)+")");if(e.messages.length===0&&a.push(E(2)+"// this gateway takes no messages"),a.push(E(1)+"}"),a.push(""),a.push(E(1)+"public static func encode(_ message: Send) throws -> (event: String, data: Data) {"),e.messages.length===0)a.push(E(2)+"// this gateway takes no messages: there is none to encode");else{a.push(E(2)+"switch message {");for(let p of e.messages)a.push(E(2)+"case ."+se(p.name)+"(let value):"),a.push(E(3)+"return ("+Le(p.name)+", try JSONEncoder.palbaseDefault.encode(value))");a.push(E(2)+"}")}a.push(E(1)+"}"),a.push(""),a.push(E(1)+"public enum Reply: Sendable {");for(let p of e.messages)a.push(E(2)+"case "+se(p.name)+"("+l(p)+")");if(e.messages.length===0&&a.push(E(2)+"// this gateway takes no messages"),a.push(E(1)+"}"),a.push(""),a.push(E(1)+"public static func decode(reply data: Data, to message: Send) throws -> Reply {"),e.messages.length===0)a.push(E(2)+"// this gateway takes no messages: there is no ack to read");else{a.push(E(2)+"switch message {");for(let p of e.messages)a.push(E(2)+"case ."+se(p.name)+":"),a.push(E(3)+"return ."+se(p.name)+"(try JSONDecoder.palbaseDefault.decode("+l(p)+".self, from: data))");a.push(E(2)+"}")}return a.push(E(1)+"}"),a.push("}"),a.join(`
|
|
562
562
|
`)+`
|
|
563
563
|
`}function fS(e,t,n,s,a,r,i){let o=e.pathParams.map(p=>se(p)+": String");o.push("file: PBFileSource"),e.input!==void 0&&o.push("input: "+n),e.query!==void 0&&o.push("query: "+la(e.operationID)),o.push("onProgress: (@Sendable (BackendUploadProgress) -> Void)? = nil");let l=e.pathParams.map(p=>se(p)+": "+se(p));e.input!==void 0&&l.push("input: input"),e.query!==void 0&&l.push("query: query");let d=vr(e.operationID)+"("+l.join(", ")+")";return[E(1)+"@discardableResult",E(1)+r+"func "+t+"("+o.join(", ")+") async "+a+" -> "+s+" {",E(2)+"return try await "+i+".call("+d+", file: file, onProgress: onProgress)",E(1)+"}"]}var kr=/^[A-Za-z_$][A-Za-z0-9_$]*$/,xo=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),yS=new Set(xo),bS=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function Sr(e){return e==="then"||e==="toJSON"||bS.has(e)}function Qh(e){return e==="call"||e==="join"||Sr(e)}function $r(e){return typeof e=="string"&&kr.test(e)&&!yS.has(e)&&!Sr(e)}function em(e){return typeof e=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(e)}function tm(e){Ma(e)}function nm(e){return Ma(e).origin}function Y(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function at(e){return typeof e=="string"?e:""}function wS(e,t=new pa){let n=Y(Y(e)?.paths);if(!n)throw new Error("the contract has no `paths`");let s=[];for(let[a,r]of Object.entries(n)){let i=Y(r);if(i)for(let[o,l]of Object.entries(i)){let d=Y(l);if(!d)continue;let p=at(d.operationId);p!==""&&s.push({operationId:p,method:o.toUpperCase(),path:pm(a),pathParams:AS(a),input:SS(d,t),output:RS(d,t),headers:am(d,"header",t),query:am(d,"query",t),errors:_S(d,t),sse:d["x-palbase-sse"]!==void 0,idempotent:PS(d),upload:$S(d),...vS(Gt(e,d,`${o.toUpperCase()} ${a}`))})}}return s.sort((a,r)=>a.operationId<r.operationId?-1:a.operationId>r.operationId?1:0),s}function vS(e){return e?{encryption:e}:{}}function _S(e,t){let n=Y(e["x-palbase-errors"]);if(!n)return[];let s=Y(e.responses),a=[];for(let[r,i]of Object.entries(n)){let o=Y(i);if(!o)continue;let l=typeof o.status=="number"&&Number.isFinite(o.status)?Math.trunc(o.status):0,d=at(o.code),p=at(o.description),u=o.hasData===!0;if(d===""||l===0)continue;let m={name:r,code:d,status:l,description:p};u&&(m.data=kS(s,l,d,t)),a.push(m)}return a.sort((r,i)=>r.name<i.name?-1:r.name>i.name?1:0),a}function kS(e,t,n,s){let a=Y(e?.[String(t)]),r=Y(Y(a?.content)?.["application/json"]),i=Y(r?.schema);if(!i)return;let o=i.oneOf;if(Array.isArray(o)){for(let l of o){let d=Y(l);if(!d)continue;let p=Y(Y(d.properties)?.error);if(p&&at(p.const)===n)return sm(d,s)}return}return sm(i,s)}function sm(e,t){let n=Y(Y(e.properties)?.data);if(n)return ot(n,t)}function SS(e,t){let n=Y(e.requestBody);if(n)return dm(n.content,t)}function am(e,t,n){let s=e.parameters;if(!Array.isArray(s)||s.length===0)return;let a=[];for(let r of s){let i=Y(r);if(!i||at(i.in)!==t)continue;let o=at(i.name);if(o===""||t==="header"&&lm(o))continue;let l=i.required===!0,d=Y(i.schema),p=d?ot(d,n):Ye("string");a.push({name:o,schema:p,required:l})}if(a.length!==0)return a.sort((r,i)=>r.name<i.name?-1:r.name>i.name?1:0),{...Ye("object"),props:a}}function lm(e){return e.toLowerCase()==="idempotency-key"}function $S(e){let t=Y(e["x-palbase-upload"]);return at(t?.bucket)!==""&&at(t?.pathTemplate)!==""}function PS(e){let t=e.parameters;return Array.isArray(t)&&t.some(n=>at(Y(n)?.in)==="header"&&lm(at(Y(n)?.name)))}function pm(e){return e.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g,"{$1}")}function AS(e){let t=pm(e),n=[],s=t;for(;;){let a=s.indexOf("{");if(a<0)break;let r=s.indexOf("}",a);if(r<0)break;let i=s.slice(a+1,r);i!==""&&n.push(i),s=s.slice(r+1)}return n}function RS(e,t){let n=Y(e.responses);if(!n)return;let s=[];for(let a of Object.keys(n))a.startsWith("2")&&a!=="200"&&a!=="201"&&s.push(a);s.sort();for(let a of["200","201",...s]){let r=Y(n[a]);if(!r)continue;let i=dm(r.content,t);if(i)return i}}function dm(e,t){let n=Y(Y(e)?.["application/json"]),s=Y(n?.schema);if(s&&!("$ref"in s))return ot(s,t)}function Ye(e){return{kind:e,nullable:!1,props:[],enumVals:[]}}var rm=2e5,pa=class{left=rm;spend(){if(--this.left<0)throw new Error(`the contract's schemas make more than ${rm} nodes once read (each type a \`type\` list names is the schema read again, at every level it is nested) \u2014 simplify the backend's schemas and push again`)}};function ot(e,t){t.spend();let n=e.nullable===!0||Array.isArray(e.type)&&e.type.includes("null");if(e.const===null)return Ye("null");if(["string","number","boolean"].includes(typeof e.const))return{...Ye("literal"),nullable:n,literal:e.const};let s=e.anyOf??e.oneOf;if(Array.isArray(s)&&s.length>0){let i=s.map(l=>ot(Y(l)??{},t));n||=i.some(l=>l.kind==="null");let o=i.filter(l=>l.kind!=="null");return o.length===0?Ye("null"):o.length===1?{...o[0],nullable:n||o[0].nullable}:{...Ye("union"),nullable:n,members:o}}let a=e.enum;if(Array.isArray(a)){let i=[],o=!0;for(let l of a)if(typeof l=="string")i.push(l);else{o=!1;break}if(o&&i.length>0)return{...Ye("enum"),nullable:n,enumVals:i};if(a.length>0&&a.every(l=>l===null||["string","number","boolean"].includes(typeof l)))return ot({anyOf:a.map(l=>({const:l})),nullable:n},t)}let r=at(e.type);if(r===""&&Array.isArray(e.type)){let i=[...new Set(e.type)];if(i.filter(l=>typeof l=="string"&&l!=="null").length>1)return ot({anyOf:i.map(l=>({...e,type:l})),nullable:n},t);for(let l of i)typeof l=="string"&&(l==="null"?n=!0:r===""&&(r=l))}switch(r){case"null":return Ye("null");case"string":case"number":case"integer":case"boolean":return{...Ye(r),nullable:n};case"array":{let i=Y(e.items),o=i?ot(i,t):Ye("any");return{...Ye("array"),nullable:n,elem:o,...e.maxItems===0?{empty:!0}:{}}}case"object":return im(e,n,t);default:return"properties"in e?im(e,n,t):{...Ye("any"),nullable:n}}}function im(e,t,n){let s=Y(e.properties)??{},a=new Set;if(Array.isArray(e.required))for(let l of e.required)typeof l=="string"&&a.add(l);let r=Object.keys(s).sort(),i=[];for(let l of r){let d=Y(s[l]),p=d?ot(d,n):Ye("any");i.push({name:l,schema:p,required:a.has(l)})}let o=Y(e.additionalProperties);return{...Ye("object"),nullable:t,props:i,...o?{additional:ot(o,n)}:e.additionalProperties===!1?{additional:!1}:{}}}function TS(e,t=new pa){let n=Y(e),s=Y(n?.["x-palbase-gateways"]);if(!s||!n)return[];let a=[];for(let[r,i]of Object.entries(s)){let o=Y(i),l=at(o?.pattern);!o||l===""||!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(r)||ym.has(r)||VS.has(r)||a.push({name:r,pattern:l,params:ES(l),durable:typeof o.durable=="number"&&o.durable>0,chat:o.chat===!0,events:CS(o.events,n,t),messages:jS(o.messages,n,t)})}return a.sort((r,i)=>r.name<i.name?-1:r.name>i.name?1:0),a}function ES(e){let t=[];for(let n of e.split(":"))n.startsWith("{")&&n.endsWith("}")&&n.length>2&&t.push(n.slice(1,-1));return t}function CS(e,t,n){let s=Y(e);if(!s)return[];let a=[];for(let[r,i]of Object.entries(s)){let o=Y(i);if(!o)continue;let l=Io(o,t)??o;a.push({name:r,schema:ot(l,n)})}return a.sort((r,i)=>r.name<i.name?-1:r.name>i.name?1:0),a}function jS(e,t,n){let s=Y(e);if(!s)return[];let a=[];for(let[r,i]of Object.entries(s)){let o=Y(i),l=Y(o?.payload);if(!o||!l)continue;let d=Y(o.reply);a.push({name:r,schema:ot(Io(l,t)??l,n),...d?{reply:ot(Io(d,t)??d,n)}:{}})}return a.sort((r,i)=>r.name<i.name?-1:r.name>i.name?1:0),a}function Io(e,t){let n=at(e.$ref);if(!n.startsWith("#/"))return;let s=t;for(let a of n.slice(2).split("/")){let r=a.replace(/~1/g,"/").replace(/~0/g,"~"),i=Y(s);if(!i||!Object.hasOwn(i,r))return;s=i[r]}return Y(s)}function Er(e){return e.split(".").filter(t=>t!=="")}function st(e){return Rr(e,!0)}function Cr(e){return Er(e).map(st).join("")}function Rr(e,t){let n=[],s="";for(let r of e)/^[A-Za-z0-9]$/.test(r)?s+=r:s.length>0&&(n.push(s),s="");if(s.length>0&&n.push(s),n.length===0)return t?"Op":"op";let a="";if(n.forEach((r,i)=>{a+=i===0&&!t?r.charAt(0).toLowerCase()+r.slice(1):r.charAt(0).toUpperCase()+r.slice(1)}),a.charAt(0)>="0"&&a.charAt(0)<="9"&&(a=`_${a}`),!kr.test(a))throw new Error(`${JSON.stringify(e)} does not make an identifier`);return a}function um(e,t){if(!$r(t.client))throw new Error(`${JSON.stringify(t.client)} cannot name a backend: it is an identifier the client does not keep (RESERVED_CLIENT_NAMES)`);try{nm(t.project)}catch(P){throw new Error(`the project's address ${JSON.stringify(t.project)}: ${P instanceof Error?P.message:String(P)}`)}if(!em(t.machine))throw new Error(`${JSON.stringify(t.machine)} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);try{tm(t.url)}catch(P){throw new Error(`the machine's address ${JSON.stringify(t.url)}: ${P instanceof Error?P.message:String(P)}`)}let n=new pa,s=wS(e,n),a=TS(e,n),r=OS(e),i=[],o=[],l=new Set;for(let P of s){let[L]=Er(P.operationId);if(L!==void 0){if(Qh(L)){let U=L.toLowerCase();l.has(U)||(l.add(U),o.push(L));continue}i.push(P)}}o.sort();let[d,p]=MS(i),u=new Lo,[m,b,w]=IS(d,u),_=d.filter(P=>!w.has(P.operationId)),[T,S]=KS(_,u),$="";for(let P of t.header)$+=P===""?`//
|
|
564
|
-
`:`// ${
|
|
564
|
+
`:`// ${$e(P)}
|
|
565
565
|
`;let R=["BackendBase"];S>0&&R.push("BackendError"),_.some(P=>!P.upload)&&R.push("CallOptions"),_.some(P=>P.upload)&&R.push("UploadOptions"),$+=`import type { ${R.join(", ")} } from 'palbase/web';
|
|
566
566
|
`,$+=`import { __registerBackend } from 'palbase/web/palbe';
|
|
567
567
|
|
|
568
568
|
`,$+=m,$+=T,$+=`// \u2500\u2500 Namespaces \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
569
569
|
|
|
570
|
-
`;for(let P of o)$+=`// codegen: skipped reserved namespace "${
|
|
570
|
+
`;for(let P of o)$+=`// codegen: skipped reserved namespace "${$e(P)}"
|
|
571
571
|
`;for(let P of p)$+=`${P}
|
|
572
572
|
`;for(let P of b)$+=`${P}
|
|
573
573
|
`;if($+=GS(_,t),$+=`
|
|
574
574
|
`,$+=BS(_),a.length>0){$+=`
|
|
575
575
|
// \u2500\u2500 Gateways (@Gateway) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
576
576
|
|
|
577
|
-
`;for(let P of a)$+=XS(P,u)}return r!==void 0&&($+=QS(r)),$}var Lo=class{made=new Map(["__registerBackend","BackendBase","BackendError","CallOptions","UploadOptions","Backend","Roles","Role","Permissions","Permission"].map(t=>[t,"the module itself"]));claim(t,n){let s=this.made.get(t);if(s!==void 0)throw new Error(`${s} and ${n} both make the name ${t} \u2014 rename one in the backend and push again`);return this.made.set(t,n),t}},Ar=e=>`operation ${JSON.stringify(e.operationId)}`,cm=(e,t)=>`${Ar(e)}'s error ${JSON.stringify(t.name)}`,Pr=e=>`gateway ${e.name} (${JSON.stringify(e.pattern)})`;function OS(e){let t=Y(e)?.["x-palbase-roles"];if(t===void 0)return;let n=Y(t);if(!n||!Array.isArray(n.roles))throw new Error("this contract's `x-palbase-roles` carries no roles list, so what the stack defines cannot be read from it. Refresh the contract; if it comes back the same, the stack is serving a malformed document.");return t}function MS(e){let t=[],n=[],s=new Tr;for(let a of e){let r=Er(a.operationId),i=r[r.length-1];if(i===void 0)continue;let o=!1;for(let d of r.slice(1))if(Sr(d)){n.push(`// codegen: skipped operation "${
|
|
577
|
+
`;for(let P of a)$+=XS(P,u)}return r!==void 0&&($+=QS(r)),$}var Lo=class{made=new Map(["__registerBackend","BackendBase","BackendError","CallOptions","UploadOptions","Backend","Roles","Role","Permissions","Permission"].map(t=>[t,"the module itself"]));claim(t,n){let s=this.made.get(t);if(s!==void 0)throw new Error(`${s} and ${n} both make the name ${t} \u2014 rename one in the backend and push again`);return this.made.set(t,n),t}},Ar=e=>`operation ${JSON.stringify(e.operationId)}`,cm=(e,t)=>`${Ar(e)}'s error ${JSON.stringify(t.name)}`,Pr=e=>`gateway ${e.name} (${JSON.stringify(e.pattern)})`;function OS(e){let t=Y(e)?.["x-palbase-roles"];if(t===void 0)return;let n=Y(t);if(!n||!Array.isArray(n.roles))throw new Error("this contract's `x-palbase-roles` carries no roles list, so what the stack defines cannot be read from it. Refresh the contract; if it comes back the same, the stack is serving a malformed document.");return t}function MS(e){let t=[],n=[],s=new Tr;for(let a of e){let r=Er(a.operationId),i=r[r.length-1];if(i===void 0)continue;let o=!1;for(let d of r.slice(1))if(Sr(d)){n.push(`// codegen: skipped operation "${$e(a.operationId)}" (reserved segment "${$e(d)}")`),o=!0;break}if(o)continue;if(a.input&&a.query){n.push(`// codegen: skipped operation "${$e(a.operationId)}" (both body and query declared \u2014 unsupported)`);continue}if(a.sse&&a.query){n.push(`// codegen: skipped operation "${$e(a.operationId)}" (streaming with query parameters \u2014 unsupported)`);continue}if(a.upload&&(a.method!=="POST"||a.sse)){n.push(`// codegen: skipped operation "${$e(a.operationId)}" (an upload that is not one POST answered once \u2014 unsupported)`);continue}if(a.query){let d=xS(a.query);if(d!==void 0){n.push(`// codegen: skipped operation "${$e(a.operationId)}" (non-primitive query parameter "${$e(d)}")`);continue}}let l=s;for(let d of r.slice(0,-1))if(l=l.childNode(d),!l)break;if(!l?.addMethod(i,a)){n.push(`// codegen: skipped operation "${$e(a.operationId)}" (key collides with existing namespace/method)`);continue}t.push(a)}return[t,n]}function xS(e){for(let t of e.props)switch(t.schema.kind){case"string":case"number":case"integer":case"boolean":case"enum":break;default:return t.name}}function IS(e,t){let n=new Set,s=new Map,a=[],r=[];for(let o of e){let l=Cr(o.operationId),d=s.get(l);if(d!==void 0){a.push(`// codegen: skipped type "${$e(l)}" (collides with operation "${$e(d)}")`),n.add(o.operationId);continue}s.set(l,o.operationId),o.input&&r.push(...En(t.claim(`${l}Request`,Ar(o)),o.input)),o.query&&r.push(...En(t.claim(`${l}Query`,Ar(o)),o.query)),o.output&&r.push(...LS(l,o.output,u=>t.claim(u,Ar(o))));let p=Do(o);for(let u of p){if(!u.data)continue;let m=t.claim(`${l}${st(u.name)}Data`,cm(o,u));r.push(`/** ${$e(u.code)} (${u.status}): ${$e(u.description)} */`),r.push(...En(m,u.data))}}if(r.length===0)return["",a,n];let i=`// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
578
578
|
|
|
579
579
|
`;for(let o of r)i+=`${o}
|
|
580
580
|
`;return[i,a,n]}function En(e,t){return t.kind==="object"&&!t.nullable&&t.props.length>0&&!t.additional?hm(e,t):[`export type ${e} = ${jn(t)};`,""]}function LS(e,t,n){return t.kind==="array"&&!t.empty&&t.elem&&t.elem.kind==="object"&&!t.elem.nullable&&t.elem.props.length>0&&!t.elem.additional?[...hm(n(`${e}ResponseItem`),t.elem),`export type ${n(`${e}Response`)} = ${e}ResponseItem[]${t.nullable?" | null":""};`,""]:En(n(`${e}Response`),t)}function hm(e,t){let n=[`export interface ${e} {`];for(let s of t.props){if(s.name==="__proto__"){n.push(' // codegen: skipped property "__proto__"');continue}let a=s.required?"":"?";n.push(` ${wt(s.name)}${a}: ${jn(s.schema)};`)}return n.push("}",""),n}function jn(e){switch(e.kind){case"string":return e.nullable?"string | null":"string";case"number":case"integer":return e.nullable?"number | null":"number";case"boolean":return e.nullable?"boolean | null":"boolean";case"null":return"null";case"literal":{if(typeof e.literal=="number"&&!Number.isFinite(e.literal))throw new Error(`the literal ${e.literal} is not a finite number`);let t=typeof e.literal=="string"?ge(e.literal):JSON.stringify(e.literal);return e.nullable?`${t} | null`:t}case"union":{let t=(e.members??[]).map(jn);return e.nullable&&t.push("null"),t.join(" | ")}case"enum":{let t=e.enumVals.map(ge).join(" | ");return e.nullable?`(${t}) | null`:t}case"array":{if(e.empty)return e.nullable?"[] | null":"[]";if(!e.elem)return e.nullable?"unknown[] | null":"unknown[]";let t=jn(e.elem);(t.includes(" | ")||t.startsWith("("))&&(t=`(${t})`);let n=`${t}[]`;return e.nullable?`${n} | null`:n}case"object":{let t=DS(e);return e.nullable?`${t} | null`:t}default:return e.nullable?"unknown | null":"unknown"}}function DS(e){let t=[];for(let n of e.props){if(n.name==="__proto__")continue;let s=n.required?"":"?";t.push(`${wt(n.name)}${s}: ${jn(n.schema)}`)}if(e.additional){let n=`Record<string, ${jn(e.additional)}>`;return t.length===0?n:`({ ${t.join("; ")} } & ${n})`}return t.length===0?e.additional===!1?"Record<string, never>":"Record<string, unknown>":`{ ${t.join("; ")} }`}var qS=new Set(["not_configured","network_error","decode_error","validation_error","invalid_endpoint_name","unsupported_get_input","missing_path_param","unexpected_argument","invalid_query_value","reserved_namespace","invalid_namespace_tree","aborted","http_error","invalid_path_parameter","invalid_json","empty_stream","stream_failed","invalid_frame","invalid_path","missing_credential","undeclared_answer","undeclared_redirect","pow_unsolved","invalid_file"]),NS=/^http_\d+$/;function Do(e){if(e.errors.length===0)return[];let t=r=>{throw new Error(`${e.operationId}: ${r} \u2014 rename the error in the backend and push again`)},n=[...e.errors].sort((r,i)=>r.code<i.code?-1:r.code>i.code?1:0),s=new Set,a=new Map;for(let r of n){r.code==="__proto__"&&t('declares the error code "__proto__", which no lookup can hold'),(qS.has(r.code)||NS.test(r.code))&&t(`declares the error "${r.code}", a code the web client produces itself \u2014 the two could not be told apart`),s.has(r.code)&&t(`declares the error code "${r.code}" twice`);let i=st(r.name),o=a.get(i);o!==void 0&&t(`declares errors "${o}" and "${r.name}", which both become the class ${i}`),s.add(r.code),a.set(i,r.name)}return n}function KS(e,t){let n=0,s=[];for(let r of e){let i=Cr(r.operationId),o=Do(r);for(let l of o){let d=t.claim(`${i}${st(l.name)}Error`,cm(r,l)),p=l.data!==void 0;s.push(`export class ${d} extends Error {`),s.push(` readonly name = ${ge(d)};`),s.push(` readonly code = ${ge(l.code)};`),s.push(` readonly status = ${l.status};`),p&&s.push(` readonly data: ${i}${st(l.name)}Data;`),s.push(" readonly cause: BackendError;"),s.push(" constructor(cause: BackendError) {"),s.push(" super(cause.message);"),s.push(" this.cause = cause;"),p&&s.push(` this.data = cause.data as ${i}${st(l.name)}Data;`),s.push(" }"),s.push("}"),s.push(""),n++}}if(n===0)return["",0];let a=`// \u2500\u2500 Typed errors \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
@@ -604,8 +604,8 @@ public typealias JSONValue = JsonElement
|
|
|
604
604
|
`,s+=fm(a.child,t+2),s+=`${n}};
|
|
605
605
|
`;continue}a.op&&(s+=`${n}${HS(a.key)}${FS(a.op)};
|
|
606
606
|
`)}return s}function FS(e){let t=Cr(e.operationId),n=[],s=new Set;for(let r of e.pathParams)n.push(`${WS(r,s)}: string`);e.input?n.push(`input: ${t}Request`):e.query&&n.push(`query: ${t}Query`),e.upload?n.push("file: Blob","options?: UploadOptions"):n.push(JS(e.headers));let a=e.sse?`Promise<AsyncIterable<${e.output?`${t}Response`:"unknown"}>>`:e.output?`Promise<${t}Response>`:"Promise<void>";return`(${n.join(", ")}): ${a}`}function JS(e){if(!e||e.props.length===0)return"options?: CallOptions";let t=e.props.some(a=>a.required),s=`{ ${e.props.map(a=>{let r=a.required?"":"?";return`${wt(a.name)}${r}: ${jn(a.schema)}`}).join("; ")} }`;return t?`options: CallOptions & { headers: ${s} }`:`options?: CallOptions & { headers?: ${s} }`}function WS(e,t){let n=Rr(e,!1);(ym.has(n)||n==="input"||n==="query"||n==="options")&&(n+="_");let s=n;for(let a=2;t.has(s);a++)s=n+a;return t.add(s),s}var VS=new Set("undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),ym=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval".split(" "));function wt(e){return kr.test(e)?e:ge(e)}function HS(e){return e==="new"?ge(e):wt(e)}var YS=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069\ud800-\udfff]/;function bm(e,t){switch(e){case"\\":return"\\\\";case`
|
|
607
|
-
`:return"\\n";case"\r":return"\\r";case"'":return t?"\\'":e}return e.length===1&&YS.test(e)?`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`:e}function ge(e){let t="'";for(let n of e)t+=bm(n,!0);return`${t}'`}function
|
|
608
|
-
`)}function ZS(e){if(typeof e!="object"||e===null||!("roles"in e)||!Array.isArray(e.roles))throw new Error("roles artifact has no roles list");return e.roles.map((t,n)=>{if(typeof t!="object"||t===null)throw new Error(`roles artifact entry ${n} is not a role`);if(!("name"in t)||typeof t.name!="string"||t.name==="")throw new Error(`roles artifact entry ${n} has no name`);let s=t.name;if(!("isDefault"in t)||typeof t.isDefault!="boolean")throw new Error(`role "${s}" does not say whether it is the default`);if(!("permissions"in t)||!Array.isArray(t.permissions))throw new Error(`role "${s}" does not carry a list of permission names`);let a=[];for(let i of t.permissions){if(typeof i!="string")throw new Error(`role "${s}" lists a permission that is not a name`);a.push(i)}let r={name:s,isDefault:t.isDefault,permissions:a};return"description"in t&&typeof t.description=="string"&&t.description!==""&&(r.description=t.description),r})}function QS(e){let t=ZS(e).sort((d,p)=>d.name<p.name?-1:d.name>p.name?1:0),n=[...new Set(t.flatMap(d=>d.permissions))].sort(),s=[],a=new Map;for(let d of t){let p=Rr(d.name,!1),u=a.get(p);if(u!==void 0){s.push(` // codegen: skipped duplicate role "${
|
|
607
|
+
`:return"\\n";case"\r":return"\\r";case"'":return t?"\\'":e}return e.length===1&&YS.test(e)?`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`:e}function ge(e){let t="'";for(let n of e)t+=bm(n,!0);return`${t}'`}function $e(e){let t="";for(let n of e)t+=n==="@"?"\\u0040":n==="#"?"\\u0023":bm(n,!1);return t.replaceAll("*/","*\\/")}function XS(e,t){let n=e.name,s=[];for(let r of e.events)s.push(...En(t.claim(`${n}${st(r.name)}Event`,`${Pr(e)}'s event ${JSON.stringify(r.name)}`),r.schema));for(let r of e.messages)s.push(...En(t.claim(`${n}${st(r.name)}Message`,`${Pr(e)}'s message ${JSON.stringify(r.name)}`),r.schema)),r.reply&&s.push(...En(t.claim(`${n}${st(r.name)}Reply`,`${Pr(e)}'s ack of ${JSON.stringify(r.name)}`),r.reply));for(let r of[`${n}Event`,`${n}Params`,n])t.claim(r,Pr(e));if(e.events.length>0){s.push(`export type ${n}Event =`);for(let r of e.events)s.push(` | { event: ${ge(r.name)}; payload: ${n}${st(r.name)}Event }`);s[s.length-1]+=";"}else s.push(`export type ${n}Event = never;`);s.push("");let a=e.params.map(r=>`${wt(r)}: string`).join("; ");return s.push(`export interface ${n}Params { ${a} }`),s.push(`export const ${n} = {`),s.push(` name: ${ge(n)},`),s.push(` pattern: ${ge(e.pattern)},`),s.push(` params: [${Cn(e.params)}] as const,`),s.push(` durable: ${e.durable},`),e.chat&&s.push(" chat: true,"),s.push(` events: [${Cn(e.events.map(r=>r.name))}] as const,`),s.push(` messages: [${Cn(e.messages.map(r=>r.name))}] as const,`),s.push(` send: {} as { ${e.messages.map(r=>`${wt(r.name)}: ${n}${st(r.name)}Message`).join("; ")} },`),s.push(` reply: {} as { ${e.messages.map(r=>`${wt(r.name)}: ${r.reply?`${n}${st(r.name)}Reply`:"unknown"}`).join("; ")} },`),s.push(` event: {} as ${n}Event,`),s.push("} as const;"),s.push(""),s.join(`
|
|
608
|
+
`)}function ZS(e){if(typeof e!="object"||e===null||!("roles"in e)||!Array.isArray(e.roles))throw new Error("roles artifact has no roles list");return e.roles.map((t,n)=>{if(typeof t!="object"||t===null)throw new Error(`roles artifact entry ${n} is not a role`);if(!("name"in t)||typeof t.name!="string"||t.name==="")throw new Error(`roles artifact entry ${n} has no name`);let s=t.name;if(!("isDefault"in t)||typeof t.isDefault!="boolean")throw new Error(`role "${s}" does not say whether it is the default`);if(!("permissions"in t)||!Array.isArray(t.permissions))throw new Error(`role "${s}" does not carry a list of permission names`);let a=[];for(let i of t.permissions){if(typeof i!="string")throw new Error(`role "${s}" lists a permission that is not a name`);a.push(i)}let r={name:s,isDefault:t.isDefault,permissions:a};return"description"in t&&typeof t.description=="string"&&t.description!==""&&(r.description=t.description),r})}function QS(e){let t=ZS(e).sort((d,p)=>d.name<p.name?-1:d.name>p.name?1:0),n=[...new Set(t.flatMap(d=>d.permissions))].sort(),s=[],a=new Map;for(let d of t){let p=Rr(d.name,!1),u=a.get(p);if(u!==void 0){s.push(` // codegen: skipped duplicate role "${$e(d.name)}" \u2014 collides with "${$e(u)}" (both map to \`${$e(p)}\`)`);continue}a.set(p,d.name),d.description!==void 0&&s.push(` /** ${$e(d.description)} */`),d.isDefault&&s.push(" /** Assigned to every new user at signup. */"),s.push(` ${p}: ${ge(d.name)},`)}let r=[],i=new Map;for(let d of n){let p=Rr(d,!1),u=i.get(p);if(u!==void 0){r.push(` // codegen: skipped duplicate permission "${$e(d)}" \u2014 collides with "${$e(u)}" (both map to \`${$e(p)}\`)`);continue}i.set(p,d),r.push(` ${p}: ${ge(d)},`)}let o="";if(a.size>0&&(o+=`export const Roles = {
|
|
609
609
|
`,o+=`${s.join(`
|
|
610
610
|
`)}
|
|
611
611
|
`,o+=`} as const;
|
|
@@ -694,7 +694,7 @@ ${t}}`}var zt=e=>["",e.toUpperCase(),"-".repeat(e.length)],$A=[{title:"One packa
|
|
|
694
694
|
`)}},Wj={name:"auth:signing-keys",summary:"the keys the environment's tokens are signed with: the active one, those still verifying, the retired",scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET","/admin/signing-keys");e.out.result(n,()=>{e.out.table(n.keys,[{header:"kid",value:s=>A(s.kid)+(s.kid===n.active_kid?" (signing)":"")},{header:"status",value:s=>A(s.status)},{header:"algorithm",value:s=>A(s.algorithm)},{header:"created",value:s=>_t(s.created_at)},{header:"retired",value:s=>_t(s.retired_at)}]),n.next_rotation&&e.out.line(`The next key starts signing ${_t(n.next_rotation)}.`)})}},Vj={name:"auth:signing-keys:rotate",summary:"sign with a new key from now on; tokens the old one signed go on verifying until they end",scope:"environment",async run(e){let t=await f(e);await v(e,t,"rotate the token signing key");let n=await h(e,t,"POST","/admin/signing-keys/rotate");e.out.result(n,()=>e.out.line(`Tokens are signed with ${A(n.new_kid)} from now on; the old key goes on verifying the tokens it signed.`))}},Hj={name:"auth:users:export",summary:"everything the environment holds about one user, as the law lets them ask for it (GDPR art. 15/20): JSON",usage:"<user-id> [--out <file>]",args:{min:1,max:1},flags:{out:{type:"string",value:"file",description:"write it here instead of to standard output"}},scope:"environment",async run(e){let t=await f(e),n=Vt(e.args[0]),s=await h(e,t,"GET",`/admin/users/${k(n)}/export`),a=`${JSON.stringify(s,null,2)}
|
|
695
695
|
`;typeof e.flags.out=="string"?(await Ey(Cy(e.io.cwd,e.flags.out),a,{mode:384}),e.out.result({file:e.flags.out},()=>e.out.line(`Wrote ${n}'s data to ${e.flags.out}.`))):e.io.stdout(a)}},Yj={name:"realtime:broadcast",summary:"send an event to a channel's subscribers, as the server does: its payload JSON (or text)",usage:"<topic> <event> [payload]",args:{min:2,max:3},scope:"environment",async run(e){let t=await f(e),[n,s,a]=e.args,r=a===void 0?null:St(a);await v(e,t,`broadcast ${s} on ${n}`);let i=await h(e,t,"POST","/realtime/broadcast",{messages:[{topic:n,event:s,payload:r}]});e.out.result(i??{sent:1},()=>e.out.line(`Broadcast ${A(s)} on ${A(n)}.`))}},Xj={name:"analytics:events",summary:"the events analytics recorded, newest first: by name, by user, over a window",usage:"[--name <event>] [--user <distinct-id>] [--window <24h>] [--limit <n>]",flags:{name:{type:"string",value:"event",description:"only this event's"},user:{type:"string",value:"id",description:"only this user's (their distinct id)"},window:{type:"string",value:"span",description:"how far back: 30m, 24h, 7d (default 24h)"},limit:{type:"string",value:"n",description:"how many (default 50)"}},scope:"environment",async run(e){let t=await f(e),n=new URLSearchParams({window_seconds:String(jy(e.flags.window,"window")??86400),limit:String(Nn(e.flags.limit,"limit",1,1e3)??50),...e.flags.name?{name:e.flags.name}:{},...e.flags.user?{distinct_id:e.flags.user}:{}}),s=await h(e,t,"GET",`/analytics/events?${n}`);e.out.result(s,()=>{s.events.length===0&&e.out.line("No event in the window.");for(let a of s.events)e.out.line(`${A(_t(a.timestamp??a.ts))} ${A(a.name)} ${A(a.distinct_id??"")}${a.properties&&Object.keys(a.properties).length?` ${A(JSON.stringify(a.properties)).slice(0,200)}`:""}`)})}},Zj={name:"analytics:summary",summary:"what analytics counted over a window: events, users, sessions, the top events",usage:"[--window <24h>]",flags:{window:{type:"string",value:"span",description:"how far back: 30m, 24h, 7d (default 24h)"}},scope:"environment",async run(e){let t=await f(e),n=await h(e,t,"GET",`/analytics/summary?window_seconds=${jy(e.flags.window,"window")??86400}`);e.out.result(n,()=>{for(let[s,a]of Object.entries(n))e.out.line(`${A(s)}: ${typeof a=="object"?JSON.stringify(a):A(String(a))}`)})}},qy=[wj,vj,_j,kj,Sj,$j,Pj,Hj,Bj,Fj,Jj,Wj,Vj,Ej,Cj,jj,Oj,Mj,xj,Ij,Lj,Dj,Nj,Kj,Gj,Uj,zj,Yj,Xj,Zj];var Aa=["machines:read","machines:logs","machines:previews","apps:sync","auth:test-users","support"];function Ny(e){return e.scopes===null?"its minter's role":e.scopes.join(", ")}var Qj={name:"env:tokens:create",summary:"mint a token of the environment for a program (an AI agent): your role in this environment alone, a few hours; shown this once",usage:"[--scope <scope>[,<scope>]] [--minutes <n>] [--name <name>]",details:["It does in this environment what your role does \u2014 as your own CLI would \u2014 but never makes or shows a standing credential (a key, a token), changes people or roles, or deletes a project or an environment; nothing beyond this environment.",`--scope narrows it to: ${Aa.join(", ")} \u2014 machines:read reads the machines, their builds, crons, queues and pull requests' previews; machines:logs their logs; machines:previews opens a pull request's preview again (machines:previews:open: what a push to it would build anyway); apps:sync what palbase apps:sync reads; auth:test-users makes and deletes test users; support asks Palbase's support line (palbase support:ask).`,"Give it to the program as PALBASE_TOKEN: the CLI acts in this environment alone with it. It ends after --minutes (default 60, at most 240), and with what minted it."],flags:{scope:{type:"string",multiple:!0,value:"scope",description:`narrow it to: ${Aa.join(", ")} (comma-separated, or given again); none: your role`},minutes:{type:"string",value:"n",description:"how long it lives (default 60, at most 240)"},name:{type:"string",value:"name",description:"what it is for, as the environment lists it"}},scope:"environment",async run(e){let t=re(e.flags.scope),n=t===void 0?void 0:[...new Set(t)];if(n!==void 0&&n.length===0)throw g(`--scope names what the token is narrowed to: ${Aa.join(", ")}`);let s=(n??[]).filter(o=>!Aa.includes(o));if(s.length>0)throw g(`${s.join(", ")}: no scope of an environment's token (${Aa.join(", ")})`);let a=e.flags.minutes===void 0?60:Number(e.flags.minutes);if(!Number.isInteger(a)||a<5||a>240)throw g("--minutes is a whole number from 5 to 240");let r=await f(e),i=await e.studio.post(`/environments/${r.env_ref}/tokens`,{...n!==void 0?{scopes:n}:{},expires_in_minutes:a,...typeof e.flags.name=="string"?{name:e.flags.name}:{}});e.out.result(i,()=>{e.out.line(`Minted ${K(i.name)} for ${q(r)} (${Ny(i)}; until ${i.expires_at.slice(0,16).replace("T"," ")} UTC).`),e.out.line(`token (shown this once \u2014 the program's PALBASE_TOKEN): ${i.token}`)})}},eO={name:"env:tokens:list",summary:"the environment's live tokens, by their hint (never their values)",scope:"environment",async run(e){let t=await f(e),{tokens:n}=await e.studio.get(`/environments/${t.env_ref}/tokens`);e.out.result({tokens:n},()=>{n.length===0&&e.out.line(`${q(t)} has no live token: palbase env:tokens:create --scope <scope> mints one.`),e.out.table(n,[{header:"id",value:s=>s.id},{header:"name",value:s=>K(s.name)},{header:"can",value:s=>Ny(s)},{header:"ends",value:s=>s.expires_at.slice(0,16).replace("T"," ")},{header:"minted by",value:s=>s.minted_by},{header:"hint",value:s=>`\u2026${s.hint}`}])})}},tO={name:"env:tokens:revoke",summary:"revoke an environment's token (by its id; with PALBASE_TOKEN an environment's token, `self` revokes it): refused from its next request on",usage:"<id|self>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=e.args[0];if(n==="self"){let s=(await e.studio.get("/environments")).environments.find(a=>a.ref===t.env_ref)?.token_id;if(!s)throw new y("not_a_token","self is the environment token PALBASE_TOKEN is, and it is none",{hint:"name the token by its id: palbase env:tokens:list"});n=s}await e.studio.request("DELETE",`/environments/${D("the environment's ref",t.env_ref)}/tokens/${D("the token's id",n)}`),e.out.result({revoked:n},()=>e.out.line(`Revoked the environment token ${n} of ${q(t)}.`))}},Ky=[eO,Qj,tO];var As={org:{type:"string",value:"org",description:"the organization (name or id; the one of the environment chosen here, or your only one)"}};function De(e){let t=e<0?"-":"",n=Math.abs(e);if(n>0&&n<1e4)return`${t}$${(n/1e6).toFixed(6).replace(/0{1,4}$/,"")}`;let s=Math.round(n/1e4);return`${t}$${Math.floor(s/100).toLocaleString("en-US")}.${String(s%100).padStart(2,"0")}`}function nO(e,t){let n=typeof e=="string"?/^\s*\$?\s*(\d{1,9})(?:\.(\d{1,2}))?\s*$/.exec(e):null;if(!n)throw g(`${t} is an amount in US dollars, to the cent (20 or 20.50)`);return Number(n[1])*1e6+Number((n[2]??"").padEnd(2,"0"))*1e4}var Ps=e=>`${(e/2**30).toFixed(2)} GiB`,Gy=e=>`${(e/1e9).toFixed(2)} GB`,zl=e=>e.toLocaleString("en-US"),Uy={egress:Ps,storage:e=>`${Ps(e)} (month's peak)`,"db.backups":e=>`${Ps(e)} (month's peak)`,images:e=>`${Ps(e)} (month's peak)`,logs:Ps,cache:e=>`${(e/2**20).toFixed(1)} MiB (month's peak)`,builds:e=>`${(e/60).toFixed(1)} min`,"ai.workspaces":e=>`${(e/3600).toFixed(1)} h`,"ai.models":e=>`$${(e/1e9).toFixed(4)} at the provider`,"calls.data":Gy,"db.disk":e=>`${(e/(730*3600)).toFixed(2)} GiB-month`,"db.traffic":Gy,"sites.storage":e=>`${Ps(e)} (month's peak)`,domains:e=>`${zl(e)} (month's most)`,tasks:zl};function sO(e,t){return e.startsWith("machine.")||e.startsWith("db.")&&!Uy[e]?`${(t/3600).toFixed(1)} h`:(Uy[e]??zl)(t)}async function Rs(e){let t=e.flags.org;return t===void 0&&(t=(await e.state.targetFor(e.io.cwd))?.target.org_id),gt(e,t)}async function aO(e,t){let n=await Re(e.studio);if(t===void 0){let i=(await e.state.targetFor(e.io.cwd))?.target.env_ref;if(!i)throw g("name the environment: its ref, or project/env (palbase projects:list shows them)");t=i}let s=t.lastIndexOf("/"),a=n.filter(i=>i.ref===t||s>0&&i.slug===t.slice(s+1)&&(i.project_name===t.slice(0,s)||`${i.org_name}/${i.project_name}`===t.slice(0,s)));if(a.length===0)throw new y("no_such_environment",`no environment ${JSON.stringify(t)} among yours`,{hint:"name it by its ref, or project/env: palbase projects:list shows them"});if(a.length>1)throw new y("ambiguous_environment",`${JSON.stringify(t)} names more than one environment`,{hint:"name it by its ref"});let r=a[0];return{ref:r.ref,organization_id:r.organization_id,where:`${r.org_name} \u203A ${r.project_name} \u203A ${r.name}`}}function By(e,t){return e.gone?"purged":e.deleted?"deleted":e.frozen?"frozen":e.plan==="free"?"Free":e.at_limit?"at its limit (Free until the month ends)":t?"Pay as you go, held to the Free quotas (its payment account is unpaid)":e.paid?"Pay as you go":"Pay as you go (Free quotas)"}function Fy(e){if(e.exempt)return"Not billed: measured, never charged";let t=e.paid_by;if(!t)return"no payment account pays for it (Studio, Billing): 2 Free projects of 2 environments each";let n=t.organization_id===e.organization_id,s=e.account,a=n?"paid for by its own payment account":`paid for by ${K(t.name)}'s payment account`;return n&&s&&(a+=` \xB7 ${s.payment_method?`card ${K(s.payment_method)}`:"no card saved yet"}${s.stripe_mode==="test"?" \xB7 test mode":""}`),t.held&&(a+=" \xB7 HELD: its environments are on the Free quotas until it pays"),a}function rO(e){let t=[`owed, not yet charged: ${De(e.owed_micros)} \u2014 charged at ${De(e.threshold_micros)}, and at the month's end`];return e.unpaid_micros>0&&t.push(`unpaid: ${De(e.unpaid_micros)}${e.free_on?` \u2014 its environments go Free on ${e.free_on.slice(0,10)} if it is still unpaid`:""}`),e.held&&t.push(e.held==="disputed"?"held: a payment was disputed \u2014 save a card in Studio to go on":"held: unpaid \u2014 it goes on once the charge is paid"),e.paid_organizations>1&&t.push(`it pays for ${e.paid_organizations} organizations (palbase billing:paid)`),t}function iO(e,t,n){let s=new Map(n.environments.map(i=>[i.platform_id,`${i.project_name} \u203A ${i.name}`]));if(e.out.line(`${K(t)} \u2014 ${Fy(n)}`),n.account&&n.paid_by?.organization_id===n.organization_id)for(let i of rO(n.account))e.out.line(i);let a=new Date(`${n.period}-01T00:00:00Z`).toLocaleDateString("en-US",{month:"long",year:"numeric",timeZone:"UTC"});n.owed_micros!==void 0&&e.out.line(`${a}: ${De(n.exempt?n.charged_micros??0:n.owed_micros)} ${n.exempt?"priced, not charged":"owed by its environments so far"}`),e.out.line();let r=n.paid_by?.held??!1;e.out.table(n.projects.filter(i=>!i.gone),[{header:"environment",value:i=>K(s.get(i.project_id)??i.name)},{header:"ref",value:i=>i.ref},{header:"plan",value:i=>By(i,r)},{header:"this month",value:i=>i.charged_micros===void 0?"":De(i.charged_micros)},{header:"limit",value:i=>i.monthly_limit_micros==null?"":De(i.monthly_limit_micros)}])}function zy(e,t,n){e.out.line(`${K(t)} \u2014 ${By(n,!1)}`),n.monthly_limit_micros!==void 0&&e.out.line(`monthly limit: ${n.monthly_limit_micros===null?"none":De(n.monthly_limit_micros)}`),n.charged_micros!==void 0&&e.out.line(`this month: ${De(n.charged_micros)} charged of ${De(n.gross_micros??0)} at the price table (its free quota taken off)${n.owed_micros===void 0?"":`, ${De(n.owed_micros)} owed`}`)}var oO={name:"billing",summary:"who pays for an organization, how its payment account stands, and each environment's plan, month and limit",usage:"[--org <org>]",details:["A member reads the plans, what was used and who pays; the money (amounts, the card) is an owner's or an admin's."],flags:As,scope:"account",async run(e){let t=await Rs(e),n=await e.studio.get(`/orgs/${t.id}/billing`);e.out.result(n,()=>iO(e,t.name,n))}},Jy={period:{type:"string",value:"YYYY-MM",description:"the month (this one by default)"},csv:{type:"boolean",description:"print it as CSV"}};function Wy(e){let t=e.flags.period;if(t!==void 0&&!/^\d{4}-(0[1-9]|1[0-2])$/.test(t))throw g("--period is a month: YYYY-MM");return t?`?period=${t}`:""}var lO={name:"billing:charges",summary:"a month's charges, by environment and item \u2014 used, at the price table, charged past each one's free quota \u2014 as a table or as CSV",usage:"[--period <YYYY-MM>] [--csv] [--org <org>]",details:["--csv prints the CSV Studio downloads."],flags:{...As,...Jy},scope:"account",async run(e){let t=Wy(e),n=await Rs(e);if(e.flags.csv===!0){e.io.stdout(K(await e.studio.get(`/orgs/${n.id}/billing/charges.csv${t}`)));return}let s=await e.studio.get(`/orgs/${n.id}/billing/charges${t}`);e.out.result(s,()=>{if(s.charges.length===0){e.out.line(`${K(n.name)} used nothing in ${s.period}.`);return}let a=i=>K(i.environment?`${i.environment.project_name} \u203A ${i.environment.name}`:i.project_id);e.out.table(s.charges,[{header:"environment",value:a},{header:"item",value:i=>i.item},{header:"used",value:i=>i.item==="total"?"":sO(i.item,i.units)},{header:"at the price table",value:i=>De(i.gross_micros)},{header:"charged",value:i=>De(i.micros)}]);let r=Object.values(s.owed_micros).reduce((i,o)=>i+o,0);e.out.line(`${s.period}: ${De(r)} owed to the payment account that pays for it.`)})}},pO={month:"the month's charge",threshold:"charged at the threshold",checkout:"top-up (card), before",auto:"automatic top-up, before",card:"top-up (saved card), before",bank_transfer:"bank transfer, before"},dO={name:"billing:invoices",summary:"the invoices of an organization's payment account \u2014 each month's charge, and each charge at its threshold: Stripe makes one of each, and emails it",usage:"[--org <org>]",flags:As,scope:"account",async run(e){let t=await Rs(e),{invoices:n}=await e.studio.get(`/orgs/${t.id}/billing/invoices`);e.out.result({invoices:n},()=>{n.length===0?e.out.line(`${K(t.name)} has no invoice yet.`):e.out.table(n,[{header:"date",value:s=>s.created_at.slice(0,16).replace("T"," ")},{header:"charge",value:s=>pO[s.kind]??s.kind},{header:"amount",value:s=>`${De(s.amount_micros)}${s.tax_micros>0?` + ${De(s.tax_micros)} tax`:""}`},{header:"status",value:s=>s.status==="open"?"unpaid":s.status},{header:"invoice",value:s=>s.hosted_url??""}])})}},uO={name:"billing:env",summary:"an environment's place in the bill \u2014 its plan, frozen, its month's limit \u2014 read, or changed",usage:"[<project/env | ref>] [--plan free|pay_as_you_go] [--limit <usd>|none] [--frozen yes|no] [-y]",details:["With no flag it shows the environment: its plan, limit and month.","Pay as you go: what it uses past its free quota is owed to the payment account that pays for its organization (palbase billing:payer), charged at the month's end and as it comes to the account's threshold. An environment is moved to it only while its organization is paid for by an account with a card.","At its limit it is Free until the month ends; the organization's other environments go on.","Frozen, its requests are refused and its machines and databases stopped, its data kept; only what it stores is charged. Freezing asks first; -y does not."],args:{min:0,max:1},flags:{plan:{type:"string",value:"free|pay_as_you_go",description:"Free (charged nothing, held to the free quotas) or Pay as you go (what it uses past its free quota is charged)"},limit:{type:"string",value:"usd|none",description:"at most this much a month; none for no limit"},frozen:{type:"string",value:"yes|no",description:"frozen: its requests refused, its machines and databases stopped, its data kept"}},scope:"account",async run(e){let t={},n=e.flags.plan;if(n!==void 0){if(n!=="free"&&n!=="pay_as_you_go")throw g("--plan is free or pay_as_you_go");t.plan=n}e.flags.limit!==void 0&&(t.monthly_limit_micros=e.flags.limit==="none"?null:nO(e.flags.limit,"--limit"));let s=en(e.flags.frozen,"frozen");s!==void 0&&(t.frozen=s);let a=await aO(e,e.args[0]),r=`/orgs/${a.organization_id}/billing/environments/${a.ref}`;if(Object.keys(t).length===0){let o=await e.studio.get(r);e.out.result(o,()=>zy(e,a.where,o));return}if(s===!0&&!e.global.yes){if(!e.interactive)throw new y("confirmation_needed","freezing an environment refuses its requests",{hint:"confirm with -y"});let o=(await e.io.prompt(K(`Freeze ${a.where}: its requests are refused until it is thawed. Go ahead? [y/N] `))).trim().toLowerCase();if(o!=="y"&&o!=="yes")throw new y("cancelled","nothing was changed")}let i=await e.studio.request("PATCH",r,t);e.out.result(i,()=>zy(e,a.where,i))}},cO={name:"billing:payer",summary:"link an organization to the payment account that pays for it \u2014 an organization of yours whose account it is \u2014 or to none",usage:"<account org | none> [--org <org>]",details:["One payment account pays for many organizations: it is charged for what each one's environments on Pay as you go owe, in one invoice a month (palbase billing:report).","An admin of the organization who also manages the account (an owner or an admin of its organization) links it \u2014 or their account token. With none, its environments on Pay as you go go Free; what they owed so far stays the account's."],args:{min:1,max:1},flags:As,scope:"account",async run(e){let t=await Rs(e),n=e.args[0]==="none"?null:(await gt(e,e.args[0])).id,s=await e.studio.request("PUT",`/orgs/${t.id}/billing/payer`,{account:n});e.out.result(s,()=>e.out.line(`${K(t.name)} \u2014 ${Fy(s)}`))}},hO={name:"billing:paid",summary:"the organizations an organization's payment account pays for \u2014 its managers'",usage:"[--org <org>]",flags:As,scope:"account",async run(e){let t=await Rs(e),{organizations:n}=await e.studio.get(`/orgs/${t.id}/billing/paid`);e.out.result({organizations:n},()=>{n.length===0?e.out.line(`${K(t.name)}'s payment account pays for no organization.`):e.out.table(n,[{header:"organization",value:s=>K(s.name)},{header:"id",value:s=>s.organization_id},{header:"environments",value:s=>String(s.environments)},{header:"on Pay as you go",value:s=>String(s.pay_as_you_go)}])})}},mO={name:"billing:report",summary:"a payment account's month: each organization it paid for, each environment, what it owes \u2014 as a table or as CSV (item by item)",usage:"[--period <YYYY-MM>] [--csv] [--org <org>]",details:["What an organization that pays for its own customers' organizations bills them by: --csv gives each item of each environment, and what the account is charged for it (owed)."],flags:{...As,...Jy},scope:"account",async run(e){let t=Wy(e),n=await Rs(e);if(e.flags.csv===!0){e.io.stdout(K(await e.studio.get(`/orgs/${n.id}/billing/report.csv${t}`)));return}let s=await e.studio.get(`/orgs/${n.id}/billing/report${t}`);e.out.result(s,()=>{let a=s.organizations.flatMap(r=>r.environments.map(i=>({org:r.name,e:i})));if(a.length===0){e.out.line(`${K(n.name)}'s payment account owes nothing for ${s.period}.`);return}e.out.table(a,[{header:"organization",value:r=>K(r.org)},{header:"environment",value:r=>K(r.e.environment?`${r.e.environment.project_name} \u203A ${r.e.environment.name}`:r.e.name)},{header:"ref",value:r=>r.e.environment?.ref??r.e.ref},{header:"at the price table",value:r=>De(r.e.gross_micros)},{header:"owed",value:r=>De(r.e.owed_micros)}]),e.out.line(`${s.period}: ${De(s.owed_micros)} owed by ${s.organizations.length} organization${s.organizations.length===1?"":"s"}.`)})}},Vy=[oO,lO,dO,uO,cO,hO,mO];import{mkdtemp as gO,rm as fO}from"node:fs/promises";import{tmpdir as yO}from"node:os";import{extname as bO,join as Hy}from"node:path";async function Ra(e,t,n){if(n!==void 0)return n;let{body:s}=await ye(e.studio,t.env_ref,"GET","/databases?limit=100");if(s.databases.length===1)return s.databases[0].name;throw s.databases.length===0?new y("no_database","the environment has no database",{hint:"palbase databases:create opens one"}):g("which database? name it",`the environment's databases: ${s.databases.map(a=>a.name).join(", ")}`)}async function Ht(e,t,n,s,a){let{body:r}=await ye(e.studio,t.env_ref,"GET",`/databases/${D("the database's name",n)}/credentials`),i=(await e.state.databasePasswords(t.env_ref,n))[s];if(!i)throw new y("no_password",`this computer holds no ${s} password of ${n}: the platform showed it once, where the database was opened`,{hint:`palbase databases:password:reset ${n} --role ${s} makes a new one and keeps it here${s==="app"?" (the machines given it roll out with it)":""}`});let o=s==="owner"?r.owner:r.app,l=new URL(a?o.pooled_url:o.url);return l.password="",{url:l.toString(),password:i,role:s}}function wO(e){let t=new URL(e.url);return t.password=encodeURIComponent(e.password),t.toString()}var Xy={type:"string",value:"role",description:"owner (migrations, dumps) or app (what the machines use); default owner"};function Zy(e){let t=e.flags.role??"owner";if(t!=="owner"&&t!=="app")throw g("--role is owner or app");return t}var Qy={PGSSLROOTCERT:"system"};async function Kn(e,t,n,s,a=!1){let r=await e.io.run(t,n,{env:{PGPASSWORD:s.password,...Qy,PGAPPNAME:"palbase-cli"},inherit:a});if(r.code===127)throw new y("missing_tool",`${t} is not installed here`,{hint:"install the Postgres 18 client tools (brew install postgresql@18, apt install postgresql-client-18)"});return r}var eb={name:"db:url",summary:"a database's connection address, for any tool (Prisma, Drizzle, pg_dump, a GUI)",usage:"[name] [--role owner|app] [--pooled] [--with-password]",details:["Without --with-password the address holds no password: give the tool PGPASSWORD, or pass --with-password and keep the line out of your history.","The address asks for a checked certificate (sslmode=verify-full). Node drivers check it against the system's roots by themselves; psql, pg_dump and other libpq tools do only with PGSSLROOTCERT=system (Postgres 16+). The address does not say so itself: a driver that sends what it does not know to the server (postgres.js) would be refused."],args:{min:0,max:1},flags:{role:Xy,pooled:{type:"boolean",description:"the pooled port (PgBouncer, transaction mode): for an app's many short connections"},"with-password":{type:"boolean",description:"put the password in the address"}},scope:"environment",async run(e){let t=await f(e),n=await Ra(e,t,e.args[0]),s=await Ht(e,t,n,Zy(e),e.flags.pooled===!0),a=e.flags["with-password"]===!0?wO(s):s.url;e.out.result({database:n,role:s.role,url:a,libpq_env:Qy},()=>{e.io.stdout(`${a}
|
|
696
696
|
`),e.out.note("psql, pg_dump and other libpq tools: PGSSLROOTCERT=system (Postgres 16+), or they cannot check the certificate")})}},tb={name:"db:shell",summary:"psql on a database (it wakes if asleep); -c runs one statement and ends",usage:"[name] [--role owner|app] [--command <sql>]",args:{min:0,max:1},flags:{role:Xy,command:{type:"string",short:"c",value:"sql",description:"run this and end"}},scope:"environment",async run(e){let t=await f(e),n=await Ra(e,t,e.args[0]),s=await Ht(e,t,n,Zy(e),!1),a=e.flags.command;if(a!==void 0){let i=await Kn(e,"psql",[s.url,"-v","ON_ERROR_STOP=1","-X","-c",a],s);if(i.stdout&&e.io.stdout(i.stdout),i.code!==0)throw new y("psql_failed",i.stderr.trim()||`psql ended with ${i.code}`);return}if(!e.interactive)throw g("db:shell with no person at the terminal needs --command <sql>");return e.out.note(`${q(t)} \u203A ${n} as ${s.role}`),(await Kn(e,"psql",[s.url],s,!0)).code}},nb={name:"db:dump",summary:"a copy of a database (pg_dump's custom format), as its owner",usage:"[name] [--file <path>] [--schema-only]",args:{min:0,max:1},flags:{file:{type:"string",value:"path",description:"where to write it (default <database>-<time>.dump)"},"schema-only":{type:"boolean",description:"its structure, not its data"}},scope:"environment",async run(e){let t=await f(e),n=await Ra(e,t,e.args[0]),s=await Ht(e,t,n,"owner",!1),a=e.flags.file??`${n}-${new Date(e.io.now()).toISOString().replaceAll(":","-").slice(0,19)}.dump`,r=await Kn(e,"pg_dump",["--format=custom","--no-owner","--no-acl",...e.flags["schema-only"]===!0?["--schema-only"]:[],"--file",a,s.url],s);if(r.code!==0)throw new y("pg_dump_failed",r.stderr.trim()||`pg_dump ended with ${r.code}`);e.out.result({database:n,file:a},()=>e.out.line(`Wrote ${a}.`))}},sb={name:"db:restore",summary:"load a dump into a database, as its owner: a custom-format dump (pg_restore) or a .sql file (psql)",usage:"<file> [--db <name>] [--clean]",details:["A database Palbase did not make is taken over by its first release: its tables stay as they are (palbase db:pull writes their schema files)."],args:{min:1,max:1},flags:{db:{type:"string",value:"name",description:"the database (default: the environment's only one)"},clean:{type:"boolean",description:"drop what the dump makes before making it again"}},scope:"environment",async run(e){let t=await f(e),n=await Ra(e,t,e.flags.db),s=e.args[0];await v(e,t,`load ${s} into the database ${n}`);let a=await Ht(e,t,n,"owner",!1);await ab(e,a,s,e.flags.clean===!0),e.out.result({database:n,loaded:s},()=>e.out.line(`Loaded ${s} into ${n}.`))}};async function ab(e,t,n,s){let a=bO(n).toLowerCase()===".sql",r=a?await Kn(e,"psql",[t.url,"-v","ON_ERROR_STOP=1","-X","--single-transaction","-f",n],t):await Kn(e,"pg_restore",["--no-owner","--no-acl","--exit-on-error","--single-transaction",...s?["--clean","--if-exists"]:[],"--dbname",t.url,n],t);if(r.code!==0)throw new y("restore_failed",r.stderr.trim()||`${a?"psql":"pg_restore"} ended with ${r.code}`)}var Yy="\u2022\u2022\u2022";async function vO(e,t,n){let s=async l=>{let d=await Kn(e,"psql",[n.url,"-v","ON_ERROR_STOP=1","-X","-At","-F"," ","-c",l],n);if(d.code!==0)throw new y("redact_failed",d.stderr.trim()||`psql ended with ${d.code}`);return d.stdout.split(`
|
|
697
|
-
`).filter(p=>p!=="").map(p=>p.split(" "))},a=l=>`"${l.replace(/"/g,'""')}"`,r=l=>`'${l.replace(/'/g,"''")}'`,i=await s("SELECT c.table_schema, c.table_name, c.column_name, EXISTS (SELECT 1 FROM information_schema.columns l WHERE l.table_schema = c.table_schema AND l.table_name = c.table_name AND l.column_name = c.column_name || '_lookup') FROM information_schema.columns c JOIN information_schema.tables t ON t.table_schema = c.table_schema AND t.table_name = c.table_name AND t.table_type = 'BASE TABLE' WHERE c.data_type = 'text' AND c.table_schema NOT IN ('pg_catalog', 'information_schema', 'palgres', 'palgres_search', 'palbase') AND c.table_schema NOT LIKE 'palgres\\_%' ORDER BY 1, 2, 3"),o=[];if(i.length>0){let l=await s(i.map(([d,p,u])=>`SELECT ${r(`${d} ${p} ${u}`)} WHERE EXISTS (SELECT 1 FROM ${a(d)}.${a(p)} WHERE ${a(u)} LIKE 'pbe1.%')`).join(" UNION ALL "));for(let[d,p,u]of l){let m=i.find(T=>T[0]===d&&T[1]===p&&T[2]===u)?.[3]==="t",b=d==="public"?`${p}.${u}`:`${d}.${p}.${u}`,{value:w}=await h(e,t,"POST","/secrets/fields/placeholder",{address:b}),[[_]]=await s(`WITH done AS (UPDATE ${a(d)}.${a(p)} SET ${a(u)} = ${r(w)}${m?`, ${a(`${u}_lookup`)} = NULL`:""} WHERE ${a(u)} LIKE 'pbe1.%' RETURNING 1) SELECT count(*) FROM done`);o.push({address:b,rows:Number(_)})}}return await s("DO $$ BEGIN IF to_regclass('palbase.idempotency_keys') IS NOT NULL THEN DELETE FROM palbase.idempotency_keys WHERE response_body LIKE 'pbe1.%'; END IF; END $$"),o}var rb={name:"db:copy",summary:"copy a database's data from one environment of the project to another",usage:"--from <env> --to <env> [--db <name>] [--to-db <name>]",details:["The target is overwritten with the source: what it held of the same tables goes (pg_restore --clean).",`An encrypted field (.encrypted(), palbase/server's fields) is copied as ${Yy}, sealed with the target's keys: one environment's values never land readable in another.`],flags:{from:{type:"string",value:"env",description:"the environment copied from (slug)"},to:{type:"string",value:"env",description:"the environment copied into (slug)"},db:{type:"string",value:"name",description:"the source's database (default: its only one)"},"to-db":{type:"string",value:"name",description:"the target's database (default: the same name)"}},scope:"environment",async run(e){let t=e.flags.from,n=e.flags.to;if(!t||!n)throw g("db:copy needs --from <env> and --to <env>");if(t===n)throw g("--from and --to are two environments");let s=await Nt(e),a=s.find(w=>w.slug===t),r=s.find(w=>w.slug===n);if(!a||!r)throw new y("no_such_environment",`the project has no environment ${JSON.stringify(a?n:t)}`);let i
|
|
697
|
+
`).filter(p=>p!=="").map(p=>p.split(" "))},a=l=>`"${l.replace(/"/g,'""')}"`,r=l=>`'${l.replace(/'/g,"''")}'`,i=await s("SELECT c.table_schema, c.table_name, c.column_name, EXISTS (SELECT 1 FROM information_schema.columns l WHERE l.table_schema = c.table_schema AND l.table_name = c.table_name AND l.column_name = c.column_name || '_lookup') FROM information_schema.columns c JOIN information_schema.tables t ON t.table_schema = c.table_schema AND t.table_name = c.table_name AND t.table_type = 'BASE TABLE' WHERE c.data_type = 'text' AND c.table_schema NOT IN ('pg_catalog', 'information_schema', 'palgres', 'palgres_search', 'palbase') AND c.table_schema NOT LIKE 'palgres\\_%' ORDER BY 1, 2, 3"),o=[];if(i.length>0){let l=await s(i.map(([d,p,u])=>`SELECT ${r(`${d} ${p} ${u}`)} WHERE EXISTS (SELECT 1 FROM ${a(d)}.${a(p)} WHERE ${a(u)} LIKE 'pbe1.%')`).join(" UNION ALL "));for(let[d,p,u]of l){let m=i.find(T=>T[0]===d&&T[1]===p&&T[2]===u)?.[3]==="t",b=d==="public"?`${p}.${u}`:`${d}.${p}.${u}`,{value:w}=await h(e,t,"POST","/secrets/fields/placeholder",{address:b}),[[_]]=await s(`WITH done AS (UPDATE ${a(d)}.${a(p)} SET ${a(u)} = ${r(w)}${m?`, ${a(`${u}_lookup`)} = NULL`:""} WHERE ${a(u)} LIKE 'pbe1.%' RETURNING 1) SELECT count(*) FROM done`);o.push({address:b,rows:Number(_)})}}return await s("DO $$ BEGIN IF to_regclass('palbase.idempotency_keys') IS NOT NULL THEN DELETE FROM palbase.idempotency_keys WHERE response_body LIKE 'pbe1.%'; END IF; END $$"),o}var rb={name:"db:copy",summary:"copy a database's data from one environment of the project to another",usage:"--from <env> --to <env> [--db <name>] [--to-db <name>]",details:["The target is overwritten with the source: what it held of the same tables goes (pg_restore --clean).",`An encrypted field (.encrypted(), palbase/server's fields) is copied as ${Yy}, sealed with the target's keys: one environment's values never land readable in another.`],flags:{from:{type:"string",value:"env",description:"the environment copied from (slug)"},to:{type:"string",value:"env",description:"the environment copied into (slug)"},db:{type:"string",value:"name",description:"the source's database (default: its only one)"},"to-db":{type:"string",value:"name",description:"the target's database (default: the same name)"}},scope:"environment",async run(e){let t=e.flags.from,n=e.flags.to;if(!t||!n)throw g("db:copy needs --from <env> and --to <env>");if(t===n)throw g("--from and --to are two environments");let s=await Nt(e),a=s.find(w=>w.slug===t),r=s.find(w=>w.slug===n);if(!a||!r)throw new y("no_such_environment",`the project has no environment ${JSON.stringify(a?n:t)}`);let i=_e(a),o=_e(r),l=await Ra(e,i,e.flags.db),d=e.flags["to-db"]??l;await v(e,o,`overwrite the database ${d} with ${i.env_slug}'s ${l}`);let p=await Ht(e,i,l,"owner",!1),u=await Ht(e,o,d,"owner",!1),m=await gO(Hy(yO(),"palbase-copy-"));try{let w=Hy(m,"copy.dump"),_=await Kn(e,"pg_dump",["--format=custom","--no-owner","--no-acl","--file",w,p.url],p);if(_.code!==0)throw new y("pg_dump_failed",_.stderr.trim()||`pg_dump ended with ${_.code}`);await ab(e,u,w,!0)}finally{await fO(m,{recursive:!0,force:!0})}let b=await vO(e,o,u);e.out.result({from:{env:i.env_slug,database:l},to:{env:o.env_slug,database:d},redacted:b},()=>{e.out.line(`Copied ${i.env_slug}/${l} into ${o.env_slug}/${d}.`);for(let w of b)e.out.line(` ${w.address}: ${w.rows} encrypted value(s) copied as ${Yy}`)})}};import{lstat as _O,mkdir as kO,readFile as SO,rename as $O,rm as PO,writeFile as AO}from"node:fs/promises";import{dirname as ib,resolve as RO}from"node:path";var ob="// palbase:stack:begin",lb="// palbase:stack:end",TO=/^[A-Za-z_$][A-Za-z0-9_$]*$/,mi=e=>TO.test(e)?e:JSON.stringify(e),Gn=e=>[...new Set(e)].sort();function gi(e,t){return t.length===0?[` interface ${e} {}`]:[` interface ${e} {`,...t.map(n=>` ${n}`)," }"]}function Bl(e){let t=[...e.buckets].sort((n,s)=>n.name<s.name?-1:n.name>s.name?1:0);return[ob,'declare module "palbase/backend/stack" {',...gi("Secrets",Gn(e.secrets).map(n=>`${mi(n)}: true;`)),"",...gi("Flags",Gn(e.flags).map(n=>`${mi(n)}: true;`)),"",...gi("Buckets",t.map(n=>{let s=Gn(n.variants);return`${mi(n.name)}: { variants: ${s.length===0?"never":s.map(a=>JSON.stringify(a)).join(" | ")} };`})),"",...gi("Roles",Gn(e.roles).map(n=>`${mi(n)}: true;`)),"}",lb].join(`
|
|
698
698
|
`)}function Ts(e,t,n={begin:ob,end:lb,said:"palbase types:pull writes the block between the markers: the names this environment holds, for palbase/backend/stack."}){if(e===void 0)return`// ${n.said}
|
|
699
699
|
${t}
|
|
700
700
|
|