palbase 0.49.0 → 0.49.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/{IUGMANUF.js → 2UAWAVQQ.js} +2 -2
- package/dist/chunks/{3FC6NPWB.js → 3FGMN6RY.js} +2 -2
- package/dist/chunks/{II5ZOVO7.js → 6A2VBW6K.js} +1 -1
- package/dist/chunks/{W6JZCKGZ.js → 6KDYTSBW.js} +2 -2
- package/dist/chunks/{O6QKTBCO.js → 6KMUQIWT.js} +1 -1
- package/dist/chunks/{BCYMBEPZ.js → 7K4TPV5K.js} +2 -2
- package/dist/chunks/{RQ566QRF.js → 7ZI7MROG.js} +2 -2
- package/dist/chunks/{MNCSPLYJ.js → ATMJMBCH.js} +2 -2
- package/dist/chunks/{UCCWWRSG.js → BVYPUWPA.js} +2 -2
- package/dist/chunks/{IXAFS446.js → F7YGHYPE.js} +1 -1
- package/dist/chunks/{H4FHFAYZ.js → FTMPWUYS.js} +1 -1
- package/dist/chunks/{QN7U2HDQ.js → ITYU3ULX.js} +2 -2
- package/dist/chunks/{UOPSIYOR.js → KKIBIULO.js} +2 -2
- package/dist/chunks/{BJKCSPL7.js → MDUU6F7S.js} +2 -2
- package/dist/chunks/{4APZNNDJ.js → MHOFOVSN.js} +1 -1
- package/dist/chunks/{F3QV7MM4.js → PNLFGVB5.js} +2 -2
- package/dist/chunks/{TNNXR5HZ.js → TJXEAKZH.js} +1 -1
- package/dist/chunks/{XXFB4FZB.js → UIJMULI2.js} +2 -2
- package/dist/chunks/{KYQI6JIX.js → WP6DXNB4.js} +2 -2
- package/dist/chunks/{3XOEVUSV.js → XHKKFLT7.js} +2 -2
- package/dist/chunks/{WCY54JBH.js → XWHDZWXY.js} +1 -1
- package/dist/chunks/{OU7OK4LY.js → YZW6CRBE.js} +2 -2
- package/dist/chunks/{3BAMKWCP.js → ZHCIXVJU.js} +2 -2
- package/dist/cli.js +28 -28
- 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/web/src/ssr.d.ts +5 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
/*! palbase 0.49.
|
|
2
|
+
/*! palbase 0.49.2 — Palbase SDK License (see LICENSE) */
|
|
3
3
|
var Hw=Object.defineProperty;var Ye=(e,t)=>{for(var n in t)Hw(e,n,{get:t[n],enumerable:!0})};import{parseArgs as Ov}from"node:util";var Yw=Symbol.for("palbase.data"),Xw=globalThis,xd=Xw[Yw]??=new WeakSet;function Zw(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function Za(e){let t=[e];for(;t.length>0;){let n=t.pop();if(!(typeof n!="object"||n===null||xd.has(n)||Zw(n))){xd.add(n);for(let s of Array.isArray(n)?n:Object.values(n))t.push(s)}}return e}var Qw="X-PoW-Challenge-ID",ev="X-PoW-Nonce";function Nd(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 tv(e){return 8*2**e}var ps;async function nv(){if(ps)return ps;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 ps=a=>new Uint8Array(s("sha256").update(a).digest()),ps}catch{}let t=new TextEncoder;return ps=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),ps}function sv(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var av=4096,iv=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function qd(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 nv(),s=tv(e.difficulty),a=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<s;i++){if(i%av===0&&i>0){if(await iv(),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 ${i} attempts`)}let r=n(e.prefix+i),o=r instanceof Uint8Array?r:await r;if(sv(o)>=e.difficulty)return{[Qw]:e.id,[ev]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${s} attempts`)}var E=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 E({op:e,status:0,code:"invalid_path_parameter",message:`${e}: ${t} cannot be ${s===""?"empty":JSON.stringify(s)}`});return encodeURIComponent(s)}var rv=new Set(["apikey","authorization"]),ov=64*1024;function Hr(e){let t=Qa(e.baseUrl),n=e.fetch??globalThis.fetch,s=e.solveProofOfWork??!0,a=async(i,r)=>{let o=pv(t,i),l=new Headers;for(let[y,w]of Object.entries(i.headers??{}))w!=null&&!rv.has(y.toLowerCase())&&l.set(y,String(w));for(let[y,w]of Object.entries(r))l.set(y,w);await uv(i,e.credentials,l),l.has("accept")||l.set("accept","application/json");let d={method:i.method,headers:l,redirect:"manual",signal:i.signal,...i.keepalive?{keepalive:!0}:{}};i.body&&i.body.value!==void 0&&(l.set("content-type",i.body.contentType),d.body=cv(i.body.kind,i.body.value),us(d.body)||(d.duplex="half"));let p;try{p=i.onUploadProgress&&e.xmlHttpRequest?await lv(e.xmlHttpRequest,i.op,o,d,i.onUploadProgress):await n(o,d)}catch(y){throw i.signal?.aborted||y instanceof E?y:new E({op:i.op,status:0,code:"network_error",message:`${i.op}: the request did not reach ${t.origin}`,cause:y})}let u=i.answers[p.status]??(i.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 E({op:i.op,status:p.status,code:"undeclared_answer",message:`${i.op}: the server answered ${p.status}, which its contract does not declare; the request may have taken effect`})):await mv(i.op,p);let g;switch(u){case"json":try{g=Za(await p.json())}catch(y){throw new E({op:i.op,status:p.status,code:"invalid_json",message:`${i.op}: the answer is not JSON`,cause:y})}break;case"raw":g=p;break;default:await p.body?.cancel(),g=void 0}return{status:p.status,data:g,headers:p.headers}};return{async send(i){try{return await a(i,{})}catch(r){let o=s&&r instanceof E&&r.status===403?Nd(r.body):null,l=i.body?.value;if(!o||i.body?.kind==="raw"&&!us(l))throw r;let d=r,p;try{p=await qd(o,{signal:i.signal})}catch(u){throw i.signal?.aborted?u:new E({op:i.op,status:403,code:"pow_unsolved",message:`${i.op}: ${u instanceof Error?u.message:String(u)}`,requestId:d.requestId,body:d.body,cause:u})}return a(i,p)}}}}function lv(e,t,n,s,a){return new Promise((i,r)=>{let o=s.signal;if(o?.aborted)return r(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,g)=>l.setRequestHeader(g,u)),l.upload&&(l.upload.onprogress=u=>{u.lengthComputable&&a(u.loaded,u.total)}),l.onload=()=>p(()=>{if(l.responseURL!==""&&l.responseURL!==n.href){r(new E({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 r(new TypeError(`${t}: answered ${l.status}`));let u=l.status===204||l.status===205||l.status===304;i(new Response(u?null:l.response,{status:l.status,statusText:l.statusText,headers:dv(l.getAllResponseHeaders())}))}),l.onerror=()=>p(()=>r(new TypeError(`${t}: the request failed`))),l.onabort=()=>p(()=>r(o?.reason??new DOMException("The request was aborted","AbortError"))),l.send(s.body)})}function dv(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 Qa(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 pv(e,t){if(!t.path.startsWith("/")||t.path.startsWith("//"))throw new E({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+hv(t.query),e);if(n.origin!==e.origin)throw new E({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path leaves the project's origin`});return n}async function uv(e,t,n){if(e.auth.length===0)return;let s=e.auth.some(r=>r.includes("userJWT"))?await t.accessToken?.():void 0,a=r=>{switch(r){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}},i=e.auth.filter(r=>r.every(a)).reduce((r,o)=>r===void 0||o.length>r.length?o:r,void 0);if(!i)throw new E({op:e.op,status:0,code:"missing_credential",message:`${e.op} needs one of: ${e.auth.map(r=>r.length===0?"nothing":r.join(" + ")).join(" | ")}`});for(let r of i)r==="ApiKeyAuth"?n.set("apikey",t.publishableKey??t.secretKey):(r==="SecretKeyAuth"||r==="AdminAuth"||r==="PalbaseBearer")&&t.token?n.set("authorization",`Bearer ${t.token}`):r==="SecretKeyAuth"||r==="AdminAuth"?n.set("apikey",t.secretKey):r==="userJWT"&&n.set("authorization",`Bearer ${s}`)}function cv(e,t){switch(e){case"json":return JSON.stringify(t);case"form":{let n=new URLSearchParams;for(let[s,a]of Object.entries(t))Yr(n,s,a);return n}case"raw":return t}}function us(e){return!!(e==null||typeof e=="string"||e instanceof URLSearchParams||e instanceof Blob||e instanceof FormData||e instanceof ArrayBuffer||ArrayBuffer.isView(e))}function hv(e){if(!e)return"";let t=new URLSearchParams;for(let[s,a]of Object.entries(e))Yr(t,s,a);let n=t.toString();return n===""?"":`?${n}`}function Yr(e,t,n){if(n!=null){if(Array.isArray(n)){for(let s of n)Yr(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 mv(e,t){let n=await gv(t,ov).catch(()=>""),s;try{s=n===""?void 0:JSON.parse(n)}catch{s=n}let a=fv(s)?s:void 0,i=Number(t.headers.get("retry-after")),r=t.status>=300&&t.status<400;return new E({op:e,status:t.status,code:a?.error??(r?"undeclared_redirect":`http_${t.status}`),message:a?.error_description??(r?`${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(i)&&i>0?i:void 0),body:s})}async function gv(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 i=new Uint8Array(Math.min(a,t)),r=0;for(let o of s){let l=Math.min(o.byteLength,i.byteLength-r);if(i.set(o.subarray(0,l),r),r+=l,r>=i.byteLength)break}return new TextDecoder().decode(i)}function fv(e){return typeof e=="object"&&e!==null&&typeof e.error=="string"}var ei={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 f=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 m(e,t){return new f("usage",e,{hint:t,exitCode:2})}var ti=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(`${q(t)}
|
|
5
5
|
`)}note(t){this.io.stderr(`${q(t)}
|
|
@@ -9,7 +9,7 @@ var Hw=Object.defineProperty;var Ye=(e,t)=>{for(var n in t)Hw(e,n,{get:t[n],enum
|
|
|
9
9
|
`);let r;try{r=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 f("network_error",`${new URL(t).origin} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(this.debug&&this.io.stderr(`< ${r.status} ${r.headers.get("x-request-id")??""}
|
|
10
10
|
`),r.status!==503||!s||i>=Ev||!Tv.has(await Qr(r)??""))return r;await r.body?.cancel();let o=Number(r.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(),i=await this.send(t,n,s,a.value);if(i.status===401&&a.renewable){let r=await this.renew(await this.currentSession());i=await this.send(t,n,s,r.access_token)}return{res:i,renewable:a.renewable}}async answered(t,n,s,a){if(s.status===204)return;let i=await s.text(),r=i===""?void 0:Cv(i);if(s.ok)return r;let o=r??{};throw s.status===401?o.error==="token_not_for_machines"?tp(new URL(this.cloud.studioApi).host):a?cs():this.tokenRefused("Studio"):new E({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:r})}tokenRefused(t){return(this.io.env.PALBASE_TOKEN??"").startsWith("pbe_")?new f("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 f("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 f("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 Xd(this.io,this.cloud,t);return await this.state.writeSession(n),this.session=n,n}async send(t,n,s,a){let i=`${this.cloud.studioApi}${Rv}${n}`;this.debug&&this.io.stderr(`> ${t} ${i}
|
|
11
11
|
`);try{let r=await this.io.fetch(i,{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(`< ${r.status} ${r.headers.get("x-request-id")??""}
|
|
12
|
-
`),r}catch(r){throw new f("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${r instanceof Error?r.message:String(r)}`)}}};function tp(e){return new f("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 Qr(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 Cv(e){try{return JSON.parse(e)}catch{return e}}var np={version:"0.49.
|
|
12
|
+
`),r}catch(r){throw new f("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${r instanceof Error?r.message:String(r)}`)}}};function tp(e){return new f("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 Qr(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 Cv(e){try{return JSON.parse(e)}catch{return e}}var np={version:"0.49.2"};var ri=np.version;async function op(e,t,n){let s=new Map(n.map(r=>[r.name,r])),a=e.includes("--json"),i=e.includes("--debug");try{let{name:r,at:o}=Mv(e);if(r===void 0)return e.includes("--version")?(t.stdout(`palbase ${ri}
|
|
13
13
|
`),0):(t.stdout(rp(n)),e.length===0||e.includes("--help")||e.includes("-h")?0:2);if(r==="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($?ip($):rp(n)),0}let l=s.get(r);if(!l)throw sp(r,n);let d=[...e.slice(0,o),...e.slice(o+1)];if(d.includes("--help")||d.includes("-h"))return t.stdout(ip(l)),0;let{flags:p,positionals:u}=Iv(l,d),g=l.args??{min:0,max:0};if(u.length<g.min)throw m(`${l.name} needs ${g.min===1?"an argument":`${g.min} arguments`}`,to(l));if(u.length>g.max)throw m(`${l.name} takes ${g.max===0?"no argument":`at most ${g.max}`}: ${JSON.stringify(u.slice(g.max))} is left over`,to(l));let y={project:p.project,env:p.env,json:p.json===!0,nonInteractive:p["non-interactive"]===!0,yes:p.yes===!0,debug:p.debug===!0},w=Wd(t.env),_=new ni(Vd(t.configDir,w)),P={io:t,state:_,out:new ti(t,y.json),global:y,args:u,flags:p,interactive:t.interactive&&!y.nonInteractive,cloud:w,studio:new ii(t,w,_,y.debug)};return await l.run(P)??0}catch(r){return Lv(r,t,a,i)}}function Mv(e){let t=new Set;for(let[n,s]of Object.entries(ei))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 Iv(e,t){let n={...ei,...e.flags??{}},s={};for(let[a,i]of Object.entries(n))s[a]={type:i.type,...i.short?{short:i.short}:{},...i.multiple?{multiple:!0}:{}};try{let{values:a,positionals:i}=Ov({args:t,options:s,strict:!0,allowPositionals:!0});return{flags:a,positionals:i}}catch(a){throw m(a instanceof Error?a.message.replace(/^.*?: /,""):String(a),`palbase help ${e.name}`)}}function Lv(e,t,n,s){let a="error",i,r,o=1,l;return e instanceof f?(a=e.code,i=e.message,r=e.hint,o=e.exitCode):e instanceof E?(a=e.code,i=e.message,l=e.requestId,e.code==="token_out_of_scope"&&t.env.PALBASE_TOKEN&&(i=`${e.op} refused PALBASE_TOKEN: ${e.message}`,r="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")):i=e instanceof Error?e.message:String(e),n&&e instanceof f&&e.reported||(n&&t.stdout(`${JSON.stringify({error:a,message:i,...r?{hint:r}:{},...l?{request_id:l}:{}},null,2)}
|
|
14
14
|
`),t.stderr(`error: ${q(i)}${l?` (request ${q(l)})`:""}
|
|
15
15
|
`),r&&t.stderr(` ${q(r)}
|
|
@@ -19,7 +19,7 @@ var Hw=Object.defineProperty;var Ye=(e,t)=>{for(var n in t)Hw(e,n,{get:t[n],enum
|
|
|
19
19
|
`}function rp(e){let t=new Map;for(let a of e){let i=a.name.includes(":")?a.name.slice(0,a.name.indexOf(":")):"";t.set(i,[...t.get(i)??[],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,i]of t){s.push(a===""?"Commands:":`${a}:`);for(let r of i)s.push(` ${r.name.padEnd(n)} ${r.summary}`);s.push("")}return s.push("palbase help <command> shows a command in full."),`${s.join(`
|
|
20
20
|
`)}
|
|
21
21
|
`}import{createHash as yL,randomBytes as bL,timingSafeEqual as wL}from"node:crypto";import{createServer as _L}from"node:http";var no="owner.json";var $L=300*1e3;function x(e,t){try{return c("palbase",e,t)}catch(n){throw n instanceof E&&n.code==="invalid_path_parameter"?new f("unsafe_path",`${e} cannot be ${t===""?"empty":JSON.stringify(t)}: a request's path cannot carry it`):n}}var lp={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 f("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 Hd(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 Yd(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}.`))}},dp={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 f("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/${x("the environment's ref",n)}/personal-key/${x("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(no);try{await Zd(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}.`))}},pp={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"),i=a[0];n={id:`token \u2026${t.slice(-4)}`,via:"token",...i&&{organization:{id:i.id,name:i.name,role:i.role}}}}else if(t){let a=si(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 ${q(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 xv={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=>q(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}])})}},Nv={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 m("--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 ${q(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}`)})}},qv={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 f("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 f("ambiguous_token",`${JSON.stringify(e.args[0])} names more than one token`,{hint:"pass its id"});await e.studio.request("DELETE",`/account/tokens/${x("the token's id",n[0].id)}`),e.out.result({revoked:n[0].id},()=>e.out.line(`Revoked the account token ${q(n[0].name)}.`))}},up=[xv,Nv,qv];var oi={};Ye(oi,{client:()=>Kv});function Kv(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 putChatWorkspaceFile(t){return e.send({op:"PutChatWorkspaceFile",method:"PUT",path:"/ai/chats/"+c("PutChatWorkspaceFile","chat_id",t.path.chat_id)+"/workspace/files",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},query:t.query,body:{kind:"raw",contentType:t.contentType??"application/octet-stream",value:t.body},signal:t.signal})},async deleteChatWorkspaceFile(t){return e.send({op:"DeleteChatWorkspaceFile",method:"DELETE",path:"/ai/chats/"+c("DeleteChatWorkspaceFile","chat_id",t.path.chat_id)+"/workspace/files",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},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 listChatWorkspaceTokens(t){return e.send({op:"ListChatWorkspaceTokens",method:"GET",path:"/ai/chats/"+c("ListChatWorkspaceTokens","chat_id",t.path.chat_id)+"/workspace/tokens",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async createChatWorkspaceToken(t){return e.send({op:"CreateChatWorkspaceToken",method:"POST",path:"/ai/chats/"+c("CreateChatWorkspaceToken","chat_id",t.path.chat_id)+"/workspace/tokens",auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async revokeChatWorkspaceToken(t){return e.send({op:"RevokeChatWorkspaceToken",method:"DELETE",path:"/ai/chats/"+c("RevokeChatWorkspaceToken","chat_id",t.path.chat_id)+"/workspace/tokens/"+c("RevokeChatWorkspaceToken","token",t.path.token),auth:[["ApiKeyAuth","userJWT"],["SecretKeyAuth"]],answers:{204:"empty"},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 listEnv(t){return e.send({op:"ListEnv",method:"GET",path:"/ai/env",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async putEnv(t){return e.send({op:"PutEnv",method:"PUT",path:"/ai/env/"+c("PutEnv","key",t.path.key),auth:[["SecretKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteEnv(t){return e.send({op:"DeleteEnv",method:"DELETE",path:"/ai/env/"+c("DeleteEnv","key",t.path.key),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 deleteMachine(t){return e.send({op:"DeleteMachine",method:"DELETE",path:"/ai/machines/"+c("DeleteMachine","machine",t.path.machine),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async cordonMachine(t){return e.send({op:"CordonMachine",method:"POST",path:"/ai/machines/"+c("CordonMachine","machine",t.path.machine)+"/cordon",auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async resumeMachine(t){return e.send({op:"ResumeMachine",method:"POST",path:"/ai/machines/"+c("ResumeMachine","machine",t.path.machine)+"/resume",auth:[["SecretKeyAuth"]],answers:{204:"empty"},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 revokePoolKey(t){return e.send({op:"RevokePoolKey",method:"POST",path:"/ai/pool-keys/"+c("RevokePoolKey","key",t.path.key)+"/revoke",auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listPools(t){return e.send({op:"ListPools",method:"GET",path:"/ai/pools",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t?.signal})},async createPool(t){return e.send({op:"CreatePool",method:"POST",path:"/ai/pools",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deletePool(t){return e.send({op:"DeletePool",method:"DELETE",path:"/ai/pools/"+c("DeletePool","pool",t.path.pool),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listPoolKeys(t){return e.send({op:"ListPoolKeys",method:"GET",path:"/ai/pools/"+c("ListPoolKeys","pool",t.path.pool)+"/keys",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async createPoolKey(t){return e.send({op:"CreatePoolKey",method:"POST",path:"/ai/pools/"+c("CreatePoolKey","pool",t.path.pool)+"/keys",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getPoolState(t){return e.send({op:"GetPoolState",method:"GET",path:"/ai/pools/"+c("GetPoolState","pool",t.path.pool)+"/state",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})},async getWorkspaceSyncChanges(t){return e.send({op:"GetWorkspaceSyncChanges",method:"GET",path:"/ai/workspace-sync/changes",auth:[["WorkspaceTokenAuth"]],answers:{200:"json"},query:t?.query,signal:t?.signal})},async createWorkspaceSyncChangeSet(t){return e.send({op:"CreateWorkspaceSyncChangeSet",method:"POST",path:"/ai/workspace-sync/changesets",auth:[["WorkspaceTokenAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getWorkspaceSyncConflict(t){return e.send({op:"GetWorkspaceSyncConflict",method:"GET",path:"/ai/workspace-sync/conflicts/"+c("GetWorkspaceSyncConflict","conflict_id",t.path.conflict_id),auth:[["WorkspaceTokenAuth"]],answers:{200:"json"},signal:t.signal})},async getWorkspaceSyncEvents(t){return e.send({op:"GetWorkspaceSyncEvents",method:"GET",path:"/ai/workspace-sync/events",auth:[["WorkspaceTokenAuth"]],answers:{200:"raw"},signal:t?.signal})},async createWorkspaceSyncGrants(t){return e.send({op:"CreateWorkspaceSyncGrants",method:"POST",path:"/ai/workspace-sync/grants",auth:[["WorkspaceTokenAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async getWorkspaceSyncHead(t){return e.send({op:"GetWorkspaceSyncHead",method:"GET",path:"/ai/workspace-sync/head",auth:[["WorkspaceTokenAuth"]],answers:{200:"json"},signal:t?.signal})}}}var Zs={};Ye(Zs,{client:()=>Gv});function Gv(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 Qs={};Ye(Qs,{client:()=>Uv});function Uv(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})},async adminInviteUser(t){return e.send({op:"AdminInviteUser",method:"POST",path:"/admin/users/invite",auth:[["AdminAuth"]],answers:{200:"json",201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async acceptInvitation(t){return e.send({op:"AcceptInvitation",method:"POST",path:"/auth/invitations/accept",auth:[["ApiKeyAuth"]],answers:{200:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async hostedAcceptInvitationPage(t){return e.send({op:"HostedAcceptInvitationPage",method:"GET",path:"/auth/pages/accept-invitation",auth:[],answers:{200:"raw"},query:t?.query,signal:t?.signal})},async hostedAcceptInvitationSubmit(t){return e.send({op:"HostedAcceptInvitationSubmit",method:"POST",path:"/auth/pages/accept-invitation",auth:[],answers:{200:"raw"},body:{kind:"form",contentType:"application/x-www-form-urlencoded",value:t.body},signal:t.signal})}}}var li={};Ye(li,{client:()=>Bv});function Bv(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 di={};Ye(di,{client:()=>zv});function zv(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 ea={};Ye(ea,{client:()=>Wv});function Wv(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 ta={};Ye(ta,{client:()=>Jv});function Jv(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:{200:"json",204:"empty"},headers:t.headers,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:{200:"json",202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async moveSite(t){return e.send({op:"MoveSite",method:"POST",path:"/sites/"+c("MoveSite","name",t.path.name)+"/move",auth:[["SecretKeyAuth"]],answers:{200:"json",202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async moveDatabase(t){return e.send({op:"MoveDatabase",method:"POST",path:"/databases/"+c("MoveDatabase","name",t.path.name)+"/move",auth:[["SecretKeyAuth"]],answers:{200:"json",202:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async cancelSiteBuild(t){return e.send({op:"CancelSiteBuild",method:"POST",path:"/sites/"+c("CancelSiteBuild","name",t.path.name)+"/builds/"+c("CancelSiteBuild","build",t.path.build)+"/cancel",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async cancelBuild(t){return e.send({op:"CancelBuild",method:"POST",path:"/machines/"+c("CancelBuild","name",t.path.name)+"/builds/"+c("CancelBuild","build",t.path.build)+"/cancel",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async listSiteHooks(t){return e.send({op:"ListSiteHooks",method:"GET",path:"/sites/"+c("ListSiteHooks","name",t.path.name)+"/hooks",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async createSiteHook(t){return e.send({op:"CreateSiteHook",method:"POST",path:"/sites/"+c("CreateSiteHook","name",t.path.name)+"/hooks",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteSiteHook(t){return e.send({op:"DeleteSiteHook",method:"DELETE",path:"/sites/"+c("DeleteSiteHook","name",t.path.name)+"/hooks/"+c("DeleteSiteHook","hook",t.path.hook),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async listMachineHooks(t){return e.send({op:"ListMachineHooks",method:"GET",path:"/machines/"+c("ListMachineHooks","name",t.path.name)+"/hooks",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async createMachineHook(t){return e.send({op:"CreateMachineHook",method:"POST",path:"/machines/"+c("CreateMachineHook","name",t.path.name)+"/hooks",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deleteMachineHook(t){return e.send({op:"DeleteMachineHook",method:"DELETE",path:"/machines/"+c("DeleteMachineHook","name",t.path.name)+"/hooks/"+c("DeleteMachineHook","hook",t.path.hook),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})},async detectProject(t){return e.send({op:"DetectProject",method:"GET",path:"/machines/github/detect",auth:[["SecretKeyAuth"]],answers:{200:"json"},query:t.query,signal:t.signal})},async createPreviewPass(t){return e.send({op:"CreatePreviewPass",method:"POST",path:"/sites/"+c("CreatePreviewPass","name",t.path.name)+"/previews/pass",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async listPreviewLinks(t){return e.send({op:"ListPreviewLinks",method:"GET",path:"/sites/"+c("ListPreviewLinks","name",t.path.name)+"/previews/links",auth:[["SecretKeyAuth"]],answers:{200:"json"},signal:t.signal})},async createPreviewLink(t){return e.send({op:"CreatePreviewLink",method:"POST",path:"/sites/"+c("CreatePreviewLink","name",t.path.name)+"/previews/links",auth:[["SecretKeyAuth"]],answers:{201:"json"},body:{kind:"json",contentType:"application/json",value:t.body},signal:t.signal})},async deletePreviewLink(t){return e.send({op:"DeletePreviewLink",method:"DELETE",path:"/sites/"+c("DeletePreviewLink","name",t.path.name)+"/previews/links/"+c("DeletePreviewLink","link",t.path.link),auth:[["SecretKeyAuth"]],answers:{204:"empty"},signal:t.signal})}}}var pi={};Ye(pi,{client:()=>Vv});function Vv(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 na={};Ye(na,{client:()=>Hv});function Hv(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 sa={};Ye(sa,{client:()=>Yv});function Yv(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 aa={};Ye(aa,{client:()=>Xv});function Xv(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 ia={};Ye(ia,{client:()=>Zv});function Zv(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 ra={};Ye(ra,{client:()=>Qv});function Qv(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 oa={};Ye(oa,{client:()=>e_});function e_(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 ui={attempts:3,maxWaitSeconds:30},t_=new Set([429,502,503,504]);function so(e,t=ui){let n=t.sleep??a_;return{async send(s){let a=n_(s),i=a.body,r=!i||i.kind!=="raw"||us(i.value),o=(a.method==="GET"||a.method==="HEAD"||a.idempotent===!0)&&r;for(let l=1;;l++)try{return await e.send(a)}catch(d){if(!o||l>=t.attempts||!(d instanceof E)||a.signal?.aborted)throw d;let p=s_(d,l,t.maxWaitSeconds);if(p===void 0)throw d;await n(p*1e3,a.signal)}}}}function n_(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":i_()}}:e}function s_(e,t,n){return t_.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 a_(e,t){return new Promise((n,s)=>{if(t?.aborted)return s(t.reason);let a=()=>{clearTimeout(i),s(t?.reason)},i=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}function i_(){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 r_}from"node:os";var o_=new Set(["apikey","authorization",eo]);function l_(e){let t={accept:"application/json"};for(let[n,s]of Object.entries(e??{}))s!=null&&!o_.has(n.toLowerCase())&&(t[n.toLowerCase()]=String(s));return t}function d_(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 E({op:t,status:0,code:"invalid_path",message:`${t}: a module's path stays at its environment's address`});return s.href}async function p_(e){let t=e.status===204||e.status===304?"":await e.text();if(t!=="")try{return JSON.parse(t)}catch{return t}}function u_(e,t,n){let s=n??{},a=Number(t.headers.get("retry-after")??"");return new E({op:e,status:t.status,code:typeof s.error=="string"?s.error:`http_${t.status}`,message:ci(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 Wt=class{bytes;contentType;constructor(t,n){this.bytes=t,this.contentType=n}};function c_(e){return e instanceof Wt?{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 _e(e,t,n,s,a,i){let r=`${n} ${s}`,o=c_(a),l=await e.module(d_(st(e.cloud,t),r,s),{method:n,headers:{...l_(i),...o.headers},body:o.body}),d=await p_(l);if(l.status>=200&&l.status<300)return{status:l.status,body:Za(d),etag:l.headers.get("etag")??void 0};throw u_(r,l,d)}var h_=10080*60*1e3;async function ao(e,t,n=!1){let s=await e.state.personalKey(t);if(!n&&s&&Date.parse(s.expires_at)-e.io.now()>h_)return s;let a=await e.post(`/environments/${x("the environment's ref",t)}/personal-key`,{host:r_().slice(0,100)||"computer"});return await e.state.keepPersonalKey(t,a),a}function ci(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(i=>{let{pointer:r,message:o}=i??{};return typeof o=="string"?[`${typeof r=="string"&&r!==""?`${r}: `:""}${o}`]:[]}):[];return a.length>0?`${s}: ${a.join("; ")}`:s}import{relative as m_}from"node:path";async function hs(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}),i=await e.run("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t}),r=i.code===0?i.stdout.trim():"";return{root:s,repository:a.code===0?g_(a.stdout.trim()):void 0,branch:r!==""&&r!=="HEAD"?r:void 0,path:m_(s,t).split("\\").join("/")}}function g_(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 ms(e,t){let n=await Pe(e);return new Map(n.filter(s=>s.project_id===t.project_id).map(s=>[s.ref,s.slug]))}function Ft(e,t){return t?e.get(t.ref)??t.ref:""}var Be="main";async function Pe(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 ie(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 N(e){return`${e.org_name} \u203A ${e.project_name} \u203A ${e.env_name}${e.env_name!==e.env_slug?` (${e.env_slug})`:""}`}function Jt(e){return(e.env.PALBASE_TOKEN??"").startsWith("pbe_")}async function la(e){let[t]=await Pe(e.studio);if(!t)throw new f("token_refused","Studio names no environment for PALBASE_TOKEN",{hint:"mint another: palbase env:tokens:create"});let n=ie(t),s=r=>new f("token_environment",`PALBASE_TOKEN is ${N(n)}'s environment token: it acts there alone, not in ${r}`,{hint:"mint one there: palbase env:tokens:create -P <project> -E <env>"}),{project:a,env:i}=e.global;if(a!==void 0&&t.project_id!==a&&!oo(t.project_name,a.slice(a.indexOf("/")+1)))throw s(a);if(i!==void 0&&i!==t.slug&&i!==t.ref)throw s(i);if(a===void 0&&i===void 0){let r=await e.state.targetFor(e.io.cwd);if(r&&r.target.env_ref!==t.ref)throw s(`${N(r.target)}, chosen for ${r.dir}`)}return t}async function b(e){if(Jt(e.io))return ie(await la(e));let{project:t,env:n}=e.global;if(t!==void 0||n!==void 0){let r=await Pe(e.studio),o;if(t!==void 0)o=un(r,t);else{let l=await e.state.targetFor(e.io.cwd);if(!l)throw ro("-E names an environment of the project chosen here, and none is chosen: add -P <project>");o=r.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 f("no_such_environment",`the project has no environment ${JSON.stringify(n)}`,{hint:`its environments: ${o.map(d=>d.slug).join(", ")}`});return ie(l)}return o.length===1?ie(o[0]):ie(await io(e,o,"Which environment?"))}let s=await e.state.targetFor(e.io.cwd);if(s)return s.target;if(!e.interactive)throw ro("no environment is chosen for this directory");let a=await Pe(e.studio);if(a.length===0)throw new f("no_environments","your account reaches no environment yet",{hint:"make one: palbase projects:create <name>"});let i=ie(await io(e,a,"Which environment?"));return e.out.note(`Acting on ${N(i)}. palbase use remembers it for this directory.`),i}async function jn(e){return(await pn(e)).t}async function pn(e){if(Jt(e.io))return{t:ie(await la(e)),by:"token"};let t=await e.state.targetFor(e.io.cwd);if(e.global.project===void 0&&e.global.env===void 0&&t)return{t:t.target,by:"here"};let n=await mp(e,t?.target);if(e.global.env!==void 0)return{t:ie(lo(n,e.global.env)),by:"env"};let s=n.find(a=>a.ref===t?.target.env_ref);return s?{t:ie(s),by:"here"}:{t:ie(n.find(a=>a.slug===Be)??n[0]),by:"fallback"}}function hi(e,t){return e.by==="fallback"?t:`${t}${t.includes("?")?"&":"?"}environment=${encodeURIComponent(e.t.env_ref)}`}var hp=1e3;async function On(e){let t=[],n=new Set,s;for(;;){let a=await e(s);if(t.push(...a.items),!a.next)return t;if(n.has(a.next)||n.size>=hp)throw new f("list_unending",`the platform's list did not end: ${n.has(a.next)?`it gave the cursor ${JSON.stringify(a.next)} twice`:`it ran past ${hp} pages`}`);n.add(a.next),s=a.next}}async function Mn(e,t,n,s,a){if(t.by==="env"||t.by==="token"||t.by==="here"&&(n.environment?.ref??t.t.env_ref)===t.t.env_ref)return;let i=(await s()).filter(o=>o.name===n.name);if(i.length<2)return;let r=await ms(e.studio,t.t);throw new f("ambiguous_name",`${a} is held by more than one of ${t.t.project_name}'s environments: ${i.map(o=>Ft(r,o.environment)).join(", ")}`,{hint:"name the environment: -E <env>"})}async function In(e){if(Jt(e.io))return ie(await la(e));let t=await e.state.targetFor(e.io.cwd);if(e.global.project===void 0&&e.global.env===void 0&&t)return t.target;let n=await mp(e,t?.target);if(e.global.env!==void 0)return ie(lo(n,e.global.env));let s=n.find(i=>i.ref===t?.target.env_ref);if(s)return ie(s);let a=n[0].project_name;if(!e.interactive)throw m(`which environment of ${a} is it bound to? name it with -E <env>`,`its environments: ${n.map(i=>i.slug).join(", ")}`);return ie(await io(e,n,q(`Which environment of ${a} does it belong to?`)))}async function Ln(e,t,n,s){if(!n||n.ref===t.env_ref)return t;let a=(await Pe(e.studio)).find(i=>i.ref===n.ref);if(e.global.env!==void 0){let i=a?.slug??n.name??n.ref;throw new f("bound_elsewhere",`${s} is bound to ${t.project_name}'s environment ${i}, not ${t.env_slug}`,{hint:`leave -E out: the command acts where it is bound${a?` (or name it, -E ${a.slug})`:""}`})}if(!a)throw new f("environment_out_of_reach",`${s} is bound to ${t.project_name}'s environment ${n.name||n.ref}, which your account does not reach`,{hint:"an admin of the project's organization adds you to that environment"});return ie(a)}function mi(e,t,n){return e.global.env===void 0?n:`${n}${n.includes("?")?"&":"?"}environment=${encodeURIComponent(t.env_ref)}`}async function da(e,t,n){let s=(await Pe(e.studio)).filter(a=>a.project_id===t.project_id);return lo(s,n)}function te(e){return`The ${e} is the project's: the command acts in the environment it is bound to. -E picks it where two environments hold its name, and is refused when it names another.`}var Dn="It is bound to the environment -E names, or to the one chosen for this directory: a person at the terminal is asked which, anyone else names it with -E.";async function mp(e,t){let n=await Pe(e.studio);if(e.global.project!==void 0)return un(n,e.global.project);if(t){let a=n.filter(i=>i.project_id===t.project_id);if(a.length===0)throw new f("no_such_project",`the project chosen here (${t.project_name}) is not among yours any more`,{hint:"palbase use another"});return a}if(!e.interactive)throw new f("no_target","which project? none is chosen for this directory",{hint:"pass -P <project>, or choose one here with palbase use"});if(n.length===0)throw new f("no_environments","your account reaches no environment yet",{hint:"make one: palbase projects:create <name>"});let s=[...new Map(n.map(a=>[a.project_id,a])).values()];for(s.forEach((a,i)=>e.out.note(` ${String(i+1).padStart(2)}) ${a.org_name} \u203A ${a.project_name}`));;){let a=Number((await e.io.prompt(`Which project? [1-${s.length}] `)).trim());if(Number.isInteger(a)&&a>=1&&a<=s.length){let i=s[a-1];return e.out.note(`Acting on ${i.org_name} \u203A ${i.project_name}. palbase use remembers one for this directory.`),n.filter(r=>r.project_id===i.project_id)}e.out.note(`answer with a number from 1 to ${s.length}`)}}function lo(e,t){let n=e.find(s=>s.slug===t||s.ref===t);if(!n)throw new f("no_such_environment",`the project has no environment ${JSON.stringify(t)}`,{hint:`its environments: ${e.map(s=>s.slug).join(", ")}`});return n}function un(e,t){let n=e.filter(l=>l.project_id===t);if(n.length>0)return n;let s=t.indexOf("/"),[a,i]=s>=0?[t.slice(0,s),t.slice(s+1)]:[void 0,t],r=e.filter(l=>oo(l.project_name,i)&&(a===void 0||oo(l.org_name,a)||l.organization_id===a)),o=new Set(r.map(l=>l.project_id));if(o.size===0)throw new f("no_such_project",`no project ${JSON.stringify(t)} among yours`,{hint:"palbase projects:list shows them"});if(o.size>1){let l=[...new Set(r.map(d=>`${d.org_name}/${d.project_name}`))].join(", ");throw new f("ambiguous_project",`${JSON.stringify(t)} is a project in more than one organization: ${l}`,{hint:"name it as org/project"})}return r}async function v(e,t,n,s){e.out.note(`${N(t)}: ${n}${e.global.yes?" (confirmed with -y)":""}`);let a=t.env_slug===Be;if(!a&&s===void 0||e.global.yes)return;if(!e.interactive){let r=Jt(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 f("confirmation_needed",a?`${t.project_name} \u203A ${t.env_name} is the project's production environment`:s,{hint:r})}let i=(await e.io.prompt(q(`${a?`This is ${t.project_name}'s production environment`:s}. Go ahead? [y/N] `))).trim().toLowerCase();if(i!=="y"&&i!=="yes")throw new f("cancelled","nothing was changed")}async function io(e,t,n){if(!e.interactive)throw ro(`${n.replace(/\?$/,"")}: ${t.map(s=>`${s.project_name}/${s.slug}`).join(", ")}`);for(t.forEach((s,a)=>e.out.note(` ${String(a+1).padStart(2)}) ${N(ie(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 ro(e){return new f("no_target",e,{hint:"choose one here with palbase use, or pass -P <project> -E <env>"})}function oo(e,t){return e.localeCompare(t,void 0,{sensitivity:"accent"})===0}import{randomUUID as f_}from"node:crypto";import{readFile as y_}from"node:fs/promises";import{resolve as b_}from"node:path";var w_=6,po=0,gp=[];async function v_(e){po<w_?po++:await new Promise(t=>gp.push(t));try{return await e()}finally{let t=gp.shift();t?t():po--}}async function qe(e,t,n,s,a,i){return v_(()=>_e(e.studio,t.env_ref,n,s,a,i))}async function h(e,t,n,s,a,i){return(await qe(e,t,n,s,a,i)).body}async function Ke(e,t,n){let s=await qe(e,t,"GET",n);return{body:s.body,etag:s.etag}}function je(e){return e?{"if-match":e}:void 0}function j(){return{"idempotency-key":f_()}}function k(e){return encodeURIComponent(e)}function cn(e){return e.map(t=>{let n=t.indexOf("=");if(n<=0)throw m(`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 m(`${JSON.stringify(t.slice(0,n))} is not a key`);return{path:s,value:jt(t.slice(n+1))}})}function jt(e){try{return JSON.parse(e)}catch{return e}}function hn(e,t){let n=structuredClone(e);for(let{path:s,value:a}of t){let i=n;for(let r of s.slice(0,-1)){let o=i[r];(typeof o!="object"||o===null)&&(i[r]={}),i=i[r]}i[s[s.length-1]]=a}return n}function Vt(e,t){return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!We(e[n],t[n])).sort()}function fp(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 We(e,t){return fp(e)===fp(t)}function Oe(e){return e===void 0?"(not set)":typeof e=="string"&&e!==""?e:JSON.stringify(e)}function gs(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)} ${Oe(t[a])}`)}function Fe(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 ke(e,t,n){let s;if(t!==void 0&&t!=="-")try{s=await y_(b_(e.io.cwd,t),"utf8")}catch(a){throw new f("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 m(`no ${n} was given`,t===void 0?"pass --file <path>, or pipe it in":void 0);return s}function me(e,t){try{return JSON.parse(e)}catch(n){throw m(`${t} is not JSON: ${n instanceof Error?n.message:String(n)}`)}}async function Me(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 m(`no ${t} was piped in`,"pipe it in: palbase \u2026 < file");return n}function fs(e){if(e.flags.enable===!0&&e.flags.disable===!0)throw m("--enable and --disable are one or the other");if(e.flags.enable===!0)return!0;if(e.flags.disable===!0)return!1}function mn(e,t){if(e!==void 0){if(e==="yes"||e==="true")return!0;if(e==="no"||e==="false")return!1;throw m(`--${t} is yes or no`)}}function oe(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 se(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw m(`--${t} is a whole number`);return n}var pa={enable:{type:"boolean",description:"turn it on"},disable:{type:"boolean",description:"turn it off"}};async function Q(e,t,n){try{await n(),e.done(t)}catch(s){if(!(s instanceof E))throw s;e.left(`${t}: refused \u2014 ${s.message}`)}}function fe(e,t){return e.filter(n=>n.key.startsWith(t)).map(n=>({...n,name:n.key.slice(t.length)}))}function uo(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>!(t==null||t===""||Array.isArray(t)&&t.length===0)))}import{writeFile as __}from"node:fs/promises";var k_=/^[A-Z][A-Z0-9_]{0,127}$/,ys={dev:{type:"boolean",description:"the development set (what a backend on a developer's computer reads, and a machine started with it), not production \u2014 whatever the environment is named"}};function bs(e){return e.flags.dev===!0?"development":"production"}function ua(e){let t=e.args[0];if(!k_.test(t))throw m(`${JSON.stringify(t)} is not a secret's name: capital letters, digits and _, a letter first`);return t}async function co(e,t,n){try{let s=await On(async a=>{let i=await h(e,t,"GET",`/machines?limit=100&environment=${encodeURIComponent(t.env_ref)}${a?`&cursor=${encodeURIComponent(a)}`:""}`);return{items:i.machines,next:i.next_cursor}});return{using:s.filter(a=>a.secrets===n).map(a=>a.name).sort(),others:s.filter(a=>a.secrets!==n)}}catch(s){return{unread:s instanceof Error?s.message:String(s)}}}function ho(e,t,n,s){if("unread"in s){e.out.note(`which machines start with the ${n} set could not be read (${s.unread}): palbase machines:list -E ${t.env_slug} says each one's`);return}if(s.using.length>0){let o=s.using.join(", ");e.out.line(`${o} ${s.using.length===1?"starts":"start"} with the ${n} set: rolling out with the new value \u2014 palbase machines:list -E ${t.env_slug} shows it until every copy runs it.`);return}let a=n==="production"?"development":"production",i=n==="development"?" Only a backend run on a computer (palbase run, env:pull) reads it.":"";if(s.others.length===0){n==="production"&&e.out.note(`${N(t)} has no machine yet: one started with the ${n} set reads it.`);return}let r=s.others.map(o=>`${o.name} starts with ${o.secrets?`the ${o.secrets} set`:"no set"}`).join(", ");e.out.warn(`no machine of ${N(t)} starts with the ${n} set (${r}): this value reaches none of them.${i} palbase machines:update <name> --secrets ${n} starts a machine with it; ${n==="production"?"--dev writes":"leaving --dev out writes"} the ${a} set.`)}async function ws(e,t,n){let s=[],a;do{let i=await h(e,t,"GET",`/secrets/${n}?limit=1000${a?`&cursor=${encodeURIComponent(a)}`:""}`);s.push(...i.secrets),a=i.next_cursor}while(a);return s}var S_={name:"secrets:list",summary:"the environment's secrets by name, with their version \u2014 never their values",usage:"[--dev]",flags:ys,scope:"environment",async run(e){let t=await b(e),n=bs(e),s=await ws(e,t,n);e.out.result({set:n,secrets:s},()=>{s.length===0&&e.out.line(`No ${n} secrets.`);for(let a of s)e.out.line(`${a.name} v${a.version} ${a.updated_at}`)})}},$_={name:"secrets:set",summary:"set a secret: its value is read from stdin, never from the command line",usage:"<NAME> [--dev] < value",details:["An environment has two sets, production and development, whatever the environment is named: Development's machines may start with its production set. A machine starts with the set it names (machines:update --secrets), and a change of that set rolls it out with the new value; a backend run with palbase run or env:pull reads development.","It says which of the environment's machines start with the set, and warns when none does."],args:{min:1,max:1},flags:ys,scope:"environment",async run(e){let t=await b(e),n=ua(e),s=bs(e),a=await Me(e,`the value of ${n}`);await v(e,t,`set the ${s} secret ${n}`);let i=await h(e,t,"PUT",`/secrets/${s}/${n}`,{value:a}),r=await co(e,t,s);e.out.result({set:s,name:n,version:i.version,environment:t.env_slug,machines:"using"in r?r.using:null},()=>{e.out.line(`Set ${n} v${i.version} in the ${s} set of ${N(t)}.`),ho(e,t,s,r)})}},P_={name:"secrets:unset",summary:"take a secret away",usage:"<NAME> [--dev]",args:{min:1,max:1},flags:ys,scope:"environment",async run(e){let t=await b(e),n=ua(e),s=bs(e);await v(e,t,`take away the ${s} secret ${n}`),await h(e,t,"DELETE",`/secrets/${s}/${n}`);let a=await co(e,t,s);e.out.result({set:s,name:n,deleted:!0,environment:t.env_slug,machines:"using"in a?a.using:null},()=>{e.out.line(`Took ${n} away from the ${s} set of ${N(t)}.`),ho(e,t,s,a)})}},A_={name:"secrets:get",summary:"print one secret's value (an admin's)",usage:"<NAME> [--dev]",args:{min:1,max:1},flags:ys,scope:"environment",async run(e){let t=await b(e),n=ua(e),s=await h(e,t,"GET",`/secrets/${bs(e)}/${n}`);e.out.result({name:n,version:s.version,value:s.value},()=>e.out.line(s.value))}},R_={name:"secrets:versions",summary:"a secret's versions, newest first \u2014 never their values",usage:"<NAME> [--dev]",args:{min:1,max:1},flags:ys,scope:"environment",async run(e){let t=await b(e),n=ua(e),s=await h(e,t,"GET",`/secrets/${bs(e)}/${n}/versions`);e.out.result(s,()=>{for(let a of s.versions)e.out.line(`v${a.version} ${a.created_at}${a.current?" (current)":""}`)})}},T_={name:"secrets:rollback",summary:"put a secret back to one of its versions (a new version with that value)",usage:"<NAME> --version <n> [--dev]",args:{min:1,max:1},flags:{...ys,version:{type:"string",value:"n",description:"the version to go back to"}},scope:"environment",async run(e){let t=await b(e),n=ua(e),s=Number(e.flags.version);if(!Number.isInteger(s)||s<1)throw m("--version is a version number (secrets:versions lists them)");let a=bs(e);await v(e,t,`put the ${a} secret ${n} back to v${s}`);let i=await h(e,t,"POST",`/secrets/${a}/${n}/rollback`,{version:s}),r=await co(e,t,a);e.out.result({set:a,name:n,version:i.version,environment:t.env_slug,machines:"using"in r?r.using:null},()=>{e.out.line(`${n} in the ${a} set of ${N(t)} is v${s}'s value again, as v${i.version}.`),ho(e,t,a,r)})}},E_={name:"secrets:audit",summary:"every read and write of the environment's secrets, newest first: which secret, which key did it, when \u2014 never a value",usage:"[--name <NAME>] [--dev | --prod] [--limit <n>]",details:["A backend that reads the secrets at boot (palbase run, a machine) shows here as a read, with the key it read with: palbase keys:list names the key.","An encrypted column's values opened through Palbase (Studio's table, a secret key) are recorded under the column's address: --name patients.tc lists who opened them, and when."],flags:{name:{type:"string",value:"NAME",description:"only this secret's, or an encrypted field's opens (table.column)"},dev:{type:"boolean",description:"only the development secrets"},prod:{type:"boolean",description:"only the production secrets"},limit:{type:"string",value:"n",description:"how many (default 30)"}},scope:"environment",async run(e){let t=await b(e);if(e.flags.dev===!0&&e.flags.prod===!0)throw m("--dev or --prod, not both");let n=Number(e.flags.limit??30);if(!Number.isInteger(n)||n<1||n>500)throw m("--limit is a whole number from 1 to 500");let s=new URLSearchParams({limit:String(n),...e.flags.name?{name:e.flags.name}:{},...e.flags.dev===!0?{environment:"development"}:e.flags.prod===!0?{environment:"production"}:{}}),a=await h(e,t,"GET",`/secrets/audit?${s}`);e.out.result(a,()=>{a.entries.length===0?e.out.line("No read or write of a secret yet."):e.out.table(a.entries,[{header:"when",value:i=>i.at.slice(0,19).replace("T"," ")},{header:"what",value:i=>i.action},{header:"set",value:i=>i.environment??""},{header:"secret",value:i=>i.name?`${i.name}${i.version?` v${i.version}`:""}`:"every one"},{header:"key",value:i=>i.key_id}])})}};function yp(e,t){e.out.table(t.keys,[{header:"key",value:n=>`${n.id}${n.id===t.current?" (in force)":""}`},{header:"in force from",value:n=>n.activates_at.slice(0,19).replace("T"," ")},{header:"made by",value:n=>n.created_by}])}var C_={name:"fields:list",summary:"the keys the environment's encrypted database fields are sealed with \u2014 never the keys themselves",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/secrets/fields");e.out.result(n,()=>yp(e,n))}},j_={name:"fields:rotate",summary:"make a new key for the environment's encrypted fields (an owner's or an admin's)",details:["It comes into force in five minutes: by then every running backend has fetched it. New values are sealed with it from then on; a palbase/backend app seals its older values again with it, in the background.","The older keys go on opening what they sealed."],scope:"environment",async run(e){let t=await b(e);await v(e,t,"rotate the encrypted fields' key");let n=await h(e,t,"POST","/secrets/fields/rotate"),s=n.keys[n.keys.length-1];e.out.result(n,()=>{e.out.line(`Made ${s.id} in ${N(t)}: in force from ${s.activates_at.slice(0,19).replace("T"," ")} UTC.`),yp(e,n)})}},O_={name:"fields:keys",summary:"download the environment's field keys into a file (its owner's): what opens a dump of its database elsewhere",usage:"--out <file>",details:["The file opens every encrypted field of the environment: keep it as you would the database's password. It is the shape palbase/server's Fields reads: new Fields({ fetch: async () => JSON.parse(readFileSync(file, 'utf8')) }).","The download is in the secrets audit trail (secrets:audit)."],flags:{out:{type:"string",value:"file",description:"where the keys go (made readable by you alone); never the screen"}},scope:"environment",async run(e){let t=e.flags.out;if(!t)throw m("fields:keys writes the keys into a file: --out <file> (never onto the screen, which keeps them)");let n=await b(e),s=await h(e,n,"GET","/secrets/fields/keys");await __(t,`${JSON.stringify(s,null,2)}
|
|
22
|
-
`,{mode:384,flag:"wx"}),e.out.result({file:t,keys:s.keys.map(a=>a.id)},()=>e.out.line(`Wrote the keys of ${N(n)} (${s.keys.map(a=>a.id).join(", ")}) to ${t}.`))}};function mo(e,t){e.out.table(t.keys,[{header:"key",value:n=>`${n.id}${n.id===t.current?" (in use)":""}`},{header:"made",value:n=>n.created_at.slice(0,19).replace("T"," ")},{header:"made by",value:n=>n.created_by},{header:"retired",value:n=>n.retired_at?`${n.retired_at.slice(0,19).replace("T"," ")} by ${n.retired_by}`:""}])}var M_={name:"transit:list",summary:"the keys the encrypted fields of a request to the environment's backend are sealed to \u2014 their public halves alone",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/secrets/transit");e.out.result(n,()=>mo(e,n))}},I_={name:"transit:rotate",summary:"make a new key for the encrypted fields of requests to the backend (an owner's or an admin's)",usage:"[--retire-previous]",details:["Apps seal to it from their next fetch of the project's keys (within the hour), or at once with --retire-previous: every older key is retired with it \u2014 what to do when one may have been taken \u2014 and an app that seals to a retired one is told so, fetches the keys again and sends its call once more.","No app needs a new build: an app holds the project's signing key, not its keys."],flags:{"retire-previous":{type:"boolean",description:"retire every older key at once"}},scope:"environment",async run(e){let t=await b(e),n=e.flags["retire-previous"]===!0;await v(e,t,n?"rotate the transit keys, retiring every older one":"rotate the transit keys");let s=await h(e,t,"POST","/secrets/transit/rotate",{retire_previous:n});e.out.result(s,()=>{e.out.line(`Made ${s.current} in ${N(t)}: apps seal to it from now${n?"; every older key is retired":""}.`),mo(e,s)})}},L_={name:"transit:retire",summary:"retire a transit key that is not the one in use: no request sealed to it opens from then on",usage:"<key>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=e.args[0];if(!/^t[1-9][0-9]{0,5}$/.test(n))throw m(`${n} is not a transit key's id`,"palbase transit:list names them (t1, t2, \u2026)");await v(e,t,`retire the transit key ${n}`);let s=await h(e,t,"POST",`/secrets/transit/${n}/retire`);e.out.result(s,()=>{e.out.line(`Retired ${n} in ${N(t)}.`),mo(e,s)})}},bp=[S_,$_,A_,P_,R_,T_,E_,C_,j_,O_,M_,I_,L_];import{randomBytes as Gp}from"node:crypto";import{chmod as a0,lstat as i0,readFile as Dp,rename as r0,writeFile as xp}from"node:fs/promises";function wp(){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 Ht=class extends Error{code;constructor(t,n){super(n),this.name="FieldError",this.code=t}},gi="pbe1.",D_="pbl1.",x_=6e4,go="[A-Za-z_][A-Za-z0-9_$]{0,62}",N_=new RegExp(`^${go}\\.${go}(\\.${go})?$`);function q_(e){return N_.test(e)}var ca=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),()=>{})},x_),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 Ht("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 Ht("unknown_key","the project has no field key in force");return t.id}encrypt(t,n){let s=this.ready();fo(t);let a=this.currentKey(),i=s.randomBytes(12);return K_(s,this.keys.get(a).key,i,a,t,n)}decrypt(t,n){let s=this.ready();if(fo(t),!n.startsWith(gi))throw new Ht("not_encrypted",`${t} holds a value that is not encrypted`);let a=n.slice(gi.length),i=a.indexOf("."),r=i<0?a:a.slice(0,i),o=this.keys.get(r);if(o===void 0)throw new Ht("unknown_key",`${t} was sealed with field key ${r}, which this project does not hold`);let l=Buffer.from(a.slice(i+1),"base64url");if(i<0||l.length<28||l.toString("base64url")!==a.slice(i+1))throw new Ht("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(vp(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 Ht("unopenable",`${t} holds a value that does not open here: tampered, or another column's`)}}isEncrypted(t){return t.startsWith(gi)}lookup(t,n){let s=this.ready();return fo(t),G_(s,this.lookupKey,t,n)}};function fo(e){if(!q_(e))throw new TypeError(`a field's address is table.column, or schema.table.column, not ${JSON.stringify(e)}`)}function vp(e){return Buffer.from(`pbe1\0${e}`,"utf8")}function K_(e,t,n,s,a,i){let r=e.createCipheriv("aes-256-gcm",t,n);r.setAAD(vp(a));let o=Buffer.concat([n,r.update(i,"utf8"),r.final(),r.getAuthTag()]);return`${gi}${s}.${o.toString("base64url")}`}function G_(e,t,n,s){let a=e.createHmac("sha256",t);return a.update(`pbl1\0${n}\0`,"utf8"),a.update(s,"utf8"),`${D_}${a.digest("base64url")}`}var bo="pbt1.",yt="Palbase-Encryption";var bi="x-palbase-encrypted",Ae=class extends Error{code;constructor(t,n){super(n),this.name="TransitError",this.code=t}},gn=new TextEncoder,U_=new TextDecoder("utf-8",{fatal:!0}),bt=()=>{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 ze(e){return new Uint8Array(new ArrayBuffer(e))}function wt(...e){let t=ze(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 Ot(e){return wt(e)}function ma(e,t){let n=ze(t);for(let s=t-1;s>=0;s--)n[s]=e&255,e>>>=8;return n}function ga(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Mt(e){let t=e.replace(/=+$/,"");if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)throw new Ae("malformed","not base64url");let n=atob(t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4)),s=ze(n.length);for(let a=0;a<n.length;a++)s[a]=n.charCodeAt(a);return s}var _p=wt(gn.encode("KEM"),ma(32,2)),ha=wt(gn.encode("HPKE"),ma(32,2),ma(1,2),ma(1,2)),kp=gn.encode("HPKE-v1"),B_=16,z_=12,W_=32,Sp=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function $p(e,t){let n=await bt().importKey("raw",e.length===0?ze(32):Ot(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await bt().sign("HMAC",n,Ot(t)))}async function fi(e,t,n,s){return $p(t,wt(kp,e,gn.encode(n),s))}async function yo(e,t,n,s,a){let i=wt(ma(a,2),kp,e,gn.encode(n),s),r=ze(a),o=ze(0);for(let l=1,d=0;d<a;l++)o=await $p(t,wt(o,i,Uint8Array.of(l))),r.set(o.subarray(0,Math.min(o.length,a-d)),d),d+=o.length;return r}async function Pp(e){if(e.length!==32)throw new Ae("malformed","an X25519 private key is 32 bytes");return bt().importKey("pkcs8",wt(Sp,e),{name:"X25519"},!1,["deriveBits"])}async function Ap(e){if(e.length!==32)throw new Ae("malformed","an X25519 public key is 32 bytes");return bt().importKey("raw",Ot(e),{name:"X25519"},!1,[])}async function Rp(e,t){return new Uint8Array(await bt().deriveBits({name:"X25519",public:t},e,256))}async function Tp(e,t,n){let s=await fi(_p,ze(0),"eae_prk",e);return yo(_p,s,"shared_secret",wt(t,n),W_)}async function Ep(e,t){let n=await fi(ha,ze(0),"psk_id_hash",ze(0)),s=await fi(ha,ze(0),"info_hash",t),a=wt(Uint8Array.of(0),n,s),i=await fi(ha,e,"secret",ze(0));return{key:await yo(ha,i,"key",a,B_),nonce:await yo(ha,i,"base_nonce",a,z_)}}async function wi(e,t,n,s,a){let i=await bt().importKey("raw",Ot(t),"AES-GCM",!1,[e]);return new Uint8Array(await bt()[e]({name:"AES-GCM",iv:Ot(n),additionalData:Ot(s)},i,Ot(a)))}async function wo(e,t,n,s=ze(0),a){let i,r;if(a)i=await Pp(a.privateKey),r=Ot(a.publicKey);else{let p=await bt().generateKey({name:"X25519"},!0,["deriveBits"]);i=p.privateKey,r=new Uint8Array(await bt().exportKey("raw",p.publicKey))}let o=await Tp(await Rp(i,await Ap(e)),r,e),{key:l,nonce:d}=await Ep(o,t);return{enc:r,ct:await wi("encrypt",l,d,s,n)}}async function F_(e,t,n,s,a,i=ze(0)){if(n.length!==32)throw new Ae("malformed","an encapsulated X25519 key is 32 bytes");try{let r=await Tp(await Rp(await Pp(e),await Ap(n)),n,t),{key:o,nonce:l}=await Ep(r,s);return await wi("decrypt",o,l,i,a)}catch{throw new Ae("unopenable","the request's key does not open with the project's key it names")}}async function Cp(e){let t=await bt().importKey("pkcs8",wt(Sp,e),{name:"X25519"},!0,["deriveBits"]),n=await bt().exportKey("jwk",t);return Mt(n.x)}function vi(e,t,n,s=[]){if(s.some(a=>a.includes("\0")))throw new Ae("malformed","a path's value holds no NUL");return gn.encode(["palbase-encryption","1",e,t.toUpperCase(),J_(n),...s].join("\0"))}function J_(e){return e.replace(/\{[^/{}]*\}/g,"{}")}async function jp(e,t,n,s={}){let a=s.key?Ot(s.key):crypto.getRandomValues(ze(32)),{enc:i,ct:r}=await wo(t,n,a,ze(0),s.ephemeral);return{kid:e,key:a,header:`1.${e}.${ga(i)}.${ga(r)}`}}function vo(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 Ae("malformed",`${yt} is 1.<key id>.<enc>.<ct>`);let n=Mt(t[2]),s=Mt(t[3]);if(n.length!==32||s.length!==48)throw new Ae("malformed",`${yt} carries a 32-byte encapsulated key and a sealed 32-byte key`);return{kid:t[1],enc:n,ct:s}}async function Op(e,t,n,s){let{enc:a,ct:i}=vo(e),r=await F_(t,n,a,s,i);if(r.length!==32)throw new Ae("unopenable","the request's key is not 32 bytes");return r}function Mp(e){return gn.encode(`pbt1\0${e}`)}async function fa(e,t,n,s){let a=s?Ot(s):crypto.getRandomValues(ze(12)),i=JSON.stringify(n);if(i===void 0)throw new Ae("malformed",`${t}: an encrypted field holds a JSON value`);let r=await wi("encrypt",e,a,Mp(t),gn.encode(i));return bo+ga(wt(a,r))}function ya(e){return typeof e=="string"&&e.startsWith(bo)}async function _i(e,t,n){if(!ya(n))throw new Ae("unopenable",`${t} is not an encrypted field`);let s;try{s=Mt(n.slice(bo.length))}catch{throw new Ae("unopenable",`${t} is not an encrypted field`)}if(s.length<28)throw new Ae("unopenable",`${t} is too short to be an encrypted field`);let a;try{a=await wi("decrypt",e,s.subarray(0,12),Mp(t),s.subarray(12))}catch{throw new Ae("unopenable",`${t} does not open: changed, moved from another field, or another request's`)}try{return JSON.parse(U_.decode(a))}catch{throw new Ae("unopenable",`${t} opens to no JSON value`)}}function ki(e){return e.replace(/~/g,"~0").replace(/\//g,"~1").replace(/\*/g,"~2")}function V_(e){return e.replace(/~2/g,"*").replace(/~1/g,"/").replace(/~0/g,"~")}var Ip=Symbol("items");function H_(e,t){if(!(e!==t&&!e.startsWith(t+"/")))return e===t?[]:e.slice(t.length+1).split("/").map(n=>n==="*"?Ip:V_(n))}async function vs(e,t,n,s){let a=e;for(let i of n){let r=H_(i,t);r!==void 0&&(a=await yi(a,r,t,s))}return a}async function yi(e,t,n,s){if(t.length===0)return e===void 0?void 0:s(n,e);let[a,...i]=t;if(a===Ip){if(!Array.isArray(e))return e;let o=[];for(let[l,d]of e.entries())o.push(await yi(d,i,`${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 yi(o[Number(a)],i,`${n}/${a}`,s),o}if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,a))return e;let r={...e};return r[a]=await yi(r[a],i,`${n}/${ki(a)}`,s),r}var vt=class extends Error{status=400;code;data;constructor(t,n,s={}){super(n),this.name="TransitRefusal",this.code=t,this.data=s}},Y_=6e4,X_=1e3;function _o(e){return/^t[1-9][0-9]{0,5}$/.test(e)?Number(e.slice(1)):0}var ba=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(()=>{})},Y_),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 i of s.keys){let r=Mt(i.key);a.set(i.id,{privateKey:r,publicKey:this.keys.get(i.id)?.publicKey??await Cp(r)})}this.keys=a,this.order=s.keys.map(i=>i.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(_o),...[...this.retired].map(_o))}async key(t){let n=this.now();for(;_o(t)>this.newest()&&this.heldFrom<n;){let i=this.fetchedAt+X_-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let s=this.keys.get(t),a=this.current();if(this.retired.has(t))throw new vt("encryption_key_retired",`the request is sealed to ${t}, retired: fetch the project's keys again`,{current:a});if(s===void 0)throw new vt("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 vt("encryption_required",`this route carries encrypted fields: the request names its key in ${yt}`,{field:yt,current:this.current()});let n;try{n=vo(t.header).kid}catch{throw new vt("encryption_unopenable",`${yt} is not one`,{field:yt})}let s=await this.key(n),a;try{a=vi(this.projectId,t.method,t.path,t.params??[])}catch{throw new vt("encryption_unopenable","the request's path holds a value no key is sealed for",{field:yt})}try{return new Si(n,await Op(t.header,s.privateKey,s.publicKey,a))}catch(i){throw i instanceof Ae?new vt("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:yt}):i}}},Si=class{kid;key;constructor(t,n){this.kid=t,this.key=n}async open(t,n,s){return vs(t,n,s,async(a,i)=>{if(!ya(i))throw new vt("encryption_required",`${a} is an encrypted field: it came plain`,{field:a});try{return await _i(this.key,a,i)}catch{throw new vt("encryption_unopenable",`${a} does not open: changed, moved from another field, or another request's`,{field:a})}})}async seal(t,n){return vs(t,"/response",n,(s,a)=>fa(this.key,s,a))}sealField(t,n){return fa(this.key,t,n)}};var Z_=/^pb_[a-z0-9]+_s/;function $i(e){if(wp())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"||!Z_.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=so(Hr({baseUrl:e.url,credentials:{secretKey:e.secretKey},fetch:e.fetch,solveProofOfWork:e.solveProofOfWork??!1}),e.retry??ui),n=ia.client(t);return{ai:oi.client(t),analytics:Zs.client(t),auth:Qs.client(t),cache:li.client(t),calls:di.client(t),fields:new ca({fetch:async s=>(await n.getFieldKeys({signal:s})).data}),flags:ea.client(t),machines:ta.client(t),messaging:pi.client(t),notify:na.client(t),purchases:sa.client(t),realtime:aa.client(t),secrets:n,storage:ra.client(t),stores:oa.client(t),transit:new ba({fetch:async s=>(await n.getTransitKeys({signal:s})).data}),transport:t,url:new URL(e.url).origin}}var FD=1024*1024;var HD=8*1024;var tx=16*1024,nx=10*6e4;var t0=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,n0=/^(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 ko(e){return!t0.test(e)||n0.test(e)||/_PROXY$/i.test(e)}var s0=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function So(e){return s0.test(e)}import"node:os";import{join as o0,resolve as l0}from"node:path";var Ux=10080*60*1e3,Lp="# >>> palbase (palbase env:pull writes this block; edit outside it)",$o="# <<< palbase";async function wa(e,t){let n=await ao(e.studio,t.env_ref),{keys:s}=await e.studio.get(`/environments/${x("the environment's ref",t.env_ref)}/keys`),a=s.find(i=>i.id===n.id);return a&&!a.revoked_at?n:ao(e.studio,t.env_ref,!0)}async function Pi(e,t){return{...await Ao(e,t),key:await wa(e,t)}}async function Ao(e,t){let n=await e.studio.get(`/environments/${t.env_ref}`);return{url:st(e.cloud,t.env_ref),projectId:n.platform_id}}function Ai(e){let t=e.flags.secrets??"development";if(t!=="development"&&t!=="production")throw m("--secrets is development or production");return t}function Ri(e,t){return t==="production"?`the app reads ${e.project_name} \u203A ${e.env_name}'s production secrets here`:void 0}var Ti={type:"string",value:"set",description:"the project's secrets the app reads at boot: development (default) or production"},Np={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:Ti},scope:"environment",async run(e){let t=await b(e),n=Ai(e);(t.env_slug===Be||n==="production")&&await v(e,t,`write a key of ${t.env_slug===Be?"the production environment":`${t.env_slug}`} into a file on this computer`,Ri(t,n));let s=await Pi(e,t),a=await _e(e.studio,t.env_ref,"GET",`/secrets/${n}`).then(y=>(y.body.secrets??y.body.items??[]).map(w=>w.name).filter(w=>typeof w=="string"&&!ko(w)).sort(),()=>[]),i=l0(e.io.cwd,e.flags.file??".env.local"),r=[Lp,`# ${Po(N(t))} \u2014 ${new Date(e.io.now()).toISOString()}`,`# PALBASE_SECRET_KEY is your own: ${Po(s.key.label)}, good until ${Po(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(y=>`# ${y}=`)]:[],$o].join(`
|
|
22
|
+
`,{mode:384,flag:"wx"}),e.out.result({file:t,keys:s.keys.map(a=>a.id)},()=>e.out.line(`Wrote the keys of ${N(n)} (${s.keys.map(a=>a.id).join(", ")}) to ${t}.`))}};function mo(e,t){e.out.table(t.keys,[{header:"key",value:n=>`${n.id}${n.id===t.current?" (in use)":""}`},{header:"made",value:n=>n.created_at.slice(0,19).replace("T"," ")},{header:"made by",value:n=>n.created_by},{header:"retired",value:n=>n.retired_at?`${n.retired_at.slice(0,19).replace("T"," ")} by ${n.retired_by}`:""}])}var M_={name:"transit:list",summary:"the keys the encrypted fields of a request to the environment's backend are sealed to \u2014 their public halves alone",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/secrets/transit");e.out.result(n,()=>mo(e,n))}},I_={name:"transit:rotate",summary:"make a new key for the encrypted fields of requests to the backend (an owner's or an admin's)",usage:"[--retire-previous]",details:["Apps seal to it from their next fetch of the project's keys (within the hour), or at once with --retire-previous: every older key is retired with it \u2014 what to do when one may have been taken \u2014 and an app that seals to a retired one is told so, fetches the keys again and sends its call once more.","No app needs a new build: an app holds the project's signing key, not its keys."],flags:{"retire-previous":{type:"boolean",description:"retire every older key at once"}},scope:"environment",async run(e){let t=await b(e),n=e.flags["retire-previous"]===!0;await v(e,t,n?"rotate the transit keys, retiring every older one":"rotate the transit keys");let s=await h(e,t,"POST","/secrets/transit/rotate",{retire_previous:n});e.out.result(s,()=>{e.out.line(`Made ${s.current} in ${N(t)}: apps seal to it from now${n?"; every older key is retired":""}.`),mo(e,s)})}},L_={name:"transit:retire",summary:"retire a transit key that is not the one in use: no request sealed to it opens from then on",usage:"<key>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=e.args[0];if(!/^t[1-9][0-9]{0,5}$/.test(n))throw m(`${n} is not a transit key's id`,"palbase transit:list names them (t1, t2, \u2026)");await v(e,t,`retire the transit key ${n}`);let s=await h(e,t,"POST",`/secrets/transit/${n}/retire`);e.out.result(s,()=>{e.out.line(`Retired ${n} in ${N(t)}.`),mo(e,s)})}},bp=[S_,$_,A_,P_,R_,T_,E_,C_,j_,O_,M_,I_,L_];import{randomBytes as Gp}from"node:crypto";import{chmod as a0,lstat as i0,readFile as Dp,rename as r0,writeFile as xp}from"node:fs/promises";function wp(){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 Ht=class extends Error{code;constructor(t,n){super(n),this.name="FieldError",this.code=t}},gi="pbe1.",D_="pbl1.",x_=6e4,go="[A-Za-z_][A-Za-z0-9_$]{0,62}",N_=new RegExp(`^${go}\\.${go}(\\.${go})?$`);function q_(e){return N_.test(e)}var ca=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),()=>{})},x_),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 Ht("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 Ht("unknown_key","the project has no field key in force");return t.id}encrypt(t,n){let s=this.ready();fo(t);let a=this.currentKey(),i=s.randomBytes(12);return K_(s,this.keys.get(a).key,i,a,t,n)}decrypt(t,n){let s=this.ready();if(fo(t),!n.startsWith(gi))throw new Ht("not_encrypted",`${t} holds a value that is not encrypted`);let a=n.slice(gi.length),i=a.indexOf("."),r=i<0?a:a.slice(0,i),o=this.keys.get(r);if(o===void 0)throw new Ht("unknown_key",`${t} was sealed with field key ${r}, which this project does not hold`);let l=Buffer.from(a.slice(i+1),"base64url");if(i<0||l.length<28||l.toString("base64url")!==a.slice(i+1))throw new Ht("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(vp(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 Ht("unopenable",`${t} holds a value that does not open here: tampered, or another column's`)}}isEncrypted(t){return t.startsWith(gi)}lookup(t,n){let s=this.ready();return fo(t),G_(s,this.lookupKey,t,n)}};function fo(e){if(!q_(e))throw new TypeError(`a field's address is table.column, or schema.table.column, not ${JSON.stringify(e)}`)}function vp(e){return Buffer.from(`pbe1\0${e}`,"utf8")}function K_(e,t,n,s,a,i){let r=e.createCipheriv("aes-256-gcm",t,n);r.setAAD(vp(a));let o=Buffer.concat([n,r.update(i,"utf8"),r.final(),r.getAuthTag()]);return`${gi}${s}.${o.toString("base64url")}`}function G_(e,t,n,s){let a=e.createHmac("sha256",t);return a.update(`pbl1\0${n}\0`,"utf8"),a.update(s,"utf8"),`${D_}${a.digest("base64url")}`}var bo="pbt1.",bt="Palbase-Encryption";var bi="x-palbase-encrypted",Ae=class extends Error{code;constructor(t,n){super(n),this.name="TransitError",this.code=t}},gn=new TextEncoder,U_=new TextDecoder("utf-8",{fatal:!0}),wt=()=>{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 ze(e){return new Uint8Array(new ArrayBuffer(e))}function vt(...e){let t=ze(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 Ot(e){return vt(e)}function ma(e,t){let n=ze(t);for(let s=t-1;s>=0;s--)n[s]=e&255,e>>>=8;return n}function ga(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Mt(e){let t=e.replace(/=+$/,"");if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)throw new Ae("malformed","not base64url");let n=atob(t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4)),s=ze(n.length);for(let a=0;a<n.length;a++)s[a]=n.charCodeAt(a);return s}var _p=vt(gn.encode("KEM"),ma(32,2)),ha=vt(gn.encode("HPKE"),ma(32,2),ma(1,2),ma(1,2)),kp=gn.encode("HPKE-v1"),B_=16,z_=12,W_=32,Sp=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function $p(e,t){let n=await wt().importKey("raw",e.length===0?ze(32):Ot(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await wt().sign("HMAC",n,Ot(t)))}async function fi(e,t,n,s){return $p(t,vt(kp,e,gn.encode(n),s))}async function yo(e,t,n,s,a){let i=vt(ma(a,2),kp,e,gn.encode(n),s),r=ze(a),o=ze(0);for(let l=1,d=0;d<a;l++)o=await $p(t,vt(o,i,Uint8Array.of(l))),r.set(o.subarray(0,Math.min(o.length,a-d)),d),d+=o.length;return r}async function Pp(e){if(e.length!==32)throw new Ae("malformed","an X25519 private key is 32 bytes");return wt().importKey("pkcs8",vt(Sp,e),{name:"X25519"},!1,["deriveBits"])}async function Ap(e){if(e.length!==32)throw new Ae("malformed","an X25519 public key is 32 bytes");return wt().importKey("raw",Ot(e),{name:"X25519"},!1,[])}async function Rp(e,t){return new Uint8Array(await wt().deriveBits({name:"X25519",public:t},e,256))}async function Tp(e,t,n){let s=await fi(_p,ze(0),"eae_prk",e);return yo(_p,s,"shared_secret",vt(t,n),W_)}async function Ep(e,t){let n=await fi(ha,ze(0),"psk_id_hash",ze(0)),s=await fi(ha,ze(0),"info_hash",t),a=vt(Uint8Array.of(0),n,s),i=await fi(ha,e,"secret",ze(0));return{key:await yo(ha,i,"key",a,B_),nonce:await yo(ha,i,"base_nonce",a,z_)}}async function wi(e,t,n,s,a){let i=await wt().importKey("raw",Ot(t),"AES-GCM",!1,[e]);return new Uint8Array(await wt()[e]({name:"AES-GCM",iv:Ot(n),additionalData:Ot(s)},i,Ot(a)))}async function wo(e,t,n,s=ze(0),a){let i,r;if(a)i=await Pp(a.privateKey),r=Ot(a.publicKey);else{let p=await wt().generateKey({name:"X25519"},!0,["deriveBits"]);i=p.privateKey,r=new Uint8Array(await wt().exportKey("raw",p.publicKey))}let o=await Tp(await Rp(i,await Ap(e)),r,e),{key:l,nonce:d}=await Ep(o,t);return{enc:r,ct:await wi("encrypt",l,d,s,n)}}async function F_(e,t,n,s,a,i=ze(0)){if(n.length!==32)throw new Ae("malformed","an encapsulated X25519 key is 32 bytes");try{let r=await Tp(await Rp(await Pp(e),await Ap(n)),n,t),{key:o,nonce:l}=await Ep(r,s);return await wi("decrypt",o,l,i,a)}catch{throw new Ae("unopenable","the request's key does not open with the project's key it names")}}async function Cp(e){let t=await wt().importKey("pkcs8",vt(Sp,e),{name:"X25519"},!0,["deriveBits"]),n=await wt().exportKey("jwk",t);return Mt(n.x)}function vi(e,t,n,s=[]){if(s.some(a=>a.includes("\0")))throw new Ae("malformed","a path's value holds no NUL");return gn.encode(["palbase-encryption","1",e,t.toUpperCase(),J_(n),...s].join("\0"))}function J_(e){return e.replace(/\{[^/{}]*\}/g,"{}")}async function jp(e,t,n,s={}){let a=s.key?Ot(s.key):crypto.getRandomValues(ze(32)),{enc:i,ct:r}=await wo(t,n,a,ze(0),s.ephemeral);return{kid:e,key:a,header:`1.${e}.${ga(i)}.${ga(r)}`}}function vo(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 Ae("malformed",`${bt} is 1.<key id>.<enc>.<ct>`);let n=Mt(t[2]),s=Mt(t[3]);if(n.length!==32||s.length!==48)throw new Ae("malformed",`${bt} carries a 32-byte encapsulated key and a sealed 32-byte key`);return{kid:t[1],enc:n,ct:s}}async function Op(e,t,n,s){let{enc:a,ct:i}=vo(e),r=await F_(t,n,a,s,i);if(r.length!==32)throw new Ae("unopenable","the request's key is not 32 bytes");return r}function Mp(e){return gn.encode(`pbt1\0${e}`)}async function fa(e,t,n,s){let a=s?Ot(s):crypto.getRandomValues(ze(12)),i=JSON.stringify(n);if(i===void 0)throw new Ae("malformed",`${t}: an encrypted field holds a JSON value`);let r=await wi("encrypt",e,a,Mp(t),gn.encode(i));return bo+ga(vt(a,r))}function ya(e){return typeof e=="string"&&e.startsWith(bo)}async function _i(e,t,n){if(!ya(n))throw new Ae("unopenable",`${t} is not an encrypted field`);let s;try{s=Mt(n.slice(bo.length))}catch{throw new Ae("unopenable",`${t} is not an encrypted field`)}if(s.length<28)throw new Ae("unopenable",`${t} is too short to be an encrypted field`);let a;try{a=await wi("decrypt",e,s.subarray(0,12),Mp(t),s.subarray(12))}catch{throw new Ae("unopenable",`${t} does not open: changed, moved from another field, or another request's`)}try{return JSON.parse(U_.decode(a))}catch{throw new Ae("unopenable",`${t} opens to no JSON value`)}}function ki(e){return e.replace(/~/g,"~0").replace(/\//g,"~1").replace(/\*/g,"~2")}function V_(e){return e.replace(/~2/g,"*").replace(/~1/g,"/").replace(/~0/g,"~")}var Ip=Symbol("items");function H_(e,t){if(!(e!==t&&!e.startsWith(t+"/")))return e===t?[]:e.slice(t.length+1).split("/").map(n=>n==="*"?Ip:V_(n))}async function vs(e,t,n,s){let a=e;for(let i of n){let r=H_(i,t);r!==void 0&&(a=await yi(a,r,t,s))}return a}async function yi(e,t,n,s){if(t.length===0)return e===void 0?void 0:s(n,e);let[a,...i]=t;if(a===Ip){if(!Array.isArray(e))return e;let o=[];for(let[l,d]of e.entries())o.push(await yi(d,i,`${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 yi(o[Number(a)],i,`${n}/${a}`,s),o}if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,a))return e;let r={...e};return r[a]=await yi(r[a],i,`${n}/${ki(a)}`,s),r}var _t=class extends Error{status=400;code;data;constructor(t,n,s={}){super(n),this.name="TransitRefusal",this.code=t,this.data=s}},Y_=6e4,X_=1e3;function _o(e){return/^t[1-9][0-9]{0,5}$/.test(e)?Number(e.slice(1)):0}var ba=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(()=>{})},Y_),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 i of s.keys){let r=Mt(i.key);a.set(i.id,{privateKey:r,publicKey:this.keys.get(i.id)?.publicKey??await Cp(r)})}this.keys=a,this.order=s.keys.map(i=>i.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(_o),...[...this.retired].map(_o))}async key(t){let n=this.now();for(;_o(t)>this.newest()&&this.heldFrom<n;){let i=this.fetchedAt+X_-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let s=this.keys.get(t),a=this.current();if(this.retired.has(t))throw new _t("encryption_key_retired",`the request is sealed to ${t}, retired: fetch the project's keys again`,{current:a});if(s===void 0)throw new _t("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 _t("encryption_required",`this route carries encrypted fields: the request names its key in ${bt}`,{field:bt,current:this.current()});let n;try{n=vo(t.header).kid}catch{throw new _t("encryption_unopenable",`${bt} is not one`,{field:bt})}let s=await this.key(n),a;try{a=vi(this.projectId,t.method,t.path,t.params??[])}catch{throw new _t("encryption_unopenable","the request's path holds a value no key is sealed for",{field:bt})}try{return new Si(n,await Op(t.header,s.privateKey,s.publicKey,a))}catch(i){throw i instanceof Ae?new _t("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:bt}):i}}},Si=class{kid;key;constructor(t,n){this.kid=t,this.key=n}async open(t,n,s){return vs(t,n,s,async(a,i)=>{if(!ya(i))throw new _t("encryption_required",`${a} is an encrypted field: it came plain`,{field:a});try{return await _i(this.key,a,i)}catch{throw new _t("encryption_unopenable",`${a} does not open: changed, moved from another field, or another request's`,{field:a})}})}async seal(t,n){return vs(t,"/response",n,(s,a)=>fa(this.key,s,a))}sealField(t,n){return fa(this.key,t,n)}};var Z_=/^pb_[a-z0-9]+_s/;function $i(e){if(wp())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"||!Z_.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=so(Hr({baseUrl:e.url,credentials:{secretKey:e.secretKey},fetch:e.fetch,solveProofOfWork:e.solveProofOfWork??!1}),e.retry??ui),n=ia.client(t);return{ai:oi.client(t),analytics:Zs.client(t),auth:Qs.client(t),cache:li.client(t),calls:di.client(t),fields:new ca({fetch:async s=>(await n.getFieldKeys({signal:s})).data}),flags:ea.client(t),machines:ta.client(t),messaging:pi.client(t),notify:na.client(t),purchases:sa.client(t),realtime:aa.client(t),secrets:n,storage:ra.client(t),stores:oa.client(t),transit:new ba({fetch:async s=>(await n.getTransitKeys({signal:s})).data}),transport:t,url:new URL(e.url).origin}}var FD=1024*1024;var HD=8*1024;var tx=16*1024,nx=10*6e4;var t0=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,n0=/^(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 ko(e){return!t0.test(e)||n0.test(e)||/_PROXY$/i.test(e)}var s0=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function So(e){return s0.test(e)}import"node:os";import{join as o0,resolve as l0}from"node:path";var Ux=10080*60*1e3,Lp="# >>> palbase (palbase env:pull writes this block; edit outside it)",$o="# <<< palbase";async function wa(e,t){let n=await ao(e.studio,t.env_ref),{keys:s}=await e.studio.get(`/environments/${x("the environment's ref",t.env_ref)}/keys`),a=s.find(i=>i.id===n.id);return a&&!a.revoked_at?n:ao(e.studio,t.env_ref,!0)}async function Pi(e,t){return{...await Ao(e,t),key:await wa(e,t)}}async function Ao(e,t){let n=await e.studio.get(`/environments/${t.env_ref}`);return{url:st(e.cloud,t.env_ref),projectId:n.platform_id}}function Ai(e){let t=e.flags.secrets??"development";if(t!=="development"&&t!=="production")throw m("--secrets is development or production");return t}function Ri(e,t){return t==="production"?`the app reads ${e.project_name} \u203A ${e.env_name}'s production secrets here`:void 0}var Ti={type:"string",value:"set",description:"the project's secrets the app reads at boot: development (default) or production"},Np={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:Ti},scope:"environment",async run(e){let t=await b(e),n=Ai(e);(t.env_slug===Be||n==="production")&&await v(e,t,`write a key of ${t.env_slug===Be?"the production environment":`${t.env_slug}`} into a file on this computer`,Ri(t,n));let s=await Pi(e,t),a=await _e(e.studio,t.env_ref,"GET",`/secrets/${n}`).then(y=>(y.body.secrets??y.body.items??[]).map(w=>w.name).filter(w=>typeof w=="string"&&!ko(w)).sort(),()=>[]),i=l0(e.io.cwd,e.flags.file??".env.local"),r=[Lp,`# ${Po(N(t))} \u2014 ${new Date(e.io.now()).toISOString()}`,`# PALBASE_SECRET_KEY is your own: ${Po(s.key.label)}, good until ${Po(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(y=>`# ${y}=`)]:[],$o].join(`
|
|
23
23
|
`),o="";try{if((await i0(i)).isSymbolicLink())throw new f("symlink",`${i} is a link: env:pull writes the key into a file of its own`,{hint:"remove the link, or pass --file <path>"});o=await Dp(i,"utf8")}catch(y){if(y.code!=="ENOENT")throw y}let l=o.indexOf(Lp),d=o.indexOf($o),p=l>=0&&d>l?`${o.slice(0,l)}${r}${o.slice(d+$o.length)}`:`${o}${o===""||o.endsWith(`
|
|
24
24
|
`)?"":`
|
|
25
25
|
`}${r}
|
|
@@ -29,18 +29,18 @@ var Hw=Object.defineProperty;var Ye=(e,t)=>{for(var n in t)Hw(e,n,{get:t[n],enum
|
|
|
29
29
|
/${i}
|
|
30
30
|
`),"added"}var qp={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:Ti},scope:"environment",async run(e){let t=await b(e),n=Ai(e);(t.env_slug===Be||n==="production")&&await v(e,t,`run ${e.args[0]} with a key of ${t.env_slug}`,Ri(t,n));let s=await Pi(e,t);e.out.note(`${N(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 f("not_found",`${e.args[0]}: no such program`);return a.code}};var p0=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,Kp=20;async function u0(e,t,n,s){if(n.length===0)return{};let a=n.map(r=>({email:`${r.toLowerCase()}.${s}@test.invalid`,password:Gp(18).toString("base64url")})),i=await h(e,t,"POST","/admin/test-users",{users:a,with_tokens:!0},j()).catch(r=>{throw r instanceof E&&r.code==="token_out_of_scope"&&Jt(e.io)?new f("token_out_of_scope",`PALBASE_TOKEN, an environment's token, may not make test users: its scopes do not name auth:test-users (${r.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)"}):r});if(i.users.length!==n.length)throw new f("unexpected_answer",`auth made ${i.users.length} test users of the ${n.length} asked for`);return Object.fromEntries(n.map((r,o)=>{let l=i.users[o];return[r,{id:l.user_id,email:l.email??a[o].email,password:a[o].password,...l.access_token?{accessToken:l.access_token}:{}}]}))}async function c0(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(i){i.status!==404&&s.push(a.id)}return s}async function h0(e,t,n){if(e.out.note(`${t}'s test command, as the platform holds it: ${m0(n)}`),e.global.yes)return;if(!e.interactive)throw new f("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 f("cancelled","nothing was run")}function m0(e){return A(e).replace(/\p{Cf}/gu,t=>`\\u${t.codePointAt(0).toString(16).padStart(4,"0")}`)}function Ro(e){let t=[...new Set(oe(e)??[])];for(let s of t)if(!p0.test(s))throw m(`${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 m(`${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>Kp)throw m(`--users names ${t.length}; a run makes ${Kp} at most`);return t}var Up={SIGHUP:1,SIGINT:2,SIGTERM:15};function g0(){let e,t=Object.keys(Up).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 Bp={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:Ti},scope:"environment",async run(e){let t=Ro(e.flags.users),n=e.flags["base-url"];if(n!==void 0&&!/^https?:\/\/[^\s/]+/.test(n))throw m(`--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 m("which tests? give their command after --, or --machine <name> to run its own","palbase test -- bun test");let a=await b(e),i=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??[]),i===void 0){if(!w.test_command)throw m(`the machine ${s} runs no tests`,`give their command after --, or set it: palbase machines:update ${s} --test-command "bun test"`);await h0(e,s,w.test_command),i={cmd:"sh",args:["-c",w.test_command]}}}let r=i,o=Jt(e.io);if(o&&e.flags.secrets!==void 0)throw m("--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=Ai(e);o?(a.env_slug===Be&&t.length>0&&await v(e,a,`make ${t.length} test user(s) there for ${r.cmd}, deleted when it ends`),e.out.note(`PALBASE_TOKEN is an environment's token: no key is made, and ${r.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===Be||l==="production")&&await v(e,a,`run ${r.cmd} with a key of ${a.env_slug}${t.length?` and ${t.length} test user(s) made there`:""}`,Ri(a,l));let d=o?{...await Ao(e,a),key:void 0}:await Pi(e,a),p=Gp(4).toString("hex"),u=t.length>0?g0():void 0,g=0;try{let w=await u0(e,a,t,p);t.length>0&&e.out.note(`${N(a)}: test users ${t.join(", ")} made for this run (${p})`);try{if(u?.got()===void 0){let _=await e.io.run(r.cmd,r.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 f("not_found",`${r.cmd}: no such program`);g=_.code}}finally{if(t.length>0){let _=await c0(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 y=u?.got();return y===void 0?g:128+Up[y]}};var zp={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 b(e),{body:n}=await Ke(e,t,"/admin/auth-settings");e.out.result(n,()=>gs(e,n))}},Wp={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 b(e),n=cn(e.args),{body:s,etag:a}=await Ke(e,t,"/admin/auth-settings"),i=hn(s,n),r=Vt(s,i);if(r.length===0)return Fe(e,"the auth settings",s);await v(e,t,`set the auth settings ${r.join(", ")}`);let o=await h(e,t,"PUT","/admin/auth-settings",Object.fromEntries(r.map(l=>[l,i[l]])),je(a));e.out.result({settings:o,changed:r},()=>{for(let l of r)e.out.line(`${l}: ${Oe(s[l])} \u2192 ${Oe(o[l])}`)})}},_s=["google","apple","github","microsoft"],f0={google:"web_client_id",apple:"services_id",microsoft:"application_id",github:"oauth_client_id"},y0=new Set(["organizations","consumers","common"]),Fp={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 b(e),[n,s]=await Promise.all([h(e,t,"GET","/admin/providers"),h(e,t,"GET","/admin/social-auth")]),a=[...n.providers.map(i=>({provider:i.id,on:i.enabled,detail:i.settings?`codes by ${i.settings.sender??"sms"}, ${i.settings.otp_ttl_seconds}s, ${i.settings.otp_max_attempts} tries, sign-up ${i.settings.allow_signups?"on":"off"}`:"",secrets:""})),..._s.map(i=>{let r=s.providers[i]??{enabled:!1,browser_clients:[],native_clients:[]},o=[...r.browser_clients.map(l=>`${l.key} (${l.platform})`),...r.native_clients.map(l=>`${l.key} (${l.platform}, native)`)];return{provider:i,on:r.enabled,detail:o.length===0?"no client":o.join(", "),secrets:s.credentials.filter(l=>l.provider===i).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:i=>i.provider},{header:"on",value:i=>i.on?"yes":"no"},{header:"clients / settings",value:i=>i.detail},{header:"secrets",value:i=>i.secrets}]))}},Jp={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:{...pa,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 b(e);if(t==="email")throw new f("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 b0(e,n,e.args.slice(1));if(!_s.includes(t))throw m(`no provider ${JSON.stringify(t)}`,`the providers: email, phone, ${_s.join(", ")}`);if(e.args.length>1)throw m(`${t} takes flags, not settings: palbase help auth:providers:set`);await v0(e,n,t)}};async function b0(e,t,n){let s=fs(e),a=cn(n);if(s===void 0&&a.length===0)throw m("nothing to change: --enable, --disable or setting=value","palbase help auth:providers:set");let i=await h(e,t,"GET","/admin/providers/phone/settings"),r=hn(i,a),o=Vt(i,r);if(s===void 0&&o.length===0)return Fe(e,"the phone settings",i);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",r):i,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}: ${Oe(i[p])} \u2192 ${Oe(l[p])}`)})}function w0(e){if(y0.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 m("--directory is a tenant id, organizations, consumers or common")}async function v0(e,t,n){let s=e.flags,a=fs(e),i=await Ke(e,t,"/admin/social-auth"),r=i.etag,o=i.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 m("Apple's signing key goes with --team-id and --key-id");u=await Me(e,n==="apple"?"Apple's .p8 signing key":`${n}'s client secret`),d.push(`keep its secret as ${p}`)}let g=["client","client-id","return-uri","application","variant","directory","credential"].filter(P=>s[P]!==void 0);if(s["clients-file"]!==void 0){if(g.length>0)throw m(`--clients-file and --${g[0]} are one or the other`);let P=me(await ke(e,s["clients-file"],"the clients"),"the clients file");if(typeof P!="object"||P===null||P.browser_clients===void 0&&P.native_clients===void 0)throw m('the clients file is {"browser_clients": [\u2026], "native_clients": [\u2026]}');l.browser_clients=P.browser_clients??o.browser_clients,l.native_clients=P.native_clients??o.native_clients,d.push(`set its clients from ${s["clients-file"]}`)}else if(g.length>0||u!==void 0){let P=s.client??"web",S=[...o.browser_clients],$=S.findIndex(T=>T.key===P),R=u!==void 0&&g.every(T=>T==="credential");if($>=0||!R){let T=$>=0?{...S[$]}:{key:P,enabled:!0,application_key:"app",platform:"web",variant:"release",return_uris:[]},D=f0[n];if(s["client-id"]!==void 0&&(T[D]=s["client-id"]),!T[D])throw m(`the ${n} client ${P} is new: give it --client-id`);if(s["return-uri"]!==void 0&&(T.return_uris=s["return-uri"]),s.application!==void 0&&(T.application_key=s.application),s.variant!==void 0&&(T.variant=s.variant),n==="microsoft")T.directory=s.directory!==void 0?w0(s.directory):T.directory??{mode:"common"};else if(s.directory!==void 0)throw m("--directory is a Microsoft client's");(u!==void 0||s.credential!==void 0||!T.credential_ref)&&(T.credential_ref=p),S[$>=0?$:S.length]=T,l.browser_clients=S,d.push(`${$>=0?"change":"add"} its browser client ${P}`)}}if(a!==void 0&&(l.enabled=a,d.push(a?"turn it on":"turn it off")),d.length===0)throw m("nothing to change: give a flag","palbase help auth:providers:set");await v(e,t,`${n} sign-in: ${d.join(", ")}`);let y=i.body;if(u!==void 0){let P=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};r=(await qe(e,t,"PUT",`/admin/social-auth/credentials/${k(p)}`,P,je(r))).etag??r}Object.keys(l).length>0?y=await h(e,t,"PATCH",`/admin/social-auth/providers/${k(n)}`,l,je(r)):y=await h(e,t,"GET","/admin/social-auth");let w=y.providers[n],_=y.credentials.filter(P=>P.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 P of _)e.out.line(` secret ${P.key}: ${P.configured?"set":"not set"}`)})}var Vp={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 b(e),{body:s,etag:a}=await Ke(e,n,"/admin/social-auth");if(!s.credentials.some(i=>i.key===t))throw m(`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,je(a)),e.out.result({deleted:t},()=>e.out.line(`Deleted the provider secret ${t}.`))}},Hp={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 b(e);if(t==="email")throw new f("always_on","email sign-in cannot be turned off");if(t==="phone"){await v(e,n,"turn phone sign-in off");let i=await h(e,n,"POST","/admin/providers/phone",{enabled:!1});e.out.result(i,()=>e.out.line("phone sign-in is off."));return}if(!_s.includes(t))throw m(`no provider ${JSON.stringify(t)}`,`the providers: phone, ${_s.join(", ")}`);let{etag:s}=await Ke(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},je(s));e.out.result({provider:t,...a.providers[t]},()=>e.out.line(`${t} sign-in is off; its clients and secrets stay.`))}},Yp={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 b(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}])})}},Xp={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 b(e),n=e.args[0],{roles:s}=await h(e,t,"GET","/admin/roles"),a=s.find(p=>p.name===n),i=oe(e.flags.permissions),r=mn(e.flags.default,"default");if(a&&i===void 0&&e.flags.description===void 0&&r===void 0)throw m("nothing to change: give a flag","palbase help auth:roles:set");let o={permissions:i??a?.permissions??[],description:e.flags.description??a?.description??"",is_default:r??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":""}.`))}},Zp={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 b(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}.`))}},Qp={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)"}},eu={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 b(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"}])})}},tu={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:{...Qp,disable:{type:"boolean",description:"register it turned off"}},scope:"environment",async run(e){let t=await b(e);if(e.flags.event===void 0||e.flags.url===void 0)throw m("a hook needs --event and --url");let n=uo({event:e.flags.event,url:e.flags.url,failure_mode:e.flags["failure-mode"],timeout_ms:se(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,j());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}`)})}},nu={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:{...Qp,...pa},scope:"environment",async run(e){let t=await b(e),{hooks:n}=await h(e,t,"GET","/admin/hooks"),s=n.find(o=>o.id===e.args[0]);if(!s)throw new f("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:se(e.flags.timeout,"timeout")??s.timeout_ms,enabled:fs(e)??s.enabled},i=Vt(_0(s),a);if(i.length===0)throw m("nothing to change: give a flag","palbase help auth:hooks:update");await v(e,t,`change the hook ${s.id}: ${i.join(", ")}`);let r=await h(e,t,"PUT",`/admin/hooks/${k(s.id)}`,a);e.out.result(r,()=>e.out.line(`${r.id}: ${r.event} \u2192 ${r.url}, ${r.failure_mode} on failure, ${r.timeout_ms} ms, ${r.enabled?"on":"off"}.`))}};function _0(e){return{event:e.event,url:e.url,failure_mode:e.failure_mode,timeout_ms:e.timeout_ms,enabled:e.enabled}}var su={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 b(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]}.`))}},au={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 b(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(", ")}])})}},iu={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 b(e),n=uo({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:oe(e.flags.grant),scopes:oe(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,j());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}`)})}},ru={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 b(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 f("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 k0(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 ou={name:"auth",async read(e,t){let[n,s,a,i,r,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 _s){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 i.roles)l[`roles.${p.name}`]={description:p.description,is_default:p.is_default,permissions:[...p.permissions].sort()};for(let p of r.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}`]=k0(p);return l},async copy(e,t,n,s){await S0(e,t,fe(n,"settings."),s);for(let i of fe(n,"phone."))i.name==="enabled"&&await Q(s,`turn phone sign-in ${i.from?"on":"off"}`,async()=>{await h(e,t,"POST","/admin/providers/phone",{enabled:i.from===!0})}),i.name==="settings"&&i.from!==void 0&&await Q(s,"set the phone code settings",async()=>{await h(e,t,"PUT","/admin/providers/phone/settings",i.from)});await $0(e,t,fe(n,"social."),fe(n,"secrets."),s);let a=fe(n,"roles.").sort((i,r)=>+(i.from?.is_default===!0)-+(r.from?.is_default===!0));for(let i of a)i.from===void 0?await Q(s,`delete the role ${i.name}`,async()=>{await h(e,t,"DELETE",`/admin/roles/${k(i.name)}`)}):await Q(s,`set the role ${i.name}`,async()=>{await h(e,t,"PUT",`/admin/roles/${k(i.name)}`,i.from)});await P0(e,t,fe(n,"hooks."),s),await A0(e,t,fe(n,"oauth_clients."),s)}};async function S0(e,t,n,s){let a=n.filter(r=>r.from!==void 0);for(let r of n.filter(o=>o.from===void 0))s.left(`auth settings ${r.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:i}=await Ke(e,t,"/admin/auth-settings");await Q(s,`set the auth settings ${a.map(r=>r.name).join(", ")}`,async()=>{await h(e,t,"PUT","/admin/auth-settings",Object.fromEntries(a.map(r=>[r.name,r.from])),je(i))})}async function $0(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 i=await Ke(e,t,"/admin/social-auth"),r=i.etag,o=new Set(i.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 Q(a,`set ${l.name} sign-in (${d.enabled?"on":"off"}, ${d.browser_clients.length+d.native_clients.length} client(s))`,async()=>{r=(await qe(e,t,"PATCH",`/admin/social-auth/providers/${k(l.name)}`,d,je(r))).etag??r})}}async function P0(e,t,n,s){if(n.length===0)return;let{hooks:a}=await h(e,t,"GET","/admin/hooks");for(let i of n){let r=i.name.indexOf(" "),o=i.name.slice(0,r),l=i.name.slice(r+1),d=a.find(p=>p.event===o&&p.url===l);if(i.from===void 0)d&&await Q(s,`delete the hook ${o} \u2192 ${l}`,async()=>{await h(e,t,"DELETE",`/admin/hooks/${k(d.id)}`)});else if(d)await Q(s,`change the hook ${o} \u2192 ${l}`,async()=>{await h(e,t,"PUT",`/admin/hooks/${k(d.id)}`,{event:o,url:l,...i.from})});else{let p;await Q(s,`register the hook ${o} \u2192 ${l}`,async()=>{p=(await h(e,t,"POST","/admin/hooks",{event:o,url:l,...i.from},j())).secret}),p&&s.shown(`the hook ${o} \u2192 ${l} signs with`,p)}}}async function A0(e,t,n,s){if(n.length===0)return;let{clients:a}=await h(e,t,"GET","/admin/oauth-clients");for(let i of n){let r=a.find(l=>l.client_name===i.name),o=i.from;if(o===void 0)r&&await Q(s,`delete the OAuth client ${i.name}`,async()=>{await h(e,t,"DELETE",`/admin/oauth-clients/${k(r.id)}`)});else if(r)if(!We(o.is_public,r.is_public)||o.client_id!==void 0&&o.client_id!==r.client_id)s.left(`OAuth client ${i.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 Q(s,`change the OAuth client ${i.name}`,async()=>{await h(e,t,"PATCH",`/admin/oauth-clients/${k(r.id)}`,p)})}else{let l;await Q(s,`register the OAuth client ${i.name}`,async()=>{l=await h(e,t,"POST","/admin/oauth-clients",{client_name:i.name,...o},j())}),l?.client_secret&&s.shown(`the OAuth client ${i.name} (${l.client_id}) has the secret`,l.client_secret)}}}var lu=["bool","number","string","object"];async function yn(e,t){return(await h(e,t,"GET","/flags/templates/capabilities")).publish_enabled}async function fn(e,t,n){let s=await Ke(e,t,"/flags/templates/draft");if(s.body.draft||!n)return{draft:s.body.draft,etag:s.etag};let a=await Ke(e,t,"/flags/templates/active"),i=await qe(e,t,"POST","/flags/templates/draft",{},je(a.etag));return{draft:i.body.draft,etag:i.etag}}function du(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 R0(e){return typeof e=="boolean"?"bool":typeof e=="number"?"number":typeof e=="string"?"string":"object"}function pu(e,t){switch(t){case"bool":if(e==="true"||e==="false")return e==="true";throw m(`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 m(`a number flag's value is a number, not ${JSON.stringify(e)}`);return n}case"string":{let n=jt(e);return typeof n=="string"?n:e}default:{let n=jt(e);if(typeof n!="object"||n===null)throw m(`an object flag's value is a JSON object or list, not ${JSON.stringify(e)}`);return n}}}function T0(e,t){let n=e.lastIndexOf("=>");if(n<=0)throw m(`a condition is "<expression> => <value>", not ${JSON.stringify(e)}`,`--condition "client.platform == 'ios' => true"`);return{when:e.slice(0,n).trim(),value:pu(e.slice(n+2).trim(),t)}}var uu={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 b(e),n=await yn(e,t),s,a,i;if(n){let[r,o]=await Promise.all([h(e,t,"GET","/flags/templates/active"),fn(e,t,!1)]);s=Object.entries(r.definitions).map(([l,d])=>({key:l,...d})),a=r.version,i=o.draft}else s=await h(e,t,"GET","/flags/system");s.sort((r,o)=>r.key<o.key?-1:1),e.out.result({publishing:n,...a?{version:a}:{},flags:s,...i?{draft:{revision:i.revision,base_version:i.base_version}}:{}},()=>{n&&e.out.line(`Version ${a} is live${i?`; a draft (from ${i.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:r=>r.key},{header:"type",value:r=>r.value_type},{header:"value",value:r=>JSON.stringify(r.value)},{header:"targeting",value:r=>r.conditions?.length?`${r.conditions.length} condition(s)`:""},{header:"description",value:r=>r.description??""}])})}},cu={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 b(e),[n,s]=e.args,a=e.flags.type;if(a!==void 0&&!lu.includes(a))throw m(`--type is one of ${lu.join(", ")}`);if(e.flags.condition!==void 0&&e.flags["clear-conditions"]===!0)throw m("--condition and --clear-conditions are one or the other");let i=await yn(e,t),r,o;i?(o=await fn(e,t,!1),r=o.draft?.definitions[n]??(await h(e,t,"GET","/flags/templates/active")).definitions[n]):r=(await h(e,t,"GET","/flags/system")).find(u=>u.key===n);let l=a??r?.value_type??R0(jt(s)),d=e.flags["clear-conditions"]===!0?[]:e.flags.condition!==void 0?e.flags.condition.map(u=>T0(u,l)):r?.value_type===l?r.conditions??[]:[],p=du({value_type:l,value:pu(s,l),description:e.flags.description??r?.description,variants:oe(e.flags.variants)??(r?.value_type===l?r.variants:void 0),conditions:d});if(await v(e,t,i?`put ${n} = ${Oe(p.value)} into the flags draft`:`set the flag ${n} = ${Oe(p.value)}, live at once`),i){o?.draft||(o=await fn(e,t,!0));let u=await qe(e,t,"PUT",`/flags/templates/draft/parameters/${k(n)}`,p,je(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.`))}}},hu={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 b(e),n=e.args[0],s=await yn(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 fn(e,t,!0);await h(e,t,"DELETE",`/flags/templates/draft/parameters/${k(n)}`,void 0,je(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 To(){return new f("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 E0(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 Eo(e,t,n,s){return h(e,t,"POST","/flags/templates/publish",s===""?{}:{note:s},{...je(n),...j()})}var mu={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 b(e);if(!await yn(e,t))throw To();if(!(await fn(e,t,!1)).draft)throw new f("no_draft","there is no draft to publish",{hint:"palbase flags:set puts a change into one"});let s=await Ke(e,t,"/flags/templates/draft/review");if(e.out.json||E0(e,s.body),!s.body.can_publish)throw new f("cannot_publish",`the draft cannot be published: ${s.body.issues.map(i=>i.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 Eo(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}.`))}},gu={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 b(e);if(await yn(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.`))}},fu={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 b(e);if(!await yn(e,t))throw To();let n=Number(e.flags.limit??20);if(!Number.isInteger(n)||n<=0)throw m("--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}]))}},yu={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 b(e),n=e.args[0];if(!await yn(e,t))throw To();if((await fn(e,t,!1)).draft)throw new f("draft_in_progress","a draft is in progress: publish it (flags:publish) before a rollback");let s=await Ke(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)}`,{},je(s.etag)),i=await Eo(e,t,a.etag,e.flags.note??`rollback to ${n}`);e.out.result(i,()=>e.out.line(i.unchanged?`Version ${n} is what is live already.`:`Version ${n} is live again, as version ${i.template.version}.`))}},bu={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}`]=du(a);return s},async copy(e,t,n,s){let a=fe(n,"flags.");if(a.length===0)return;if(!await yn(e,t)){for(let r of a)r.from===void 0?await Q(s,`delete the flag ${r.name}`,async()=>{await h(e,t,"DELETE",`/flags/system/${k(r.name)}`)}):await Q(s,`set the flag ${r.name}`,async()=>{await h(e,t,"PUT",`/flags/system/${k(r.name)}`,r.from)});return}if((await fn(e,t,!1)).draft){s.left("flags: the target has a draft in progress \u2014 publish it (flags:publish) and copy again");return}let i=(await fn(e,t,!0)).etag;for(let r of a)await Q(s,`${r.from===void 0?"take":"put"} the flag ${r.name} ${r.from===void 0?"out of":"into"} the draft`,async()=>{let o=`/flags/templates/draft/parameters/${k(r.name)}`;i=(r.from===void 0?await qe(e,t,"DELETE",o,void 0,je(i)):await qe(e,t,"PUT",o,r.from,je(i))).etag??i});await Q(s,"publish the flags draft",async()=>{await Eo(e,t,i,"config:copy")})}};var wu=["email","sms","verify","whatsapp","push"],Co=["email","sms","whatsapp"],vu={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 b(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"}])})}},_u={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"},...pa},scope:"environment",async run(e){let[t,n]=e.args;if(!wu.includes(t))throw m(`the channels: ${wu.join(", ")}`);let s=await b(e),a=me(await Me(e,`${n}'s credentials (JSON)`),"the credentials");if(typeof a!="object"||a===null||Array.isArray(a))throw m("the credentials are a JSON object");let i=fs(e),r=se(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,...i!==void 0?{active:i}:{},...r!==void 0?{priority:r}:{}},j());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.`))}},ku={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 b(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,j()),e.out.result({removed:{channel:t,provider:n}},()=>e.out.line(`${t} no longer goes through ${n}.`))}},Oo={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 va(e){let t=e.flags.channel??"email";if(!Co.includes(t))throw m(`--channel is one of ${Co.join(", ")}`);return t}function Mo(e,t){let n=e.flags.locale;if(n===void 0)throw m("which locale? pass --locale <locale>");return`/notify/templates/${va(e)}/${k(t)}/${k(n)}`}function C0(e,t){if(e==="sms"){let s=j0(t);return typeof s=="object"&&s!==null&&typeof s.body=="string"?{body:s.body}:{body:t.replace(/\n$/,"")}}let n=me(t,`the ${e} template`);if(e==="email"){for(let s of["subject","html_body","text_body"])if(typeof n[s]!="string")throw m(`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 m('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 j0(e){try{return JSON.parse(e)}catch{return e}}var Su={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 b(e),n=e.flags.channel===void 0?Co:[va(e)],s=await Promise.all(n.map(i=>h(e,t,"GET",`/notify/templates/${i}`))),a=n.flatMap((i,r)=>s[r].templates.map(o=>({channel:i,...o})));e.out.result({templates:a},()=>e.out.table(a,[{header:"channel",value:i=>i.channel},{header:"slug",value:i=>i.slug},{header:"locale",value:i=>i.locale},{header:"yours",value:i=>"customized"in i?i.customized?"yes":"default":"yes"},{header:"subject / text / template",value:i=>"subject"in i?i.subject:"body"in i?i.body.split(`
|
|
31
31
|
`)[0].slice(0,60):`${i.name} (${i.language})`}]))}},$u={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:Oo,scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",Mo(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(`
|
|
32
|
-
`))e.out.line(a)}})}},Pu={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:{...Oo,file:{type:"string",value:"path",description:"the template (default: stdin)"}},scope:"environment",async run(e){let t=await b(e),n=va(e),s=Mo(e,e.args[0]),a=C0(n,await ke(e,e.flags.file,"the template"));await v(e,t,`override the ${n} template ${e.args[0]} (${e.flags.locale})`);let i=await h(e,t,"PUT",s,a,j());e.out.result(i,()=>e.out.line(`The ${n} template ${e.args[0]} (${e.flags.locale}) is yours now${typeof i.subject=="string"?`: "${i.subject}"`:""}.`))}},Au={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:Oo,scope:"environment",async run(e){let t=await b(e),n=Mo(e,e.args[0]);await v(e,t,`remove the ${va(e)} template ${e.args[0]} (${e.flags.locale})`),await h(e,t,"DELETE",n,void 0,j()),e.out.result({deleted:{channel:va(e),slug:e.args[0],locale:e.flags.locale}},()=>e.out.line(`Removed the override of ${e.args[0]} (${e.flags.locale}).`))}};async function jo(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 Ru={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 b(e),n=await jo(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"}])})}},Tu={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 b(e),n=mn(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}:{}},j());e.out.result(s,()=>e.out.line(`Made the topic ${s.name}${s.self_subscribe?", followed from the app":""}.`))}},Eu={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 b(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,j()),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the topic ${e.args[0]}.`))}},Cu={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 b(e),{body:n}=await Ke(e,t,"/notify/settings");e.out.result(n,()=>gs(e,n))}},ju={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 b(e),n=cn(e.args),{body:s,etag:a}=await Ke(e,t,"/notify/settings"),i=hn(s,n),r=Vt(s,i);if(r.length===0)return Fe(e,"the message settings",s);await v(e,t,`set the message settings ${r.join(", ")}`);let o=await h(e,t,"PUT","/notify/settings",i,{...je(a),...j()});e.out.result({settings:o,changed:r},()=>{for(let l of r)e.out.line(`${l}: ${Oe(s[l])} \u2192 ${Oe(o[l])}`)})}},O0=new Set(["sms_countries","sms_blocked_countries"]);function M0(e){return{...e,sms_countries:e.sms_countries??[],sms_blocked_countries:e.sms_blocked_countries??[],mx_check:e.mx_check??!1}}var Ou={name:"notify",async read(e,t){let[n,s,a,i,r,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"),jo(e,t)]),l={};for(let[u,g]of Object.entries(M0(n)))l[`settings.${u}`]=g;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 i.templates.filter(g=>g.customized))l[`templates.sms/${u.slug}/${u.locale}`]={body:u.body};for(let u of r.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=fe(n,"settings.");if(a.length>0){let{body:o,etag:l}=await Ke(e,t,"/notify/settings"),d={...o};for(let p of a)d[p.name]=O0.has(p.name)&&Array.isArray(p.from)&&p.from.length===0?null:p.from;await Q(s,`set the message settings ${a.map(p=>p.name).join(", ")}`,async()=>{await h(e,t,"PUT","/notify/settings",d,{...je(l),...j()})})}for(let o of fe(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 fe(n,"templates.")){let l=`/notify/templates/${o.name.split("/").map(k).join("/")}`;o.from===void 0?await Q(s,`remove the template override ${o.name}`,async()=>{await h(e,t,"DELETE",l,void 0,j())}):await Q(s,`override the template ${o.name}`,async()=>{await h(e,t,"PUT",l,o.from,j())})}let i=fe(n,"topics."),r=i.some(o=>o.from===void 0)?new Map((await jo(e,t)).map(o=>[o.name,o.subscribers])):new Map;for(let o of i){let l=`/notify/topics/${k(o.name)}`,d=o.from?.self_subscribe;if(o.from===void 0){let p=r.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 Q(s,`delete the topic ${o.name}`,async()=>{await h(e,t,"DELETE",l,void 0,j())})}else o.change==="only_in_from"?await Q(s,`make the topic ${o.name}`,async()=>{await h(e,t,"POST","/notify/topics",{name:o.name,self_subscribe:d},j())}):await Q(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},j())})}}};var ks=["max_connections","max_events_per_second","max_joins_per_second","max_channels_per_connection"];function I0(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 Io(e){return Object.fromEntries(ks.map(t=>[t,e[t]??null]))}var Mu={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 b(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=>I0(s)}])})}},Iu={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 b(e),n=me(await ke(e,e.flags.file,"the channel declaration"),"the channel declaration"),s=Array.isArray(n)?n:n.channels;if(!Array.isArray(s))throw m('the declaration is {"channels": [\u2026]} or a list of channels');let a=await h(e,t,"GET","/realtime/channels");if(We(a.channels,s))return Fe(e,"the channel declaration",a);await v(e,t,`declare ${s.length} channel pattern(s) (now ${a.channels.length})`);let i=await h(e,t,"PUT","/realtime/channels",{channels:s});e.out.result(i,()=>e.out.line(i.channels.length===0?"No channel is declared now.":`Declared ${i.channels.length} channel pattern(s): ${i.channels.map(r=>r.pattern).join(", ")}.`))}},Lu={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 b(e),n=await h(e,t,"GET","/realtime/limits");e.out.result(n,()=>{let s=n.platform??{},a=Math.max(...ks.map(i=>i.length));for(let i of ks)e.out.line(`${i.padEnd(a)} ${n[i]===void 0||n[i]===null?"the platform's":Oe(n[i])}${s[i]!==void 0?` (platform ${s[i]===0?"no ceiling":Oe(s[i])})`:""}`)})}},Du={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: ${ks.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 b(e),n=cn(e.args);for(let o of n)if(o.path.length!==1||!ks.includes(o.path[0]))throw m(`no limit ${JSON.stringify(o.path.join("."))}`,`the limits: ${ks.join(", ")}`);let s=Io(await h(e,t,"GET","/realtime/limits")),a=hn(s,n),i=Vt(s,a);if(i.length===0)return Fe(e,"the realtime limits",s);await v(e,t,`set the realtime limits ${i.join(", ")}`);let r=await h(e,t,"PUT","/realtime/limits",a);e.out.result({limits:r,changed:i},()=>{for(let o of i)e.out.line(`${o}: ${Oe(s[o]??"the platform's")} \u2192 ${Oe(r[o]??"the platform's")}`)})}},xu={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[i,r]of Object.entries(Io(s)))a[`limits.${i}`]=r;return a},async copy(e,t,n,s){let a=n.find(r=>r.key==="channels");a&&await Q(s,"declare the channels",async()=>{await h(e,t,"PUT","/realtime/channels",{channels:a.from??[]})});let i=fe(n,"limits.");if(i.length>0){let r=Io(await h(e,t,"GET","/realtime/limits"));for(let o of i)r[o.name]=o.from??null;await Q(s,`set the realtime limits ${i.map(o=>o.name).join(", ")}`,async()=>{await h(e,t,"PUT","/realtime/limits",r)})}}},Nu={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 b(e),n=await h(e,t,"GET","/analytics/settings");e.out.result(n,()=>gs(e,n))}},qu={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 b(e),n=cn(e.args),s=await h(e,t,"GET","/analytics/settings"),a=hn(s,n),i=Vt(s,a);if(i.length===0)return Fe(e,"the analytics settings",s);await v(e,t,`set the analytics settings ${i.join(", ")}`);let r=await h(e,t,"PUT","/analytics/settings",a);e.out.result({settings:r,changed:i},()=>{for(let o of i)e.out.line(`${o}: ${Oe(s[o])} \u2192 ${Oe(r[o])}`)})}},Ku={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=fe(n,"settings.");if(a.length===0)return;let i=await h(e,t,"GET","/analytics/settings");for(let r of a)r.from!==void 0&&(i[r.name]=r.from);await Q(s,`set the analytics settings ${a.map(r=>r.name).join(", ")}`,async()=>{await h(e,t,"PUT","/analytics/settings",i)})}};var at="/messaging/settings",L0=/^[A-Z][A-Z0-9_]{0,127}$/,Do=["retention_days","push_preview","deleted_user_messages","search_by_meaning","event_text"];function Ss(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?Gu(t):"none: anyone may reach anyone"}}function Gu(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 D0(e,t){let n=[...Do.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,i]of n)e.out.line(`${a.padEnd(s)} ${Ss(a,i)}`)}function Lo(e,t){if(e!==void 0){if(e==="on")return!0;if(e==="off")return!1;throw m(`--${t} is on or off`)}}function x0(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 m("--retention-days is a whole number of days from 1 to 36500, or off (kept for good)");return t}var N0={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 b(e),n=await h(e,t,"GET",at);e.out.result(n,()=>D0(e,n))}},q0={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=x0(e.flags["retention-days"]);n!==void 0&&(t.retention_days=n);let s=Lo(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 m("--deleted-user-messages is keep or delete");t.deleted_user_messages=a}let i=Lo(e.flags["search-by-meaning"],"search-by-meaning");i!==void 0&&(t.search_by_meaning=i);let r=Lo(e.flags["event-text"],"event-text");if(r!==void 0&&(t.event_text=r),Object.keys(t).length===0)throw m("nothing to change","pass --retention-days, --push-preview, --deleted-user-messages, --search-by-meaning or --event-text");let o=await b(e),l=await h(e,o,"GET",at),d=Do.filter(u=>u in t&&!We(l[u],t[u]));if(d.length===0)return Fe(e,"the messaging settings",l);await v(e,o,`set the messaging settings ${d.join(", ")}`);let p=await h(e,o,"PUT",at,Object.fromEntries(d.map(u=>[u,t[u]])));e.out.result({settings:p,changed:d},()=>{for(let u of d)e.out.line(`${u}: ${Ss(u,l[u])} \u2192 ${Ss(u,p[u])}`)})}},Uu={"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 Bu(e){let t=e.flags["secret-to"];if(t!==void 0&&!L0.test(t))throw m(`--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 m("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function zu(e,t,n,s,a){let{hook_secret:i,...r}=n;if(i===void 0){e.out.result({settings:r},()=>e.out.line(`${a}: ${Ss("hook",r.hook)}.`));return}if(s!==void 0){let o=await h(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:i});e.out.result({settings:r,secret_to:{set:s.set,name:s.name,version:o.version}},()=>e.out.line(`${a}: ${Ss("hook",r.hook)}; its signing secret is ${s.name} (${s.set}, v${o.version}) in ${N(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${Ss("hook",r.hook)}.`),e.out.line(`signing secret (shown this once): ${i}`)})}var K0={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 b(e),{hook:n}=await h(e,t,"GET",at);e.out.result({hook:n},()=>e.out.line(n?Gu(n):"No hook: anyone may reach anyone. palbase messaging:hook:set --url <url> sets one."))}},G0={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)"},...Uu},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw m("--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 m("--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 m("--on-error is allow or deny");if(t===void 0&&n===void 0&&s===void 0)throw m("nothing to change","pass --url, --timeout-ms or --on-error");let a=Bu(e),i=await b(e),r=await h(e,i,"GET",at),o=r.hook;if(!o&&t===void 0)throw m("the environment has no hook yet: --url names where it is asked");if(o&&a!==void 0)throw m("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&&We(o,{...o,...l}))return Fe(e,"the hook",r);let u=o?["url","timeout_ms","on_error"].filter(y=>l[y]!==o[y]):[];await v(e,i,o?`change the messaging hook: ${u.join(", ")}`:`set the messaging hook ${l.url}${a?`, its secret kept in ${a.name} (${a.set})`:""}`);let g=await h(e,i,"PUT",at,{hook:l});await zu(e,i,g,a,o?"Changed the hook":"Set the hook")}},U0={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 b(e),n=await h(e,t,"GET",at);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",at,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may reach anyone."))}},B0={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:Uu,scope:"environment",async run(e){let t=Bu(e),n=await b(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",`${at}/hook-secret`);await zu(e,n,s,t,"Made the signing secret anew for the hook")}},Wu={name:"messaging",async read(e,t){let n=await h(e,t,"GET",at),s={};for(let a of Do)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=fe(n,"settings.");a.length>0&&await Q(s,`set the messaging settings ${a.map(l=>l.name).join(", ")}`,async()=>{await h(e,t,"PUT",at,Object.fromEntries(a.map(l=>[l.name,l.from])))});let i=n.find(l=>l.key==="hook");if(!i)return;if(i.from===void 0){await Q(s,`remove the hook ${i.to.url}`,async()=>{await h(e,t,"PUT",at,{hook:null})});return}let r=i.from,o;await Q(s,`${i.change==="differs"?"change":"set"} the hook ${r.url}`,async()=>{o=(await h(e,t,"PUT",at,{hook:r})).hook_secret}),o&&s.shown(`the hook ${r.url} signs with`,o)}},Fu=[N0,q0,K0,G0,U0,B0];var it="/calls/settings",z0=/^[A-Z][A-Z0-9_]{0,127}$/,No=["max_participants","calls_per_hour"];function $s(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?Ju(t):"none: anyone may call anyone (blocks aside)"}}function Ju(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 W0(e,t){let n=[...No.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,i]of n)e.out.line(`${a.padEnd(s)} ${$s(a,i)}`)}function xo(e,t,n,s){if(e===void 0)return;let a=Number(e);if(!/^[0-9]+$/.test(String(e))||a<n||a>s)throw m(`--${t} is a whole number from ${n} to ${s}`);return a}var F0={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 b(e),n=await h(e,t,"GET",it);e.out.result(n,()=>W0(e,n))}},J0={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=xo(e.flags["max-participants"],"max-participants",2,100);n!==void 0&&(t.max_participants=n);let s=xo(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 m("nothing to change","pass --max-participants or --calls-per-hour");let a=await b(e),i=await h(e,a,"GET",it),r=No.filter(l=>l in t&&!We(i[l],t[l]));if(r.length===0)return Fe(e,"the call settings",i);await v(e,a,`set the call settings ${r.join(", ")}`);let o=await h(e,a,"PUT",it,Object.fromEntries(r.map(l=>[l,t[l]])));e.out.result({settings:o,changed:r},()=>{for(let l of r)e.out.line(`${l}: ${$s(l,i[l])} \u2192 ${$s(l,o[l])}`)})}},Vu={"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 Hu(e){let t=e.flags["secret-to"];if(t!==void 0&&!z0.test(t))throw m(`--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 m("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function Yu(e,t,n,s,a){let{hook_secret:i,...r}=n;if(i===void 0){e.out.result({settings:r},()=>e.out.line(`${a}: ${$s("hook",r.hook)}.`));return}if(s!==void 0){let o=await h(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:i});e.out.result({settings:r,secret_to:{set:s.set,name:s.name,version:o.version}},()=>e.out.line(`${a}: ${$s("hook",r.hook)}; its signing secret is ${s.name} (${s.set}, v${o.version}) in ${N(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${$s("hook",r.hook)}.`),e.out.line(`signing secret (shown this once): ${i}`)})}var V0={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 b(e),{hook:n}=await h(e,t,"GET",it);e.out.result({hook:n},()=>e.out.line(n?Ju(n):"No hook: anyone may call anyone (blocks aside). palbase calls:hook:set --url <url> sets one."))}},H0={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)"},...Vu},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw m("--url is where the hook is asked: a URL");let n=xo(e.flags["timeout-ms"],"timeout-ms",100,5e3),s=e.flags["on-error"];if(s!==void 0&&s!=="allow"&&s!=="deny")throw m("--on-error is allow or deny");let a=e.flags.places;if(a!==void 0&&a!=="on"&&a!=="off")throw m("--places is on or off");let i=a===void 0?void 0:a==="on";if(t===void 0&&n===void 0&&s===void 0&&i===void 0)throw m("nothing to change","pass --url, --timeout-ms, --on-error or --places");let r=Hu(e),o=await b(e),l=await h(e,o,"GET",it),d=l.hook;if(!d&&t===void 0)throw m("the environment has no hook yet: --url names where it is asked");if(d&&r!==void 0)throw m("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 g=s??d?.on_error;g!==void 0&&(p.on_error=g);let y=i??d?.places;if(y!==void 0&&(p.places=y),d&&We(d,{...d,...p}))return Fe(e,"the hook",l);let w=d?["url","timeout_ms","on_error","places"].filter(P=>(p[P]??!1)!==(d[P]??!1)):[];await v(e,o,d?`change the calls hook: ${w.join(", ")}`:`set the calls hook ${p.url}${r?`, its secret kept in ${r.name} (${r.set})`:""}`);let _=await h(e,o,"PUT",it,{hook:p});await Yu(e,o,_,r,d?"Changed the hook":"Set the hook")}},Y0={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 b(e),n=await h(e,t,"GET",it);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",it,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may call anyone (blocks aside)."))}},X0={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:Vu,scope:"environment",async run(e){let t=Hu(e),n=await b(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",`${it}/hook-secret`);await Yu(e,n,s,t,"Made the signing secret anew for the hook")}},Xu={name:"calls",async read(e,t){let n=await h(e,t,"GET",it),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=fe(n,"settings.");a.length>0&&await Q(s,`set the call settings ${a.map(l=>l.name).join(", ")}`,async()=>{await h(e,t,"PUT",it,Object.fromEntries(a.map(l=>[l.name,l.from])))});let i=n.find(l=>l.key==="hook");if(!i)return;if(i.from===void 0){await Q(s,`remove the hook ${i.to.url}`,async()=>{await h(e,t,"PUT",it,{hook:null})});return}let r=i.from,o;await Q(s,`${i.change==="differs"?"change":"set"} the hook ${r.url}`,async()=>{o=(await h(e,t,"PUT",it,{hook:r})).hook_secret}),o&&s.shown(`the hook ${r.url} signs with`,o)}},Zu=[F0,J0,V0,H0,Y0,X0];var Z0=/^[a-z][a-z0-9-]{1,62}$/;function Ps(e){if(!Z0.test(e))throw m(`${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 Ko(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 Q0(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 m(`--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 qo(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 ek(e,t,n){try{return await h(e,t,"GET",Ps(n))}catch(s){if(s instanceof E&&s.status===404)return;throw s}}var Qu={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 b(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=>Ko(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(", ")}])})}},ec={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 b(e),n=await h(e,t,"GET",Ps(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 ${Ko(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}`:""}`)})}},tc={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 b(e),n=e.args[0];if(e.flags.public===!0&&e.flags.private===!0)throw m("--public and --private are one or the other");let s=await ek(e,t,n),a=qo(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=Q0(e.flags["max-size"])),e.flags.types!==void 0&&(a.allowed_mime_types=oe(e.flags.types)??[]),e.flags["variants-file"]!==void 0){let r=me(await ke(e,e.flags["variants-file"],"the renditions"),"the renditions file"),o=Array.isArray(r)?r:r.variants;if(!Array.isArray(o))throw m("the renditions file is a JSON list of {name, width, height, fit, format, quality}");a.variants=o}if(s&&We(qo(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 i=await h(e,t,"PUT",Ps(n),a);e.out.result(i,()=>e.out.line(`${s?"Changed":"Made"} the bucket ${i.name}: ${i.public?"public":"private"}, files up to ${Ko(i.file_size_limit)}, ${i.allowed_mime_types.length===0?"any type":i.allowed_mime_types.join(", ")}.`))}},nc={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 b(e),n=Ps(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]}.`))}},sc={name:"storage",async read(e,t){let{buckets:n}=await h(e,t,"GET","/storage/buckets"),s={};for(let a of n){let i=qo(a);s[`buckets.${a.name}`]={...i,allowed_mime_types:[...i.allowed_mime_types].sort()}}return s},async copy(e,t,n,s){for(let a of fe(n,"buckets."))a.from===void 0?await Q(s,`delete the bucket ${a.name}`,async()=>{await h(e,t,"DELETE",Ps(a.name))}):await Q(s,`declare the bucket ${a.name}`,async()=>{await h(e,t,"PUT",Ps(a.name),a.from)})}};var xn=[ou,sc,bu,Ou,xu,Ku,Wu,Xu];function zo(e="<env>"){return new f("not_copied","machines, databases and sites are the project's, each bound to one environment: only settings are compared and copied between environments",{hint:`make one bound to it with palbase machines:create -E ${e} (or databases:create -E ${e}), or move one there with palbase machines:move <name> --to ${e}`})}var ac={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: ${xn.map(e=>e.name).join(",")} (the default)`}};async function ic(e){if(e.global.env!==void 0)throw m("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 m("name both environments: --from <env> --to <env>");let s=await Pe(e.studio),a;if(e.global.project!==void 0)a=un(s,e.global.project);else{let l=await e.state.targetFor(e.io.cwd);if(!l)throw new f("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 i=l=>{let d=a.find(p=>p.slug===l||p.ref===l);if(!d)throw new f("no_such_environment",`the project has no environment ${JSON.stringify(l)}`,{hint:`its environments: ${a.map(p=>p.slug).join(", ")}`});return ie(d)},r=i(t),o=i(n);if(r.env_ref===o.env_ref)throw m("--from and --to name the same environment");return{from:r,to:o}}function rc(e,t){let n=oe(e.flags.only);if(n===void 0)return xn;if(n.some(s=>s==="machines"||s==="databases"||s==="sites"))throw zo(t.env_slug);for(let s of n)if(!xn.some(a=>a.name===s))throw m(`no module ${JSON.stringify(s)}`,`the modules: ${xn.map(a=>a.name).join(", ")}`);return xn.filter(s=>n.includes(s.name))}function tk(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),s=[];for(let a of n){let i=a in e,r=a in t;i&&!r?s.push({key:a,change:"only_in_from",from:e[a]}):!i&&r?s.push({key:a,change:"only_in_to",to:t[a]}):We(e[a],t[a])||s.push({key:a,change:"differs",from:e[a],to:t[a]})}return s}async function Go(e,t,n,s){let a=l=>Promise.all(t.map(d=>d.read(e,l))),[i,r]=await Promise.all([a(n),a(s)]),o=Object.fromEntries(t.map((l,d)=>[l.name,tk(i[d],r[d])]));return{from:n,to:s,modules:o,count:Object.values(o).reduce((l,d)=>l+d.length,0)}}function Uo(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 Ei(e){let t=JSON.stringify(e)??"undefined";return t.length>140?`${t.slice(0,139)}\u2026`:t}function Bo(e,t){let n=t.from.env_slug,s=t.to.env_slug;for(let[i,r]of Object.entries(t.modules))if(r.length!==0){e.out.line(`${i} (${r.length})`);for(let o of r)o.change==="differs"?e.out.line(` ~ ${o.key}: ${n} ${Ei(o.from)} \xB7 ${s} ${Ei(o.to)}`):o.change==="only_in_from"?e.out.line(` - ${o.key}: only in ${n}: ${Ei(o.from)}`):e.out.line(` + ${o.key}: only in ${s}: ${Ei(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 nk={name:"config:diff",summary:"how two environments' module settings differ (auth, storage, flags, notify, realtime, analytics, messaging, calls)",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:ac,scope:"environment",async run(e){let{from:t,to:n}=await ic(e),s=await Go(e,rc(e,n),t,n);return e.out.result(Uo(s),()=>Bo(e,s)),s.count===0?0:1}},sk={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.","Machines, databases and sites are not settings: they are the project's, each bound to one environment (machines:create -E, machines:move --to).","Exit code 0 when the two are the same afterwards, 1 when a difference remains."],flags:ac,scope:"environment",async run(e){let{from:t,to:n}=await ic(e);return Wo(e,rc(e,n),t,n)}};async function Wo(e,t,n,s,a={}){let i=await Go(e,t,n,s);if(i.count===0)return e.out.result({...a,copied:[],left:[],shown_once:[],after:Uo(i)},()=>e.out.line(`Nothing to copy: ${n.env_slug} and ${s.env_slug} have the same settings.`)),0;e.out.json||Bo(e,i);let r=t.filter(u=>i.modules[u.name].length>0).map(u=>u.name);await v(e,s,`make its ${r.join(", ")} settings equal to ${n.env_slug}'s (${i.count} difference(s))`);let o=[],l=[],d=[];e.out.json||e.out.line();for(let u of t){let g=i.modules[u.name];if(g.length===0)continue;let y={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,g,y)}let p=await Go(e,t,n,s);return e.out.result({...a,copied:o,left:l,shown_once:d,after:Uo(p)},()=>{e.out.line(),e.out.line("Compared again:"),Bo(e,p)}),p.count===0?0:1}var oc=[zp,Wp,Fp,Jp,Hp,Vp,Yp,Xp,Zp,eu,tu,nu,su,au,iu,ru,Qu,ec,tc,nc,uu,cu,hu,mu,fu,yu,gu,vu,_u,ku,Su,$u,Pu,Au,Ru,Tu,Eu,Cu,ju,Mu,Iu,Lu,Du,Nu,qu,...Fu,...Zu,nk,sk];async function Fo(e){return(await e.studio.get("/orgs")).organizations}async function _t(e,t){let n=await Fo(e);if(t===void 0){if(n.length===1)return n[0];throw m(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 f("no_such_org",`no organization ${JSON.stringify(t)} among yours`,{hint:"palbase orgs:list shows them"});if(s.length>1)throw new f("ambiguous_org",`${JSON.stringify(t)} names more than one of your organizations`,{hint:"pass its id"});return s[0]}var lc={name:"orgs:list",summary:"your organizations and your role in each",scope:"account",async run(e){let t=await Fo(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}])})}},dc={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 ${q(t.name)} (${t.id}).`))}},pc={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 _t(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}]))})}},uc={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 _t(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw m("--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 ${q(s.email)} to ${q(t.name)} as ${s.role}.`))}},cc={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 _t(e,e.flags.org),n=e.args[0],s=await e.studio.get(`/orgs/${t.id}/members`),a=s.members.find(r=>r.user_id===n||r.email!==null&&r.email.toLowerCase()===n.toLowerCase());if(a){await e.studio.request("DELETE",`/orgs/${x("the organization's id",t.id)}/members/${x("the member's id",a.user_id)}`),e.out.result({removed:a},()=>e.out.line(`${q(a.email??a.user_id)} is no longer in ${q(t.name)}.`));return}let i=s.invitations.find(r=>r.id===n||r.email.toLowerCase()===n.toLowerCase());if(!i)throw new f("no_such_member",`${JSON.stringify(n)} is neither a member of ${t.name} nor invited to it`);await e.studio.request("DELETE",`/orgs/${x("the organization's id",t.id)}/invitations/${x("the invitation's id",i.id)}`),e.out.result({withdrawn:i},()=>e.out.line(`The invitation of ${q(i.email)} is withdrawn.`))}},hc={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 _t(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(`${q(t.name)} has no access token yet: palbase tokens:create <name> makes one.`):e.out.table(n,[{header:"name",value:s=>q(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}])})}},mc={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 _t(e,e.flags.org),n=e.flags.limit===void 0?50:Number(e.flags.limit);if(!Number.isInteger(n)||n<1||n>1e4)throw m("--limit is a whole number from 1 to 10000");let s=[],a=null;do{let i=new URLSearchParams({limit:String(Math.min(100,n-s.length)),...a?{before:a}:{}}),r=await e.studio.get(`/orgs/${t.id}/audit?${i}`);s.push(...r.entries),a=r.next_before}while(a&&s.length<n);e.out.result({entries:s},()=>{s.length===0?e.out.line(`Nothing changed at ${q(t.name)}'s environments yet.`):e.out.table(s,[{header:"when",value:i=>i.at.slice(0,16).replace("T"," ")},{header:"who",value:i=>q(i.actor_name??i.actor)},{header:"environment",value:i=>q(i.environment_ref)},{header:"what",value:i=>q(`${i.method} ${i.path}`)},{header:"answer",value:i=>String(i.status)}])})}},gc={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 _t(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw m("--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 m("--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 ${q(a.name)} of ${q(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}`)})}},fc={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 _t(e,e.flags.org),{tokens:n}=await e.studio.get(`/orgs/${t.id}/tokens`),s=n.filter(r=>r.id===e.args[0]||r.name===e.args[0]);if(s.length===0)throw new f("no_such_token",`${q(t.name)} has no access token ${JSON.stringify(e.args[0])}`,{hint:"palbase tokens:list shows them"});if(s.length>1)throw new f("ambiguous_token",`${JSON.stringify(e.args[0])} names more than one token`,{hint:"pass its id"});let a=`/orgs/${x("the organization's id",t.id)}/tokens/${x("the token's id",s[0].id)}`,{endpoints:i}=await e.studio.get(`${a}/webhooks`);await e.studio.request("DELETE",a),e.out.result({revoked:s[0].id,kept_webhooks:i},()=>{if(e.out.line(`Revoked the access token ${q(s[0].name)} of ${q(t.name)}.`),i.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 r of i)e.out.line(` ${A(r.url)} \u2014 ${A(r.environment_ref)} (${A(r.id)})`)}})}},yc={name:"projects:list",summary:"every project of your organizations, with its environments",scope:"account",async run(e){let t=await Pe(e.studio),n=await e.state.targetFor(e.io.cwd),s=(await e.studio.get("/projects")).projects,a=new Map(t.map(i=>[i.organization_id,i.org_name]));for(let i of await Fo(e))a.set(i.id,i.name);e.out.result({projects:s.map(i=>({...i,organization_name:a.get(i.organization_id)??null}))},()=>{s.length===0&&e.out.line("No project yet: palbase projects:create <name> makes one.");let i=s.flatMap(r=>r.environments.length===0?[{org:a.get(r.organization_id)??"",project:r.name,env:"(none)",ref:"",here:""}]:r.environments.map(o=>({org:a.get(r.organization_id)??"",project:r.name,env:o.slug,ref:o.ref,here:n?.target.env_ref===o.ref?"*":""})));e.out.table(i,[{header:"",value:r=>r.here},{header:"organization",value:r=>r.org},{header:"project",value:r=>r.project},{header:"env",value:r=>r.env},{header:"ref",value:r=>r.ref}])})}},bc={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 _t(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 ${q(t.name)} \u203A ${q(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.`)})}},wc={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=un(await Pe(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 f("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 f("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 ${q(n.project_name)}.`))}},vc={name:"envs:list",summary:"a project's environments (the project chosen here, or -P)",scope:"environment",async run(e){let t=await Yt(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}]))}},_c={name:"envs:create",summary:"add an environment to a project (staging, a developer's own)",usage:"<slug> [--name <name>] [--from <env>]",details:["Each environment is a project of its own on the platform: its users, data and keys are its own.","--from opens it with another environment's module settings (palbase config:copy: secrets are named, not copied).","Machines, databases and sites are the project's, each bound to one environment: a new environment opens with its settings alone, and one is made bound to it (machines:create -E <slug>) or moved there (machines:move <name> --to <slug>)."],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:"refused: machines, databases and sites are the project's, and no environment opens with copies of them"}},scope:"environment",async run(e){let t=e.args[0];if(e.flags["with-cloud"]===!0)throw zo(t);let n=await ak(e),s=e.flags.from,a=s===void 0?[]:(await Pe(e.studio)).filter(d=>d.project_id===n.project_id),i=s===void 0?void 0:a.find(d=>d.slug===s||d.ref===s);if(s!==void 0&&!i)throw new f("no_such_environment",`the project has no environment ${JSON.stringify(s)}`,{hint:`its environments: ${a.map(d=>d.slug).join(", ")}`});let r=await e.studio.post(`/projects/${n.project_id}/environments`,{name:e.flags.name??t,slug:t}),o=()=>{e.out.line(`Made ${q(n.project_name)} \u203A ${r.environment.slug} (ref ${r.environment.ref}).`),r.keys&&(e.out.line(`publishable key: ${r.keys.publishable.key}`),e.out.line(`secret key (shown this once): ${r.keys.secret.key}`))};if(!i){e.out.result(r,o);return}e.out.json||o();let l=ie({...i,ref:r.environment.ref,slug:r.environment.slug,name:r.environment.name});return e.out.json||e.out.line(),Wo(e,xn,ie(i),l,{made:r})}},kc={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 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.","Moved, they keep their data and answer throughout, and their old addresses keep working: the environment is deleted once each is up where it moved. The passwords this computer holds for its databases go with them."],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, databases and sites to this environment of the project (its slug) before it is deleted"}},scope:"environment",async run(e){let t=await Yt(e),n=t.find(d=>d.slug===e.args[0]||d.ref===e.args[0]);if(!n)throw new f("no_such_environment",`the project has no environment ${JSON.stringify(e.args[0])}`);let s=ie(n);if(e.out.note(`${N(s)}: delete the environment, its users, data, machines and databases`),!e.global.yes){if(!e.interactive)throw new f("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 f("cancelled","nothing was deleted")}let a=e.flags["delete-bound"]===!0,i=typeof e.flags["move-to"]=="string"?e.flags["move-to"]:void 0;if(a&&i!==void 0)throw m("--delete-bound or --move-to: what is bound to it is deleted with it, or moved");let r=a?"?delete_bound=true":i!==void 0?`?move_to=${encodeURIComponent(i)}`:"",o=async()=>{let d=e.io.now()+6e5;for(;;)try{return await e.studio.request("DELETE",`/environments/${n.ref}${r}`)}catch(p){if(!(p instanceof E)||p.code!=="machines_still_moving"||e.io.now()>d)throw p;e.out.note(`still moving to ${decodeURIComponent(r.slice(9))}; asking again`),await e.io.sleep(5e3)}};try{await o()}catch(d){if(!(d instanceof E)||d.code!=="environment_has_resources"||r!=="")throw d;let p=d.body?.data??{},u=[p.machines?.length?`machines ${p.machines.join(", ")}`:"",p.databases?.length?`databases ${p.databases.join(", ")}`:"",p.sites?.length?`sites ${p.sites.join(", ")}`:""].filter(w=>w!=="").join("; "),g=t.filter(w=>w.ref!==n.ref).map(w=>w.slug);if(!e.interactive||e.global.yes)throw new f("environment_has_resources",`bound to ${n.slug}: ${u}`,{hint:`delete them with it (--delete-bound), or move them first (--move-to ${g[0]??"<env>"})`});e.out.line(`Bound to ${n.slug}: ${u}.`);let y=(await e.io.prompt(`Delete them with it (delete), move them to another environment (${g.join(", ")}), or keep it (keep)? `)).trim();if(y==="delete")r="?delete_bound=true";else if(g.includes(y))r=`?move_to=${encodeURIComponent(y)}`;else throw new f("cancelled","nothing was deleted");await o()}if(r.startsWith("?move_to=")){let d=t.find(p=>p.slug===decodeURIComponent(r.slice(9))||p.ref===decodeURIComponent(r.slice(9)));d&&await e.state.moveDatabasePasswords(n.ref,d.ref)}let l=await e.state.targetFor(e.io.cwd);l?.target.env_ref===n.ref&&await e.state.clearTarget(l.dir),e.out.result({deleted:n.ref},()=>e.out.line(`Deleted ${N(s)}.`))}},Sc={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 b(e);else{let n=await Pe(e.studio);t=ie(ik(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 ${N(t)}.`))}},$c={name:"status",summary:"the environment this directory acts on: who you are there, the machines and databases bound to it",scope:"environment",async run(e){let t=await b(e),n=await e.studio.get(`/environments/${t.env_ref}`),s=p=>_e(e.studio,t.env_ref,"GET",p).then(u=>u.body,u=>u instanceof E?null:Promise.reject(u)),a=`limit=100&environment=${encodeURIComponent(t.env_ref)}`,[i,r]=await Promise.all([s(`/machines?${a}`),s(`/databases?${a}`)]),o=i?.machines??[],l=r?.databases??[],d=await e.state.targetFor(e.io.cwd);e.out.result({target:t,role:n.role,address:`https://${t.env_ref}.${e.cloud.domain}`,machines:o,databases:l,chosen_for:d?.dir??null},()=>{e.out.line(N(t)),e.out.line(` ref ${t.env_ref} \xB7 your role ${n.role} \xB7 https://${t.env_ref}.${e.cloud.domain}`),d&&d.target.env_ref===t.env_ref&&e.out.line(` chosen for ${d.dir}`),e.out.line(` machines: ${o.length===0?"none":o.map(p=>`${p.name} (${p.size}, ${p.state})`).join(", ")}`),e.out.line(` databases: ${l.length===0?"none":l.map(p=>`${p.name} (${p.size}, ${p.state})`).join(", ")}`)})}},Pc={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 b(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))}},Ac={name:"keys:list",summary:"the environment's API keys (never their values)",scope:"environment",async run(e){let t=await b(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}]))}},Rc={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 m("--kind is publishable or secret");let n=await b(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)})}},Tc={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 b(e),n=`/environments/${x("the environment's ref",t.env_ref)}/keys/${x("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 ak(e){return(await Yt(e))[0]}async function Yt(e){if(Jt(e.io))return[await la(e)];let t=await Pe(e.studio);if(e.global.project!==void 0)return un(t,e.global.project);let n=await e.state.targetFor(e.io.cwd);if(!n)throw new f("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 f("no_such_project",`the project chosen here (${n.target.project_name}) is not among yours any more`,{hint:"palbase use another"});return s}function ik(e,t){let n=t.split("/");if(n.length>3||n.some(i=>i===""))throw m(`${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 i of s){let r;try{r=un(e,i.project)}catch(o){a=o;continue}if(i.env!==void 0){let o=r.find(l=>l.slug===i.env||l.ref===i.env);if(o)return o;a=new f("no_such_environment",`${r[0].project_name} has no environment ${JSON.stringify(i.env)}`,{hint:`its environments: ${r.map(l=>l.slug).join(", ")}`});continue}if(r.length===1)return r[0];throw new f("which_environment",`${r[0].project_name} has more than one environment`,{hint:`name one: ${r.map(o=>`${o.project_name}/${o.slug}`).join(", ")}`})}throw a}import{mkdtemp as rk,rm as ok}from"node:fs/promises";import{tmpdir as lk}from"node:os";import{extname as dk,join as Ec}from"node:path";var Jo="Named by none, it is the only database of the environment chosen for this directory or named by -E \u2014 never one bound elsewhere \u2014 else, when neither says, the project's only one.";async function bn(e,t){let n=await pn(e),s=n.t,a=t??await Mc(e,s,hi(n,"/databases?limit=100"),n.by==="fallback"?"the project":`the environment ${s.env_slug}`),i=await Oc(e,s,a),r=()=>On(async o=>{let{body:l}=await _e(e.studio,s.env_ref,"GET",`/databases?limit=100${o?`&cursor=${encodeURIComponent(o)}`:""}`);return{items:l.databases,next:l.next_cursor}});return await Mn(e,n,i.d,r,`the database ${i.d.name}`),i}async function Oc(e,t,n){let{body:s}=await _e(e.studio,t.env_ref,"GET",`/databases/${x("the database's name",n)}`);return{t:await Ln(e,t,s.environment,`the database ${s.name}`),d:s}}async function Mc(e,t,n,s){let{body:a}=await _e(e.studio,t.env_ref,"GET",n);if(a.databases.length===1)return a.databases[0].name;throw a.databases.length===0?new f("no_database",`${s} has no database`,{hint:"palbase databases:create opens one"}):m("which database? name it",`${s}'s databases: ${a.databases.map(i=>i.name).join(", ")}`)}async function Xt(e,t,n,s,a){let{body:i}=await _e(e.studio,t.env_ref,"GET",`/databases/${x("the database's name",n)}/credentials`),r=(await e.state.databasePasswords(t.env_ref,n))[s];if(!r)throw new f("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"?i.owner:i.app,l=new URL(a?o.pooled_url:o.url);return l.password="",{url:l.toString(),password:r,role:s}}function pk(e){let t=new URL(e.url);return t.password=encodeURIComponent(e.password),t.toString()}var Ic={type:"string",value:"role",description:"owner (migrations, dumps) or app (what the machines use); default owner"};function Lc(e){let t=e.flags.role??"owner";if(t!=="owner"&&t!=="app")throw m("--role is owner or app");return t}var Dc={PGSSLROOTCERT:"system"};async function Nn(e,t,n,s,a=!1){let i=await e.io.run(t,n,{env:{PGPASSWORD:s.password,...Dc,PGAPPNAME:"palbase-cli"},inherit:a});if(i.code===127)throw new f("missing_tool",`${t} is not installed here`,{hint:"install the Postgres 18 client tools (brew install postgresql@18, apt install postgresql-client-18)"});return i}var xc={name:"db:url",summary:"a project database's connection address, for any tool (Prisma, Drizzle, pg_dump, a GUI)",usage:"[name] [--role owner|app] [--pooled] [--with-password]",details:[te("database"),Jo,"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:Ic,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,d:n}=await bn(e,e.args[0]),s=n.name,a=await Xt(e,t,s,Lc(e),e.flags.pooled===!0),i=e.flags["with-password"]===!0?pk(a):a.url;e.out.result({database:s,role:a.role,url:i,libpq_env:Dc},()=>{e.io.stdout(`${i}
|
|
32
|
+
`))e.out.line(a)}})}},Pu={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:{...Oo,file:{type:"string",value:"path",description:"the template (default: stdin)"}},scope:"environment",async run(e){let t=await b(e),n=va(e),s=Mo(e,e.args[0]),a=C0(n,await ke(e,e.flags.file,"the template"));await v(e,t,`override the ${n} template ${e.args[0]} (${e.flags.locale})`);let i=await h(e,t,"PUT",s,a,j());e.out.result(i,()=>e.out.line(`The ${n} template ${e.args[0]} (${e.flags.locale}) is yours now${typeof i.subject=="string"?`: "${i.subject}"`:""}.`))}},Au={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:Oo,scope:"environment",async run(e){let t=await b(e),n=Mo(e,e.args[0]);await v(e,t,`remove the ${va(e)} template ${e.args[0]} (${e.flags.locale})`),await h(e,t,"DELETE",n,void 0,j()),e.out.result({deleted:{channel:va(e),slug:e.args[0],locale:e.flags.locale}},()=>e.out.line(`Removed the override of ${e.args[0]} (${e.flags.locale}).`))}};async function jo(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 Ru={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 b(e),n=await jo(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"}])})}},Tu={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 b(e),n=mn(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}:{}},j());e.out.result(s,()=>e.out.line(`Made the topic ${s.name}${s.self_subscribe?", followed from the app":""}.`))}},Eu={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 b(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,j()),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the topic ${e.args[0]}.`))}},Cu={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 b(e),{body:n}=await Ke(e,t,"/notify/settings");e.out.result(n,()=>gs(e,n))}},ju={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 b(e),n=cn(e.args),{body:s,etag:a}=await Ke(e,t,"/notify/settings"),i=hn(s,n),r=Vt(s,i);if(r.length===0)return Fe(e,"the message settings",s);await v(e,t,`set the message settings ${r.join(", ")}`);let o=await h(e,t,"PUT","/notify/settings",i,{...je(a),...j()});e.out.result({settings:o,changed:r},()=>{for(let l of r)e.out.line(`${l}: ${Oe(s[l])} \u2192 ${Oe(o[l])}`)})}},O0=new Set(["sms_countries","sms_blocked_countries"]);function M0(e){return{...e,sms_countries:e.sms_countries??[],sms_blocked_countries:e.sms_blocked_countries??[],mx_check:e.mx_check??!1}}var Ou={name:"notify",async read(e,t){let[n,s,a,i,r,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"),jo(e,t)]),l={};for(let[u,g]of Object.entries(M0(n)))l[`settings.${u}`]=g;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 i.templates.filter(g=>g.customized))l[`templates.sms/${u.slug}/${u.locale}`]={body:u.body};for(let u of r.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=fe(n,"settings.");if(a.length>0){let{body:o,etag:l}=await Ke(e,t,"/notify/settings"),d={...o};for(let p of a)d[p.name]=O0.has(p.name)&&Array.isArray(p.from)&&p.from.length===0?null:p.from;await Q(s,`set the message settings ${a.map(p=>p.name).join(", ")}`,async()=>{await h(e,t,"PUT","/notify/settings",d,{...je(l),...j()})})}for(let o of fe(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 fe(n,"templates.")){let l=`/notify/templates/${o.name.split("/").map(k).join("/")}`;o.from===void 0?await Q(s,`remove the template override ${o.name}`,async()=>{await h(e,t,"DELETE",l,void 0,j())}):await Q(s,`override the template ${o.name}`,async()=>{await h(e,t,"PUT",l,o.from,j())})}let i=fe(n,"topics."),r=i.some(o=>o.from===void 0)?new Map((await jo(e,t)).map(o=>[o.name,o.subscribers])):new Map;for(let o of i){let l=`/notify/topics/${k(o.name)}`,d=o.from?.self_subscribe;if(o.from===void 0){let p=r.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 Q(s,`delete the topic ${o.name}`,async()=>{await h(e,t,"DELETE",l,void 0,j())})}else o.change==="only_in_from"?await Q(s,`make the topic ${o.name}`,async()=>{await h(e,t,"POST","/notify/topics",{name:o.name,self_subscribe:d},j())}):await Q(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},j())})}}};var ks=["max_connections","max_events_per_second","max_joins_per_second","max_channels_per_connection"];function I0(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 Io(e){return Object.fromEntries(ks.map(t=>[t,e[t]??null]))}var Mu={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 b(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=>I0(s)}])})}},Iu={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 b(e),n=me(await ke(e,e.flags.file,"the channel declaration"),"the channel declaration"),s=Array.isArray(n)?n:n.channels;if(!Array.isArray(s))throw m('the declaration is {"channels": [\u2026]} or a list of channels');let a=await h(e,t,"GET","/realtime/channels");if(We(a.channels,s))return Fe(e,"the channel declaration",a);await v(e,t,`declare ${s.length} channel pattern(s) (now ${a.channels.length})`);let i=await h(e,t,"PUT","/realtime/channels",{channels:s});e.out.result(i,()=>e.out.line(i.channels.length===0?"No channel is declared now.":`Declared ${i.channels.length} channel pattern(s): ${i.channels.map(r=>r.pattern).join(", ")}.`))}},Lu={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 b(e),n=await h(e,t,"GET","/realtime/limits");e.out.result(n,()=>{let s=n.platform??{},a=Math.max(...ks.map(i=>i.length));for(let i of ks)e.out.line(`${i.padEnd(a)} ${n[i]===void 0||n[i]===null?"the platform's":Oe(n[i])}${s[i]!==void 0?` (platform ${s[i]===0?"no ceiling":Oe(s[i])})`:""}`)})}},Du={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: ${ks.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 b(e),n=cn(e.args);for(let o of n)if(o.path.length!==1||!ks.includes(o.path[0]))throw m(`no limit ${JSON.stringify(o.path.join("."))}`,`the limits: ${ks.join(", ")}`);let s=Io(await h(e,t,"GET","/realtime/limits")),a=hn(s,n),i=Vt(s,a);if(i.length===0)return Fe(e,"the realtime limits",s);await v(e,t,`set the realtime limits ${i.join(", ")}`);let r=await h(e,t,"PUT","/realtime/limits",a);e.out.result({limits:r,changed:i},()=>{for(let o of i)e.out.line(`${o}: ${Oe(s[o]??"the platform's")} \u2192 ${Oe(r[o]??"the platform's")}`)})}},xu={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[i,r]of Object.entries(Io(s)))a[`limits.${i}`]=r;return a},async copy(e,t,n,s){let a=n.find(r=>r.key==="channels");a&&await Q(s,"declare the channels",async()=>{await h(e,t,"PUT","/realtime/channels",{channels:a.from??[]})});let i=fe(n,"limits.");if(i.length>0){let r=Io(await h(e,t,"GET","/realtime/limits"));for(let o of i)r[o.name]=o.from??null;await Q(s,`set the realtime limits ${i.map(o=>o.name).join(", ")}`,async()=>{await h(e,t,"PUT","/realtime/limits",r)})}}},Nu={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 b(e),n=await h(e,t,"GET","/analytics/settings");e.out.result(n,()=>gs(e,n))}},qu={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 b(e),n=cn(e.args),s=await h(e,t,"GET","/analytics/settings"),a=hn(s,n),i=Vt(s,a);if(i.length===0)return Fe(e,"the analytics settings",s);await v(e,t,`set the analytics settings ${i.join(", ")}`);let r=await h(e,t,"PUT","/analytics/settings",a);e.out.result({settings:r,changed:i},()=>{for(let o of i)e.out.line(`${o}: ${Oe(s[o])} \u2192 ${Oe(r[o])}`)})}},Ku={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=fe(n,"settings.");if(a.length===0)return;let i=await h(e,t,"GET","/analytics/settings");for(let r of a)r.from!==void 0&&(i[r.name]=r.from);await Q(s,`set the analytics settings ${a.map(r=>r.name).join(", ")}`,async()=>{await h(e,t,"PUT","/analytics/settings",i)})}};var at="/messaging/settings",L0=/^[A-Z][A-Z0-9_]{0,127}$/,Do=["retention_days","push_preview","deleted_user_messages","search_by_meaning","event_text"];function Ss(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?Gu(t):"none: anyone may reach anyone"}}function Gu(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 D0(e,t){let n=[...Do.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,i]of n)e.out.line(`${a.padEnd(s)} ${Ss(a,i)}`)}function Lo(e,t){if(e!==void 0){if(e==="on")return!0;if(e==="off")return!1;throw m(`--${t} is on or off`)}}function x0(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 m("--retention-days is a whole number of days from 1 to 36500, or off (kept for good)");return t}var N0={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 b(e),n=await h(e,t,"GET",at);e.out.result(n,()=>D0(e,n))}},q0={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=x0(e.flags["retention-days"]);n!==void 0&&(t.retention_days=n);let s=Lo(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 m("--deleted-user-messages is keep or delete");t.deleted_user_messages=a}let i=Lo(e.flags["search-by-meaning"],"search-by-meaning");i!==void 0&&(t.search_by_meaning=i);let r=Lo(e.flags["event-text"],"event-text");if(r!==void 0&&(t.event_text=r),Object.keys(t).length===0)throw m("nothing to change","pass --retention-days, --push-preview, --deleted-user-messages, --search-by-meaning or --event-text");let o=await b(e),l=await h(e,o,"GET",at),d=Do.filter(u=>u in t&&!We(l[u],t[u]));if(d.length===0)return Fe(e,"the messaging settings",l);await v(e,o,`set the messaging settings ${d.join(", ")}`);let p=await h(e,o,"PUT",at,Object.fromEntries(d.map(u=>[u,t[u]])));e.out.result({settings:p,changed:d},()=>{for(let u of d)e.out.line(`${u}: ${Ss(u,l[u])} \u2192 ${Ss(u,p[u])}`)})}},Uu={"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 Bu(e){let t=e.flags["secret-to"];if(t!==void 0&&!L0.test(t))throw m(`--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 m("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function zu(e,t,n,s,a){let{hook_secret:i,...r}=n;if(i===void 0){e.out.result({settings:r},()=>e.out.line(`${a}: ${Ss("hook",r.hook)}.`));return}if(s!==void 0){let o=await h(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:i});e.out.result({settings:r,secret_to:{set:s.set,name:s.name,version:o.version}},()=>e.out.line(`${a}: ${Ss("hook",r.hook)}; its signing secret is ${s.name} (${s.set}, v${o.version}) in ${N(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${Ss("hook",r.hook)}.`),e.out.line(`signing secret (shown this once): ${i}`)})}var K0={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 b(e),{hook:n}=await h(e,t,"GET",at);e.out.result({hook:n},()=>e.out.line(n?Gu(n):"No hook: anyone may reach anyone. palbase messaging:hook:set --url <url> sets one."))}},G0={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)"},...Uu},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw m("--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 m("--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 m("--on-error is allow or deny");if(t===void 0&&n===void 0&&s===void 0)throw m("nothing to change","pass --url, --timeout-ms or --on-error");let a=Bu(e),i=await b(e),r=await h(e,i,"GET",at),o=r.hook;if(!o&&t===void 0)throw m("the environment has no hook yet: --url names where it is asked");if(o&&a!==void 0)throw m("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&&We(o,{...o,...l}))return Fe(e,"the hook",r);let u=o?["url","timeout_ms","on_error"].filter(y=>l[y]!==o[y]):[];await v(e,i,o?`change the messaging hook: ${u.join(", ")}`:`set the messaging hook ${l.url}${a?`, its secret kept in ${a.name} (${a.set})`:""}`);let g=await h(e,i,"PUT",at,{hook:l});await zu(e,i,g,a,o?"Changed the hook":"Set the hook")}},U0={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 b(e),n=await h(e,t,"GET",at);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",at,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may reach anyone."))}},B0={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:Uu,scope:"environment",async run(e){let t=Bu(e),n=await b(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",`${at}/hook-secret`);await zu(e,n,s,t,"Made the signing secret anew for the hook")}},Wu={name:"messaging",async read(e,t){let n=await h(e,t,"GET",at),s={};for(let a of Do)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=fe(n,"settings.");a.length>0&&await Q(s,`set the messaging settings ${a.map(l=>l.name).join(", ")}`,async()=>{await h(e,t,"PUT",at,Object.fromEntries(a.map(l=>[l.name,l.from])))});let i=n.find(l=>l.key==="hook");if(!i)return;if(i.from===void 0){await Q(s,`remove the hook ${i.to.url}`,async()=>{await h(e,t,"PUT",at,{hook:null})});return}let r=i.from,o;await Q(s,`${i.change==="differs"?"change":"set"} the hook ${r.url}`,async()=>{o=(await h(e,t,"PUT",at,{hook:r})).hook_secret}),o&&s.shown(`the hook ${r.url} signs with`,o)}},Fu=[N0,q0,K0,G0,U0,B0];var it="/calls/settings",z0=/^[A-Z][A-Z0-9_]{0,127}$/,No=["max_participants","calls_per_hour"];function $s(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?Ju(t):"none: anyone may call anyone (blocks aside)"}}function Ju(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 W0(e,t){let n=[...No.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,i]of n)e.out.line(`${a.padEnd(s)} ${$s(a,i)}`)}function xo(e,t,n,s){if(e===void 0)return;let a=Number(e);if(!/^[0-9]+$/.test(String(e))||a<n||a>s)throw m(`--${t} is a whole number from ${n} to ${s}`);return a}var F0={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 b(e),n=await h(e,t,"GET",it);e.out.result(n,()=>W0(e,n))}},J0={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=xo(e.flags["max-participants"],"max-participants",2,100);n!==void 0&&(t.max_participants=n);let s=xo(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 m("nothing to change","pass --max-participants or --calls-per-hour");let a=await b(e),i=await h(e,a,"GET",it),r=No.filter(l=>l in t&&!We(i[l],t[l]));if(r.length===0)return Fe(e,"the call settings",i);await v(e,a,`set the call settings ${r.join(", ")}`);let o=await h(e,a,"PUT",it,Object.fromEntries(r.map(l=>[l,t[l]])));e.out.result({settings:o,changed:r},()=>{for(let l of r)e.out.line(`${l}: ${$s(l,i[l])} \u2192 ${$s(l,o[l])}`)})}},Vu={"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 Hu(e){let t=e.flags["secret-to"];if(t!==void 0&&!z0.test(t))throw m(`--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 m("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function Yu(e,t,n,s,a){let{hook_secret:i,...r}=n;if(i===void 0){e.out.result({settings:r},()=>e.out.line(`${a}: ${$s("hook",r.hook)}.`));return}if(s!==void 0){let o=await h(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:i});e.out.result({settings:r,secret_to:{set:s.set,name:s.name,version:o.version}},()=>e.out.line(`${a}: ${$s("hook",r.hook)}; its signing secret is ${s.name} (${s.set}, v${o.version}) in ${N(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${$s("hook",r.hook)}.`),e.out.line(`signing secret (shown this once): ${i}`)})}var V0={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 b(e),{hook:n}=await h(e,t,"GET",it);e.out.result({hook:n},()=>e.out.line(n?Ju(n):"No hook: anyone may call anyone (blocks aside). palbase calls:hook:set --url <url> sets one."))}},H0={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)"},...Vu},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw m("--url is where the hook is asked: a URL");let n=xo(e.flags["timeout-ms"],"timeout-ms",100,5e3),s=e.flags["on-error"];if(s!==void 0&&s!=="allow"&&s!=="deny")throw m("--on-error is allow or deny");let a=e.flags.places;if(a!==void 0&&a!=="on"&&a!=="off")throw m("--places is on or off");let i=a===void 0?void 0:a==="on";if(t===void 0&&n===void 0&&s===void 0&&i===void 0)throw m("nothing to change","pass --url, --timeout-ms, --on-error or --places");let r=Hu(e),o=await b(e),l=await h(e,o,"GET",it),d=l.hook;if(!d&&t===void 0)throw m("the environment has no hook yet: --url names where it is asked");if(d&&r!==void 0)throw m("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 g=s??d?.on_error;g!==void 0&&(p.on_error=g);let y=i??d?.places;if(y!==void 0&&(p.places=y),d&&We(d,{...d,...p}))return Fe(e,"the hook",l);let w=d?["url","timeout_ms","on_error","places"].filter(P=>(p[P]??!1)!==(d[P]??!1)):[];await v(e,o,d?`change the calls hook: ${w.join(", ")}`:`set the calls hook ${p.url}${r?`, its secret kept in ${r.name} (${r.set})`:""}`);let _=await h(e,o,"PUT",it,{hook:p});await Yu(e,o,_,r,d?"Changed the hook":"Set the hook")}},Y0={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 b(e),n=await h(e,t,"GET",it);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",it,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may call anyone (blocks aside)."))}},X0={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:Vu,scope:"environment",async run(e){let t=Hu(e),n=await b(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",`${it}/hook-secret`);await Yu(e,n,s,t,"Made the signing secret anew for the hook")}},Xu={name:"calls",async read(e,t){let n=await h(e,t,"GET",it),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=fe(n,"settings.");a.length>0&&await Q(s,`set the call settings ${a.map(l=>l.name).join(", ")}`,async()=>{await h(e,t,"PUT",it,Object.fromEntries(a.map(l=>[l.name,l.from])))});let i=n.find(l=>l.key==="hook");if(!i)return;if(i.from===void 0){await Q(s,`remove the hook ${i.to.url}`,async()=>{await h(e,t,"PUT",it,{hook:null})});return}let r=i.from,o;await Q(s,`${i.change==="differs"?"change":"set"} the hook ${r.url}`,async()=>{o=(await h(e,t,"PUT",it,{hook:r})).hook_secret}),o&&s.shown(`the hook ${r.url} signs with`,o)}},Zu=[F0,J0,V0,H0,Y0,X0];var Z0=/^[a-z][a-z0-9-]{1,62}$/;function Ps(e){if(!Z0.test(e))throw m(`${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 Ko(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 Q0(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 m(`--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 qo(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 ek(e,t,n){try{return await h(e,t,"GET",Ps(n))}catch(s){if(s instanceof E&&s.status===404)return;throw s}}var Qu={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 b(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=>Ko(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(", ")}])})}},ec={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 b(e),n=await h(e,t,"GET",Ps(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 ${Ko(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}`:""}`)})}},tc={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 b(e),n=e.args[0];if(e.flags.public===!0&&e.flags.private===!0)throw m("--public and --private are one or the other");let s=await ek(e,t,n),a=qo(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=Q0(e.flags["max-size"])),e.flags.types!==void 0&&(a.allowed_mime_types=oe(e.flags.types)??[]),e.flags["variants-file"]!==void 0){let r=me(await ke(e,e.flags["variants-file"],"the renditions"),"the renditions file"),o=Array.isArray(r)?r:r.variants;if(!Array.isArray(o))throw m("the renditions file is a JSON list of {name, width, height, fit, format, quality}");a.variants=o}if(s&&We(qo(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 i=await h(e,t,"PUT",Ps(n),a);e.out.result(i,()=>e.out.line(`${s?"Changed":"Made"} the bucket ${i.name}: ${i.public?"public":"private"}, files up to ${Ko(i.file_size_limit)}, ${i.allowed_mime_types.length===0?"any type":i.allowed_mime_types.join(", ")}.`))}},nc={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 b(e),n=Ps(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]}.`))}},sc={name:"storage",async read(e,t){let{buckets:n}=await h(e,t,"GET","/storage/buckets"),s={};for(let a of n){let i=qo(a);s[`buckets.${a.name}`]={...i,allowed_mime_types:[...i.allowed_mime_types].sort()}}return s},async copy(e,t,n,s){for(let a of fe(n,"buckets."))a.from===void 0?await Q(s,`delete the bucket ${a.name}`,async()=>{await h(e,t,"DELETE",Ps(a.name))}):await Q(s,`declare the bucket ${a.name}`,async()=>{await h(e,t,"PUT",Ps(a.name),a.from)})}};var xn=[ou,sc,bu,Ou,xu,Ku,Wu,Xu];function zo(e="<env>"){return new f("not_copied","machines, databases and sites are the project's, each bound to one environment: only settings are compared and copied between environments",{hint:`make one bound to it with palbase machines:create -E ${e} (or databases:create -E ${e}), or move one there with palbase machines:move <name> --to ${e}`})}var ac={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: ${xn.map(e=>e.name).join(",")} (the default)`}};async function ic(e){if(e.global.env!==void 0)throw m("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 m("name both environments: --from <env> --to <env>");let s=await Pe(e.studio),a;if(e.global.project!==void 0)a=un(s,e.global.project);else{let l=await e.state.targetFor(e.io.cwd);if(!l)throw new f("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 i=l=>{let d=a.find(p=>p.slug===l||p.ref===l);if(!d)throw new f("no_such_environment",`the project has no environment ${JSON.stringify(l)}`,{hint:`its environments: ${a.map(p=>p.slug).join(", ")}`});return ie(d)},r=i(t),o=i(n);if(r.env_ref===o.env_ref)throw m("--from and --to name the same environment");return{from:r,to:o}}function rc(e,t){let n=oe(e.flags.only);if(n===void 0)return xn;if(n.some(s=>s==="machines"||s==="databases"||s==="sites"))throw zo(t.env_slug);for(let s of n)if(!xn.some(a=>a.name===s))throw m(`no module ${JSON.stringify(s)}`,`the modules: ${xn.map(a=>a.name).join(", ")}`);return xn.filter(s=>n.includes(s.name))}function tk(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),s=[];for(let a of n){let i=a in e,r=a in t;i&&!r?s.push({key:a,change:"only_in_from",from:e[a]}):!i&&r?s.push({key:a,change:"only_in_to",to:t[a]}):We(e[a],t[a])||s.push({key:a,change:"differs",from:e[a],to:t[a]})}return s}async function Go(e,t,n,s){let a=l=>Promise.all(t.map(d=>d.read(e,l))),[i,r]=await Promise.all([a(n),a(s)]),o=Object.fromEntries(t.map((l,d)=>[l.name,tk(i[d],r[d])]));return{from:n,to:s,modules:o,count:Object.values(o).reduce((l,d)=>l+d.length,0)}}function Uo(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 Ei(e){let t=JSON.stringify(e)??"undefined";return t.length>140?`${t.slice(0,139)}\u2026`:t}function Bo(e,t){let n=t.from.env_slug,s=t.to.env_slug;for(let[i,r]of Object.entries(t.modules))if(r.length!==0){e.out.line(`${i} (${r.length})`);for(let o of r)o.change==="differs"?e.out.line(` ~ ${o.key}: ${n} ${Ei(o.from)} \xB7 ${s} ${Ei(o.to)}`):o.change==="only_in_from"?e.out.line(` - ${o.key}: only in ${n}: ${Ei(o.from)}`):e.out.line(` + ${o.key}: only in ${s}: ${Ei(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 nk={name:"config:diff",summary:"how two environments' module settings differ (auth, storage, flags, notify, realtime, analytics, messaging, calls)",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:ac,scope:"environment",async run(e){let{from:t,to:n}=await ic(e),s=await Go(e,rc(e,n),t,n);return e.out.result(Uo(s),()=>Bo(e,s)),s.count===0?0:1}},sk={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.","Machines, databases and sites are not settings: they are the project's, each bound to one environment (machines:create -E, machines:move --to).","Exit code 0 when the two are the same afterwards, 1 when a difference remains."],flags:ac,scope:"environment",async run(e){let{from:t,to:n}=await ic(e);return Wo(e,rc(e,n),t,n)}};async function Wo(e,t,n,s,a={}){let i=await Go(e,t,n,s);if(i.count===0)return e.out.result({...a,copied:[],left:[],shown_once:[],after:Uo(i)},()=>e.out.line(`Nothing to copy: ${n.env_slug} and ${s.env_slug} have the same settings.`)),0;e.out.json||Bo(e,i);let r=t.filter(u=>i.modules[u.name].length>0).map(u=>u.name);await v(e,s,`make its ${r.join(", ")} settings equal to ${n.env_slug}'s (${i.count} difference(s))`);let o=[],l=[],d=[];e.out.json||e.out.line();for(let u of t){let g=i.modules[u.name];if(g.length===0)continue;let y={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,g,y)}let p=await Go(e,t,n,s);return e.out.result({...a,copied:o,left:l,shown_once:d,after:Uo(p)},()=>{e.out.line(),e.out.line("Compared again:"),Bo(e,p)}),p.count===0?0:1}var oc=[zp,Wp,Fp,Jp,Hp,Vp,Yp,Xp,Zp,eu,tu,nu,su,au,iu,ru,Qu,ec,tc,nc,uu,cu,hu,mu,fu,yu,gu,vu,_u,ku,Su,$u,Pu,Au,Ru,Tu,Eu,Cu,ju,Mu,Iu,Lu,Du,Nu,qu,...Fu,...Zu,nk,sk];async function Fo(e){return(await e.studio.get("/orgs")).organizations}async function kt(e,t){let n=await Fo(e);if(t===void 0){if(n.length===1)return n[0];throw m(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 f("no_such_org",`no organization ${JSON.stringify(t)} among yours`,{hint:"palbase orgs:list shows them"});if(s.length>1)throw new f("ambiguous_org",`${JSON.stringify(t)} names more than one of your organizations`,{hint:"pass its id"});return s[0]}var lc={name:"orgs:list",summary:"your organizations and your role in each",scope:"account",async run(e){let t=await Fo(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}])})}},dc={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 ${q(t.name)} (${t.id}).`))}},pc={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 kt(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}]))})}},uc={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 kt(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw m("--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 ${q(s.email)} to ${q(t.name)} as ${s.role}.`))}},cc={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 kt(e,e.flags.org),n=e.args[0],s=await e.studio.get(`/orgs/${t.id}/members`),a=s.members.find(r=>r.user_id===n||r.email!==null&&r.email.toLowerCase()===n.toLowerCase());if(a){await e.studio.request("DELETE",`/orgs/${x("the organization's id",t.id)}/members/${x("the member's id",a.user_id)}`),e.out.result({removed:a},()=>e.out.line(`${q(a.email??a.user_id)} is no longer in ${q(t.name)}.`));return}let i=s.invitations.find(r=>r.id===n||r.email.toLowerCase()===n.toLowerCase());if(!i)throw new f("no_such_member",`${JSON.stringify(n)} is neither a member of ${t.name} nor invited to it`);await e.studio.request("DELETE",`/orgs/${x("the organization's id",t.id)}/invitations/${x("the invitation's id",i.id)}`),e.out.result({withdrawn:i},()=>e.out.line(`The invitation of ${q(i.email)} is withdrawn.`))}},hc={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 kt(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(`${q(t.name)} has no access token yet: palbase tokens:create <name> makes one.`):e.out.table(n,[{header:"name",value:s=>q(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}])})}},mc={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 kt(e,e.flags.org),n=e.flags.limit===void 0?50:Number(e.flags.limit);if(!Number.isInteger(n)||n<1||n>1e4)throw m("--limit is a whole number from 1 to 10000");let s=[],a=null;do{let i=new URLSearchParams({limit:String(Math.min(100,n-s.length)),...a?{before:a}:{}}),r=await e.studio.get(`/orgs/${t.id}/audit?${i}`);s.push(...r.entries),a=r.next_before}while(a&&s.length<n);e.out.result({entries:s},()=>{s.length===0?e.out.line(`Nothing changed at ${q(t.name)}'s environments yet.`):e.out.table(s,[{header:"when",value:i=>i.at.slice(0,16).replace("T"," ")},{header:"who",value:i=>q(i.actor_name??i.actor)},{header:"environment",value:i=>q(i.environment_ref)},{header:"what",value:i=>q(`${i.method} ${i.path}`)},{header:"answer",value:i=>String(i.status)}])})}},gc={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 kt(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw m("--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 m("--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 ${q(a.name)} of ${q(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}`)})}},fc={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 kt(e,e.flags.org),{tokens:n}=await e.studio.get(`/orgs/${t.id}/tokens`),s=n.filter(r=>r.id===e.args[0]||r.name===e.args[0]);if(s.length===0)throw new f("no_such_token",`${q(t.name)} has no access token ${JSON.stringify(e.args[0])}`,{hint:"palbase tokens:list shows them"});if(s.length>1)throw new f("ambiguous_token",`${JSON.stringify(e.args[0])} names more than one token`,{hint:"pass its id"});let a=`/orgs/${x("the organization's id",t.id)}/tokens/${x("the token's id",s[0].id)}`,{endpoints:i}=await e.studio.get(`${a}/webhooks`);await e.studio.request("DELETE",a),e.out.result({revoked:s[0].id,kept_webhooks:i},()=>{if(e.out.line(`Revoked the access token ${q(s[0].name)} of ${q(t.name)}.`),i.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 r of i)e.out.line(` ${A(r.url)} \u2014 ${A(r.environment_ref)} (${A(r.id)})`)}})}},yc={name:"projects:list",summary:"every project of your organizations, with its environments",scope:"account",async run(e){let t=await Pe(e.studio),n=await e.state.targetFor(e.io.cwd),s=(await e.studio.get("/projects")).projects,a=new Map(t.map(i=>[i.organization_id,i.org_name]));for(let i of await Fo(e))a.set(i.id,i.name);e.out.result({projects:s.map(i=>({...i,organization_name:a.get(i.organization_id)??null}))},()=>{s.length===0&&e.out.line("No project yet: palbase projects:create <name> makes one.");let i=s.flatMap(r=>r.environments.length===0?[{org:a.get(r.organization_id)??"",project:r.name,env:"(none)",ref:"",here:""}]:r.environments.map(o=>({org:a.get(r.organization_id)??"",project:r.name,env:o.slug,ref:o.ref,here:n?.target.env_ref===o.ref?"*":""})));e.out.table(i,[{header:"",value:r=>r.here},{header:"organization",value:r=>r.org},{header:"project",value:r=>r.project},{header:"env",value:r=>r.env},{header:"ref",value:r=>r.ref}])})}},bc={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 kt(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 ${q(t.name)} \u203A ${q(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.`)})}},wc={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=un(await Pe(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 f("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 f("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 ${q(n.project_name)}.`))}},vc={name:"envs:list",summary:"a project's environments (the project chosen here, or -P)",scope:"environment",async run(e){let t=await Yt(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}]))}},_c={name:"envs:create",summary:"add an environment to a project (staging, a developer's own)",usage:"<slug> [--name <name>] [--from <env>]",details:["Each environment is a project of its own on the platform: its users, data and keys are its own.","--from opens it with another environment's module settings (palbase config:copy: secrets are named, not copied).","Machines, databases and sites are the project's, each bound to one environment: a new environment opens with its settings alone, and one is made bound to it (machines:create -E <slug>) or moved there (machines:move <name> --to <slug>)."],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:"refused: machines, databases and sites are the project's, and no environment opens with copies of them"}},scope:"environment",async run(e){let t=e.args[0];if(e.flags["with-cloud"]===!0)throw zo(t);let n=await ak(e),s=e.flags.from,a=s===void 0?[]:(await Pe(e.studio)).filter(d=>d.project_id===n.project_id),i=s===void 0?void 0:a.find(d=>d.slug===s||d.ref===s);if(s!==void 0&&!i)throw new f("no_such_environment",`the project has no environment ${JSON.stringify(s)}`,{hint:`its environments: ${a.map(d=>d.slug).join(", ")}`});let r=await e.studio.post(`/projects/${n.project_id}/environments`,{name:e.flags.name??t,slug:t}),o=()=>{e.out.line(`Made ${q(n.project_name)} \u203A ${r.environment.slug} (ref ${r.environment.ref}).`),r.keys&&(e.out.line(`publishable key: ${r.keys.publishable.key}`),e.out.line(`secret key (shown this once): ${r.keys.secret.key}`))};if(!i){e.out.result(r,o);return}e.out.json||o();let l=ie({...i,ref:r.environment.ref,slug:r.environment.slug,name:r.environment.name});return e.out.json||e.out.line(),Wo(e,xn,ie(i),l,{made:r})}},kc={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 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.","Moved, they keep their data and answer throughout, and their old addresses keep working: the environment is deleted once each is up where it moved. The passwords this computer holds for its databases go with them."],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, databases and sites to this environment of the project (its slug) before it is deleted"}},scope:"environment",async run(e){let t=await Yt(e),n=t.find(d=>d.slug===e.args[0]||d.ref===e.args[0]);if(!n)throw new f("no_such_environment",`the project has no environment ${JSON.stringify(e.args[0])}`);let s=ie(n);if(e.out.note(`${N(s)}: delete the environment, its users, data, machines and databases`),!e.global.yes){if(!e.interactive)throw new f("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 f("cancelled","nothing was deleted")}let a=e.flags["delete-bound"]===!0,i=typeof e.flags["move-to"]=="string"?e.flags["move-to"]:void 0;if(a&&i!==void 0)throw m("--delete-bound or --move-to: what is bound to it is deleted with it, or moved");let r=a?"?delete_bound=true":i!==void 0?`?move_to=${encodeURIComponent(i)}`:"",o=async()=>{let d=e.io.now()+6e5;for(;;)try{return await e.studio.request("DELETE",`/environments/${n.ref}${r}`)}catch(p){if(!(p instanceof E)||p.code!=="machines_still_moving"||e.io.now()>d)throw p;e.out.note(`still moving to ${decodeURIComponent(r.slice(9))}; asking again`),await e.io.sleep(5e3)}};try{await o()}catch(d){if(!(d instanceof E)||d.code!=="environment_has_resources"||r!=="")throw d;let p=d.body?.data??{},u=[p.machines?.length?`machines ${p.machines.join(", ")}`:"",p.databases?.length?`databases ${p.databases.join(", ")}`:"",p.sites?.length?`sites ${p.sites.join(", ")}`:""].filter(w=>w!=="").join("; "),g=t.filter(w=>w.ref!==n.ref).map(w=>w.slug);if(!e.interactive||e.global.yes)throw new f("environment_has_resources",`bound to ${n.slug}: ${u}`,{hint:`delete them with it (--delete-bound), or move them first (--move-to ${g[0]??"<env>"})`});e.out.line(`Bound to ${n.slug}: ${u}.`);let y=(await e.io.prompt(`Delete them with it (delete), move them to another environment (${g.join(", ")}), or keep it (keep)? `)).trim();if(y==="delete")r="?delete_bound=true";else if(g.includes(y))r=`?move_to=${encodeURIComponent(y)}`;else throw new f("cancelled","nothing was deleted");await o()}if(r.startsWith("?move_to=")){let d=t.find(p=>p.slug===decodeURIComponent(r.slice(9))||p.ref===decodeURIComponent(r.slice(9)));d&&await e.state.moveDatabasePasswords(n.ref,d.ref)}let l=await e.state.targetFor(e.io.cwd);l?.target.env_ref===n.ref&&await e.state.clearTarget(l.dir),e.out.result({deleted:n.ref},()=>e.out.line(`Deleted ${N(s)}.`))}},Sc={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 b(e);else{let n=await Pe(e.studio);t=ie(ik(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 ${N(t)}.`))}},$c={name:"status",summary:"the environment this directory acts on: who you are there, the machines and databases bound to it",scope:"environment",async run(e){let t=await b(e),n=await e.studio.get(`/environments/${t.env_ref}`),s=p=>_e(e.studio,t.env_ref,"GET",p).then(u=>u.body,u=>u instanceof E?null:Promise.reject(u)),a=`limit=100&environment=${encodeURIComponent(t.env_ref)}`,[i,r]=await Promise.all([s(`/machines?${a}`),s(`/databases?${a}`)]),o=i?.machines??[],l=r?.databases??[],d=await e.state.targetFor(e.io.cwd);e.out.result({target:t,role:n.role,address:`https://${t.env_ref}.${e.cloud.domain}`,machines:o,databases:l,chosen_for:d?.dir??null},()=>{e.out.line(N(t)),e.out.line(` ref ${t.env_ref} \xB7 your role ${n.role} \xB7 https://${t.env_ref}.${e.cloud.domain}`),d&&d.target.env_ref===t.env_ref&&e.out.line(` chosen for ${d.dir}`),e.out.line(` machines: ${o.length===0?"none":o.map(p=>`${p.name} (${p.size}, ${p.state})`).join(", ")}`),e.out.line(` databases: ${l.length===0?"none":l.map(p=>`${p.name} (${p.size}, ${p.state})`).join(", ")}`)})}},Pc={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 b(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))}},Ac={name:"keys:list",summary:"the environment's API keys (never their values)",scope:"environment",async run(e){let t=await b(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}]))}},Rc={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 m("--kind is publishable or secret");let n=await b(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)})}},Tc={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 b(e),n=`/environments/${x("the environment's ref",t.env_ref)}/keys/${x("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 ak(e){return(await Yt(e))[0]}async function Yt(e){if(Jt(e.io))return[await la(e)];let t=await Pe(e.studio);if(e.global.project!==void 0)return un(t,e.global.project);let n=await e.state.targetFor(e.io.cwd);if(!n)throw new f("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 f("no_such_project",`the project chosen here (${n.target.project_name}) is not among yours any more`,{hint:"palbase use another"});return s}function ik(e,t){let n=t.split("/");if(n.length>3||n.some(i=>i===""))throw m(`${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 i of s){let r;try{r=un(e,i.project)}catch(o){a=o;continue}if(i.env!==void 0){let o=r.find(l=>l.slug===i.env||l.ref===i.env);if(o)return o;a=new f("no_such_environment",`${r[0].project_name} has no environment ${JSON.stringify(i.env)}`,{hint:`its environments: ${r.map(l=>l.slug).join(", ")}`});continue}if(r.length===1)return r[0];throw new f("which_environment",`${r[0].project_name} has more than one environment`,{hint:`name one: ${r.map(o=>`${o.project_name}/${o.slug}`).join(", ")}`})}throw a}import{mkdtemp as rk,rm as ok}from"node:fs/promises";import{tmpdir as lk}from"node:os";import{extname as dk,join as Ec}from"node:path";var Jo="Named by none, it is the only database of the environment chosen for this directory or named by -E \u2014 never one bound elsewhere \u2014 else, when neither says, the project's only one.";async function bn(e,t){let n=await pn(e),s=n.t,a=t??await Mc(e,s,hi(n,"/databases?limit=100"),n.by==="fallback"?"the project":`the environment ${s.env_slug}`),i=await Oc(e,s,a),r=()=>On(async o=>{let{body:l}=await _e(e.studio,s.env_ref,"GET",`/databases?limit=100${o?`&cursor=${encodeURIComponent(o)}`:""}`);return{items:l.databases,next:l.next_cursor}});return await Mn(e,n,i.d,r,`the database ${i.d.name}`),i}async function Oc(e,t,n){let{body:s}=await _e(e.studio,t.env_ref,"GET",`/databases/${x("the database's name",n)}`);return{t:await Ln(e,t,s.environment,`the database ${s.name}`),d:s}}async function Mc(e,t,n,s){let{body:a}=await _e(e.studio,t.env_ref,"GET",n);if(a.databases.length===1)return a.databases[0].name;throw a.databases.length===0?new f("no_database",`${s} has no database`,{hint:"palbase databases:create opens one"}):m("which database? name it",`${s}'s databases: ${a.databases.map(i=>i.name).join(", ")}`)}async function Xt(e,t,n,s,a){let{body:i}=await _e(e.studio,t.env_ref,"GET",`/databases/${x("the database's name",n)}/credentials`),r=(await e.state.databasePasswords(t.env_ref,n))[s];if(!r)throw new f("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"?i.owner:i.app,l=new URL(a?o.pooled_url:o.url);return l.password="",{url:l.toString(),password:r,role:s}}function pk(e){let t=new URL(e.url);return t.password=encodeURIComponent(e.password),t.toString()}var Ic={type:"string",value:"role",description:"owner (migrations, dumps) or app (what the machines use); default owner"};function Lc(e){let t=e.flags.role??"owner";if(t!=="owner"&&t!=="app")throw m("--role is owner or app");return t}var Dc={PGSSLROOTCERT:"system"};async function Nn(e,t,n,s,a=!1){let i=await e.io.run(t,n,{env:{PGPASSWORD:s.password,...Dc,PGAPPNAME:"palbase-cli"},inherit:a});if(i.code===127)throw new f("missing_tool",`${t} is not installed here`,{hint:"install the Postgres 18 client tools (brew install postgresql@18, apt install postgresql-client-18)"});return i}var xc={name:"db:url",summary:"a project database's connection address, for any tool (Prisma, Drizzle, pg_dump, a GUI)",usage:"[name] [--role owner|app] [--pooled] [--with-password]",details:[te("database"),Jo,"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:Ic,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,d:n}=await bn(e,e.args[0]),s=n.name,a=await Xt(e,t,s,Lc(e),e.flags.pooled===!0),i=e.flags["with-password"]===!0?pk(a):a.url;e.out.result({database:s,role:a.role,url:i,libpq_env:Dc},()=>{e.io.stdout(`${i}
|
|
33
33
|
`),e.out.note("psql, pg_dump and other libpq tools: PGSSLROOTCERT=system (Postgres 16+), or they cannot check the certificate")})}},Nc={name:"db:shell",summary:"psql on a database of the project (it wakes if asleep); -c runs one statement and ends",usage:"[name] [--role owner|app] [--command <sql>]",details:[te("database"),Jo],args:{min:0,max:1},flags:{role:Ic,command:{type:"string",short:"c",value:"sql",description:"run this and end"}},scope:"environment",async run(e){let{t,d:n}=await bn(e,e.args[0]),s=n.name,a=await Xt(e,t,s,Lc(e),!1),i=e.flags.command;if(i!==void 0){let o=await Nn(e,"psql",[a.url,"-v","ON_ERROR_STOP=1","-X","-c",i],a);if(o.stdout&&e.io.stdout(o.stdout),o.code!==0)throw new f("psql_failed",o.stderr.trim()||`psql ended with ${o.code}`);return}if(!e.interactive)throw m("db:shell with no person at the terminal needs --command <sql>");return e.out.note(`${N(t)} \u203A ${s} as ${a.role}`),(await Nn(e,"psql",[a.url],a,!0)).code}},qc={name:"db:dump",summary:"a copy of a database of the project (pg_dump's custom format), as its owner",usage:"[name] [--file <path>] [--schema-only]",details:[te("database"),Jo],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,d:n}=await bn(e,e.args[0]),s=n.name,a=await Xt(e,t,s,"owner",!1),i=e.flags.file??`${s}-${new Date(e.io.now()).toISOString().replaceAll(":","-").slice(0,19)}.dump`,r=await Nn(e,"pg_dump",["--format=custom","--no-owner","--no-acl",...e.flags["schema-only"]===!0?["--schema-only"]:[],"--file",i,a.url],a);if(r.code!==0)throw new f("pg_dump_failed",r.stderr.trim()||`pg_dump ended with ${r.code}`);e.out.result({database:s,file:i},()=>e.out.line(`Wrote ${i}.`))}},Kc={name:"db:restore",summary:"load a dump into a database of the project, 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).",te("database"),"Named by no --db, it is the only database of the environment chosen for this directory or named by -E, else, when neither says, the project's only one."],args:{min:1,max:1},flags:{db:{type:"string",value:"name",description:"the database (default: the environment's only one \u2014 chosen here or -E's \u2014 else the project's)"},clean:{type:"boolean",description:"drop what the dump makes before making it again"}},scope:"environment",async run(e){let{t,d:n}=await bn(e,e.flags.db),s=n.name,a=e.args[0];await v(e,t,`load ${a} into the database ${s}`);let i=await Xt(e,t,s,"owner",!1);await Gc(e,i,a,e.flags.clean===!0),e.out.result({database:s,loaded:a},()=>e.out.line(`Loaded ${a} into ${s}.`))}};async function Gc(e,t,n,s){let a=dk(n).toLowerCase()===".sql",i=a?await Nn(e,"psql",[t.url,"-v","ON_ERROR_STOP=1","-X","--single-transaction","-f",n],t):await Nn(e,"pg_restore",["--no-owner","--no-acl","--exit-on-error","--single-transaction",...s?["--clean","--if-exists"]:[],"--dbname",t.url,n],t);if(i.code!==0)throw new f("restore_failed",i.stderr.trim()||`${a?"psql":"pg_restore"} ended with ${i.code}`)}var Cc="\u2022\u2022\u2022";async function uk(e,t,n){let s=async l=>{let d=await Nn(e,"psql",[n.url,"-v","ON_ERROR_STOP=1","-X","-At","-F"," ","-c",l],n);if(d.code!==0)throw new f("redact_failed",d.stderr.trim()||`psql ended with ${d.code}`);return d.stdout.split(`
|
|
34
|
-
`).filter(p=>p!=="").map(p=>p.split(" "))},a=l=>`"${l.replace(/"/g,'""')}"`,i=l=>`'${l.replace(/'/g,"''")}'`,r=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(r.length>0){let l=await s(r.map(([d,p,u])=>`SELECT ${i(`${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 g=r.find(P=>P[0]===d&&P[1]===p&&P[2]===u)?.[3]==="t",y=d==="public"?`${p}.${u}`:`${d}.${p}.${u}`,{value:w}=await h(e,t,"POST","/secrets/fields/placeholder",{address:y}),[[_]]=await s(`WITH done AS (UPDATE ${a(d)}.${a(p)} SET ${a(u)} = ${i(w)}${g?`, ${a(`${u}_lookup`)} = NULL`:""} WHERE ${a(u)} LIKE 'pbe1.%' RETURNING 1) SELECT count(*) FROM done`);o.push({address:y,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}async function jc(e,t,n){let s=n??await Mc(e,t,`/databases?limit=100&environment=${encodeURIComponent(t.env_ref)}`,t.env_slug),{t:a,d:i}=await Oc(e,t,s);if(a.env_ref!==t.env_ref)throw new f("database_elsewhere",`the database ${i.name} is bound to ${a.env_slug}, not ${t.env_slug}`,{hint:`name ${a.env_slug} as the environment it is copied from or into`});return i.name}var Uc={name:"db:copy",summary:"copy the data of a database one environment of the project keeps into a database another keeps",usage:"--from <env> --to <env> [--db <name>] [--to-db <name>]",details:["A database is the project's, bound to one environment: --db is one --from keeps, --to-db one --to keeps \u2014 each its environment's only one when it is not named.","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 ${Cc}, 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 database --from keeps (default: its only one)"},"to-db":{type:"string",value:"name",description:"the database --to keeps (default: its only one)"}},scope:"environment",async run(e){let t=e.flags.from,n=e.flags.to;if(!t||!n)throw m("db:copy needs --from <env> and --to <env>");if(t===n)throw m("--from and --to are two environments");let s=await Yt(e),a=s.find(w=>w.slug===t),i=s.find(w=>w.slug===n);if(!a||!i)throw new f("no_such_environment",`the project has no environment ${JSON.stringify(a?n:t)}`);let r=ie(a),o=ie(i),l=await jc(e,r,e.flags.db),d=await jc(e,o,e.flags["to-db"]);await v(e,o,`overwrite the database ${d} with ${r.env_slug}'s ${l}`);let p=await Xt(e,r,l,"owner",!1),u=await Xt(e,o,d,"owner",!1),g=await rk(Ec(lk(),"palbase-copy-"));try{let w=Ec(g,"copy.dump"),_=await Nn(e,"pg_dump",["--format=custom","--no-owner","--no-acl","--file",w,p.url],p);if(_.code!==0)throw new f("pg_dump_failed",_.stderr.trim()||`pg_dump ended with ${_.code}`);await Gc(e,u,w,!0)}finally{await ok(g,{recursive:!0,force:!0})}let y=await uk(e,o,u);e.out.result({from:{env:r.env_slug,database:l},to:{env:o.env_slug,database:d},redacted:y},()=>{e.out.line(`Copied ${r.env_slug}/${l} into ${o.env_slug}/${d}.`);for(let w of y)e.out.line(` ${w.address}: ${w.rows} encrypted value(s) copied as ${Cc}`)})}};import{createReadStream as ck,openAsBlob as hk}from"node:fs";import{lstat as mk,readdir as gk,realpath as Bc,stat as fk}from"node:fs/promises";import{createHash as yk}from"node:crypto";import{join as bk,relative as zc,resolve as wk,sep as Wc}from"node:path";var Vo=2e4,vk=25<<20,_k=1<<30,kk=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/,Sk=6;function ji(e){return`${e.machine} answers ${e.paths.length===0?"every path":e.paths.join(", ")}`}var _a={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 Sa(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 Ci(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 Ho(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>]`,details:[te(e)],flags:s,scope:"environment",async run(l){let{t:d,path:p}=await n(l),{domains:u}=await h(l,d,"GET",`${p}/domains`);l.out.result({domains:u},()=>{u.length===0&&l.out.line(`No domain yet: palbase ${t}:domains:add <host> adds one.`);for(let g of u)Ci(l,g)})}},i={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 the environment's the ${e} is bound to (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.",te(e)],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 m("--primary is www or apex");if(l.flags.only===!0&&l.flags.primary!==void 0)throw m("--only adds the domain alone: no --primary");let u=Fc(l.flags["redirect-status"]),{t:g,path:y}=await n(l),w=`www.${d}`,_=l.flags.only!==!0&&!d.startsWith("www.");await v(l,g,_?`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 P=await h(l,g,"POST",`${y}/domains`,{host:d});if(!_||!P.apex){l.out.result(P,()=>Ci(l,P));return}let S=T=>({redirect_to:T,...u!==void 0?{redirect_status:u}:{}}),$;p==="www"?($=await $k(l,g,y,{host:w}),P=await h(l,g,"PATCH",`${y}/domains/${x("the domain",d)}`,S(w))):$=await Pk(l,g,y,w,S(d));let R=p==="www"?[$,P]:[P,$];l.out.result({domains:R},()=>R.forEach(T=>Ci(l,T)))}},r={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.",te(e)],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 m("name where it redirects (--to <host>), or --none");let u=Fc(l.flags.status);if(l.flags.none===!0&&u!==void 0)throw m("--status goes with --to");let{t:g,path:y}=await n(l);await v(l,g,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,g,"PATCH",`${y}/domains/${x("the domain",d)}`,w);l.out.result(_,()=>Ci(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>]`,details:[te(e)],args:{min:1,max:1},flags:s,scope:"environment",async run(l){let{t:d,path:p}=await n(l);await v(l,d,`remove the domain ${l.args[0]}`),await h(l,d,"DELETE",`${p}/domains/${x("the domain",l.args[0].toLowerCase())}`),l.out.result({removed:l.args[0]},()=>l.out.line(`${l.args[0]} answers no more.`))}};return[a,i,r,o]}function Fc(e){if(e===void 0)return;let t=Number(e);if(![301,302,307,308].includes(t))throw m("a redirect's status is 301, 302, 307 or 308");return t}async function $k(e,t,n,s){try{return await h(e,t,"POST",`${n}/domains`,s)}catch(a){if(!(a instanceof E&&a.code==="domain_exists"))throw a;let{domains:i}=await h(e,t,"GET",`${n}/domains`),r=i.find(o=>o.host===s.host);if(!r)throw a;return r}}async function Pk(e,t,n,s,a){try{return await h(e,t,"POST",`${n}/domains`,{host:s,...a})}catch(i){if(!(i instanceof E&&i.code==="domain_exists"))throw i;return await h(e,t,"PATCH",`${n}/domains/${x("the domain",s)}`,a)}}function Yo(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.",te(e)],args:{min:1,max:1},flags:s,scope:"environment",async run(a){let i=Number(a.args[0].replace(/^#/,""));if(!Number.isInteger(i)||i<=0)throw m("the pull request is its number: 12, or #12");let{t:r,path:o}=await n(a),{previews:l}=await h(a,r,"GET",`${o}/previews`),d=l.find(u=>u.pull_request===i&&u.state!=="closed");if(!d)throw new f("preview_not_found",`no open preview of pull request #${i}`,{hint:`palbase ${t}:previews lists them`});if(d.state!=="authorization_required")throw new f("preview_not_waiting",`#${i}'s preview waits for no authorization: it is ${d.state}`);await v(a,r,`build pull request #${i} at ${d.commit.slice(0,7)}, from a fork`,`Pull request #${i} 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,r,"POST",`${o}/previews/${i}/authorize`,{commit:d.commit});a.out.result(p,()=>a.out.line(`#${i} authorized at ${d.commit.slice(0,7)}: its preview is being built (palbase ${t}:previews).`))}}}function Xo(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})`:""}`)}}var Ak=/^[A-Za-z0-9][A-Za-z0-9 ._-]{0,63}$/;function Zo(e,t,n,s){let a={name:`${t}:hooks`,summary:`a ${e}'s deploy hooks: what each is called, and when it last built \u2014 never their URLs`,usage:`[--${e} <name>]`,details:[te(e)],flags:s,scope:"environment",async run(o){let{t:l,path:d}=await n(o),{hooks:p}=await h(o,l,"GET",`${d}/hooks`);o.out.result({hooks:p},()=>{p.length===0&&o.out.line(`No deploy hook: palbase ${t}:hooks:create <name> makes one.`),o.out.table(p,[{header:"hook",value:u=>u.id},{header:"name",value:u=>u.name},{header:"created",value:u=>u.created_at},{header:"last used",value:u=>u.last_used_at??"never"}])})}},i={name:`${t}:hooks:create`,summary:`make a deploy hook: a URL that builds the ${e}'s branch head when it is POSTed to (a CMS's publish, a schedule)`,usage:`<name> [--${e} <name>]`,details:[`Its URL is printed this once: anyone who holds it builds the ${e}, so keep it as a secret, and delete the hook if it leaks. A build it asks for is held to the project's builds as a push's is.`,`A ${e} has 5 at most.`,te(e)],args:{min:1,max:1},flags:s,scope:"environment",async run(o){let l=o.args[0];if(!Ak.test(l))throw m(`${JSON.stringify(l)} is not a hook's name: letters, digits, spaces, dots, dashes and underscores, 64 at most`);let{t:d,path:p}=await n(o);await v(o,d,`make a deploy hook ${l}: its URL builds the ${e} when it is POSTed to`);let u=await h(o,d,"POST",`${p}/hooks`,{name:l});o.out.result(u,()=>{o.out.line(`Made the deploy hook ${u.name} (${u.id}). POST to it to build:`),o.out.line(` ${u.url??""}`),o.out.line(`It is shown this once. Keep it secret: anyone who holds it builds the ${e} (palbase ${t}:hooks:delete ${u.id} takes it away).`)})}},r={name:`${t}:hooks:delete`,summary:"delete a deploy hook: its URL builds nothing from now on",usage:`<hook id> [--${e} <name>]`,details:[te(e)],args:{min:1,max:1},flags:s,scope:"environment",async run(o){let{t:l,path:d}=await n(o);await v(o,l,`delete the deploy hook ${o.args[0]}`),await h(o,l,"DELETE",`${d}/hooks/${x("the hook's id",o.args[0])}`),o.out.result({deleted:o.args[0]},()=>o.out.line(`Deleted the deploy hook ${o.args[0]}: its URL builds nothing from now on.`))}};return[a,i,r]}function Qo(e,t,n,s){return{name:`${t}:builds:cancel`,summary:`cancel a ${e}'s build that has not ended: its run is stopped, and the ${e} serves what it served`,usage:`<build> [--${e} <name>]`,details:["A push, a deploy or a deploy hook builds again.",te(e)],args:{min:1,max:1},flags:s,scope:"environment",async run(a){let{t:i,path:r}=await n(a),o=a.args[0];await v(a,i,`cancel the build ${o}`);let l;try{l=await h(a,i,"POST",`${r}/builds/${x("the build",o)}/cancel`)}catch(d){throw d instanceof E&&d.code==="build_not_cancellable"?new f("build_not_cancellable",d.message,{hint:`palbase ${t}:builds says where each build is`}):d}a.out.result(l,()=>a.out.line(`Cancelled the build ${l.id} (${l.commit.slice(0,7)}): the ${e} serves what it served.`))}}}function de(e){if(!kk.test(e))throw m(`${JSON.stringify(e)} is not a site's name: lowercase letters, digits and dashes, starting with a letter`);return x("the site",e)}var Hc={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 Yc(e,t){let n={};if(e.flags.repo!==void 0||e.flags.branch!==void 0||t){let i=await hs(e.io,e.io.cwd),r=e.flags.repo??i?.repository,o=e.flags.branch??i?.branch;if(!r)throw m("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!o)throw m("which branch? none is checked out here","pass --branch <branch>");n.source={repository:r,branch:o,path:e.flags.path??(e.flags.repo===void 0?i?.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 i={};for(let r of a){let o=r.indexOf("=");if(o<=0)throw m(`a setting is K=V, not ${JSON.stringify(r)}`);i[r.slice(0,o)]=r.slice(o+1)}s.env=i}return Object.keys(s).length>0&&(n.build=s),n}function ka(e){return e<1024?`${e} B`:e<1<<20?`${(e/1024).toFixed(1)} KiB`:`${(e/(1<<20)).toFixed(1)} MiB`}async function Rk(e){let t=await Bc(e),n=[],s=async i=>{let r=await gk(i,{withFileTypes:!0});for(let o of r){if(o.name==="node_modules"||o.name.startsWith(".")&&!(o.name===".well-known"&&i===t))continue;let l=bk(i,o.name),d=await mk(l),p=l;if(d.isSymbolicLink()&&(p=await Bc(l),p!==t&&!p.startsWith(t+Wc)))throw new f("unsafe_path",`${zc(t,l)} links outside ${e}`);let u=d.isSymbolicLink()?await fk(p):d;if(u.isDirectory()){await s(l);continue}if(!u.isFile())continue;let g="/"+zc(t,l).split(Wc).join("/");if(/[\u0000-\u001f\u007f?#\\]/.test(g))throw new f("invalid_path",`${g} has a character a site's path cannot carry (?, #, \\ or a control character): rename it`);if(g.length>1024)throw new f("invalid_path",`${g.slice(0,80)}\u2026 is longer than a site's path may be (1024 bytes)`);if(u.size>vk)throw new f("file_too_large",`${g} is ${ka(u.size)}: a site's file is 25 MiB at most (keep large media in storage)`);if(n.push({path:g,file:p,size:u.size,digest:""}),n.length>Vo)throw new f("too_many_files",`${e} holds more than ${Vo} files: a site holds ${Vo} at most`)}};await s(t),n.sort((i,r)=>i.path<r.path?-1:i.path>r.path?1:0);let a=n.reduce((i,r)=>i+r.size,0);if(a>_k)throw new f("release_too_large",`${e} holds ${ka(a)}: a release is 1 GiB at most`);for(let i of n)i.digest=await Tk(i.file);return n}function Tk(e){return new Promise((t,n)=>{let s=yk("sha256");ck(e).on("data",a=>s.update(a)).on("error",n).on("end",()=>t(s.digest("hex")))})}function Ek(e){let t=e.filter(n=>/\.html?$/i.test(n.path));return t.length===1&&t[0].path==="/index.html"}async function Ck(e,t,n){try{return await h(e,t,"GET",`/sites/${de(n)}`)}catch(s){if(s instanceof E&&s.code==="site_not_found")return null;throw s}}async function rt(e,t,n=!0){let s=await pn(e),a=s.t,i=await h(e,a,"GET",`/sites/${de(t)}`);return await Mn(e,s,i,()=>Zc(e,a),`the site ${i.name}`),Xc(s,i,n),{t:await Ln(e,a,i.environment,`the site ${i.name}`),site:i}}function Xc(e,t,n){if(!(n||e.by!=="here"||!t.environment||t.environment.ref===e.t.env_ref))throw new f("site_elsewhere",`the environment ${e.t.env_slug} has no site ${t.name}: the project's ${t.name} is bound to ${t.environment.name||t.environment.ref}`,{hint:"name the site with --site <name> (palbase hosting:sites:list), or act where it is bound with -E"})}async function Zc(e,t){return(await h(e,t,"GET","/sites")).sites}var ot={site:{type:"string",value:"name",description:"the site (default: web \u2014 that of the environment chosen here or -E's, refused when it is bound elsewhere; with neither, the project's)"}},kt=e=>e.flags.site??"web",Oi=async e=>{let{t,site:n}=await rt(e,kt(e),e.flags.site!==void 0);return{t,path:`/sites/${de(n.name)}`}};async function Jc(e,t,n,s,a,i){let r=0,o=0,l=async()=>{for(;o<a.length;){let d=a[o++],p=i.get(d);if(!p)throw new f("internal",`the release asked for ${d}, which no file here is`);let u=await hk(p.file);await h(e,t,"PUT",`/sites/${de(n)}/releases/${x("the release",s)}/files/${d}`,new Wt(u,"application/octet-stream")),r+=p.size}};return await Promise.all(Array.from({length:Math.min(Sk,a.length)},l)),r}async function Vc(e,t,n,s){await h(e,t,"PATCH",`/sites/${de(n)}`,{spa:s}),e.out.note(` ${n} is ${s?"a single-page app now: every route is its index.html":"no single-page app now: a path no file answers is 404"}`)}var jk={name:"hosting:deploy",summary:"deploy a folder as a static site of the project: only the files that changed are sent, and the site serves them at once",usage:"<folder> [--site <name>] [-E <env>] [--spa | --no-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 answers a path no file answers with /index.html (a single-page app), --no-spa with 404: the site is changed to it when it is not that already.","A folder of one page, index.html, is taken for a single-page app when the site is opened.",te("site"),`One its first deploy opens is the project's too. ${Dn}`],args:{min:1,max:1},flags:{site:{type:"string",value:"name",description:"the site (default: web \u2014 that of the environment chosen here or -E's, refused when it is bound elsewhere; with neither, the project's; it answers at the ref of the environment it is bound to)"},spa:{type:"boolean",description:"a single-page app: answer every path no file answers with /index.html"},"no-spa":{type:"boolean",description:"not a single-page app: a path no file answers is 404"}},scope:"environment",async run(e){if(e.flags.spa===!0&&e.flags["no-spa"]===!0)throw m("--spa or --no-spa, not both");let t=e.flags.spa===!0?!0:e.flags["no-spa"]===!0?!1:void 0,n=kt(e);de(n);let s=wk(e.io.cwd,e.args[0]),a=await Rk(s).catch($=>{throw $ instanceof f?$:new f("no_folder",`${e.args[0]}: ${$ instanceof Error?$.message:String($)}`)});if(a.length===0)throw new f("empty_folder",`${e.args[0]} holds no file to serve`);a.some($=>$.path==="/index.html")||e.out.note(` ${e.args[0]} has no index.html: the site's root answers 404.`);let i=a.reduce(($,R)=>$+R.size,0),r=await pn(e),o=r.t,l=await Ck(e,o,n);l&&(await Mn(e,r,l,()=>Zc(e,o),`the site ${n}`),Xc(r,l,e.flags.site!==void 0));let d=l?await Ln(e,o,l.environment,`the site ${n}`):await In(e);if(await v(e,d,`deploy ${a.length} files (${ka(i)}) to the site ${n}`),!l){let $=t??Ek(a);l=await h(e,d,"POST","/sites",{name:n,spa:$}),e.out.note(` opened the site ${n}${$?" (a single-page app: every route is its index.html)":""}`)}let p=t!==void 0&&l.spa!==t;p&&t&&await Vc(e,d,n,!0);let u={},g=new Map;for(let $ of a)u[$.path]=$.digest,g.set($.digest,$);let y=await h(e,d,"POST",`/sites/${de(n)}/releases`,{files:u}),w=y.missing??[];e.out.note(` release #${y.number}: ${a.length} files, ${w.length} to send${w.length<g.size?` (${g.size-w.length} kept from before)`:""}`);let _=await Jc(e,d,n,y.id,w,g),P;for(let $=0;$<3&&!P;$++)try{P=await h(e,d,"POST",`/sites/${de(n)}/releases/${x("the release",y.id)}/finish`)}catch(R){let T=R instanceof E&&R.code==="files_missing"?R.body?.missing??[]:[];if(T.length===0)throw R;_+=await Jc(e,d,n,y.id,T,g)}if(!P)throw new f("release_unfinished",`the release #${y.number} could not be finished`,{hint:"deploy again"});p&&!t&&await Vc(e,d,n,!1),l=await h(e,d,"GET",`/sites/${de(n)}`);let S={site:l.name,url:l.url,urls:l.urls,release:P,sent_bytes:_};e.out.result(S,()=>{e.out.line(`Deployed release #${P.number} of ${l.name} (${a.length} files, ${ka(_)} sent).`);for(let $ of l.urls)e.out.line(` ${$}`)})}},Ok={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",usage:"[-E <env>]",details:["A project's sites are the project's, each bound to one of its environments and built with its settings and secrets. The list is every environment's you reach; -E lists that environment's alone, as an environment's own token does."],scope:"environment",async run(e){let t=await jn(e),[{sites:n},s]=await Promise.all([h(e,t,"GET",mi(e,t,"/sites")),ms(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 i=a.taken_down?`taken down: ${a.taken_down.reason}`:a.release?`release #${a.release.number}`:"nothing deployed",r=a.previews_protected===void 0?"":a.previews_protected?" previews protected":" previews public";e.out.line(`${a.name} ${Ft(s,a.environment)}${a.moving_to?` \u2192 ${Ft(s,a.moving_to)}`:""} ${a.url} ${i}${a.spa?" (single-page app)":""}${a.server?` server ${ji(a.server)}`:""}${r}`)}})}},Qc={server:{type:"string",value:"machine",description:"the environment's machine that answers what the site's files do not: its API (--server-path), or every path of a web app that runs on a server (Next.js, Nuxt, SvelteKit) \u2014 at the site's addresses, through its CDN"},"server-path":{type:"string",multiple:!0,value:"prefix",description:"a path the server answers, ending in / (repeat it): /api/; none, and it answers every path"},"protect-previews":{type:"boolean",description:"its previews \u2014 its pull requests' and its branches' \u2014 are its team's alone: a visitor signs in with Studio, or holds a share link (hosting:previews:link); the default"},"no-protect-previews":{type:"boolean",description:"anyone with a preview's address opens it"}};async function eh(e,t,n){let s=e.flags.server,a=e.flags["server-path"];if(e.flags["no-server"]===!0){if(s!==void 0||a!==void 0)throw m("--no-server takes the server away: no --server or --server-path with it");t.server={machine:"",paths:[]}}else if(s!==void 0||a!==void 0){for(let r of a??[])if(!r.startsWith("/")||!r.endsWith("/"))throw m(`a server's path is a prefix of the site's paths ending in /, as /api/: not ${JSON.stringify(r)}`);let i=s;if(i===void 0&&(i=n?(await n())?.machine:void 0,!i))throw m("--server-path goes with --server <machine>",n?"the site has no server yet":void 0);t.server={machine:i,paths:a??[]}}e.flags["protect-previews"]===!0&&(t.previews_protected=!0),e.flags["no-protect-previews"]===!0&&(t.previews_protected=!1)}var Mk={name:"hosting:sites:create",summary:"open a static site of the project \u2014 built from GitHub on every push with --repo/--branch, or deployed from a folder (hosting:deploy opens one too)",usage:"[name] [-E <env>] [--spa] [--repo <owner/name> --branch <branch> --path <dir>] [--build-command \u2026] [--output <dir>] [--build-env K=V]\u2026 [--previews [--preview-forks]] [--server <machine> [--server-path <prefix>]\u2026] [--no-protect-previews]",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.","With --server, a machine of the environment answers what its files do not \u2014 the paths --server-path names, or every path: a site with no files whose server is a web app's machine is that app's address and CDN.","Its previews are its team's alone unless --no-protect-previews: hosting:previews:link shares them.",`${Dn} It is built with that environment's settings and secrets.`,"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"},...Hc,previews:_a.previews,"preview-forks":_a["preview-forks"],...Qc},scope:"environment",async run(e){let t=await In(e),n=e.args[0]??"web";de(n);let{source:s,build:a}=await Yc(e,!1),i={};Sa(e,i),await eh(e,i);let r=i.server;await v(e,t,`open the site ${n}${s?`, built from ${s.repository}@${s.branch}`:""}${r?`, ${ji(r)}`:""}`);let o=await h(e,t,"POST","/sites",{name:n,spa:e.flags.spa===!0,...s?{source:s}:{},...a?{build:a}:{},...i});e.out.result(o,()=>e.out.line(o.source?`Opened ${o.name}: ${o.url} \u2014 its first build is on its way (palbase hosting:builds --site ${o.name}).`:o.server?`Opened ${o.name}: ${o.url} \u2014 ${ji(o.server)}${o.server.paths.length>0?` (nothing else deployed yet: palbase hosting:deploy <folder> --site ${o.name})`:""}.`:`Opened ${o.name}: ${o.url} (nothing deployed yet: palbase hosting:deploy <folder> --site ${o.name}).`))}},Ik={name:"hosting:sites:update",summary:"change a site of the project, where it is bound: whether it is a single-page app, where it is built from, what its build runs, its server, who opens its previews",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] [--server <machine>] [--server-path <prefix>]\u2026 [--no-server] [--protect-previews | --no-protect-previews]",details:[te("site")],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"},...Hc,"no-source":{type:"boolean",description:"build it from no repository any more: deploy folders alone"},..._a,...Qc,"no-server":{type:"boolean",description:"no machine answers for it any more: its files answer every path"}},scope:"environment",async run(e){let t=e.args[0];de(t);let n,s=()=>n??=rt(e,t),a={};e.flags.spa===!0&&(a.spa=!0),e.flags["no-spa"]===!0&&(a.spa=!1);let{source:i,build:r}=await Yc(e,!1);if(i&&(a.source=i),e.flags["no-source"]===!0&&(a.source={repository:""}),r&&(a.build=r),Sa(e,a),await eh(e,a,async()=>(await s()).site.server),Object.keys(a).length===0)throw m("nothing to change: give a flag","palbase help hosting:sites:update");let{t:o}=await s();await v(e,o,`change the site ${t}`);let l=await h(e,o,"PATCH",`/sites/${de(t)}`,a);e.out.result(l,()=>e.out.line(`${l.name}: ${l.url}${l.spa?" (single-page app)":""}${l.source?` \u2014 built from ${l.source.repository}@${l.source.branch}`:""}${l.server?` \u2014 ${ji(l.server)}`:""}${a.previews_protected===void 0?"":l.previews_protected?" \u2014 its previews are its team's alone":" \u2014 its previews open to anyone with their address"}`))}},Lk={name:"hosting:sites:move",summary:"bind a site to another environment of the project: its files go with it, and it answers throughout",usage:"<name> --to <env>",details:["Its files and releases are copied to the new environment while it serves on, then it is the new environment's, in a few seconds: its address names it (<name>-<its ref>), and the one it had keeps working, for good. Its domains of its own move with it and answer throughout.","Its pull requests' previews are closed: a new push opens them there. A build of it going on is stopped and built again there; its GitHub link is made in the new environment when it has none.","It moves out of the environment it is bound to; -E picks it where two environments hold its name.","It needs the admin role in both environments, and the new environment room for it: a site more, its files, its domains."],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=e.flags.to;if(typeof t!="string"||t==="")throw m("--to names the environment of the project it moves to");let{t:n,site:{name:s}}=await rt(e,e.args[0]),a=await da(e,n,t);await v(e,n,`move the site ${s} out of this environment, into ${a.slug}`),await v(e,ie(a),`move the site ${s} into this environment: it is built with this environment's settings and secrets`);let i=await h(e,n,"POST",`/sites/${de(s)}/move`,{environment:a.ref});e.out.result(i,()=>e.out.line(`${i.name} moves to ${a.slug} in a few seconds; ${i.url} keeps working (palbase hosting:sites:list -E ${a.slug}).`))}},Dk={name:"hosting:sites:delete",summary:"delete a site of the project, in the environment it is bound to: its addresses serve nothing from now on",usage:"<name>",details:[te("site")],args:{min:1,max:1},scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,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/${de(n)}`),e.out.result({deleted:n},()=>e.out.line(`Deleted ${n}.`))}},xk={name:"hosting:releases",summary:"a site's releases, newest first: the ten newest are kept to return to",usage:"[--site <name>]",details:[te("site")],flags:ot,scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,kt(e),e.flags.site!==void 0),{releases:s}=await h(e,t,"GET",`/sites/${de(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 ${ka(a.bytes)} ${a.created_at}${a.commit?` ${a.commit.slice(0,7)}`:""}`)})}},Nk={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>]",details:[te("site")],flags:{...ot,to:{type:"string",value:"release",description:"the release: its id, or its number (#3)"}},scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,kt(e),e.flags.site!==void 0),s=e.flags.to;if(s!==void 0&&/^#?\d+$/.test(s)){let i=Number(s.replace("#","")),{releases:r}=await h(e,t,"GET",`/sites/${de(n)}/releases`),o=r.find(l=>l.number===i);if(!o)throw new f("release_not_found",`${n} keeps no release #${i}`,{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/${de(n)}/rollback`,s?{release:s}:{});e.out.result(a,()=>e.out.line(`${a.name} serves release #${a.release?.number}: ${a.url}`))}},qk={name:"hosting:builds",summary:"a site's newest builds (a site built from GitHub), or one with its log",usage:"[build] [--site <name>] [--wait]",details:[te("site")],args:{min:0,max:1},flags:{...ot,wait:{type:"boolean",description:"with a build: follow it until it ends"}},scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,kt(e),e.flags.site!==void 0),s=e.args[0];if(s===void 0){let{builds:i}=await h(e,t,"GET",`/sites/${de(n)}/builds`);e.out.result({builds:i},()=>{i.length===0&&e.out.line(`${n} has no build: it is built from GitHub with hosting:sites:create --repo \u2026 --branch \u2026.`);for(let r of i)e.out.line(`${r.id} ${r.commit.slice(0,7)} ${r.state}${r.reason?`: ${r.reason}`:""}${Gk(r)} ${r.message}`)});return}let a=await h(e,t,"GET",`/sites/${de(n)}/builds/${x("the build",s)}`);for(let i=0;e.flags.wait===!0&&(a.state==="queued"||a.state==="building")&&i<900;i++)await e.io.sleep(2e3),a=await h(e,t,"GET",`/sites/${de(n)}/builds/${x("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"||a.state==="cancelled")return 1}};function Kk(e,t){if(t.startsWith(e))return t.slice(e.length);let n=t.indexOf(`
|
|
34
|
+
`).filter(p=>p!=="").map(p=>p.split(" "))},a=l=>`"${l.replace(/"/g,'""')}"`,i=l=>`'${l.replace(/'/g,"''")}'`,r=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(r.length>0){let l=await s(r.map(([d,p,u])=>`SELECT ${i(`${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 g=r.find(P=>P[0]===d&&P[1]===p&&P[2]===u)?.[3]==="t",y=d==="public"?`${p}.${u}`:`${d}.${p}.${u}`,{value:w}=await h(e,t,"POST","/secrets/fields/placeholder",{address:y}),[[_]]=await s(`WITH done AS (UPDATE ${a(d)}.${a(p)} SET ${a(u)} = ${i(w)}${g?`, ${a(`${u}_lookup`)} = NULL`:""} WHERE ${a(u)} LIKE 'pbe1.%' RETURNING 1) SELECT count(*) FROM done`);o.push({address:y,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}async function jc(e,t,n){let s=n??await Mc(e,t,`/databases?limit=100&environment=${encodeURIComponent(t.env_ref)}`,t.env_slug),{t:a,d:i}=await Oc(e,t,s);if(a.env_ref!==t.env_ref)throw new f("database_elsewhere",`the database ${i.name} is bound to ${a.env_slug}, not ${t.env_slug}`,{hint:`name ${a.env_slug} as the environment it is copied from or into`});return i.name}var Uc={name:"db:copy",summary:"copy the data of a database one environment of the project keeps into a database another keeps",usage:"--from <env> --to <env> [--db <name>] [--to-db <name>]",details:["A database is the project's, bound to one environment: --db is one --from keeps, --to-db one --to keeps \u2014 each its environment's only one when it is not named.","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 ${Cc}, 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 database --from keeps (default: its only one)"},"to-db":{type:"string",value:"name",description:"the database --to keeps (default: its only one)"}},scope:"environment",async run(e){let t=e.flags.from,n=e.flags.to;if(!t||!n)throw m("db:copy needs --from <env> and --to <env>");if(t===n)throw m("--from and --to are two environments");let s=await Yt(e),a=s.find(w=>w.slug===t),i=s.find(w=>w.slug===n);if(!a||!i)throw new f("no_such_environment",`the project has no environment ${JSON.stringify(a?n:t)}`);let r=ie(a),o=ie(i),l=await jc(e,r,e.flags.db),d=await jc(e,o,e.flags["to-db"]);await v(e,o,`overwrite the database ${d} with ${r.env_slug}'s ${l}`);let p=await Xt(e,r,l,"owner",!1),u=await Xt(e,o,d,"owner",!1),g=await rk(Ec(lk(),"palbase-copy-"));try{let w=Ec(g,"copy.dump"),_=await Nn(e,"pg_dump",["--format=custom","--no-owner","--no-acl","--file",w,p.url],p);if(_.code!==0)throw new f("pg_dump_failed",_.stderr.trim()||`pg_dump ended with ${_.code}`);await Gc(e,u,w,!0)}finally{await ok(g,{recursive:!0,force:!0})}let y=await uk(e,o,u);e.out.result({from:{env:r.env_slug,database:l},to:{env:o.env_slug,database:d},redacted:y},()=>{e.out.line(`Copied ${r.env_slug}/${l} into ${o.env_slug}/${d}.`);for(let w of y)e.out.line(` ${w.address}: ${w.rows} encrypted value(s) copied as ${Cc}`)})}};import{createReadStream as ck,openAsBlob as hk}from"node:fs";import{lstat as mk,readdir as gk,realpath as Bc,stat as fk}from"node:fs/promises";import{createHash as yk}from"node:crypto";import{join as bk,relative as zc,resolve as wk,sep as Wc}from"node:path";var Vo=2e4,vk=25<<20,_k=1<<30,kk=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/,Sk=6;function ji(e){return`${e.machine} answers ${e.paths.length===0?"every path":e.paths.join(", ")}`}var _a={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 Sa(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 Ci(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 Ho(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>]`,details:[te(e)],flags:s,scope:"environment",async run(l){let{t:d,path:p}=await n(l),{domains:u}=await h(l,d,"GET",`${p}/domains`);l.out.result({domains:u},()=>{u.length===0&&l.out.line(`No domain yet: palbase ${t}:domains:add <host> adds one.`);for(let g of u)Ci(l,g)})}},i={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 the environment's the ${e} is bound to (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.",te(e)],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 m("--primary is www or apex");if(l.flags.only===!0&&l.flags.primary!==void 0)throw m("--only adds the domain alone: no --primary");let u=Fc(l.flags["redirect-status"]),{t:g,path:y}=await n(l),w=`www.${d}`,_=l.flags.only!==!0&&!d.startsWith("www.");await v(l,g,_?`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 P=await h(l,g,"POST",`${y}/domains`,{host:d});if(!_||!P.apex){l.out.result(P,()=>Ci(l,P));return}let S=T=>({redirect_to:T,...u!==void 0?{redirect_status:u}:{}}),$;p==="www"?($=await $k(l,g,y,{host:w}),P=await h(l,g,"PATCH",`${y}/domains/${x("the domain",d)}`,S(w))):$=await Pk(l,g,y,w,S(d));let R=p==="www"?[$,P]:[P,$];l.out.result({domains:R},()=>R.forEach(T=>Ci(l,T)))}},r={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.",te(e)],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 m("name where it redirects (--to <host>), or --none");let u=Fc(l.flags.status);if(l.flags.none===!0&&u!==void 0)throw m("--status goes with --to");let{t:g,path:y}=await n(l);await v(l,g,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,g,"PATCH",`${y}/domains/${x("the domain",d)}`,w);l.out.result(_,()=>Ci(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>]`,details:[te(e)],args:{min:1,max:1},flags:s,scope:"environment",async run(l){let{t:d,path:p}=await n(l);await v(l,d,`remove the domain ${l.args[0]}`),await h(l,d,"DELETE",`${p}/domains/${x("the domain",l.args[0].toLowerCase())}`),l.out.result({removed:l.args[0]},()=>l.out.line(`${l.args[0]} answers no more.`))}};return[a,i,r,o]}function Fc(e){if(e===void 0)return;let t=Number(e);if(![301,302,307,308].includes(t))throw m("a redirect's status is 301, 302, 307 or 308");return t}async function $k(e,t,n,s){try{return await h(e,t,"POST",`${n}/domains`,s)}catch(a){if(!(a instanceof E&&a.code==="domain_exists"))throw a;let{domains:i}=await h(e,t,"GET",`${n}/domains`),r=i.find(o=>o.host===s.host);if(!r)throw a;return r}}async function Pk(e,t,n,s,a){try{return await h(e,t,"POST",`${n}/domains`,{host:s,...a})}catch(i){if(!(i instanceof E&&i.code==="domain_exists"))throw i;return await h(e,t,"PATCH",`${n}/domains/${x("the domain",s)}`,a)}}function Yo(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.",te(e)],args:{min:1,max:1},flags:s,scope:"environment",async run(a){let i=Number(a.args[0].replace(/^#/,""));if(!Number.isInteger(i)||i<=0)throw m("the pull request is its number: 12, or #12");let{t:r,path:o}=await n(a),{previews:l}=await h(a,r,"GET",`${o}/previews`),d=l.find(u=>u.pull_request===i&&u.state!=="closed");if(!d)throw new f("preview_not_found",`no open preview of pull request #${i}`,{hint:`palbase ${t}:previews lists them`});if(d.state!=="authorization_required")throw new f("preview_not_waiting",`#${i}'s preview waits for no authorization: it is ${d.state}`);await v(a,r,`build pull request #${i} at ${d.commit.slice(0,7)}, from a fork`,`Pull request #${i} 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,r,"POST",`${o}/previews/${i}/authorize`,{commit:d.commit});a.out.result(p,()=>a.out.line(`#${i} authorized at ${d.commit.slice(0,7)}: its preview is being built (palbase ${t}:previews).`))}}}function Xo(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})`:""}`)}}var Ak=/^[A-Za-z0-9][A-Za-z0-9 ._-]{0,63}$/;function Zo(e,t,n,s){let a={name:`${t}:hooks`,summary:`a ${e}'s deploy hooks: what each is called, and when it last built \u2014 never their URLs`,usage:`[--${e} <name>]`,details:[te(e)],flags:s,scope:"environment",async run(o){let{t:l,path:d}=await n(o),{hooks:p}=await h(o,l,"GET",`${d}/hooks`);o.out.result({hooks:p},()=>{p.length===0&&o.out.line(`No deploy hook: palbase ${t}:hooks:create <name> makes one.`),o.out.table(p,[{header:"hook",value:u=>u.id},{header:"name",value:u=>u.name},{header:"created",value:u=>u.created_at},{header:"last used",value:u=>u.last_used_at??"never"}])})}},i={name:`${t}:hooks:create`,summary:`make a deploy hook: a URL that builds the ${e}'s branch head when it is POSTed to (a CMS's publish, a schedule)`,usage:`<name> [--${e} <name>]`,details:[`Its URL is printed this once: anyone who holds it builds the ${e}, so keep it as a secret, and delete the hook if it leaks. A build it asks for is held to the project's builds as a push's is.`,`A ${e} has 5 at most.`,te(e)],args:{min:1,max:1},flags:s,scope:"environment",async run(o){let l=o.args[0];if(!Ak.test(l))throw m(`${JSON.stringify(l)} is not a hook's name: letters, digits, spaces, dots, dashes and underscores, 64 at most`);let{t:d,path:p}=await n(o);await v(o,d,`make a deploy hook ${l}: its URL builds the ${e} when it is POSTed to`);let u=await h(o,d,"POST",`${p}/hooks`,{name:l});o.out.result(u,()=>{o.out.line(`Made the deploy hook ${u.name} (${u.id}). POST to it to build:`),o.out.line(` ${u.url??""}`),o.out.line(`It is shown this once. Keep it secret: anyone who holds it builds the ${e} (palbase ${t}:hooks:delete ${u.id} takes it away).`)})}},r={name:`${t}:hooks:delete`,summary:"delete a deploy hook: its URL builds nothing from now on",usage:`<hook id> [--${e} <name>]`,details:[te(e)],args:{min:1,max:1},flags:s,scope:"environment",async run(o){let{t:l,path:d}=await n(o);await v(o,l,`delete the deploy hook ${o.args[0]}`),await h(o,l,"DELETE",`${d}/hooks/${x("the hook's id",o.args[0])}`),o.out.result({deleted:o.args[0]},()=>o.out.line(`Deleted the deploy hook ${o.args[0]}: its URL builds nothing from now on.`))}};return[a,i,r]}function Qo(e,t,n,s){return{name:`${t}:builds:cancel`,summary:`cancel a ${e}'s build that has not ended: its run is stopped, and the ${e} serves what it served`,usage:`<build> [--${e} <name>]`,details:["A push, a deploy or a deploy hook builds again.",te(e)],args:{min:1,max:1},flags:s,scope:"environment",async run(a){let{t:i,path:r}=await n(a),o=a.args[0];await v(a,i,`cancel the build ${o}`);let l;try{l=await h(a,i,"POST",`${r}/builds/${x("the build",o)}/cancel`)}catch(d){throw d instanceof E&&d.code==="build_not_cancellable"?new f("build_not_cancellable",d.message,{hint:`palbase ${t}:builds says where each build is`}):d}a.out.result(l,()=>a.out.line(`Cancelled the build ${l.id} (${l.commit.slice(0,7)}): the ${e} serves what it served.`))}}}function de(e){if(!kk.test(e))throw m(`${JSON.stringify(e)} is not a site's name: lowercase letters, digits and dashes, starting with a letter`);return x("the site",e)}var Hc={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 Yc(e,t){let n={};if(e.flags.repo!==void 0||e.flags.branch!==void 0||t){let i=await hs(e.io,e.io.cwd),r=e.flags.repo??i?.repository,o=e.flags.branch??i?.branch;if(!r)throw m("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!o)throw m("which branch? none is checked out here","pass --branch <branch>");n.source={repository:r,branch:o,path:e.flags.path??(e.flags.repo===void 0?i?.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 i={};for(let r of a){let o=r.indexOf("=");if(o<=0)throw m(`a setting is K=V, not ${JSON.stringify(r)}`);i[r.slice(0,o)]=r.slice(o+1)}s.env=i}return Object.keys(s).length>0&&(n.build=s),n}function ka(e){return e<1024?`${e} B`:e<1<<20?`${(e/1024).toFixed(1)} KiB`:`${(e/(1<<20)).toFixed(1)} MiB`}async function Rk(e){let t=await Bc(e),n=[],s=async i=>{let r=await gk(i,{withFileTypes:!0});for(let o of r){if(o.name==="node_modules"||o.name.startsWith(".")&&!(o.name===".well-known"&&i===t))continue;let l=bk(i,o.name),d=await mk(l),p=l;if(d.isSymbolicLink()&&(p=await Bc(l),p!==t&&!p.startsWith(t+Wc)))throw new f("unsafe_path",`${zc(t,l)} links outside ${e}`);let u=d.isSymbolicLink()?await fk(p):d;if(u.isDirectory()){await s(l);continue}if(!u.isFile())continue;let g="/"+zc(t,l).split(Wc).join("/");if(/[\u0000-\u001f\u007f?#\\]/.test(g))throw new f("invalid_path",`${g} has a character a site's path cannot carry (?, #, \\ or a control character): rename it`);if(g.length>1024)throw new f("invalid_path",`${g.slice(0,80)}\u2026 is longer than a site's path may be (1024 bytes)`);if(u.size>vk)throw new f("file_too_large",`${g} is ${ka(u.size)}: a site's file is 25 MiB at most (keep large media in storage)`);if(n.push({path:g,file:p,size:u.size,digest:""}),n.length>Vo)throw new f("too_many_files",`${e} holds more than ${Vo} files: a site holds ${Vo} at most`)}};await s(t),n.sort((i,r)=>i.path<r.path?-1:i.path>r.path?1:0);let a=n.reduce((i,r)=>i+r.size,0);if(a>_k)throw new f("release_too_large",`${e} holds ${ka(a)}: a release is 1 GiB at most`);for(let i of n)i.digest=await Tk(i.file);return n}function Tk(e){return new Promise((t,n)=>{let s=yk("sha256");ck(e).on("data",a=>s.update(a)).on("error",n).on("end",()=>t(s.digest("hex")))})}function Ek(e){let t=e.filter(n=>/\.html?$/i.test(n.path));return t.length===1&&t[0].path==="/index.html"}async function Ck(e,t,n){try{return await h(e,t,"GET",`/sites/${de(n)}`)}catch(s){if(s instanceof E&&s.code==="site_not_found")return null;throw s}}async function rt(e,t,n=!0){let s=await pn(e),a=s.t,i=await h(e,a,"GET",`/sites/${de(t)}`);return await Mn(e,s,i,()=>Zc(e,a),`the site ${i.name}`),Xc(s,i,n),{t:await Ln(e,a,i.environment,`the site ${i.name}`),site:i}}function Xc(e,t,n){if(!(n||e.by!=="here"||!t.environment||t.environment.ref===e.t.env_ref))throw new f("site_elsewhere",`the environment ${e.t.env_slug} has no site ${t.name}: the project's ${t.name} is bound to ${t.environment.name||t.environment.ref}`,{hint:"name the site with --site <name> (palbase hosting:sites:list), or act where it is bound with -E"})}async function Zc(e,t){return(await h(e,t,"GET","/sites")).sites}var ot={site:{type:"string",value:"name",description:"the site (default: web \u2014 that of the environment chosen here or -E's, refused when it is bound elsewhere; with neither, the project's)"}},St=e=>e.flags.site??"web",Oi=async e=>{let{t,site:n}=await rt(e,St(e),e.flags.site!==void 0);return{t,path:`/sites/${de(n.name)}`}};async function Jc(e,t,n,s,a,i){let r=0,o=0,l=async()=>{for(;o<a.length;){let d=a[o++],p=i.get(d);if(!p)throw new f("internal",`the release asked for ${d}, which no file here is`);let u=await hk(p.file);await h(e,t,"PUT",`/sites/${de(n)}/releases/${x("the release",s)}/files/${d}`,new Wt(u,"application/octet-stream")),r+=p.size}};return await Promise.all(Array.from({length:Math.min(Sk,a.length)},l)),r}async function Vc(e,t,n,s){await h(e,t,"PATCH",`/sites/${de(n)}`,{spa:s}),e.out.note(` ${n} is ${s?"a single-page app now: every route is its index.html":"no single-page app now: a path no file answers is 404"}`)}var jk={name:"hosting:deploy",summary:"deploy a folder as a static site of the project: only the files that changed are sent, and the site serves them at once",usage:"<folder> [--site <name>] [-E <env>] [--spa | --no-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 answers a path no file answers with /index.html (a single-page app), --no-spa with 404: the site is changed to it when it is not that already.","A folder of one page, index.html, is taken for a single-page app when the site is opened.",te("site"),`One its first deploy opens is the project's too. ${Dn}`],args:{min:1,max:1},flags:{site:{type:"string",value:"name",description:"the site (default: web \u2014 that of the environment chosen here or -E's, refused when it is bound elsewhere; with neither, the project's; it answers at the ref of the environment it is bound to)"},spa:{type:"boolean",description:"a single-page app: answer every path no file answers with /index.html"},"no-spa":{type:"boolean",description:"not a single-page app: a path no file answers is 404"}},scope:"environment",async run(e){if(e.flags.spa===!0&&e.flags["no-spa"]===!0)throw m("--spa or --no-spa, not both");let t=e.flags.spa===!0?!0:e.flags["no-spa"]===!0?!1:void 0,n=St(e);de(n);let s=wk(e.io.cwd,e.args[0]),a=await Rk(s).catch($=>{throw $ instanceof f?$:new f("no_folder",`${e.args[0]}: ${$ instanceof Error?$.message:String($)}`)});if(a.length===0)throw new f("empty_folder",`${e.args[0]} holds no file to serve`);a.some($=>$.path==="/index.html")||e.out.note(` ${e.args[0]} has no index.html: the site's root answers 404.`);let i=a.reduce(($,R)=>$+R.size,0),r=await pn(e),o=r.t,l=await Ck(e,o,n);l&&(await Mn(e,r,l,()=>Zc(e,o),`the site ${n}`),Xc(r,l,e.flags.site!==void 0));let d=l?await Ln(e,o,l.environment,`the site ${n}`):await In(e);if(await v(e,d,`deploy ${a.length} files (${ka(i)}) to the site ${n}`),!l){let $=t??Ek(a);l=await h(e,d,"POST","/sites",{name:n,spa:$}),e.out.note(` opened the site ${n}${$?" (a single-page app: every route is its index.html)":""}`)}let p=t!==void 0&&l.spa!==t;p&&t&&await Vc(e,d,n,!0);let u={},g=new Map;for(let $ of a)u[$.path]=$.digest,g.set($.digest,$);let y=await h(e,d,"POST",`/sites/${de(n)}/releases`,{files:u}),w=y.missing??[];e.out.note(` release #${y.number}: ${a.length} files, ${w.length} to send${w.length<g.size?` (${g.size-w.length} kept from before)`:""}`);let _=await Jc(e,d,n,y.id,w,g),P;for(let $=0;$<3&&!P;$++)try{P=await h(e,d,"POST",`/sites/${de(n)}/releases/${x("the release",y.id)}/finish`)}catch(R){let T=R instanceof E&&R.code==="files_missing"?R.body?.missing??[]:[];if(T.length===0)throw R;_+=await Jc(e,d,n,y.id,T,g)}if(!P)throw new f("release_unfinished",`the release #${y.number} could not be finished`,{hint:"deploy again"});p&&!t&&await Vc(e,d,n,!1),l=await h(e,d,"GET",`/sites/${de(n)}`);let S={site:l.name,url:l.url,urls:l.urls,release:P,sent_bytes:_};e.out.result(S,()=>{e.out.line(`Deployed release #${P.number} of ${l.name} (${a.length} files, ${ka(_)} sent).`);for(let $ of l.urls)e.out.line(` ${$}`)})}},Ok={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",usage:"[-E <env>]",details:["A project's sites are the project's, each bound to one of its environments and built with its settings and secrets. The list is every environment's you reach; -E lists that environment's alone, as an environment's own token does."],scope:"environment",async run(e){let t=await jn(e),[{sites:n},s]=await Promise.all([h(e,t,"GET",mi(e,t,"/sites")),ms(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 i=a.taken_down?`taken down: ${a.taken_down.reason}`:a.release?`release #${a.release.number}`:"nothing deployed",r=a.previews_protected===void 0?"":a.previews_protected?" previews protected":" previews public";e.out.line(`${a.name} ${Ft(s,a.environment)}${a.moving_to?` \u2192 ${Ft(s,a.moving_to)}`:""} ${a.url} ${i}${a.spa?" (single-page app)":""}${a.server?` server ${ji(a.server)}`:""}${r}`)}})}},Qc={server:{type:"string",value:"machine",description:"the environment's machine that answers what the site's files do not: its API (--server-path), or every path of a web app that runs on a server (Next.js, Nuxt, SvelteKit) \u2014 at the site's addresses, through its CDN"},"server-path":{type:"string",multiple:!0,value:"prefix",description:"a path the server answers, ending in / (repeat it): /api/; none, and it answers every path"},"protect-previews":{type:"boolean",description:"its previews \u2014 its pull requests' and its branches' \u2014 are its team's alone: a visitor signs in with Studio, or holds a share link (hosting:previews:link); the default"},"no-protect-previews":{type:"boolean",description:"anyone with a preview's address opens it"}};async function eh(e,t,n){let s=e.flags.server,a=e.flags["server-path"];if(e.flags["no-server"]===!0){if(s!==void 0||a!==void 0)throw m("--no-server takes the server away: no --server or --server-path with it");t.server={machine:"",paths:[]}}else if(s!==void 0||a!==void 0){for(let r of a??[])if(!r.startsWith("/")||!r.endsWith("/"))throw m(`a server's path is a prefix of the site's paths ending in /, as /api/: not ${JSON.stringify(r)}`);let i=s;if(i===void 0&&(i=n?(await n())?.machine:void 0,!i))throw m("--server-path goes with --server <machine>",n?"the site has no server yet":void 0);t.server={machine:i,paths:a??[]}}e.flags["protect-previews"]===!0&&(t.previews_protected=!0),e.flags["no-protect-previews"]===!0&&(t.previews_protected=!1)}var Mk={name:"hosting:sites:create",summary:"open a static site of the project \u2014 built from GitHub on every push with --repo/--branch, or deployed from a folder (hosting:deploy opens one too)",usage:"[name] [-E <env>] [--spa] [--repo <owner/name> --branch <branch> --path <dir>] [--build-command \u2026] [--output <dir>] [--build-env K=V]\u2026 [--previews [--preview-forks]] [--server <machine> [--server-path <prefix>]\u2026] [--no-protect-previews]",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.","With --server, a machine of the environment answers what its files do not \u2014 the paths --server-path names, or every path: a site with no files whose server is a web app's machine is that app's address and CDN.","Its previews are its team's alone unless --no-protect-previews: hosting:previews:link shares them.",`${Dn} It is built with that environment's settings and secrets.`,"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"},...Hc,previews:_a.previews,"preview-forks":_a["preview-forks"],...Qc},scope:"environment",async run(e){let t=await In(e),n=e.args[0]??"web";de(n);let{source:s,build:a}=await Yc(e,!1),i={};Sa(e,i),await eh(e,i);let r=i.server;await v(e,t,`open the site ${n}${s?`, built from ${s.repository}@${s.branch}`:""}${r?`, ${ji(r)}`:""}`);let o=await h(e,t,"POST","/sites",{name:n,spa:e.flags.spa===!0,...s?{source:s}:{},...a?{build:a}:{},...i});e.out.result(o,()=>e.out.line(o.source?`Opened ${o.name}: ${o.url} \u2014 its first build is on its way (palbase hosting:builds --site ${o.name}).`:o.server?`Opened ${o.name}: ${o.url} \u2014 ${ji(o.server)}${o.server.paths.length>0?` (nothing else deployed yet: palbase hosting:deploy <folder> --site ${o.name})`:""}.`:`Opened ${o.name}: ${o.url} (nothing deployed yet: palbase hosting:deploy <folder> --site ${o.name}).`))}},Ik={name:"hosting:sites:update",summary:"change a site of the project, where it is bound: whether it is a single-page app, where it is built from, what its build runs, its server, who opens its previews",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] [--server <machine>] [--server-path <prefix>]\u2026 [--no-server] [--protect-previews | --no-protect-previews]",details:[te("site")],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"},...Hc,"no-source":{type:"boolean",description:"build it from no repository any more: deploy folders alone"},..._a,...Qc,"no-server":{type:"boolean",description:"no machine answers for it any more: its files answer every path"}},scope:"environment",async run(e){let t=e.args[0];de(t);let n,s=()=>n??=rt(e,t),a={};e.flags.spa===!0&&(a.spa=!0),e.flags["no-spa"]===!0&&(a.spa=!1);let{source:i,build:r}=await Yc(e,!1);if(i&&(a.source=i),e.flags["no-source"]===!0&&(a.source={repository:""}),r&&(a.build=r),Sa(e,a),await eh(e,a,async()=>(await s()).site.server),Object.keys(a).length===0)throw m("nothing to change: give a flag","palbase help hosting:sites:update");let{t:o}=await s();await v(e,o,`change the site ${t}`);let l=await h(e,o,"PATCH",`/sites/${de(t)}`,a);e.out.result(l,()=>e.out.line(`${l.name}: ${l.url}${l.spa?" (single-page app)":""}${l.source?` \u2014 built from ${l.source.repository}@${l.source.branch}`:""}${l.server?` \u2014 ${ji(l.server)}`:""}${a.previews_protected===void 0?"":l.previews_protected?" \u2014 its previews are its team's alone":" \u2014 its previews open to anyone with their address"}`))}},Lk={name:"hosting:sites:move",summary:"bind a site to another environment of the project: its files go with it, and it answers throughout",usage:"<name> --to <env>",details:["Its files and releases are copied to the new environment while it serves on, then it is the new environment's, in a few seconds: its address names it (<name>-<its ref>), and the one it had keeps working, for good. Its domains of its own move with it and answer throughout.","Its pull requests' previews are closed: a new push opens them there. A build of it going on is stopped and built again there; its GitHub link is made in the new environment when it has none.","It moves out of the environment it is bound to; -E picks it where two environments hold its name.","It needs the admin role in both environments, and the new environment room for it: a site more, its files, its domains."],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=e.flags.to;if(typeof t!="string"||t==="")throw m("--to names the environment of the project it moves to");let{t:n,site:{name:s}}=await rt(e,e.args[0]),a=await da(e,n,t);await v(e,n,`move the site ${s} out of this environment, into ${a.slug}`),await v(e,ie(a),`move the site ${s} into this environment: it is built with this environment's settings and secrets`);let i=await h(e,n,"POST",`/sites/${de(s)}/move`,{environment:a.ref});e.out.result(i,()=>e.out.line(`${i.name} moves to ${a.slug} in a few seconds; ${i.url} keeps working (palbase hosting:sites:list -E ${a.slug}).`))}},Dk={name:"hosting:sites:delete",summary:"delete a site of the project, in the environment it is bound to: its addresses serve nothing from now on",usage:"<name>",details:[te("site")],args:{min:1,max:1},scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,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/${de(n)}`),e.out.result({deleted:n},()=>e.out.line(`Deleted ${n}.`))}},xk={name:"hosting:releases",summary:"a site's releases, newest first: the ten newest are kept to return to",usage:"[--site <name>]",details:[te("site")],flags:ot,scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,St(e),e.flags.site!==void 0),{releases:s}=await h(e,t,"GET",`/sites/${de(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 ${ka(a.bytes)} ${a.created_at}${a.commit?` ${a.commit.slice(0,7)}`:""}`)})}},Nk={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>]",details:[te("site")],flags:{...ot,to:{type:"string",value:"release",description:"the release: its id, or its number (#3)"}},scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,St(e),e.flags.site!==void 0),s=e.flags.to;if(s!==void 0&&/^#?\d+$/.test(s)){let i=Number(s.replace("#","")),{releases:r}=await h(e,t,"GET",`/sites/${de(n)}/releases`),o=r.find(l=>l.number===i);if(!o)throw new f("release_not_found",`${n} keeps no release #${i}`,{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/${de(n)}/rollback`,s?{release:s}:{});e.out.result(a,()=>e.out.line(`${a.name} serves release #${a.release?.number}: ${a.url}`))}},qk={name:"hosting:builds",summary:"a site's newest builds (a site built from GitHub), or one with its log",usage:"[build] [--site <name>] [--wait]",details:[te("site")],args:{min:0,max:1},flags:{...ot,wait:{type:"boolean",description:"with a build: follow it until it ends"}},scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,St(e),e.flags.site!==void 0),s=e.args[0];if(s===void 0){let{builds:i}=await h(e,t,"GET",`/sites/${de(n)}/builds`);e.out.result({builds:i},()=>{i.length===0&&e.out.line(`${n} has no build: it is built from GitHub with hosting:sites:create --repo \u2026 --branch \u2026.`);for(let r of i)e.out.line(`${r.id} ${r.commit.slice(0,7)} ${r.state}${r.reason?`: ${r.reason}`:""}${Gk(r)} ${r.message}`)});return}let a=await h(e,t,"GET",`/sites/${de(n)}/builds/${x("the build",s)}`);for(let i=0;e.flags.wait===!0&&(a.state==="queued"||a.state==="building")&&i<900;i++)await e.io.sleep(2e3),a=await h(e,t,"GET",`/sites/${de(n)}/builds/${x("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"||a.state==="cancelled")return 1}};function Kk(e,t){if(t.startsWith(e))return t.slice(e.length);let n=t.indexOf(`
|
|
35
35
|
`)+1,s=t.slice(n,n+256);if(n>0&&s!==""){for(let a=e.indexOf(s);a>=0;a=e.indexOf(s,a+1))if(t.startsWith(e.slice(a),n))return t.slice(n+e.length-a)}return t}function Gk(e){return e.pull_request?` (preview of #${e.pull_request})`:e.branch?` (preview of ${e.branch})`:""}async function Uk(e,t,n,s){let a=n.name,i=!1,r=()=>{},o=new Promise(u=>r=u),l=()=>{i=!0,r()},d=async()=>(await Promise.race([e.io.sleep(2e3),o]),i),p=u=>(e.out.note(u?`Stopped following: the build ${u} goes on (palbase hosting:builds ${u} --site ${a} --wait follows it, hosting:builds:cancel ${u} --site ${a} cancels it).`:`Stopped following: the build goes on (palbase hosting:builds --site ${a}).`),130);process.once("SIGINT",l);try{let u;for(let _=0;;_++){let{builds:P}=await h(e,t,"GET",`/sites/${de(a)}/builds`);if(u=P.find(S=>!s.has(S.id)&&!S.pull_request&&!S.branch)?.id,u)break;if(_===60)throw new f("build_not_queued",`no build of ${a} was queued in 2 minutes`,{hint:`palbase hosting:builds --site ${a}`});if(await d())return p()}let g="",y="",w="";for(let _=0;;_++){let P=await h(e,t,"GET",`/sites/${de(a)}/builds/${x("the build",u)}`),S=`build ${P.id.slice(0,8)} (${P.commit.slice(0,7)}): ${P.state}`;if(S!==g&&e.out.note(` ${S}`),g=S,P.log&&!e.global.json){let $=w+Kk(y,P.log),R=$.lastIndexOf(`
|
|
36
36
|
`)+1;e.io.stdout(q($.slice(0,R))),w=$.slice(R),y=P.log}if(P.state!=="queued"&&P.state!=="building")return w!==""&&e.io.stdout(`${q(w)}
|
|
37
|
-
`),e.out.result({site:a,url:n.url,build:P},()=>e.out.line(P.state==="succeeded"?`${a} serves the build of ${P.commit.slice(0,7)}: ${n.url}`:`The build ${P.state}${P.reason?`: ${P.reason}`:""} \u2014 ${a} serves what it served.`)),P.state==="succeeded"?0:1;if(_===900)throw new f("timeout",`the build ${u} was still ${P.state} after 30 minutes; it goes on`,{hint:`palbase hosting:builds ${u} --site ${a} --wait`});if(await d())return p(u)}}finally{process.removeListener("SIGINT",l)}}var Bk={name:"hosting:build",summary:"build a site's branch head now and serve it, as a push does \u2014 following the build to its end, its log as it grows",usage:"[--site <name>] [--no-wait]",details:["It ends as the build does: 0 once the site serves it (its address printed), 1 when it failed or was cancelled \u2014 the site serves what it served.","Ctrl-C stops following it, not the build: hosting:builds:cancel cancels it.",te("site")],flags:{...ot,"no-wait":{type:"boolean",description:"ask for the build and end: hosting:builds follows it"}},scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,
|
|
37
|
+
`),e.out.result({site:a,url:n.url,build:P},()=>e.out.line(P.state==="succeeded"?`${a} serves the build of ${P.commit.slice(0,7)}: ${n.url}`:`The build ${P.state}${P.reason?`: ${P.reason}`:""} \u2014 ${a} serves what it served.`)),P.state==="succeeded"?0:1;if(_===900)throw new f("timeout",`the build ${u} was still ${P.state} after 30 minutes; it goes on`,{hint:`palbase hosting:builds ${u} --site ${a} --wait`});if(await d())return p(u)}}finally{process.removeListener("SIGINT",l)}}var Bk={name:"hosting:build",summary:"build a site's branch head now and serve it, as a push does \u2014 following the build to its end, its log as it grows",usage:"[--site <name>] [--no-wait]",details:["It ends as the build does: 0 once the site serves it (its address printed), 1 when it failed or was cancelled \u2014 the site serves what it served.","Ctrl-C stops following it, not the build: hosting:builds:cancel cancels it.",te("site")],flags:{...ot,"no-wait":{type:"boolean",description:"ask for the build and end: hosting:builds follows it"}},scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,St(e),e.flags.site!==void 0);await v(e,t,`build ${n} from the head of its branch`);let a=e.flags["no-wait"]!==!0?new Set((await h(e,t,"GET",`/sites/${de(n)}/builds`)).builds.map(r=>r.id)):void 0,i=await h(e,t,"POST",`/sites/${de(n)}/builds`);if(a)return Uk(e,t,i,a);e.out.result(i,()=>e.out.line(`${i.name}: a build of ${i.source?.branch??"its branch"}'s head is on its way (palbase hosting:builds --site ${i.name}).`))}},zk={name:"hosting:previews",summary:"a site's previews \u2014 its pull requests' and its other branches' \u2014 newest first: where each answers, and whether it is built",usage:"[--site <name>]",details:["A branch's preview answers at <name>-git-<branch>-<ref> from its first push while the site previews, until the branch is deleted or a month passes with no push.",te("site")],flags:ot,scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,St(e),e.flags.site!==void 0),{previews:s,branches:a=[]}=await h(e,t,"GET",`/sites/${de(n)}/previews`);e.out.result({previews:s,branches:a},()=>{(s.length>0||a.length===0)&&Xo(e,s,`${n} has no preview: a site built from GitHub previews its pull requests and its other branches with hosting:sites:update ${n} --previews.`);for(let i of a)e.out.line(`branch ${i.branch} ${i.state} ${i.commit.slice(0,7)} ${i.url}`)})}},Wk={name:"hosting:previews:links",summary:"a site's share links that have not ended: each opens its protected previews to whoever holds it \u2014 never their tokens",usage:"[--site <name>]",details:[te("site")],flags:ot,scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,St(e),e.flags.site!==void 0),{links:s}=await h(e,t,"GET",`/sites/${de(n)}/previews/links`);e.out.result({links:s},()=>{s.length===0&&e.out.line(`${n} has no share link: palbase hosting:previews:link --site ${n} makes one.`),e.out.table(s,[{header:"link",value:a=>a.id},{header:"name",value:a=>a.name},{header:"made by",value:a=>a.made_by},{header:"ends",value:a=>a.expires_at}])})}},Fk={name:"hosting:previews:link",summary:"make a share link of a site's protected previews: whoever holds it opens any of them, for 1 to 30 days",usage:"[--site <name>] [--name <name>] [--days <1-30>]",details:["Its token is printed this once: add ?_palbase_pass=<token> to any preview's address and the preview opens \u2014 for a reviewer, a client, a test run. hosting:previews:unlink closes the previews to it at once.","A site has 20 at most.",te("site")],flags:{...ot,name:{type:"string",value:"name",description:"what it is for, as the links are listed: who holds it (64 at most)"},days:{type:"string",value:"days",description:"how many days it opens the previews, 1 to 30 (default: 7)"}},scope:"environment",async run(e){let t=e.flags.days===void 0?void 0:Number(e.flags.days);if(t!==void 0&&(!Number.isInteger(t)||t<1||t>30))throw m("--days is a whole number of days, 1 to 30");let n=e.flags.name;if(n!==void 0&&n.length>64)throw m("a link's --name is 64 characters at most");let{t:s,site:{name:a}}=await rt(e,St(e),e.flags.site!==void 0);await v(e,s,`make a share link that opens ${a}'s previews to whoever holds it${t!==void 0?`, for ${t} days`:""}`);let i=await h(e,s,"POST",`/sites/${de(a)}/previews/links`,{...n!==void 0?{name:n}:{},...t!==void 0?{days:t}:{}});e.out.result(i,()=>{e.out.line(`Made the share link ${i.id}${i.name?` (${i.name})`:""}: it opens ${a}'s previews until ${i.expires_at}. Its token:`),e.out.line(` ${i.token??""}`),e.out.line(`Add ?_palbase_pass=<token> to any preview's address (palbase hosting:previews --site ${a} lists them). It is shown this once; palbase hosting:previews:unlink ${i.id} --site ${a} closes the previews to it.`)})}},Jk={name:"hosting:previews:unlink",summary:"delete a share link: the site's previews close to it at once",usage:"<link id> [--site <name>]",details:[te("site")],args:{min:1,max:1},flags:ot,scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,St(e),e.flags.site!==void 0);await v(e,t,`delete the share link ${e.args[0]} of ${n}'s previews`),await h(e,t,"DELETE",`/sites/${de(n)}/previews/links/${x("the link's id",e.args[0])}`),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the share link ${e.args[0]}: ${n}'s previews are closed to it.`))}},Vk={name:"hosting:previews:pass",summary:"an address that opens one of a site's protected previews in your browser, as you: for 12 hours",usage:"<preview url> [--site <name>]",details:["The address is the preview's, with a pass of yours in its query: opened in a browser, the preview keeps it in a cookie of its own and opens for 12 hours. A team member's alone \u2014 share links (hosting:previews:link) are for others.",te("site")],args:{min:1,max:1},flags:ot,scope:"environment",async run(e){let t;try{t=new URL(e.args[0])}catch{throw m(`${JSON.stringify(e.args[0])} is not an address: a preview's, as hosting:previews lists it`)}if(t.protocol!=="https:")throw m("a preview's address is https://\u2026");let{t:n,site:{name:s}}=await rt(e,St(e),e.flags.site!==void 0),a=await h(e,n,"POST",`/sites/${de(s)}/previews/pass`,{to:t.href});e.out.result(a,()=>{e.out.line(a.url),e.out.note(`Open it in your browser: it opens the preview, as you, until ${a.expires_at}.`)})}},Hk=Ho("site","hosting",Oi,ot),Yk=Yo("site","hosting",Oi,ot),Xk=Qo("site","hosting",Oi,ot),Zk=Zo("site","hosting",Oi,ot),th=[jk,Ok,Mk,Ik,Lk,Dk,xk,Nk,qk,Bk,Xk,...Zk,zk,Yk,Wk,Fk,Jk,Vk,...Hk];function sh(e){return`its last push (${A(e.commit.slice(0,7))}) did not roll out \u2014 ${A(As(e.reason))}`}function ah(e){return e.config_version!==void 0&&e.running_config_version!==void 0&&e.running_config_version<e.config_version}var ih="new secrets or config rolling out";function Qk(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)",no_room:"waiting for room in the cluster"}[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 Ii(e){return e.state_reason_kind==="no_room"?`${e.state}, waiting for room`:e.state}function As(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t!=="").join(" \xB7 ")}function eS(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(`
|
|
38
38
|
${" ".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 tS=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/;async function B(e,t,n,s,a,i){return(await _e(e.studio,t.env_ref,n,s,a,i)).body}function ne(e){if(!tS.test(e))throw m(`${JSON.stringify(e)} is not a name: lowercase letters, digits and dashes, starting with a letter`);return encodeURIComponent(e)}async function ue(e,t){let n=await pn(e),s=n.t,{body:a,etag:i}=await _e(e.studio,s.env_ref,"GET",`/machines/${ne(t??await sS(e,n))}`);return await Mn(e,n,a,()=>nS(e,s),`the machine ${a.name}`),{t:await Ln(e,s,a.environment,`the machine ${a.name}`),name:a.name,machine:a,etag:i}}async function nS(e,t){return On(async n=>{let s=await B(e,t,"GET",`/machines?limit=100${n?`&cursor=${encodeURIComponent(n)}`:""}`);return{items:s.machines,next:s.next_cursor}})}async function rh(e,t,n){return On(async s=>{let a=await B(e,t,"GET",mi(e,t,`/${n}?limit=100${s?`&cursor=${encodeURIComponent(s)}`:""}`));return{items:a[n],next:a.next_cursor}})}async function sS(e,t){let{machines:n}=await B(e,t.t,"GET",hi(t,"/machines?limit=100"));if(n.length===1)return n[0].name;let s=await hs(e.io,e.io.cwd),a=s?.repository?n.filter(r=>r.source.repository.toLowerCase()===s.repository?.toLowerCase()&&(r.source.path??"")===s.path):[];if(a.length===1)return a[0].name;let i=t.by==="fallback"?"the project":`the environment ${t.t.env_slug}`;throw n.length===0?new f("no_machine",`${i} has no machine yet`,{hint:"make one with palbase machines:create"}):m("which machine? name it",`${i}'s machines: ${n.map(r=>r.name).join(", ")}`)}var Li=async e=>{let{t,name:n}=await ue(e,e.flags.machine);return{t,path:`/machines/${ne(n)}`}},Ge={machine:{type:"string",value:"name",description:"the machine (default: the only one of the environment chosen here or -E's, the project's only one when neither says, or this directory's)"}},aS="Named by none, it is the only machine of the environment chosen for this directory or named by -E \u2014 never one bound elsewhere \u2014 else, when neither says, the project's only one; or the one this directory's code is built into.",ye=[te("machine"),aS];function oh(e){let t=e.price_micros_per_hour;if(t===void 0)return e.free?"free":"";if(e.free)return`free, then $${(t/1e6).toFixed(3)} an hour`;let n=Math.round(t*730/1e4),s=n%100===0;return`$${(n/100).toLocaleString("en-US",{minimumFractionDigits:s?0:2,maximumFractionDigits:s?0:2})} a month${e.sleeps?" awake":""}`}function iS(e){let t=`${(e.storage_bytes/1e9).toFixed(0)} GB`;return e.storage_adjustable?`${t}, or what you say (up to ${(e.max_storage_gb??4e3).toLocaleString("en-US")})`:t}function rS(e){return`$${(e/1e6).toFixed(2)}`}function lh(e){return e>=1024&&e%1024===0?`${e/1024} GiB`:`${e} MiB`}function Mi(e){return e<1e9?`${Number((e/1e6).toFixed(1)).toLocaleString("en-US")} MB`:`${Number((e/1e9).toFixed(2)).toLocaleString("en-US")} GB`}var dh={name:"machines:sizes",summary:"the machine sizes, and which of them this environment may open now",scope:"environment",async run(e){let t=await b(e),{sizes:n}=await B(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=>lh(s.memory_mib)},{header:"sleeps",value:s=>s.sleeps?"when idle":"never"},{header:"price",value:s=>oh(s)},{header:"open",value:s=>s.available?"yes":`no \u2014 ${s.reason??""}`}]))}},ph={name:"databases:sizes",summary:"the database sizes, and which of them this environment may open now",details:["A size that never sleeps holds the storage its database says \u2014 databases:create --storage, 1 GB or a multiple of 5, up to 4,000 \u2014 or the size's own: its price is its CPU and memory, and its storage is billed beside it by the GB-month past its first GB. free and hobby hold their size's."],scope:"environment",async run(e){let t=await b(e),{sizes:n}=await B(e,t,"GET","/databases/sizes");e.out.result({sizes:n},()=>{e.out.table(n,[{header:"size",value:a=>a.name},{header:"cpu",value:a=>`${a.vcpu} vCPU`},{header:"memory",value:a=>lh(a.memory_mib)},{header:"storage",value:a=>iS(a)},{header:"sleeps",value:a=>a.sleeps?`when idle${a.awake_hours_per_month?`, ${a.awake_hours_per_month} h awake a month`:""}`:"never"},{header:"price",value:a=>`${oh(a)}${a.storage_adjustable&&a.price_micros_per_hour!==void 0?" + storage":""}`},{header:"open",value:a=>a.available?"yes":`no \u2014 ${a.reason??""}`}]);let s=n.find(a=>a.storage_adjustable&&a.storage_price_micros_per_gb_month!==void 0);s&&(e.out.line(),e.out.line(`Storage: ${rS(s.storage_price_micros_per_gb_month)} a GB-month past each database's first GB \u2014 what databases:create --storage says (1 GB or a multiple of 5), or the size's; it grows, never shrinks (databases:update --storage, --storage-autoscaling).`))})}},uh={name:"machines:list",summary:"the project's machines, each with the environment it is bound to: size, state, the version serving, address",usage:"[-E <env>]",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. -E lists that environment's alone, as an environment's own token does."],scope:"environment",async run(e){let t=await jn(e),[n,s]=await Promise.all([rh(e,t,"machines"),ms(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=>`${Ft(s,a.environment)}${a.moving_to?` \u2192 ${Ft(s,a.moving_to)}`:""}`},{header:"size",value:a=>`${a.size}${a.autoscaling?` \xD7${a.replicas}\u2013${a.autoscaling.max_replicas}`:a.replicas>1?` \xD7${a.replicas}`:""}`},{header:"state",value:a=>Ii(a)},{header:"version",value:a=>`${a.running_version===a.version?`${a.version}`:`${a.running_version} \u2192 ${a.version}`}${ah(a)?` (${ih})`:""}`},{header:"source",value:a=>`${a.source.repository}@${a.source.branch}${a.source.path?`/${a.source.path}`:""}`},{header:"url",value:a=>a.url}])})}},ch={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 starts in the new environment at the version it serves, and what ran where it left answers until it is up there: no request goes unanswered. Its address names the new environment (<name>-<its ref>), and the one it had keeps working, for good.","Its domains of its own move with it and answer throughout. 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 (databases:move moves a database).","It moves out of the environment it is bound to; -E picks it where two environments hold its name.","It needs the admin role in both environments, and the new environment room for it."],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=e.flags.to;if(typeof t!="string"||t==="")throw m("--to names the environment of the project it moves to");let{t:n,name:s}=await ue(e,e.args[0]),a=await da(e,n,t);await v(e,n,`move the machine ${s} out of this environment, into ${a.slug}`),await v(e,ie(a),`move the machine ${s} into this environment: it starts here with this environment's settings, secrets and modules`);let i=await B(e,n,"POST",`/machines/${ne(s)}/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}).`))}},hh={name:"machines:get",summary:"a machine of the project in full: the environment it is bound to, its source, size, database and the build serving",usage:"[name]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,machine:n}=await ue(e,e.args[0]);e.out.result(n,()=>{e.out.line(`${n.name} \u2014 ${Ii(n)}${n.state_reason?` (${n.state_reason})`:""}`),e.out.line(` bound to ${t.env_slug}${n.moving_to?`, moving to ${n.moving_to.name||n.moving_to.ref}`:""}`),e.out.line(` url ${n.url}`),e.out.line(` source ${n.source.repository} @ ${n.source.branch}${n.source.path?`, ${n.source.path}`:""}${n.source.context?` (context ${n.source.context})`:""}`),e.out.line(` size ${n.size} \xD7 ${n.replicas}, port ${n.port}${n.health_path?`, health ${n.health_path}`:""}`),n.autoscaling&&e.out.line(` scaling ${lS(n.replicas,n.autoscaling)}`),e.out.line(` version ${Qk(n)}`),n.failed_build&&e.out.line(` last push ${A(`${n.failed_build.commit.slice(0,7)} ${n.failed_build.state}: ${As(n.failed_build.reason)}`)} (palbase machines:builds:log ${A(n.failed_build.id)} --machine ${n.name})`),e.out.line(` contract ${eS(n)}`),e.out.line(` database ${n.database?.name?`${n.database.name}${n.database.migrations?", its migrations run before each release":""}`:"none"}`),e.out.line(` secrets ${n.secrets?`the ${n.secrets} set${ah(n)?` \u2014 ${ih}: its copies start with the new values beside the ones serving, which stop once they are up`:""}`:"none"}`),e.out.line(` tests ${n.test_command?`${n.test_command}${n.test_users?.length?`, as ${n.test_users.join(", ")}`:""} \u2014 run on each build before it rolls out`:"none"}`),e.out.line(` env ${Object.keys(n.env).length===0?"none":Object.keys(n.env).sort().join(", ")}`)})}},mh={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, 1 to 100 (one on Free), over two nodes at least and never all on one \u2014 with --max-replicas, the fewest its load runs (2 at least), spread over nodes as room allows"},"max-replicas":{type:"string",value:"n",description:"scale its copies by its load, up to n (2 to 100; Pay as you go): as many run as keep each near --cpu-percent and --memory-percent of its size"},"cpu-percent":{type:"string",value:"p",description:"with --max-replicas: the share of a copy's processor it is kept near, 10 to 95 (a copy is added above it)"},"memory-percent":{type:"string",value:"p",description:"with --max-replicas: the share of a copy's memory it is kept near, 10 to 95"},"no-autoscaling":{type:"boolean",description:"stop scaling it by its load: it runs --replicas (or the fewest it ran) always"},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 (a project 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"},..._a,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 project it is given, whichever environment keeps it (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 gh(e,t){e.flags["test-command"]!==void 0&&(t.test_command=e.flags["test-command"]),e.flags["test-users"]!==void 0&&(t.test_users=Ro(e.flags["test-users"]))}function fh(e){if(!e)return;let t={};for(let n of e){let s=n.indexOf("=");if(s<=0)throw m(`a setting is K=V, not ${JSON.stringify(n)}`);t[n.slice(0,s)]=n.slice(s+1)}return t}function yh(e,t){let n=ut(e.flags["max-replicas"],"max-replicas"),s=ut(e.flags["cpu-percent"],"cpu-percent"),a=ut(e.flags["memory-percent"],"memory-percent");if(e.flags["no-autoscaling"]===!0){if(n!==void 0||s!==void 0||a!==void 0)throw m("--no-autoscaling stops scaling it: give it alone, not with --max-replicas, --cpu-percent or --memory-percent");return null}if(n===void 0&&s===void 0&&a===void 0)return;let i=n??t?.max_replicas;if(i===void 0)throw m("--cpu-percent and --memory-percent go with --max-replicas: the most copies its load may run");let r=s??t?.cpu_percent,o=a??t?.memory_percent;if(r===void 0&&o===void 0)throw m("with --max-replicas give --cpu-percent, --memory-percent or both: what a copy is kept near");return{max_replicas:i,...r!==void 0?{cpu_percent:r}:{},...o!==void 0?{memory_percent:o}:{}}}function oS(e){return e.running_version===void 0||e.running_version===null||e.version!==e.running_version?`${e.name}: version ${e.version} rolls out${e.running_version?` beside ${e.running_version}`:""}.`:`${e.name}: changed \u2014 version ${e.version} serves on, nothing new rolls out.`}function lS(e,t){let n=[t.cpu_percent?`processor ${t.cpu_percent}%`:"",t.memory_percent?`memory ${t.memory_percent}%`:""].filter(s=>s!=="").join(" and ");return`${e}\u2013${t.max_replicas} copies by its load: ${n} of its size`}function ut(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw m(`--${t} is a whole number`);return n}async function bh(e,t){let{sizes:n}=await B(e,t,"GET","/machines/sizes"),s=n.find(a=>a.available)?.name;if(!s)throw new f("no_size_open","no machine size is open to this environment",{hint:"palbase machines:sizes says why"});return s}function wh(e,t,n){return{...e?{name:e}:{},source:{repository:t.repository,branch:t.branch,...t.path!==""?{path:t.path}:{},...t.context?{context:t.context}:{}},size:n}}var vh={name:"machines:create",summary:"make a machine of the project from the code in this directory, bound to one of its environments and built on every push to its branch",usage:"[name] [-E <env>] [--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.",`${Dn} It takes that environment's settings, secrets and modules.`,"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:{...mh,wait:{type:"boolean",description:"follow the first build until the machine serves"}},scope:"environment",async run(e){let t=await In(e),n=await hs(e.io,e.io.cwd),s=e.flags.repo??n?.repository,a=e.flags.branch??n?.branch;if(!s)throw m("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!a)throw m("which branch? none is checked out here","pass --branch <branch>");let i=e.flags.size??await bh(e,t),r=e.flags.path??n?.path??"",o=wh(e.args[0],{repository:s,branch:a,path:r,context:e.flags.context},i),l=ut(e.flags.replicas,"replicas"),d=ut(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);let p=yh(e);p!==void 0&&(o.autoscaling=p),Sa(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 u=fh(e.flags.var);if(u&&(o.env=u),e.flags.db!==void 0)o.database={name:e.flags.db,migrations:e.flags.migrations===!0};else if(e.flags.migrations===!0)throw m("--migrations goes with --db <database>");gh(e,o),await v(e,t,`make a machine from ${s}@${a}${r?`/${r}`:""} (${i})`);let g=await B(e,t,"POST","/machines",o);e.flags.wait===!0&&(g=await pS(e,t,g.name)),e.out.result(g,()=>e.out.line(`Made the machine ${g.name} (${g.size}) \u2014 ${g.state}; it answers at ${g.url}`))}},_h={name:"machines:update",summary:"change a machine of the project, in the environment it is bound to: 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",details:ye,args:{min:0,max:1},flags:mh,scope:"environment",async run(e){let{t,name:n,machine:s}=await ue(e,e.args[0]),a={};(e.flags.repo!==void 0||e.flags.branch!==void 0||e.flags.path!==void 0||e.flags.context!==void 0)&&(a.source={repository:e.flags.repo??s.source.repository,branch:e.flags.branch??s.source.branch,path:e.flags.path??s.source.path??"",context:e.flags.context??s.source.context??""}),e.flags.size!==void 0&&(a.size=e.flags.size);let i=ut(e.flags.replicas,"replicas"),r=ut(e.flags.port,"port");i!==void 0&&(a.replicas=i),r!==void 0&&(a.port=r),e.flags["always-on"]===!0&&(a.always_on=!0),e.flags["no-always-on"]===!0&&(a.always_on=!1);let o=yh(e,s.autoscaling);if(o!==void 0&&(a.autoscaling=o),Sa(e,a),e.flags.health!==void 0&&(a.health_path=e.flags.health),e.flags["openapi-path"]!==void 0&&(a.openapi_path=e.flags["openapi-path"]),e.flags.secrets!==void 0&&(a.secrets=e.flags.secrets),e.flags.var!==void 0)throw m("machines:update leaves the settings as they are: machines:env:set and machines:env:unset change them");if(e.flags.db!==void 0&&(a.database={name:e.flags.db,migrations:e.flags.migrations===!0}),gh(e,a),Object.keys(a).length===0)throw m("nothing to change: give a flag","palbase help machines:update");await v(e,t,`change the machine ${n}: ${Object.keys(a).join(", ")}`);let l=await B(e,t,"PATCH",`/machines/${ne(n)}`,a);e.out.result(l,()=>e.out.line(oS(l)))}},kh={name:"machines:env:list",summary:"what a machine of the project is started with, and where each comes from (the platform, the machine, its secrets)",usage:"[name]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,machine:n}=await ue(e,e.args[0]),s=n.secrets?(await ws(e,t,x("the machine's secret set",n.secrets))).map(r=>r.name):[],a=["PORT","PALBASE_URL","PALBASE_PROJECT_ID","PALBASE_REPLICAS","PALBASE_PLATFORM_SECRET","PALBASE_SECRET_KEY","PALBASE_WEBHOOK_SECRET",...n.database?.name?["PALBASE_DB_URL","PALBASE_DB_CONNECTIONS","PALBASE_DB_POOLED_URL","PALBASE_DB_POOLED_CONNECTIONS"]:[]],i=a.map(r=>({name:r,from:"platform",note:s.includes(r)||r in n.env?`in place of the ${r} set by hand`:""}));for(let r of Object.keys(n.env).sort())a.includes(r)||i.push({name:r,from:"machine",note:s.includes(r)?`shadows the secret ${r}`:""});for(let r of s.sort())a.includes(r)||r in n.env||i.push({name:r,from:`secrets (${n.secrets})`,note:""});e.out.result({machine:n.name,env:i},()=>e.out.table(i,[{header:"name",value:r=>r.name},{header:"from",value:r=>r.from},{header:"",value:r=>r.note}]))}};async function Sh(e,t){let{t:n,name:s,machine:a,etag:i}=await ue(e,e.flags.machine),r={body:a,etag:i};for(let o=1;;o++){o>1&&(r=await _e(e.studio,n.env_ref,"GET",`/machines/${ne(s)}`));let l={...r.body.env},d=t(l);if(o===1){if(r.body.secrets){let p=r.body.secrets,u=await ws(e,n,x("the machine's secret set",p)).then(g=>g.map(y=>y.name),g=>(e.out.warn(`the ${p} set's names could not be read (${g instanceof Error?g.message:String(g)}): whether a setting shadows a secret is not checked`),[]));for(let g of Object.keys(l))u.includes(g)&&e.out.warn(`${g} in the machine's env shadows the secret of that name`)}await v(e,n,`${d.join(", ")} on the machine ${s}`)}try{let p=await B(e,n,"PATCH",`/machines/${ne(s)}`,{env:l},r.etag?{"if-match":r.etag}:void 0);e.out.result({machine:p.name,env:Object.keys(p.env).sort()},()=>e.out.line(`${p.name}: version ${p.version} rolls out with it.`));return}catch(p){if(!(p instanceof E&&p.status===412)||o===3)throw p;e.out.note(`${s} changed meanwhile: making the change again on what it is now\u2026`)}}}var $h={name:"machines:env:set",summary:"set settings a machine of the project is started with (not secrets: secrets:set keeps those)",usage:"K=V\u2026 [--machine <name>]",details:ye,args:{min:1,max:50},flags:Ge,scope:"environment",async run(e){let t=fh(e.args);await Sh(e,n=>(Object.assign(n,t),Object.keys(t).map(s=>`set ${s}`)))}},Ph={name:"machines:env:unset",summary:"take settings away from what a machine of the project is started with",usage:"K\u2026 [--machine <name>]",details:ye,args:{min:1,max:50},flags:Ge,scope:"environment",async run(e){await Sh(e,t=>{for(let n of e.args){if(!(n in t))throw new f("no_such_setting",`the machine is not started with ${n}`);delete t[n]}return e.args.map(n=>`unset ${n}`)})}},Ah={name:"machines:builds",summary:"a machine's builds, newest first",usage:"[name]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,name:n}=await ue(e,e.args[0]),{builds:s}=await B(e,t,"GET",`/machines/${ne(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 ${As(a.reason)}`:""}`},{header:"message",value:a=>a.message.split(`
|
|
39
39
|
`)[0].slice(0,60)},{header:"created",value:a=>a.created_at}]))}},Rh={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]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,name:n}=await ue(e,e.args[0]),{previews:s}=await B(e,t,"GET",`/machines/${ne(n)}/previews`);e.out.result({previews:s},()=>Xo(e,s,`${n} has no preview: machines:update ${n} --previews previews its pull requests (in a preview environment).`))}},Th=Ho("machine","machines",Li,Ge),Eh=Yo("machine","machines",Li,Ge),Ch=Qo("machine","machines",Li,Ge),jh=Zo("machine","machines",Li,Ge),Oh={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).",...ye],args:{min:1,max:1},flags:Ge,scope:"environment",async run(e){let t=Number(e.args[0].replace(/^#/,""));if(!Number.isInteger(t)||t<=0)throw m("the pull request is its number: 12, or #12");let{t:n,name:s}=await ue(e,e.flags.machine),a=await B(e,n,"POST",`/machines/${ne(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}).`))}},Mh={name:"machines:builds:log",summary:"a build's log (the newest build's when none is named)",usage:"[build] [--machine <name>]",details:ye,args:{min:0,max:1},flags:Ge,scope:"environment",async run(e){let{t,name:n}=await ue(e,e.flags.machine),s=e.args[0];if(!s){let{builds:r}=await B(e,t,"GET",`/machines/${ne(n)}/builds?limit=1`);if(r.length===0)throw new f("no_build",`${n} has no build yet`);s=r[0].id}let a;try{a=await B(e,t,"GET",`/machines/${ne(n)}/builds/${x("the build's id",s)}/log`)}catch(r){if(!(r instanceof E))throw r;if(r.code==="log_not_ready"){e.out.result({build:s,started:!1,log:""},()=>e.out.note(`The build ${s} has not started yet: its log is there once it has (palbase machines:builds ${n}).`));return}if(r.code==="no_log"){let o=await B(e,t,"GET",`/machines/${ne(n)}/builds/${x("the build's id",s)}`);throw new f("no_log",`the build ${s} ended before it ran, so it has no log: ${o.state}${o.reason?` \u2014 ${As(o.reason)}`:""}`)}throw r}let i=typeof a=="string"?a:a==null?"":JSON.stringify(a);e.out.result({build:s,log:i},()=>{if(i==="")e.out.note(`The build ${s} has written no log yet (palbase machines:builds ${n}).`);else for(let r of i.split(`
|
|
40
40
|
`))e.out.line(r)})}},Ih={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>.",...ye],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,name:n}=await ue(e,e.args[0]),s=ut(e.flags.lines,"lines")??200,a=e.flags.since?uS(e.flags.since,e.io.now()):void 0,i=e.flags.search,r=new Set,o=async d=>{let p=new URLSearchParams({lines:String(s),order:d,...a?{since:a}:{},...i?{q:i}:{}}),u=await B(e,t,"GET",`/machines/${ne(n)}/logs?${p}`),g=u!==null&&typeof u=="object"?[u]:String(u??"").split(`
|
|
41
41
|
`).filter(y=>y.trim()!=="").map(y=>JSON.parse(y));return d==="desc"?g.reverse():g},l=d=>{for(let p of d)r.has(p.id)||(r.add(p.id),e.global.json?e.io.stdout(`${JSON.stringify(p)}
|
|
42
42
|
`):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"))}},Lh={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.",...ye],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,name:n}=await ue(e,e.args[0]);await v(e,t,`build and roll out ${n} from the head of its branch`);let s=await B(e,t,"POST",`/machines/${ne(n)}/builds`);e.flags.wait===!0&&(s=await dS(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 dS(e,t,n){let s="";for(let a=0;a<900;a++){let i=await B(e,t,"GET",`/machines/${ne(n)}`);if(!i.build_requested){let{builds:r}=await B(e,t,"GET",`/machines/${ne(n)}/builds?limit=1`),o=r[0];if(!o)throw new f("build_failed",`${n} has no build${i.state_reason?`: ${i.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 f("build_failed",`the build ${o.state}${o.reason?`: ${o.reason}`:""}`,{hint:`palbase machines:builds:log ${o.id} --machine ${n}`});if(o.state==="succeeded"&&i.state==="failed")throw new f("build_failed",`${n}: ${i.state_reason??"failed"}`,{hint:`palbase machines:get ${n}`});if(o.running&&i.running_version===i.version)return i}await e.io.sleep(2e3)}throw new f("timeout",`${n} was not serving the build after 30 minutes`,{hint:`palbase machines:builds ${n}`})}var Dh={name:"machines:rollback",summary:"serve an earlier build again (the one before the serving one, or a named one)",usage:"[name] [--to <build>]",details:ye,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,name:n}=await ue(e,e.args[0]),s=e.flags.to;if(!s){let{builds:i}=await B(e,t,"GET",`/machines/${ne(n)}/builds?limit=50`),r=i.findIndex(l=>l.running),o=i.slice(r+1).find(l=>l.state==="succeeded");if(r<0||!o)throw new f("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 B(e,t,"POST",`/machines/${ne(n)}/rollback`,{build:s});e.out.result(a,()=>e.out.line(`${a.name} rolls back to build ${s} (version ${a.version}).`))}},nl=e=>e.replace(/[\u0000-\u001f\u007f-\u009f]/g," "),Di=(e,t,n="")=>`/machines/${ne(e)}/crons/${x("the cron's name",t)}${n}`,sl=(e,t,n="")=>`/machines/${ne(e)}/tasks/${x("the task's id",t)}${n}`,xh={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]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,name:n}=await ue(e,e.args[0]),s=await B(e,t,"GET",`/machines/${ne(n)}/crons`),a=s.crons??[];e.out.result(s,()=>e.out.table(a,[{header:"cron",value:i=>i.name},{header:"schedule",value:i=>i.schedule},{header:"zone",value:i=>i.time_zone},{header:"next",value:i=>i.paused?"paused":i.next_at??""},{header:"last run",value:i=>i.last_run?`${i.last_run.state} ${i.last_run.started_at??""}${i.last_run.manual?" (run now)":""}`:""}]))}},Nh={name:"machines:crons:runs",summary:"a cron's runs, newest first",usage:"<cron> [--machine <name>]",details:ye,args:{min:1,max:1},flags:Ge,scope:"environment",async run(e){let{t,name:n}=await ue(e,e.flags.machine),s=await B(e,t,"GET",Di(n,e.args[0],"/runs")),a=s.runs??[];e.out.result(s,()=>e.out.table(a,[{header:"run",value:i=>i.id},{header:"state",value:i=>i.manual?`${i.state} (run now)`:i.state},{header:"attempt",value:i=>String(i.attempt)},{header:"started",value:i=>i.started_at??""},{header:"finished",value:i=>i.finished_at??""},{header:"reason",value:i=>nl(i.reason??"")}]))}},qh={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>]",details:ye,args:{min:1,max:1},flags:Ge,scope:"environment",async run(e){let{t,name:n}=await ue(e,e.flags.machine);await v(e,t,`run ${e.args[0]} of ${n} now`);let s=await B(e,t,"POST",Di(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).`))}},Kh={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>]",details:ye,args:{min:1,max:1},flags:Ge,scope:"environment",async run(e){let{t,name:n}=await ue(e,e.flags.machine);await v(e,t,`pause ${e.args[0]} of ${n}`);let s=await B(e,t,"POST",Di(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}.`))}},Gh={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>]",details:ye,args:{min:1,max:1},flags:Ge,scope:"environment",async run(e){let{t,name:n}=await ue(e,e.flags.machine);await v(e,t,`resume ${e.args[0]} of ${n}`);let s=await B(e,t,"POST",Di(n,e.args[0],"/resume"));e.out.result(s,()=>e.out.line(`${s.name} is resumed: next due ${s.next_at??""} (${s.time_zone}).`))}},nh=["waiting","running","succeeded","failed","cancelled"],Uh={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>]",details:ye,args:{min:0,max:0},flags:{...Ge,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&&!nh.includes(t))throw m(`--state ${t} is not one: ${nh.join(", ")}`);let{t:n,name:s}=await ue(e,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 i=await B(e,n,"GET",`/machines/${ne(s)}/tasks${a.size>0?`?${a}`:""}`),r=i.tasks??[];e.out.result(i,()=>e.out.table(r,[{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=>nl(o.reason??"")}]))}},Bh={name:"machines:tasks:types",summary:"the task types a machine's running version declares, and what each one's queue holds",usage:"[name]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,name:n}=await ue(e,e.args[0]),s=await B(e,t,"GET",`/machines/${ne(n)}/task-types`),a=s.types??[];e.out.result(s,()=>e.out.table(a,[{header:"type",value:i=>i.name},{header:"at once",value:i=>String(i.concurrency)},{header:"retries",value:i=>String(i.retries)},{header:"timeout",value:i=>`${i.timeout} s`},{header:"waiting",value:i=>String(i.waiting)},{header:"running",value:i=>String(i.running)},{header:"failed",value:i=>String(i.failed)}]))}},zh={name:"machines:tasks:get",summary:"one task on a machine's queue, with what it carries",usage:"<task id> [--machine <name>]",details:ye,args:{min:1,max:1},flags:Ge,scope:"environment",async run(e){let{t,name:n}=await ue(e,e.flags.machine),s=await B(e,t,"GET",sl(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 ${nl(s.reason)}`:""}`),e.out.line(s.payload===void 0?"payload: not kept \u2014 the task is over":`payload: ${JSON.stringify(s.payload)}`)})}},Wh={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>]",details:ye,args:{min:1,max:1},flags:{...Ge,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 m("--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 m("--delay is whole seconds");let{t:s,name:a}=await ue(e,e.flags.machine);await v(e,s,`put a ${e.args[0]} task on ${a}'s queue`);let i=await B(e,s,"POST",`/machines/${ne(a)}/tasks`,{task:e.args[0],payload:t,...n!==void 0?{delay:n}:{},...e.flags.key?{key:e.flags.key}:{}});e.out.result(i,()=>e.out.line(`${i.task} ${i.id}: ${i.state}, due ${i.run_at}.`))}},Fh={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>]",details:ye,args:{min:1,max:1},flags:Ge,scope:"environment",async run(e){let{t,name:n}=await ue(e,e.flags.machine);await v(e,t,`try task ${e.args[0]} of ${n} again`);let s=await B(e,t,"POST",sl(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.`))}},Jh={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>]",details:ye,args:{min:1,max:1},flags:Ge,scope:"environment",async run(e){let{t,name:n}=await ue(e,e.flags.machine);await v(e,t,`cancel task ${e.args[0]} of ${n}`);let s=await B(e,t,"POST",sl(n,e.args[0],"/cancel"));e.out.result(s,()=>e.out.line(`${s.task} ${s.id} is cancelled: it is not run.`))}},Vh={name:"machines:contract",summary:"the API a Palbase backend serves (its OpenAPI document), as the platform reads it from the machine",usage:"[name]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,name:n}=await ue(e,e.args[0]),s=await B(e,t,"GET",`/machines/${ne(n)}/openapi`);e.io.stdout(`${JSON.stringify(s,null,2)}
|
|
43
|
-
`)}},Hh={name:"machines:delete",summary:"delete a machine of the project, in the environment it is bound to: it stops serving, its address answers nothing",usage:"<name>",details:[te("machine")],args:{min:1,max:1},scope:"environment",async run(e){let{t,name:n}=await ue(e,e.args[0]);if(e.out.note(`${N(t)}: delete the machine ${n}`),!e.global.yes){if(!e.interactive)throw new f("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 f("cancelled","nothing was deleted")}await B(e,t,"DELETE",`/machines/${ne(n)}`),e.out.result({deleted:n},()=>e.out.line(`Deleted the machine ${n}.`))}};async function pS(e,t,n){e.out.note(`Following ${n}'s first build\u2026`);let s="";for(let a=0;a<900;a++){let i=await B(e,t,"GET",`/machines/${ne(n)}`),r=`${i.state}${i.build?` (${i.build.commit.slice(0,7)})`:""}`;if(r!==s&&e.out.note(` ${r}${i.state_reason?` \u2014 ${i.state_reason}`:""}`),s=r,i.running_version>=1&&i.running_version===i.version&&(i.state==="awake"||i.state==="asleep"))return i;if(i.state==="failed")throw new f("build_failed",`${n}'s build failed${i.state_reason?`: ${i.state_reason}`:""}`,{hint:`palbase machines:builds:log --machine ${n}`});await e.io.sleep(2e3)}throw new f("timeout",`${n} was not serving after 30 minutes`,{hint:`palbase machines:get ${n}`})}function uS(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 m(`--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()}function Rs(e,t){return ne(t),bn(e,t)}var Yh={name:"databases:list",summary:"the project's databases, each with the environment that keeps it: size, state, how full",usage:"[-E <env>]",details:["A project's databases are the project's: any machine of the project may be given one, whichever environment keeps it (machines:update --db). The list is every environment's you reach; -E lists that environment's alone, as an environment's own token does."],scope:"environment",async run(e){let t=await jn(e),[n,s]=await Promise.all([rh(e,t,"databases"),ms(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=>`${Ft(s,a.environment)}${a.moving_to?` \u2192 ${Ft(s,a.moving_to)}`:""}`},{header:"size",value:a=>a.size},{header:"state",value:a=>`${Ii(a)}${a.deleted_at?" (deleted)":""}`},{header:"storage",value:a=>`${a.used_bytes!==void 0?`${Mi(a.used_bytes)} of `:""}${Mi(a.quota_bytes)}${a.storage_autoscaling?", autoscaling":""}`},{header:"host",value:a=>a.host}])})}},Xh={name:"databases:get",summary:"a database of the project in full: the environment that keeps it, and how to connect to it",usage:"<name>",details:[te("database")],args:{min:1,max:1},scope:"environment",async run(e){let{t,d:n}=await Rs(e,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}},()=>{if(e.out.line(`${n.name} \u2014 ${n.size}, ${Ii(n)}${n.state_reason?` (${n.state_reason})`:""}`),e.out.line(` bound to ${t.env_slug}`),e.out.line(` host ${n.host}:${n.port} (pooled ${n.pooled_port})`),n.former_hosts?.length&&e.out.line(` also ${n.former_hosts.join(", ")} (its hosts before it moved)`),n.moving_to?e.out.line(` moving to ${n.moving_to.name||n.moving_to.ref}, in a moment`):n.move_note&&e.out.line(` last move ${n.move_note}`),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.storage_gb!==void 0){let a=n.storage_autoscaling?"autoscaling: grows by half when 90% full":"no autoscaling: read-only once full";e.out.line(` storage ${n.storage_gb.toLocaleString("en-US")} GB, ${a} (databases:update --storage grows it)`)}n.used_bytes!==void 0&&e.out.line(` used ${Mi(n.used_bytes)} of ${Mi(n.quota_bytes)}`),n.awake_hours_limit&&e.out.line(` awake ${n.awake_hours??0} h this month; the project's free databases ${n.project_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)"}`)})}},Zh={name:"databases:move",summary:"bind a database to another environment of the project: its data stays as it is, and it answers throughout",usage:"<name> --to <env>",details:["Nothing is copied: the database keeps its data where it is and answers throughout. In a moment it is the new environment's \u2014 what it is counted and paid for from then on, its host (<name>-<its ref>) \u2014 and the host it had keeps working, for good. The machines given it are rolled out to the new host.","Its migrations are the machines' of the environment that keeps it: the machines that run them move with it with --with-machines (each once the database has, its migrations theirs there); without it, such a move is refused, naming them.","It moves out of the environment that keeps it; -E picks it where two environments hold its name.","It needs the admin role in both environments, and the new environment room for it as for a database opened there. The passwords this computer holds for it go with it."],args:{min:1,max:1},flags:{to:{type:"string",value:"env",description:"the environment of the project it moves to (its slug)"},"with-machines":{type:"boolean",description:"move the machines that run its migrations with it"}},scope:"environment",async run(e){let t=e.flags.to;if(typeof t!="string"||t==="")throw m("--to names the environment of the project it moves to");let{t:n,d:{name:s}}=await Rs(e,e.args[0]),a=await da(e,n,t);await v(e,n,`move the database ${s}${e.flags["with-machines"]===!0?", and the machines that run its migrations,":""} out of this environment, into ${a.slug}`),await v(e,ie(a),`move the database ${s} into this environment: it is counted and paid for here`);let i=e.flags["with-machines"]===!0,r=await B(e,n,"POST",`/databases/${ne(s)}/move`,{environment:a.ref,...i?{with_machines:!0}:{}}),o=e.io.now()+6e4;for(;r.moving_to&&e.io.now()<o;)await e.io.sleep(2e3),r=await B(e,n,"GET",`/databases/${ne(s)}`);let l=r.environment?.ref===a.ref,d=await e.state.databasePasswords(n.env_ref,s);if(l&&(d.owner!==void 0||d.app!==void 0)&&(await e.state.keepDatabasePasswords(a.ref,s,d),await e.state.forgetDatabase(n.env_ref,s)),e.out.result(r,()=>{l?e.out.line(`${r.name} is ${a.slug}'s now; ${r.host} is its host, and the one it had keeps working (palbase databases:get ${r.name}).`):r.moving_to?e.out.line(`${r.name} is still moving to ${a.slug} (palbase databases:get ${r.name} shows when it has).`):e.out.line(`${r.name} did not move${r.move_note?`: ${r.move_note}`:""}.`)}),!l&&!r.moving_to)throw new f("database_not_moved",`${r.name} did not move${r.move_note?`: ${r.move_note}`:""}`)}};function Qh(e){if(e!==void 0)return String(e).split(",").map(t=>t.trim()).filter(t=>t!=="")}var em={name:"databases:create",summary:"open a database of the project, kept by one of its environments; its passwords are kept on this computer (the platform shows them once)",usage:"[name] [-E <env>] [--size <size>] [--storage <GB>] [--storage-autoscaling] [--allow <ip/cidr,\u2026>] [--backup-days <n>] [--show-passwords]",details:[`${Dn} It is counted and paid for there; any machine of the project may be given it.`,"A size that never sleeps holds the storage --storage says \u2014 1 GB or a multiple of 5, up to 4,000 \u2014 or the size's own, billed by the GB-month past its first (palbase databases:sizes); with --storage-autoscaling it grows by half when 90% full. free and hobby hold their size's."],args:{min:0,max:1},flags:{size:{type:"string",value:"size",description:"its size (palbase databases:sizes lists what is open)"},storage:{type:"string",value:"GB",description:"what it holds, in GB: 1 or a multiple of 5, up to 4,000 (default: its size's) \u2014 a size that never sleeps"},"storage-autoscaling":{type:"boolean",description:"grow its storage by itself: by half when 90% full, six hours at least apart (default: off, read-only once full)"},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 In(e),n={};e.args[0]&&(n.name=e.args[0]),e.flags.size!==void 0&&(n.size=e.flags.size);let s=ut(e.flags.storage,"storage");s!==void 0&&(n.storage_gb=s),e.flags["storage-autoscaling"]===!0&&(n.storage_autoscaling=!0);let a=Qh(e.flags.allow);a&&(n.allow=a);let i=ut(e.flags["backup-days"],"backup-days");i!==void 0&&(n.backup_days=i);let r=[n.size,s!==void 0?`${s} GB`:void 0].filter(Boolean).join(", ");await v(e,t,`open a database ${e.args[0]??"main"}${r?` (${r})`:""}`);let o=await B(e,t,"POST","/databases",n);await e.state.keepDatabasePasswords(t.env_ref,o.name,{owner:o.credentials.owner.password,app:o.credentials.app.password});let l=e.flags["show-passwords"]===!0,{credentials:d,...p}=o;e.out.result(l?o:{...p,credentials:{owner:tl(d.owner),app:tl(d.app)}},()=>{e.out.line(`Opened the database ${o.name} (${o.size}${o.storage_gb!==void 0?`, ${o.storage_gb} GB${o.storage_autoscaling?", autoscaling":""}`:""}) at ${o.host}.`),e.out.line("Its passwords are kept on this computer: palbase db:url and db:shell use them."),l&&(e.out.line(`owner: ${o.credentials.owner.password??""}`),e.out.line(`app: ${o.credentials.app.password??""}`))})}},el="[YOUR-PASSWORD]";function tl(e){let{password:t,...n}=e,s={};for(let[a,i]of Object.entries(n))s[a]=typeof i=="string"?cS(i,t):i;return s}function cS(e,t){let n=e.replace(/(postgres(?:ql)?:\/\/[^:/@\s'"]+:)[^@\s'"]*(@)/gi,`$1${el}$2`).replace(/([?&;]password=)[^&;\s'"]*/gi,`$1${el}`);if(t)for(let s of new Set([t,encodeURIComponent(t),new URLSearchParams({p:t}).toString().slice(2)]))n=n.split(s).join(el);return n}var tm={name:"databases:update",summary:"change a project database's size, its storage, who may connect to it, or how long its backups are kept",usage:'<name> [--size <size>] [--storage <GB>] [--storage-autoscaling|--no-storage-autoscaling] [--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.","--storage grows what a size that never sleeps holds, where it is, serving on: more than it holds, 1 GB or a multiple of 5, up to 4,000 \u2014 never less, and six hours at least after it last grew. It keeps it through a change of size.",te("database")],args:{min:1,max:1},flags:{size:{type:"string",value:"size",description:"the size to move it to"},storage:{type:"string",value:"GB",description:"what it holds, grown, in GB: 1 or a multiple of 5, up to 4,000"},"storage-autoscaling":{type:"boolean",description:"grow its storage by itself: by half when 90% full, six hours at least apart"},"no-storage-autoscaling":{type:"boolean",description:"grow it only when asked: read-only once full"},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={},n=e.flags.size;if(n!==void 0){if(n==="")throw m("--size is one of palbase databases:sizes");t.size=n}let s=ut(e.flags.storage,"storage");if(s!==void 0&&(t.storage_gb=s),e.flags["storage-autoscaling"]===!0&&e.flags["no-storage-autoscaling"]===!0)throw m("--storage-autoscaling or --no-storage-autoscaling, not both");e.flags["storage-autoscaling"]===!0&&(t.storage_autoscaling=!0),e.flags["no-storage-autoscaling"]===!0&&(t.storage_autoscaling=!1);let a=Qh(e.flags.allow);a&&(t.allow=a);let i=ut(e.flags["backup-days"],"backup-days");if(i!==void 0&&(t.backup_days=i),Object.keys(t).length===0)throw m("nothing to change: --size, --storage, --storage-autoscaling, --allow or --backup-days");let{t:r,d:{name:o}}=await Rs(e,e.args[0]);await v(e,r,`change the database ${o}: ${Object.keys(t).join(", ")}`);let l=await B(e,r,"PATCH",`/databases/${ne(o)}`,t);n!==void 0&&e.flags.wait===!0&&(l=await hS(e,r,o,n)),e.out.result(l,()=>{n!==void 0&&e.out.line(l.state==="resizing"?`${l.name} is moving to ${n}, serving on: its sessions on the direct port end once, when its primary moves (palbase databases:get ${l.name} follows it).`:`${l.name} serves at ${l.size} (${l.state}).`),s!==void 0&&e.out.line(`${l.name} holds ${(l.storage_gb??s).toLocaleString("en-US")} GB: it grows where it is, serving on, within a minute or two.`),t.storage_autoscaling!==void 0&&e.out.line(`${l.name}: ${l.storage_autoscaling??t.storage_autoscaling?"its storage grows by half by itself when 90% full":"its storage grows only when asked (databases:update --storage); it is read-only once full"}.`),(a||i!==void 0)&&e.out.line(`${l.name}: allows ${l.allow.length===0?"anyone with the password":l.allow.join(", ")}; backups ${l.backup_days} days.`)})}};async function hS(e,t,n,s){e.out.note(`Following ${n}'s move to ${s}\u2026`);let a="";for(let i=0;i<900;i++){let r=await B(e,t,"GET",`/databases/${ne(n)}`),o=`${r.state}${r.state_reason?` \u2014 ${r.state_reason}`:""}`;if(o!==a&&e.out.note(` ${o}`),a=o,r.size===s&&r.state!=="resizing"&&r.state!=="starting"){if(r.state==="failed")throw new f("resize_failed",`${n} did not come up at ${s}${r.state_reason?`: ${r.state_reason}`:""}`,{hint:`palbase databases:get ${n}`});return r}if(r.size!==s)throw new f("resize_changed",`${n} is asked for ${r.size} now, not ${s}: another change came`,{hint:`palbase databases:get ${n}`});await e.io.sleep(2e3)}throw new f("timeout",`${n} was still moving to ${s} after 30 minutes; it serves on meanwhile`,{hint:`palbase databases:get ${n}`})}var nm={name:"databases:password:reset",summary:"make a project 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.",te("database")],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 m("--role is owner or app");let{t:n,d:{name:s}}=await Rs(e,e.args[0]);await v(e,n,`make the ${t} password of ${s} new`);let i=(await B(e,n,"POST",`/databases/${ne(s)}/password`,{role:t}))[t];if(!i?.password)throw new f("no_password","the platform answered no password");await e.state.keepDatabasePasswords(n.env_ref,s,{[t]:i.password}),await mS(e,n,s),e.out.result(e.flags["show-password"]===!0?i:tl(i),()=>{e.out.line(`The ${t} password of ${s} is new and kept on this computer.`),e.flags["show-password"]===!0&&e.out.line(i.password??"")})}};async function mS(e,t,n){for(let s=0;s<60;s++){if((await B(e,t,"GET",`/databases/${ne(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 f("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 sm={name:"databases:restore",summary:"bring a database of the project back to a moment of its backups",usage:"<name> --to <time>",details:[te("database")],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 m("--to is the moment to go back to, as an RFC 3339 time");let{t:n,d:{name:s}}=await Rs(e,e.args[0]);await v(e,n,`bring ${s} back to ${t} (what was written since goes)`);let a=await B(e,n,"POST",`/databases/${ne(s)}/restore`,{to:new Date(t).toISOString()});e.out.result(a,()=>e.out.line(`${a.name} is being brought back to ${t} \u2014 ${a.state}.`))}};function al(e,t,n,s,a,i,r=!1){return{name:e,summary:t,usage:"<name>",details:[te("database")],args:{min:1,max:1},scope:"environment",async run(o){let{t:l,d:{name:d}}=await Rs(o,o.args[0]);if(n==="DELETE"||s==="/purge"){if(o.out.note(`${N(l)}: ${a(d)}`),!o.global.yes){if(!o.interactive)throw new f("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 f("cancelled","nothing was changed")}}else await v(o,l,a(d));await B(o,l,n,`/databases/${ne(d)}${s}`),r&&await o.state.forgetDatabase(l.env_ref,d),o.out.result({database:d,done:e},()=>o.out.line(i(d)))}}}var am=al("databases:delete","delete a database of the project (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.`),im=al("databases:undelete","take back a database of the project deleted in the last 7 days","POST","/undelete",e=>`take back the database ${e}`,e=>`${e} is back.`),rm=al("databases:purge","delete a deleted database of the project for good, now","POST","/purge",e=>`purging the database ${e} for good`,e=>`${e} is purged.`,!0),om={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 b(e),n=e.flags["all-envs"]===!0?(await Yt(e)).map(ie):[t],s=e.flags.repo;if(typeof e.flags.from=="string"){if(e.flags.device===!0||e.flags["github-token-stdin"]===!0)throw m("--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 m(`--repo names a repository as owner/name: ${JSON.stringify(d)} is none`);await gS(e,t,n,e.flags.from,s);return}if(s!==void 0)throw m("--repo goes with --from: it narrows what a shared installation reaches");let a=await B(e,t,"POST","/machines/github/connect"),i=e.flags["github-token-stdin"]===!0;if(!i&&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 r=i?await Me(e,"a GitHub user's token"):await fS(e,a.client_id),o=await yS(e,r),l=[];for(let d of n){await v(e,d,`link the GitHub account ${o.account}`);let p=await B(e,d,"POST","/machines/github/installations",{installation_id:o.id,user_token:r});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 gS(e,t,n,s,a){let i=await Pe(e.studio),r=i.find(u=>u.ref===s)??i.find(u=>u.project_id===t.project_id&&u.slug===s);if(!r||r.organization_id!==t.org_id)throw new f("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 B(e,ie(r),"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 f("no_installation",`${r.slug} (${r.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 m("which installation? --installation <account|id>",`${r.slug} links ${d.map(u=>u.account).join(", ")}`);let p=[];for(let u of n){if(u.env_ref===r.ref)continue;await v(e,u,`link the GitHub account ${d[0].account}${a?` for ${a.join(", ")} alone`:""}, as ${r.slug} (${r.ref}) links it`);let g=await e.studio.post(`/environments/${x("the environment's ref",u.env_ref)}/github/installations`,{installation_id:d[0].installation_id,from:r.ref,...a?{repositories:a}:{}});p.push({ref:u.env_ref,account:g.account})}e.out.result({linked:p},()=>{for(let u of p)e.out.line(`Linked ${u.account} to ${u.ref}, as ${r.slug} (${r.ref}) links it.`)})}async function fS(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 f("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 i=Math.max(1,a.interval??5),r=e.io.now()+(a.expires_in??900)*1e3;for(;e.io.now()<r;){await e.io.sleep(i*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"){i+=5;continue}if(l.error==="expired_token")break;throw l.error==="access_denied"?new f("access_denied","the sign-in was denied on GitHub"):new f("github_denied",`GitHub's sign-in ended: ${l.error??o.status}`)}}throw new f("expired_code","GitHub's code expired before it was entered",{hint:"run the command again"})}async function yS(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 f("github_unavailable",`GitHub did not list your installations: ${n.status}`);let s=(await n.json()).installations.map(i=>({id:i.id,account:i.account.login}));if(s.length===0)throw new f("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 i=s.find(r=>String(r.id)===a||r.account.toLowerCase()===a.toLowerCase());if(!i)throw new f("no_such_installation",`you reach no installation ${JSON.stringify(a)}: ${s.map(r=>r.account).join(", ")}`);return i}if(s.length===1)return s[0];if(!e.interactive)throw m("which installation? --installation <account>",`yours: ${s.map(i=>i.account).join(", ")}`);for(s.forEach((i,r)=>e.out.note(` ${r+1}) ${i.account}`));;){let i=Number((await e.io.prompt(`Which account? [1-${s.length}] `)).trim());if(Number.isInteger(i)&&i>=1&&i<=s.length)return s[i-1]}}var lm={name:"github:list",summary:"the GitHub accounts linked to the environment, and who linked each",scope:"environment",async run(e){let t=await b(e),{installations:n}=await B(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}])})}},dm={name:"github:repos",summary:"the repositories machines of the environment may be built from",scope:"environment",async run(e){let t=await b(e),{repositories:n}=await B(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":""}]))}},pm={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 b(e),{installations:n}=await B(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 f("no_such_installation",`no linked GitHub account ${JSON.stringify(e.args[0])}`);await v(e,t,`unlink the GitHub account ${s.account}`),await B(e,t,"DELETE",`/machines/github/installations/${s.installation_id}`),e.out.result({unlinked:s},()=>e.out.line(`Unlinked ${s.account}.`))}},bS=["static","server","backend"];function wS(e,t){let n=(e.split("/").filter(s=>s!=="").at(-1)??t.split("/").at(-1)??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^[^a-z]+/,"");for(let s="";s!==n;)s=n,n=n.slice(0,32).replace(/-+$/,"").replace(/-git(?=-|$)/,"git").replace(/-pr(\d+)$/,"pr$1");return n===""?"app":["github","network","sizes"].includes(n)?`${n}-app`:n}function vS(e,t,n){let s={static:"a static web app: a site",server:"a web app that runs on a server: a machine, and a site it serves",backend:"a backend: a machine"};if(e.out.line(`${t.repository}@${t.branch}${t.path?`/${t.path}`:""} (${t.commit.slice(0,7)}): ${t.framework_name||"no framework known"} \u2014 ${s[t.kind]}${n!==t.kind?`; made as ${n} (--as)`:""}`),e.out.line(` why ${t.why}`),n==="static"){let a=t.build??{};e.out.line(` install ${a.install_command||"found as it builds"}`),e.out.line(` build ${a.command||"found as it builds"}`),e.out.line(` output ${a.output_dir||"found as it builds"}`),t.node&&e.out.line(` node ${t.node}`)}else e.out.line(` dockerfile ${t.dockerfile?"its own":"none: its language is found as it builds"}`)}var um={name:"hosting:import",summary:"import a GitHub repository's directory, as Vercel does: what it is found to be \u2014 a static web app, a web app that runs on a server, a backend \u2014 is made and built on every push",usage:"[-E <env>] [--repo <owner/name>] [--branch <branch>] [--path <dir>] [--name <name>] [--as static|server|backend]",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.",`What it makes is the project's. ${Dn}`,"What the directory is, is read on GitHub at the branch's head \u2014 its package.json, its framework's configuration, its lockfile, its Node.js version \u2014 and printed before anything is made; at a terminal you are asked to go ahead.","static: a site, built as found. server (Next.js, Nuxt, SvelteKit on a server): a machine, and a site of its name with no files whose server it is \u2014 its address on the hosting domain, and its CDN. backend: a machine. --as makes it the other way.","A static site's pull requests and other branches, and a web app's pull requests, are previewed from the start \u2014 for the project's team alone (hosting:previews:link shares one); a backend's previews are turned on as a machine's are (machines:update --previews).","The environment needs its GitHub link first: palbase github:connect."],flags:{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 (default: the one checked out)"},path:{type:"string",value:"dir",description:"the directory, from the repository's root (default: this directory's place in it)"},name:{type:"string",value:"name",description:"the site's and the machine's name (default: the directory's, or the repository's at its root)"},as:{type:"string",value:"static|server|backend",description:"make it as this, whatever it is found to be"}},scope:"environment",async run(e){let t=e.flags.as;if(t!==void 0&&!bS.includes(t))throw m("--as is static, server or backend");let n=await In(e),s=await hs(e.io,e.io.cwd),a=e.flags.repo??s?.repository,i=e.flags.branch??s?.branch;if(!a)throw m("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!i)throw m("which branch? none is checked out here","pass --branch <branch>");let r=e.flags.path??(e.flags.repo===void 0?s?.path??"":""),o=e.flags.name??wS(r,a);ne(o);let l;try{l=await B(e,n,"GET",`/machines/github/detect?${new URLSearchParams({repository:a,branch:i,...r!==""?{path:r}:{}})}`)}catch(_){if(!(_ instanceof E&&_.code==="project_not_detected"))throw _;if(t===void 0)throw new f(_.code,_.message,{hint:"say what it is with --as static|server|backend"});e.out.warn(`${_.message}: it is made as --as ${t} says`)}let d=t??l?.kind;l&&!e.global.json&&vS(e,l,d);for(let _ of l?.warnings??[])e.out.warn(_);let p={repository:a,branch:i,path:r},u=`${a}@${i}${r?`/${r}`:""}`,g=d==="static"?void 0:await bh(e,n),y={static:`the site ${o}, built from ${u}`,server:`the machine ${o} from ${u} (${g}), and the site ${o} it serves`,backend:`the machine ${o} from ${u} (${g})`}[d];await v(e,n,`make ${y}`,e.interactive?`This makes ${y}`:void 0);let w={kind:d,...l?{detection:l}:{}};if(d==="static"){let _=l?.build;w.site=await B(e,n,"POST","/sites",{name:o,source:p,previews:!0,..._?{build:{install_command:_.install_command,command:_.command,output_dir:_.output_dir,env:{}}}:{}})}else{let _=await B(e,n,"POST","/machines",{...wh(o,p,g),...d==="server"?{previews:!0}:{}});if(w.machine=_,d==="server")try{w.site=await B(e,n,"POST","/sites",{name:o,server:{machine:_.name,paths:[]}})}catch(P){throw P instanceof E?new f(P.code,`made the machine ${_.name}, not its site: ${P.message}`,{hint:`palbase hosting:sites:create ${o} --server ${_.name} makes it`}):P}}e.out.result(w,()=>{let{machine:_,site:P}=w;_&&e.out.line(`Made the machine ${_.name} (${_.size}): ${_.url}`),P&&e.out.line(`Opened the site ${P.name}: ${P.url}${P.server?` \u2014 ${P.server.machine} answers it`:""}`),e.out.line(_?`Its first build is on its way: palbase machines:builds ${_.name} lists it, machines:builds:log <build> --machine ${_.name} prints its log.`:`Its first build is on its way: palbase hosting:builds --site ${P.name} lists it, hosting:builds <build> --site ${P.name} --wait follows it.`)})}};var xe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0;function Zt(e,t,n){let s=xe(xe(xe(e)?.components)?.schemas)??{},a=(p,u)=>{let g=new Set,y=(_,P,S)=>{let $=xe(_);if(!$)return;if(typeof $.$ref=="string"){if(S.has($.$ref)||!$.$ref.startsWith("#/components/schemas/"))return;y(s[$.$ref.slice(21)],P,new Set(S).add($.$ref));return}if($[bi]===!0){g.add(P);return}for(let T of["anyOf","oneOf","allOf"]){let D=$[T];if(Array.isArray(D))for(let U of D)y(U,P,S)}let R=xe($.properties);if(R)for(let[T,D]of Object.entries(R))y(D,`${P}/${ki(T)}`,S);xe($.items)&&y($.items,`${P}/*`,S);for(let T of["additionalProperties","patternProperties","prefixItems"])if($[T]!==void 0&&w($[T],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=(_,P)=>{if(Array.isArray(_))return _.some($=>w($,P));let S=xe(_);return S?S[bi]===!0?!0:typeof S.$ref=="string"&&!P.has(S.$ref)&&S.$ref.startsWith("#/components/schemas/")?(P.add(S.$ref),w(s[S.$ref.slice(21)],P)):Object.values(S).some($=>typeof $=="object"&&$!==null&&w($,P)):!1};return y(p,u,new Set),[...g]},i=p=>xe(xe(xe(p)?.["application/json"])?.schema),r=[];r.push(...a(i(xe(t.requestBody)?.content),"/body"));for(let p of Array.isArray(t.parameters)?t.parameters:[]){let u=xe(p);if(!u)continue;let g=a(u.schema,`/query/${ki(String(u.name))}`);if(g.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(g.some(y=>y.split("/").length!==3))throw new Error(`${n}: an encrypted query field is one of the query's own names`);r.push(...g)}}let o=xe(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(i(xe(o[l[0]])?.content),"/response"):[];if(r.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:r,response:d}}}function cm(e){return JSON.stringify(e??null).includes(`"${bi}":true`)}async function hm(e){let t=`${e.method.toUpperCase()} ${e.path}`,n=xe(xe(xe(xe(e.contract)?.paths)?.[e.path])?.[e.method.toLowerCase()]),s=n?Zt(e.contract,n,t):void 0;if(!s)return{body:e.body,query:e.query,open:async o=>o};let{key:a,header:i}=await jp(e.key.kid,Mt(e.key.publicKey),vi(e.projectId,e.method,e.path,e.params??[])),r=(o,l)=>o==null?o:vs(o,l,s.request,(d,p)=>fa(a,d,p));return{header:i,body:await r(e.body,"/body"),query:await r(e.query,"/query"),open:o=>o===void 0?Promise.resolve(o):vs(o,"/response",s.response,async(l,d)=>{if(!ya(d))throw new Ae("unopenable",`${t}: ${l} came plain where the contract says it is encrypted`);return _i(a,l,d)})}}var mm=["GET","POST","PUT","PATCH","DELETE"];function _S(e,t,n){let s=n.split("/").filter(Boolean);for(let[a,i]of Object.entries(e.paths??{})){let r=i?.[t.toLowerCase()];if(typeof r!="object"||r===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:r}}}var gm={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.",`${te("machine")} Its encrypted fields are sealed to that environment's key.`],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,n,s]=e.args,a=n.toUpperCase();if(!mm.includes(a))throw m(`${n} is not a method a route answers`,`one of ${mm.join(", ")}`);if(!s.startsWith("/"))throw m(`${s}: 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 m("--data is JSON",`--data '{"name":"x"}'`)}let{t:r,machine:o}=await ue(e,t),l=x("the machine's name",o.name),{body:d}=await _e(e.studio,r.env_ref,"GET",`/machines/${l}/openapi`),p=new URL(o.url),u=new URL(s,p);if(u.origin!==p.origin||u.pathname.startsWith("//"))throw m(`${s} is not a path of ${t}`,"palbase machines:call api GET /patients/p1");let g=_S(d,a,u.pathname);if(!g)throw new f("route_not_found",`${t}'s contract has no ${a} ${u.pathname}`,{hint:`palbase machines:contract ${t} lists its routes`});let y=u.search===""?void 0:Object.fromEntries(u.searchParams),w,_="";if(Zt(d,g.op,`${a} ${g.template}`)){_=(await e.studio.get(`/environments/${r.env_ref}`)).platform_id;let{body:W}=await _e(e.studio,r.env_ref,"GET","/secrets/transit"),I=W.keys.find(F=>F.id===W.current);if(!I)throw new f("no_transit_key","the project has no transit key in use: palbase transit:list says what there is");w={kid:I.id,publicKey:I.public_key}}let P=w?await hm({contract:d,method:a,path:g.template,params:g.params,body:i,query:y,projectId:_,key:w}):{body:i,query:y,header:void 0,open:async U=>U},S=new URL(p.origin);S.pathname=u.pathname;for(let[U,W]of Object.entries(P.query??{}))S.searchParams.set(U,typeof W=="string"?W:JSON.stringify(W));let $={accept:"application/json"};P.body!==void 0&&($["content-type"]="application/json"),e.flags.token&&($.authorization=`Bearer ${e.flags.token}`),P.header&&($[yt]=P.header);let R=await e.io.fetch(S.href,{method:a,headers:$,body:P.body===void 0?void 0:JSON.stringify(P.body),redirect:"manual"}),T=await R.text(),D=T;if(T!=="")try{D=JSON.parse(T)}catch{}return R.ok&&typeof D=="object"&&(D=await P.open(D)),e.out.result({status:R.status,encrypted:w!==void 0,answer:D},()=>{e.out.line(`${R.status} ${a} ${u.pathname}${w?` (its encrypted fields sealed to ${w.kid}, the answer's opened)`:""}`),T!==""&&e.out.line(typeof D=="string"?D:JSON.stringify(D,null,2))}),R.ok?0:1}};import{createHash as Lg}from"node:crypto";import{lstat as HP,mkdir as YP,mkdtemp as XP,readdir as Sl,readFile as ja,rm as Dg,rmdir as ZP,writeFile as QP}from"node:fs/promises";import{tmpdir as eA}from"node:os";import{dirname as tA,join as pt,relative as ar,resolve as Og,sep as sr}from"node:path";function $S(e){return e.replace(/\s+/g," ").trim()}var Fq=String.raw`
|
|
43
|
+
`)}},Hh={name:"machines:delete",summary:"delete a machine of the project, in the environment it is bound to: it stops serving, its address answers nothing",usage:"<name>",details:[te("machine")],args:{min:1,max:1},scope:"environment",async run(e){let{t,name:n}=await ue(e,e.args[0]);if(e.out.note(`${N(t)}: delete the machine ${n}`),!e.global.yes){if(!e.interactive)throw new f("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 f("cancelled","nothing was deleted")}await B(e,t,"DELETE",`/machines/${ne(n)}`),e.out.result({deleted:n},()=>e.out.line(`Deleted the machine ${n}.`))}};async function pS(e,t,n){e.out.note(`Following ${n}'s first build\u2026`);let s="";for(let a=0;a<900;a++){let i=await B(e,t,"GET",`/machines/${ne(n)}`),r=`${i.state}${i.build?` (${i.build.commit.slice(0,7)})`:""}`;if(r!==s&&e.out.note(` ${r}${i.state_reason?` \u2014 ${i.state_reason}`:""}`),s=r,i.running_version>=1&&i.running_version===i.version&&(i.state==="awake"||i.state==="asleep"))return i;if(i.state==="failed")throw new f("build_failed",`${n}'s build failed${i.state_reason?`: ${i.state_reason}`:""}`,{hint:`palbase machines:builds:log --machine ${n}`});await e.io.sleep(2e3)}throw new f("timeout",`${n} was not serving after 30 minutes`,{hint:`palbase machines:get ${n}`})}function uS(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 m(`--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()}function Rs(e,t){return ne(t),bn(e,t)}var Yh={name:"databases:list",summary:"the project's databases, each with the environment that keeps it: size, state, how full",usage:"[-E <env>]",details:["A project's databases are the project's: any machine of the project may be given one, whichever environment keeps it (machines:update --db). The list is every environment's you reach; -E lists that environment's alone, as an environment's own token does."],scope:"environment",async run(e){let t=await jn(e),[n,s]=await Promise.all([rh(e,t,"databases"),ms(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=>`${Ft(s,a.environment)}${a.moving_to?` \u2192 ${Ft(s,a.moving_to)}`:""}`},{header:"size",value:a=>a.size},{header:"state",value:a=>`${Ii(a)}${a.deleted_at?" (deleted)":""}`},{header:"storage",value:a=>`${a.used_bytes!==void 0?`${Mi(a.used_bytes)} of `:""}${Mi(a.quota_bytes)}${a.storage_autoscaling?", autoscaling":""}`},{header:"host",value:a=>a.host}])})}},Xh={name:"databases:get",summary:"a database of the project in full: the environment that keeps it, and how to connect to it",usage:"<name>",details:[te("database")],args:{min:1,max:1},scope:"environment",async run(e){let{t,d:n}=await Rs(e,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}},()=>{if(e.out.line(`${n.name} \u2014 ${n.size}, ${Ii(n)}${n.state_reason?` (${n.state_reason})`:""}`),e.out.line(` bound to ${t.env_slug}`),e.out.line(` host ${n.host}:${n.port} (pooled ${n.pooled_port})`),n.former_hosts?.length&&e.out.line(` also ${n.former_hosts.join(", ")} (its hosts before it moved)`),n.moving_to?e.out.line(` moving to ${n.moving_to.name||n.moving_to.ref}, in a moment`):n.move_note&&e.out.line(` last move ${n.move_note}`),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.storage_gb!==void 0){let a=n.storage_autoscaling?"autoscaling: grows by half when 90% full":"no autoscaling: read-only once full";e.out.line(` storage ${n.storage_gb.toLocaleString("en-US")} GB, ${a} (databases:update --storage grows it)`)}n.used_bytes!==void 0&&e.out.line(` used ${Mi(n.used_bytes)} of ${Mi(n.quota_bytes)}`),n.awake_hours_limit&&e.out.line(` awake ${n.awake_hours??0} h this month; the project's free databases ${n.project_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)"}`)})}},Zh={name:"databases:move",summary:"bind a database to another environment of the project: its data stays as it is, and it answers throughout",usage:"<name> --to <env>",details:["Nothing is copied: the database keeps its data where it is and answers throughout. In a moment it is the new environment's \u2014 what it is counted and paid for from then on, its host (<name>-<its ref>) \u2014 and the host it had keeps working, for good. The machines given it are rolled out to the new host.","Its migrations are the machines' of the environment that keeps it: the machines that run them move with it with --with-machines (each once the database has, its migrations theirs there); without it, such a move is refused, naming them.","It moves out of the environment that keeps it; -E picks it where two environments hold its name.","It needs the admin role in both environments, and the new environment room for it as for a database opened there. The passwords this computer holds for it go with it."],args:{min:1,max:1},flags:{to:{type:"string",value:"env",description:"the environment of the project it moves to (its slug)"},"with-machines":{type:"boolean",description:"move the machines that run its migrations with it"}},scope:"environment",async run(e){let t=e.flags.to;if(typeof t!="string"||t==="")throw m("--to names the environment of the project it moves to");let{t:n,d:{name:s}}=await Rs(e,e.args[0]),a=await da(e,n,t);await v(e,n,`move the database ${s}${e.flags["with-machines"]===!0?", and the machines that run its migrations,":""} out of this environment, into ${a.slug}`),await v(e,ie(a),`move the database ${s} into this environment: it is counted and paid for here`);let i=e.flags["with-machines"]===!0,r=await B(e,n,"POST",`/databases/${ne(s)}/move`,{environment:a.ref,...i?{with_machines:!0}:{}}),o=e.io.now()+6e4;for(;r.moving_to&&e.io.now()<o;)await e.io.sleep(2e3),r=await B(e,n,"GET",`/databases/${ne(s)}`);let l=r.environment?.ref===a.ref,d=await e.state.databasePasswords(n.env_ref,s);if(l&&(d.owner!==void 0||d.app!==void 0)&&(await e.state.keepDatabasePasswords(a.ref,s,d),await e.state.forgetDatabase(n.env_ref,s)),e.out.result(r,()=>{l?e.out.line(`${r.name} is ${a.slug}'s now; ${r.host} is its host, and the one it had keeps working (palbase databases:get ${r.name}).`):r.moving_to?e.out.line(`${r.name} is still moving to ${a.slug} (palbase databases:get ${r.name} shows when it has).`):e.out.line(`${r.name} did not move${r.move_note?`: ${r.move_note}`:""}.`)}),!l&&!r.moving_to)throw new f("database_not_moved",`${r.name} did not move${r.move_note?`: ${r.move_note}`:""}`)}};function Qh(e){if(e!==void 0)return String(e).split(",").map(t=>t.trim()).filter(t=>t!=="")}var em={name:"databases:create",summary:"open a database of the project, kept by one of its environments; its passwords are kept on this computer (the platform shows them once)",usage:"[name] [-E <env>] [--size <size>] [--storage <GB>] [--storage-autoscaling] [--allow <ip/cidr,\u2026>] [--backup-days <n>] [--show-passwords]",details:[`${Dn} It is counted and paid for there; any machine of the project may be given it.`,"A size that never sleeps holds the storage --storage says \u2014 1 GB or a multiple of 5, up to 4,000 \u2014 or the size's own, billed by the GB-month past its first (palbase databases:sizes); with --storage-autoscaling it grows by half when 90% full. free and hobby hold their size's."],args:{min:0,max:1},flags:{size:{type:"string",value:"size",description:"its size (palbase databases:sizes lists what is open)"},storage:{type:"string",value:"GB",description:"what it holds, in GB: 1 or a multiple of 5, up to 4,000 (default: its size's) \u2014 a size that never sleeps"},"storage-autoscaling":{type:"boolean",description:"grow its storage by itself: by half when 90% full, six hours at least apart (default: off, read-only once full)"},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 In(e),n={};e.args[0]&&(n.name=e.args[0]),e.flags.size!==void 0&&(n.size=e.flags.size);let s=ut(e.flags.storage,"storage");s!==void 0&&(n.storage_gb=s),e.flags["storage-autoscaling"]===!0&&(n.storage_autoscaling=!0);let a=Qh(e.flags.allow);a&&(n.allow=a);let i=ut(e.flags["backup-days"],"backup-days");i!==void 0&&(n.backup_days=i);let r=[n.size,s!==void 0?`${s} GB`:void 0].filter(Boolean).join(", ");await v(e,t,`open a database ${e.args[0]??"main"}${r?` (${r})`:""}`);let o=await B(e,t,"POST","/databases",n);await e.state.keepDatabasePasswords(t.env_ref,o.name,{owner:o.credentials.owner.password,app:o.credentials.app.password});let l=e.flags["show-passwords"]===!0,{credentials:d,...p}=o;e.out.result(l?o:{...p,credentials:{owner:tl(d.owner),app:tl(d.app)}},()=>{e.out.line(`Opened the database ${o.name} (${o.size}${o.storage_gb!==void 0?`, ${o.storage_gb} GB${o.storage_autoscaling?", autoscaling":""}`:""}) at ${o.host}.`),e.out.line("Its passwords are kept on this computer: palbase db:url and db:shell use them."),l&&(e.out.line(`owner: ${o.credentials.owner.password??""}`),e.out.line(`app: ${o.credentials.app.password??""}`))})}},el="[YOUR-PASSWORD]";function tl(e){let{password:t,...n}=e,s={};for(let[a,i]of Object.entries(n))s[a]=typeof i=="string"?cS(i,t):i;return s}function cS(e,t){let n=e.replace(/(postgres(?:ql)?:\/\/[^:/@\s'"]+:)[^@\s'"]*(@)/gi,`$1${el}$2`).replace(/([?&;]password=)[^&;\s'"]*/gi,`$1${el}`);if(t)for(let s of new Set([t,encodeURIComponent(t),new URLSearchParams({p:t}).toString().slice(2)]))n=n.split(s).join(el);return n}var tm={name:"databases:update",summary:"change a project database's size, its storage, who may connect to it, or how long its backups are kept",usage:'<name> [--size <size>] [--storage <GB>] [--storage-autoscaling|--no-storage-autoscaling] [--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.","--storage grows what a size that never sleeps holds, where it is, serving on: more than it holds, 1 GB or a multiple of 5, up to 4,000 \u2014 never less, and six hours at least after it last grew. It keeps it through a change of size.",te("database")],args:{min:1,max:1},flags:{size:{type:"string",value:"size",description:"the size to move it to"},storage:{type:"string",value:"GB",description:"what it holds, grown, in GB: 1 or a multiple of 5, up to 4,000"},"storage-autoscaling":{type:"boolean",description:"grow its storage by itself: by half when 90% full, six hours at least apart"},"no-storage-autoscaling":{type:"boolean",description:"grow it only when asked: read-only once full"},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={},n=e.flags.size;if(n!==void 0){if(n==="")throw m("--size is one of palbase databases:sizes");t.size=n}let s=ut(e.flags.storage,"storage");if(s!==void 0&&(t.storage_gb=s),e.flags["storage-autoscaling"]===!0&&e.flags["no-storage-autoscaling"]===!0)throw m("--storage-autoscaling or --no-storage-autoscaling, not both");e.flags["storage-autoscaling"]===!0&&(t.storage_autoscaling=!0),e.flags["no-storage-autoscaling"]===!0&&(t.storage_autoscaling=!1);let a=Qh(e.flags.allow);a&&(t.allow=a);let i=ut(e.flags["backup-days"],"backup-days");if(i!==void 0&&(t.backup_days=i),Object.keys(t).length===0)throw m("nothing to change: --size, --storage, --storage-autoscaling, --allow or --backup-days");let{t:r,d:{name:o}}=await Rs(e,e.args[0]);await v(e,r,`change the database ${o}: ${Object.keys(t).join(", ")}`);let l=await B(e,r,"PATCH",`/databases/${ne(o)}`,t);n!==void 0&&e.flags.wait===!0&&(l=await hS(e,r,o,n)),e.out.result(l,()=>{n!==void 0&&e.out.line(l.state==="resizing"?`${l.name} is moving to ${n}, serving on: its sessions on the direct port end once, when its primary moves (palbase databases:get ${l.name} follows it).`:`${l.name} serves at ${l.size} (${l.state}).`),s!==void 0&&e.out.line(`${l.name} holds ${(l.storage_gb??s).toLocaleString("en-US")} GB: it grows where it is, serving on, within a minute or two.`),t.storage_autoscaling!==void 0&&e.out.line(`${l.name}: ${l.storage_autoscaling??t.storage_autoscaling?"its storage grows by half by itself when 90% full":"its storage grows only when asked (databases:update --storage); it is read-only once full"}.`),(a||i!==void 0)&&e.out.line(`${l.name}: allows ${l.allow.length===0?"anyone with the password":l.allow.join(", ")}; backups ${l.backup_days} days.`)})}};async function hS(e,t,n,s){e.out.note(`Following ${n}'s move to ${s}\u2026`);let a="";for(let i=0;i<900;i++){let r=await B(e,t,"GET",`/databases/${ne(n)}`),o=`${r.state}${r.state_reason?` \u2014 ${r.state_reason}`:""}`;if(o!==a&&e.out.note(` ${o}`),a=o,r.size===s&&r.state!=="resizing"&&r.state!=="starting"){if(r.state==="failed")throw new f("resize_failed",`${n} did not come up at ${s}${r.state_reason?`: ${r.state_reason}`:""}`,{hint:`palbase databases:get ${n}`});return r}if(r.size!==s)throw new f("resize_changed",`${n} is asked for ${r.size} now, not ${s}: another change came`,{hint:`palbase databases:get ${n}`});await e.io.sleep(2e3)}throw new f("timeout",`${n} was still moving to ${s} after 30 minutes; it serves on meanwhile`,{hint:`palbase databases:get ${n}`})}var nm={name:"databases:password:reset",summary:"make a project 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.",te("database")],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 m("--role is owner or app");let{t:n,d:{name:s}}=await Rs(e,e.args[0]);await v(e,n,`make the ${t} password of ${s} new`);let i=(await B(e,n,"POST",`/databases/${ne(s)}/password`,{role:t}))[t];if(!i?.password)throw new f("no_password","the platform answered no password");await e.state.keepDatabasePasswords(n.env_ref,s,{[t]:i.password}),await mS(e,n,s),e.out.result(e.flags["show-password"]===!0?i:tl(i),()=>{e.out.line(`The ${t} password of ${s} is new and kept on this computer.`),e.flags["show-password"]===!0&&e.out.line(i.password??"")})}};async function mS(e,t,n){for(let s=0;s<60;s++){if((await B(e,t,"GET",`/databases/${ne(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 f("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 sm={name:"databases:restore",summary:"bring a database of the project back to a moment of its backups",usage:"<name> --to <time>",details:[te("database")],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 m("--to is the moment to go back to, as an RFC 3339 time");let{t:n,d:{name:s}}=await Rs(e,e.args[0]);await v(e,n,`bring ${s} back to ${t} (what was written since goes)`);let a=await B(e,n,"POST",`/databases/${ne(s)}/restore`,{to:new Date(t).toISOString()});e.out.result(a,()=>e.out.line(`${a.name} is being brought back to ${t} \u2014 ${a.state}.`))}};function al(e,t,n,s,a,i,r=!1){return{name:e,summary:t,usage:"<name>",details:[te("database")],args:{min:1,max:1},scope:"environment",async run(o){let{t:l,d:{name:d}}=await Rs(o,o.args[0]);if(n==="DELETE"||s==="/purge"){if(o.out.note(`${N(l)}: ${a(d)}`),!o.global.yes){if(!o.interactive)throw new f("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 f("cancelled","nothing was changed")}}else await v(o,l,a(d));await B(o,l,n,`/databases/${ne(d)}${s}`),r&&await o.state.forgetDatabase(l.env_ref,d),o.out.result({database:d,done:e},()=>o.out.line(i(d)))}}}var am=al("databases:delete","delete a database of the project (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.`),im=al("databases:undelete","take back a database of the project deleted in the last 7 days","POST","/undelete",e=>`take back the database ${e}`,e=>`${e} is back.`),rm=al("databases:purge","delete a deleted database of the project for good, now","POST","/purge",e=>`purging the database ${e} for good`,e=>`${e} is purged.`,!0),om={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 b(e),n=e.flags["all-envs"]===!0?(await Yt(e)).map(ie):[t],s=e.flags.repo;if(typeof e.flags.from=="string"){if(e.flags.device===!0||e.flags["github-token-stdin"]===!0)throw m("--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 m(`--repo names a repository as owner/name: ${JSON.stringify(d)} is none`);await gS(e,t,n,e.flags.from,s);return}if(s!==void 0)throw m("--repo goes with --from: it narrows what a shared installation reaches");let a=await B(e,t,"POST","/machines/github/connect"),i=e.flags["github-token-stdin"]===!0;if(!i&&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 r=i?await Me(e,"a GitHub user's token"):await fS(e,a.client_id),o=await yS(e,r),l=[];for(let d of n){await v(e,d,`link the GitHub account ${o.account}`);let p=await B(e,d,"POST","/machines/github/installations",{installation_id:o.id,user_token:r});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 gS(e,t,n,s,a){let i=await Pe(e.studio),r=i.find(u=>u.ref===s)??i.find(u=>u.project_id===t.project_id&&u.slug===s);if(!r||r.organization_id!==t.org_id)throw new f("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 B(e,ie(r),"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 f("no_installation",`${r.slug} (${r.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 m("which installation? --installation <account|id>",`${r.slug} links ${d.map(u=>u.account).join(", ")}`);let p=[];for(let u of n){if(u.env_ref===r.ref)continue;await v(e,u,`link the GitHub account ${d[0].account}${a?` for ${a.join(", ")} alone`:""}, as ${r.slug} (${r.ref}) links it`);let g=await e.studio.post(`/environments/${x("the environment's ref",u.env_ref)}/github/installations`,{installation_id:d[0].installation_id,from:r.ref,...a?{repositories:a}:{}});p.push({ref:u.env_ref,account:g.account})}e.out.result({linked:p},()=>{for(let u of p)e.out.line(`Linked ${u.account} to ${u.ref}, as ${r.slug} (${r.ref}) links it.`)})}async function fS(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 f("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 i=Math.max(1,a.interval??5),r=e.io.now()+(a.expires_in??900)*1e3;for(;e.io.now()<r;){await e.io.sleep(i*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"){i+=5;continue}if(l.error==="expired_token")break;throw l.error==="access_denied"?new f("access_denied","the sign-in was denied on GitHub"):new f("github_denied",`GitHub's sign-in ended: ${l.error??o.status}`)}}throw new f("expired_code","GitHub's code expired before it was entered",{hint:"run the command again"})}async function yS(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 f("github_unavailable",`GitHub did not list your installations: ${n.status}`);let s=(await n.json()).installations.map(i=>({id:i.id,account:i.account.login}));if(s.length===0)throw new f("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 i=s.find(r=>String(r.id)===a||r.account.toLowerCase()===a.toLowerCase());if(!i)throw new f("no_such_installation",`you reach no installation ${JSON.stringify(a)}: ${s.map(r=>r.account).join(", ")}`);return i}if(s.length===1)return s[0];if(!e.interactive)throw m("which installation? --installation <account>",`yours: ${s.map(i=>i.account).join(", ")}`);for(s.forEach((i,r)=>e.out.note(` ${r+1}) ${i.account}`));;){let i=Number((await e.io.prompt(`Which account? [1-${s.length}] `)).trim());if(Number.isInteger(i)&&i>=1&&i<=s.length)return s[i-1]}}var lm={name:"github:list",summary:"the GitHub accounts linked to the environment, and who linked each",scope:"environment",async run(e){let t=await b(e),{installations:n}=await B(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}])})}},dm={name:"github:repos",summary:"the repositories machines of the environment may be built from",scope:"environment",async run(e){let t=await b(e),{repositories:n}=await B(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":""}]))}},pm={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 b(e),{installations:n}=await B(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 f("no_such_installation",`no linked GitHub account ${JSON.stringify(e.args[0])}`);await v(e,t,`unlink the GitHub account ${s.account}`),await B(e,t,"DELETE",`/machines/github/installations/${s.installation_id}`),e.out.result({unlinked:s},()=>e.out.line(`Unlinked ${s.account}.`))}},bS=["static","server","backend"];function wS(e,t){let n=(e.split("/").filter(s=>s!=="").at(-1)??t.split("/").at(-1)??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^[^a-z]+/,"");for(let s="";s!==n;)s=n,n=n.slice(0,32).replace(/-+$/,"").replace(/-git(?=-|$)/,"git").replace(/-pr(\d+)$/,"pr$1");return n===""?"app":["github","network","sizes"].includes(n)?`${n}-app`:n}function vS(e,t,n){let s={static:"a static web app: a site",server:"a web app that runs on a server: a machine, and a site it serves",backend:"a backend: a machine"};if(e.out.line(`${t.repository}@${t.branch}${t.path?`/${t.path}`:""} (${t.commit.slice(0,7)}): ${t.framework_name||"no framework known"} \u2014 ${s[t.kind]}${n!==t.kind?`; made as ${n} (--as)`:""}`),e.out.line(` why ${t.why}`),n==="static"){let a=t.build??{};e.out.line(` install ${a.install_command||"found as it builds"}`),e.out.line(` build ${a.command||"found as it builds"}`),e.out.line(` output ${a.output_dir||"found as it builds"}`),t.node&&e.out.line(` node ${t.node}`)}else e.out.line(` dockerfile ${t.dockerfile?"its own":"none: its language is found as it builds"}`)}var um={name:"hosting:import",summary:"import a GitHub repository's directory, as Vercel does: what it is found to be \u2014 a static web app, a web app that runs on a server, a backend \u2014 is made and built on every push",usage:"[-E <env>] [--repo <owner/name>] [--branch <branch>] [--path <dir>] [--name <name>] [--as static|server|backend]",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.",`What it makes is the project's. ${Dn}`,"What the directory is, is read on GitHub at the branch's head \u2014 its package.json, its framework's configuration, its lockfile, its Node.js version \u2014 and printed before anything is made; at a terminal you are asked to go ahead.","static: a site, built as found. server (Next.js, Nuxt, SvelteKit on a server): a machine, and a site of its name with no files whose server it is \u2014 its address on the hosting domain, and its CDN. backend: a machine. --as makes it the other way.","A static site's pull requests and other branches, and a web app's pull requests, are previewed from the start \u2014 for the project's team alone (hosting:previews:link shares one); a backend's previews are turned on as a machine's are (machines:update --previews).","The environment needs its GitHub link first: palbase github:connect."],flags:{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 (default: the one checked out)"},path:{type:"string",value:"dir",description:"the directory, from the repository's root (default: this directory's place in it)"},name:{type:"string",value:"name",description:"the site's and the machine's name (default: the directory's, or the repository's at its root)"},as:{type:"string",value:"static|server|backend",description:"make it as this, whatever it is found to be"}},scope:"environment",async run(e){let t=e.flags.as;if(t!==void 0&&!bS.includes(t))throw m("--as is static, server or backend");let n=await In(e),s=await hs(e.io,e.io.cwd),a=e.flags.repo??s?.repository,i=e.flags.branch??s?.branch;if(!a)throw m("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!i)throw m("which branch? none is checked out here","pass --branch <branch>");let r=e.flags.path??(e.flags.repo===void 0?s?.path??"":""),o=e.flags.name??wS(r,a);ne(o);let l;try{l=await B(e,n,"GET",`/machines/github/detect?${new URLSearchParams({repository:a,branch:i,...r!==""?{path:r}:{}})}`)}catch(_){if(!(_ instanceof E&&_.code==="project_not_detected"))throw _;if(t===void 0)throw new f(_.code,_.message,{hint:"say what it is with --as static|server|backend"});e.out.warn(`${_.message}: it is made as --as ${t} says`)}let d=t??l?.kind;l&&!e.global.json&&vS(e,l,d);for(let _ of l?.warnings??[])e.out.warn(_);let p={repository:a,branch:i,path:r},u=`${a}@${i}${r?`/${r}`:""}`,g=d==="static"?void 0:await bh(e,n),y={static:`the site ${o}, built from ${u}`,server:`the machine ${o} from ${u} (${g}), and the site ${o} it serves`,backend:`the machine ${o} from ${u} (${g})`}[d];await v(e,n,`make ${y}`,e.interactive?`This makes ${y}`:void 0);let w={kind:d,...l?{detection:l}:{}};if(d==="static"){let _=l?.build;w.site=await B(e,n,"POST","/sites",{name:o,source:p,previews:!0,..._?{build:{install_command:_.install_command,command:_.command,output_dir:_.output_dir,env:{}}}:{}})}else{let _=await B(e,n,"POST","/machines",{...wh(o,p,g),...d==="server"?{previews:!0}:{}});if(w.machine=_,d==="server")try{w.site=await B(e,n,"POST","/sites",{name:o,server:{machine:_.name,paths:[]}})}catch(P){throw P instanceof E?new f(P.code,`made the machine ${_.name}, not its site: ${P.message}`,{hint:`palbase hosting:sites:create ${o} --server ${_.name} makes it`}):P}}e.out.result(w,()=>{let{machine:_,site:P}=w;_&&e.out.line(`Made the machine ${_.name} (${_.size}): ${_.url}`),P&&e.out.line(`Opened the site ${P.name}: ${P.url}${P.server?` \u2014 ${P.server.machine} answers it`:""}`),e.out.line(_?`Its first build is on its way: palbase machines:builds ${_.name} lists it, machines:builds:log <build> --machine ${_.name} prints its log.`:`Its first build is on its way: palbase hosting:builds --site ${P.name} lists it, hosting:builds <build> --site ${P.name} --wait follows it.`)})}};var xe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0;function Zt(e,t,n){let s=xe(xe(xe(e)?.components)?.schemas)??{},a=(p,u)=>{let g=new Set,y=(_,P,S)=>{let $=xe(_);if(!$)return;if(typeof $.$ref=="string"){if(S.has($.$ref)||!$.$ref.startsWith("#/components/schemas/"))return;y(s[$.$ref.slice(21)],P,new Set(S).add($.$ref));return}if($[bi]===!0){g.add(P);return}for(let T of["anyOf","oneOf","allOf"]){let D=$[T];if(Array.isArray(D))for(let U of D)y(U,P,S)}let R=xe($.properties);if(R)for(let[T,D]of Object.entries(R))y(D,`${P}/${ki(T)}`,S);xe($.items)&&y($.items,`${P}/*`,S);for(let T of["additionalProperties","patternProperties","prefixItems"])if($[T]!==void 0&&w($[T],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=(_,P)=>{if(Array.isArray(_))return _.some($=>w($,P));let S=xe(_);return S?S[bi]===!0?!0:typeof S.$ref=="string"&&!P.has(S.$ref)&&S.$ref.startsWith("#/components/schemas/")?(P.add(S.$ref),w(s[S.$ref.slice(21)],P)):Object.values(S).some($=>typeof $=="object"&&$!==null&&w($,P)):!1};return y(p,u,new Set),[...g]},i=p=>xe(xe(xe(p)?.["application/json"])?.schema),r=[];r.push(...a(i(xe(t.requestBody)?.content),"/body"));for(let p of Array.isArray(t.parameters)?t.parameters:[]){let u=xe(p);if(!u)continue;let g=a(u.schema,`/query/${ki(String(u.name))}`);if(g.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(g.some(y=>y.split("/").length!==3))throw new Error(`${n}: an encrypted query field is one of the query's own names`);r.push(...g)}}let o=xe(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(i(xe(o[l[0]])?.content),"/response"):[];if(r.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:r,response:d}}}function cm(e){return JSON.stringify(e??null).includes(`"${bi}":true`)}async function hm(e){let t=`${e.method.toUpperCase()} ${e.path}`,n=xe(xe(xe(xe(e.contract)?.paths)?.[e.path])?.[e.method.toLowerCase()]),s=n?Zt(e.contract,n,t):void 0;if(!s)return{body:e.body,query:e.query,open:async o=>o};let{key:a,header:i}=await jp(e.key.kid,Mt(e.key.publicKey),vi(e.projectId,e.method,e.path,e.params??[])),r=(o,l)=>o==null?o:vs(o,l,s.request,(d,p)=>fa(a,d,p));return{header:i,body:await r(e.body,"/body"),query:await r(e.query,"/query"),open:o=>o===void 0?Promise.resolve(o):vs(o,"/response",s.response,async(l,d)=>{if(!ya(d))throw new Ae("unopenable",`${t}: ${l} came plain where the contract says it is encrypted`);return _i(a,l,d)})}}var mm=["GET","POST","PUT","PATCH","DELETE"];function _S(e,t,n){let s=n.split("/").filter(Boolean);for(let[a,i]of Object.entries(e.paths??{})){let r=i?.[t.toLowerCase()];if(typeof r!="object"||r===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:r}}}var gm={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.",`${te("machine")} Its encrypted fields are sealed to that environment's key.`],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,n,s]=e.args,a=n.toUpperCase();if(!mm.includes(a))throw m(`${n} is not a method a route answers`,`one of ${mm.join(", ")}`);if(!s.startsWith("/"))throw m(`${s}: 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 m("--data is JSON",`--data '{"name":"x"}'`)}let{t:r,machine:o}=await ue(e,t),l=x("the machine's name",o.name),{body:d}=await _e(e.studio,r.env_ref,"GET",`/machines/${l}/openapi`),p=new URL(o.url),u=new URL(s,p);if(u.origin!==p.origin||u.pathname.startsWith("//"))throw m(`${s} is not a path of ${t}`,"palbase machines:call api GET /patients/p1");let g=_S(d,a,u.pathname);if(!g)throw new f("route_not_found",`${t}'s contract has no ${a} ${u.pathname}`,{hint:`palbase machines:contract ${t} lists its routes`});let y=u.search===""?void 0:Object.fromEntries(u.searchParams),w,_="";if(Zt(d,g.op,`${a} ${g.template}`)){_=(await e.studio.get(`/environments/${r.env_ref}`)).platform_id;let{body:W}=await _e(e.studio,r.env_ref,"GET","/secrets/transit"),I=W.keys.find(F=>F.id===W.current);if(!I)throw new f("no_transit_key","the project has no transit key in use: palbase transit:list says what there is");w={kid:I.id,publicKey:I.public_key}}let P=w?await hm({contract:d,method:a,path:g.template,params:g.params,body:i,query:y,projectId:_,key:w}):{body:i,query:y,header:void 0,open:async U=>U},S=new URL(p.origin);S.pathname=u.pathname;for(let[U,W]of Object.entries(P.query??{}))S.searchParams.set(U,typeof W=="string"?W:JSON.stringify(W));let $={accept:"application/json"};P.body!==void 0&&($["content-type"]="application/json"),e.flags.token&&($.authorization=`Bearer ${e.flags.token}`),P.header&&($[bt]=P.header);let R=await e.io.fetch(S.href,{method:a,headers:$,body:P.body===void 0?void 0:JSON.stringify(P.body),redirect:"manual"}),T=await R.text(),D=T;if(T!=="")try{D=JSON.parse(T)}catch{}return R.ok&&typeof D=="object"&&(D=await P.open(D)),e.out.result({status:R.status,encrypted:w!==void 0,answer:D},()=>{e.out.line(`${R.status} ${a} ${u.pathname}${w?` (its encrypted fields sealed to ${w.kid}, the answer's opened)`:""}`),T!==""&&e.out.line(typeof D=="string"?D:JSON.stringify(D,null,2))}),R.ok?0:1}};import{createHash as Lg}from"node:crypto";import{lstat as HP,mkdir as YP,mkdtemp as XP,readdir as Sl,readFile as ja,rm as Dg,rmdir as ZP,writeFile as QP}from"node:fs/promises";import{tmpdir as eA}from"node:os";import{dirname as tA,join as pt,relative as ar,resolve as Og,sep as sr}from"node:path";function $S(e){return e.replace(/\s+/g," ").trim()}var Fq=String.raw`
|
|
44
44
|
import Foundation
|
|
45
45
|
|
|
46
46
|
/// Any JSON value: what a contract leaves open.
|
|
@@ -537,7 +537,7 @@ public typealias JSONValue = JsonElement
|
|
|
537
537
|
`))+`
|
|
538
538
|
`}function Nm(e){return e.flatMap(t=>/^(?:data class|enum class|sealed class|sealed interface|class|interface|typealias|object|data object) ([A-Za-z_][A-Za-z0-9_]*)/.exec(t)?.[1]??[])}function Pm(e,t,n){for(let s of Nm(t))e.has(s)||e.set(s,n)}function $a(e,t,n){let s=e.get(t);if(s!==void 0)throw new ct("InvalidName",`${s} and ${n} both become ${t} in Kotlin: rename one in the backend`);e.set(t,n)}function ZS(e,t,n){let s=`PB${Je(t.client)}Backend`;return e.push(`val PalbaseClient.${Xe(t.client)}: ${s}`),e.push(` get() = ${s}(palbe(${be(t.machine)}${n?a$(t):""}))`),e.push(""),e.push(`class ${s} internal constructor(override val _pb: PalBackendClient) : PBBackend`),s}function QS(e,t){let n=xi(t),s=!1;t.input!==void 0&&(Pa(e,`${n}Request`,t.input),s=!0),t.output!==void 0&&(s&&e.push(""),Pa(e,`${n}Response`,t.output),s=!0),t.headers!==void 0&&t.upload===void 0&&(s&&e.push(""),Pa(e,`${n}Headers`,t.headers),s=!0),t.query!==void 0&&(s&&e.push(""),Pa(e,`${n}Query`,t.query),s=!0),s&&e.push(""),e$(e,t)}function Pa(e,t,n){switch(n.kind){case"object":qm(e,t,n,0);return;case"array":{let s=[],a=Kn(n.element,`${t}Item`,s);e.push(...s),s.length>0&&e.push(""),e.push(`typealias ${t} = List<${a}>`);return}case"enum":Km(e,t,n,0);return;case"map":{let s=[],a=Kn(n.values,`${t}Value`,s);e.push(...s),s.length>0&&e.push(""),e.push(`typealias ${t} = Map<String, ${a}>${n.nullable?"?":""}`);return}default:e.push(`typealias ${t} = ${Kn(n,t,[])}`)}}function qm(e,t,n,s){let a=" ".repeat(s),i=[],r=Um(n.properties).map(o=>{let l=Kn(o.property.schema,t+Je(o.property.name),i,!o.property.required);return{field:o,type:l,defaultNull:!o.property.required||o.property.schema.nullable}});i.length>0&&(e.push(...i.map(o=>a+o)),e.push("")),e.push(`${a}@Serializable`),e.push(`${a}data class ${t}(`);for(let{field:o,type:l,defaultNull:d}of r)e.push(`${a} @SerialName(${be(o.property.name)})`),e.push(`${a} val ${o.identifier}: ${l}${d?" = null":""},`);e.push(`${a})`)}function Kn(e,t,n,s=!1){let a;switch(e.kind){case"string":a="String";break;case"number":a="Double";break;case"integer":a="Int";break;case"boolean":a="Boolean";break;case"any":a="kotlinx.serialization.json.JsonElement";break;case"enum":Km(n,`${t}Value`,e,0),a=`${t}Value`;break;case"object":qm(n,t,e,0),a=t;break;case"array":a=`List<${Kn(e.element,`${t}Item`,n)}>`;break;case"map":a=`Map<String, ${Kn(e.values,`${t}Value`,n)}>`;break}return(e.nullable||s)&&!a.endsWith("?")?`${a}?`:a}function Km(e,t,n,s){let a=" ".repeat(s);e.push(`${a}@Serializable`),e.push(`${a}enum class ${t}(val wireValue: String) {`);let i=new Map;for(let r of n.values){let o=Bm(r),l=(i.get(o)??0)+1;i.set(o,l);let d=l===1?o:`${o}_${l}`;e.push(`${a} @SerialName(${be(r)})`),e.push(`${a} ${d}(${be(r)}),`)}e.push(`${a}}`)}function e$(e,t){let n=`${xi(t)}Error`;e.push(`sealed class ${n}(message: String, cause: Throwable? = null) : Exception(message, cause) {`);let s=new Map;for(let a of t.errors){if(a.data===void 0)continue;let i=[];s.set(a.name,Kn(a.data,`${Je(a.name)}Data`,i)),e.push(...i.map(r=>` ${r}`)),e.push("")}for(let a of t.errors){let i=Je(a.name);a.data===void 0?e.push(` data object ${i} : ${n}(${be(a.code)})`):e.push(` data class ${i}(val data: ${s.get(a.name)}) : ${n}(${be(a.code)})`)}if(e.push(` data class Other(val backend: BackendError) : ${n}("Backend error", backend)`),e.push(""),e.push(" companion object {"),t.errors.length===0)e.push(` fun from(backend: BackendError): ${n} = Other(backend)`);else{e.push(` fun from(backend: BackendError): ${n} {`),e.push(" val response = backend.envelope ?: return Other(backend)"),e.push(" return when {");for(let a of t.errors){let i=`response.status == ${u$(a.status)} && response.code == ${be(a.code)}`;if(a.data===void 0)e.push(` ${i} -> ${Je(a.name)}`);else{let r=c$(s.get(a.name),"?");e.push(` ${i} ->`),e.push(` response.decodeData(${Un(a.data,r)})?.let(::${Je(a.name)}) ?: Other(backend)`)}}e.push(" else -> Other(backend)"),e.push(" }"),e.push(" }")}e.push(" }"),e.push("}")}function Am(e){return[...e.children.keys()].sort(Es).map(t=>e.children.get(t))}function t$(e,t,n){if(t.length===0)return;let s={path:[],children:new Map,operations:[]};for(let o of t){let l=s;for(let d of Ra(o).slice(0,-1)){let p=l.children.get(d);p===void 0&&(p={path:[...l.path,d],children:new Map,operations:[]},l.children.set(d,p)),l=p}l.operations.push(o)}e.push("");let a=Am(s);a.forEach((o,l)=>{let d=Xe(o.path[o.path.length-1]);e.push(`val ${n}.${d}: ${qn(o.path)}`),e.push(` get() = ${qn(o.path)}(_pb)`),l!==a.length-1&&e.push("")}),e.push("");let i=[...a],r=!0;for(;i.length>0;){let o=i.shift();r||e.push(""),r=!1,e.push(`class ${qn(o.path)} internal constructor(private val client: PalBackendClient) {`);for(let d of Am(o)){let p=Xe(d.path[d.path.length-1]);e.push(` val ${p}: ${qn(d.path)}`),e.push(` get() = ${qn(d.path)}(client)`),e.push(""),i.push(d)}let l=wn(o.operations,d=>d.operationId);l.forEach((d,p)=>{n$(e,d),p!==l.length-1&&e.push("")}),e.length>0&&e[e.length-1]===""&&e.pop(),e.push("}")}}function n$(e,t){if(t.upload!==void 0){r$(e,t);return}let n=xi(t),s=t.method===""?"POST":t.method;if(!/^[a-z][a-z0-9]*$/.test(s.toLowerCase()))throw new ct("InvalidName",`operation ${Ee(t.operationId)}: the method ${Ee(s)} is not an HTTP method's name`);for(let d of t.headers?.properties??[])if(!p$.test(d.name))throw new ct("InvalidName",`operation ${Ee(t.operationId)}: the header ${Ee(d.name)} is no HTTP field name (RFC 9110's token): rename it in the backend`);let a=[];for(let d of t.pathParameters)a.push(`${Xe(d)}: String`);t.input!==void 0&&a.push(`input: ${n}Request`),t.query!==void 0&&a.push(`query: ${n}Query`),t.headers!==void 0&&a.push(`headers: ${n}Headers`);let i=t.sse&&t.output!==void 0,r=i?`: Flow<${n}Response>`:t.output!==void 0?`: ${n}Response`:"",o=i?"streamGenerated":"invokeGenerated",l=Ra(t);e.push(` suspend fun ${Xe(l[l.length-1])}(${a.join(", ")})${r} = try {`),e.push(` client.${o}(`),e.push(` GeneratedRequest${t.input===void 0?"<Unit>":""}(`),e.push(` method = ${be(s)},`),e.push(` path = ${Gm(t)},`),t.query!==void 0&&e.push(...ol("query",t.query,"query",4)),t.headers!==void 0&&e.push(...ol("headers",t.headers,"headers",4)),t.input!==void 0&&e.push(" body = input,"),t.idempotent&&!t.sse&&e.push(" idempotent = true,"),t.attests&&e.push(" attests = true,"),t.encryption&&e.push(` encryption = ${s$(t.encryption)},`),e.push(" ),"),e.push(` ${t.input===void 0?"Unit.serializer()":`${n}Request.serializer()`},`),t.output!==void 0&&e.push(` ${Un(t.output,`${n}Response`)},`),e.push(" )"),e.push(" } catch (error: BackendError) {"),e.push(` throw ${n}Error.from(error)`),e.push(" }")}function s$(e){let t=n=>`listOf(${n.map(be).join(", ")})`;return`GeneratedEncryption(request = ${t(e.request)}, response = ${t(e.response)})`}function a$(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 = PalbaseTransit(projectId = ${be(e.transit.projectId)}, signer = ${be(e.transit.signer)})`}var i$=["file","filename","contentType","onProgress"];function r$(e,t){let n=xi(t);for(let r of t.pathParameters)if(i$.includes(Xe(r)))throw new ct("InvalidName",`operation ${Ee(t.operationId)}: the path parameter ${Ee(r)} is the name of the upload's ${Xe(r)}: rename it in the backend`);let s=[];for(let r of t.pathParameters)s.push(`${Xe(r)}: String`);t.input!==void 0&&s.push(`input: ${n}Request`),t.query!==void 0&&s.push(`query: ${n}Query`),s.push("file: ByteArray","filename: String","contentType: String? = null","onProgress: ((UploadProgress) -> Unit)? = null");let a=t.output!==void 0?`: ${n}Response`:"",i=Ra(t);e.push(` suspend fun ${Xe(i[i.length-1])}(${s.join(", ")})${a} = try {`),e.push(" client.uploadGenerated("),e.push(` GeneratedRequest${t.input===void 0?"<Unit>":""}(`),e.push(` method = ${be("POST")},`),e.push(` path = ${Gm(t)},`),t.query!==void 0&&e.push(...ol("query",t.query,"query",4)),t.input!==void 0&&e.push(" body = input,"),e.push(" ),"),e.push(` ${t.input===void 0?"Unit.serializer()":`${n}Request.serializer()`},`),t.output!==void 0&&e.push(` ${Un(t.output,`${n}Response`)},`),e.push(" file = file,"),e.push(" filename = filename,"),e.push(" contentType = contentType,"),e.push(" onProgress = onProgress,"),e.push(" )"),e.push(" } catch (error: BackendError) {"),e.push(` throw ${n}Error.from(error)`),e.push(" }")}function o$(e,t,n){let s=Im(t.name,t.pattern),a=`${t.name}Event`,i=`${t.name}Send`,r=t.events.length===0?"Nothing":a,o=t.messages.length===0?"Nothing":i,l=(_,P)=>`${t.name}${Je(_.name)}${P}`,d=_=>{if(_.reply===void 0)return"kotlinx.serialization.json.JsonElement";let P=_.reply.nullable&&(_.reply.kind==="object"||_.reply.kind==="array"||_.reply.kind==="enum");return l(_,"Reply")+(P?"?":"")},p=new Map(["pattern","durable","eventNames","topic"].map(_=>[_,`the gateway's ${_}`]));for(let _ of t.params)$a(p,l$(Xe(_)),`${s}'s parameter ${Ee(_)}`);let u=(_,P,S)=>{let $=[];Pa($,P,_);for(let R of Nm($))$a(n,R,S);e.push(...$),e.push("")},g=(_,P,S)=>{let $=new Set([_,"PBGatewayMessage",...P.map(([,R])=>R)]);for(let[R]of P){let T=Je(R.name);if($.has(T))throw new ct("InvalidName",`${s}'s ${S} ${Ee(R.name)} becomes the case ${_}.${T}, which inside ${_} stands in for the type ${T}: rename it in the backend`)}};for(let _ of t.events)u(_.schema,l(_,"Event"),`${s}'s event ${Ee(_.name)}`);if(t.events.length>0){$a(n,a,s),g(a,t.events.map(_=>[_,l(_,"Event")]),"event"),e.push(`sealed interface ${a} {`);for(let _ of t.events)e.push(` data class ${Je(_.name)}(val payload: ${l(_,"Event")}) : ${a}`);e.push("}"),e.push("")}for(let _ of t.messages)u(_.schema,l(_,"Message"),`${s}'s message ${Ee(_.name)}`),_.reply!==void 0&&u(_.reply,l(_,"Reply"),`${s}'s ack of ${Ee(_.name)}`);if(t.messages.length>0){$a(n,i,s),g(i,t.messages.flatMap(_=>[[_,l(_,"Message")],..._.reply===void 0?[]:[[_,l(_,"Reply")]]]),"message"),e.push(`sealed interface ${i} {`);for(let _ of t.messages)e.push(` data class ${Je(_.name)}(val payload: ${l(_,"Message")}) : ${i}, PBGatewayMessage<${i}, ${d(_)}>`);e.push("}"),e.push("")}$a(n,t.name,s);let y=t.params.map(_=>` private val ${Xe(_)}: String,`),w=t.chat?"PBChatGateway":"PBGateway";if(y.length===0?e.push(`class ${t.name} : ${w}<${r}, ${o}> {`):(e.push(`class ${t.name}(`),e.push(...y),e.push(`) : ${w}<${r}, ${o}> {`)),e.push(` override val pattern: String = ${be(t.pattern)}`),e.push(` override val durable: Boolean = ${t.durable}`),e.push(` override val eventNames: List<String> = listOf(${t.events.map(_=>be(_.name)).join(", ")})`),e.push(` override val topic: String get() = ${d$(t)}`),e.push(""),e.push(` override fun decodeEvent(event: String, payload: JsonObject): ${r}? =`),t.events.length===0)e.push(" null");else{e.push(" when (event) {");for(let _ of t.events)e.push(` ${be(_.name)} -> ${a}.${Je(_.name)}(`),e.push(` palbaseGeneratedJson.decodeFromJsonElement(${Rm(_.schema,l(_,"Event"))}, payload),`),e.push(" )");e.push(" else -> null"),e.push(" }")}if(e.push(""),e.push(` override fun encodeMessage(message: ${o}): Pair<String, JsonObject> =`),t.messages.length===0)e.push(" message");else{e.push(" when (message) {");for(let _ of t.messages)e.push(` is ${i}.${Je(_.name)} -> ${be(_.name)} to`),e.push(` palbaseGeneratedJson.encodeToJsonElement(${Rm(_.schema,l(_,"Message"))}, message.payload).jsonObject`);e.push(" }")}if(e.push(""),e.push(` override fun decodeReply(message: ${o}, reply: kotlinx.serialization.json.JsonElement): Any? =`),t.messages.length===0)e.push(" message");else{e.push(" when (message) {");for(let _ of t.messages){let P=_.reply===void 0?"reply":`palbaseGeneratedJson.decodeFromJsonElement(${Un(_.reply,l(_,"Reply"))}, reply)`;e.push(` is ${i}.${Je(_.name)} -> ${P}`)}e.push(" }")}e.push("}")}function Rm(e,t){let n=e.kind!=="object"&&e.kind!=="array"&&e.kind!=="enum";return Un(n?e:{...e,nullable:!1},t)}function l$(e){return e.length>=2&&e.startsWith("`")&&e.endsWith("`")?e.slice(1,-1):e}function d$(e){return e.pattern.split(":").map(n=>{let s=Lm(n);return s===void 0?be(n):Xe(s)}).join(` + ${be(":")} + `)}function Gm(e){let t=new Set(e.pathParameters);return`listOf(${e.path.split("/").filter(s=>s!=="").map(s=>{let a=s.startsWith("{")&&s.endsWith("}")?s.slice(1,-1):void 0,i=a!==void 0&&t.has(a)?a:void 0;return i===void 0?`PathPart.Literal(${be(s)})`:`PathPart.Parameter(${Xe(i)})`}).join(", ")})`}function ol(e,t,n,s){let a=" ".repeat(s),i=[`${a}${e} = buildMap {`];for(let r of Um(t.properties)){let o=`${n}.${r.identifier}`;!r.property.required||r.property.schema.nullable?i.push(`${a} ${o}?.let { value -> put(${be(r.property.name)}, ${Tm("value",r.property.schema)}) }`):i.push(`${a} put(${be(r.property.name)}, ${Tm(o,r.property.schema)})`)}return i.push(`${a}},`),i}var p$=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function u$(e){return e===-2147483648?"(-2147483647 - 1)":String(e)}function Tm(e,t){switch(t.kind){case"string":return e;case"enum":return`${e}.wireValue`;case"array":return`${e}.joinToString(",")`;default:return`${e}.toString()`}}function Un(e,t){let n;switch(e.kind){case"string":n="String.serializer()";break;case"number":n="Double.serializer()";break;case"integer":n="Int.serializer()";break;case"boolean":n="Boolean.serializer()";break;case"any":n="kotlinx.serialization.json.JsonElement.serializer()";break;case"object":case"enum":n=`${t}.serializer()`;break;case"array":n=`ListSerializer(${Un(e.element,`${t}Item`)})`;break;case"map":n=`MapSerializer(String.serializer(), ${Un(e.values,`${t}Value`)})`;break}return e.nullable?`${n}.nullable`:n}function Um(e){let t=new Map;return e.map(n=>{let s=Xe(n.name),a=s.length>=2&&s.startsWith("`")&&s.endsWith("`")?s.slice(1,-1):s,i=t.get(a);if(i!==void 0)throw Cm(`wire keys ${Ee(i)} and ${Ee(n.name)} both become the Kotlin property \`${a}\``);return t.set(a,n.name),{property:n,identifier:s}})}function Ra(e){let t=e.operationId.split(".").filter(n=>n!=="");return t.length===0?["op"]:t}function xi(e){return Ra(e).map(Je).join("")}function qn(e){return`PB${e.map(Je).join("")}Namespace`}function Je(e){return ll(zm(e,!0),e)}function Xe(e){let t=ll(zm(e,!1),e);return dl.has(t)?`\`${t}\``:t}function Bm(e){let t=e.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase()||"VALUE";return ll(/^[0-9]/.test(t)?`_${t}`:t,e)}function ll(e,t){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||/^_+$/.test(e))throw new ct("InvalidName",`${Ee(t)} gives ${Ee(e)}, which is no Kotlin identifier`);return e}function zm(e,t){let n=e.match(/[A-Za-z0-9]+/g)??[];if(n.length===0)return t?"Op":"op";let s=n.map((a,i)=>(i===0&&!t?a.charAt(0).toLowerCase():a.charAt(0).toUpperCase())+a.slice(1)).join("");return/^[0-9]/.test(s)?`_${s}`:s}function c$(e,t){return e.endsWith(t)?e.slice(0,-t.length):e}var h$=/[\x85\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,Wm=e=>`\\u${e.codePointAt(0).toString(16).padStart(4,"0")}`;function be(e){return bm(e).replace(h$,Wm)}function m$(e){return e.replace(/\r\n|[\r\n\x85\u2028\u2029]/g," ").replace(new RegExp(Dm.source,"g"),Wm).replaceAll("*/","* /").replaceAll("/*","/ *").replace(/^(\s*)@/,"$1\\@")}function Ee(e){return`"${e.replace(/[\\"\n\r\t]/g,t=>({"\\":"\\\\",'"':'\\"',"\n":"\\n","\r":"\\r"," ":"\\t"})[t])}"`}function g$(e){return e.replace(/[\t\n\v\f\r\x1c-\x1f\p{Zs}\u2028\u2029]+$/u,"")}var dl=new Set(["as","break","class","continue","do","else","false","for","fun","if","in","interface","is","null","object","package","return","super","this","throw","true","try","typealias","typeof","val","var","when","while"]);function f$(e){if(!Z(e))throw il("the contract is not a JSON object");return Object.hasOwn(e,"x-palbase-roles")?e["x-palbase-roles"]:void 0}function y$(e){if(!Z(e))throw il("root must be an object");let t=J(e,"roles");if(!Array.isArray(t))throw il("the contract's `x-palbase-roles` carries no roles list, so what the stack defines cannot be read from it");let n=t.flatMap(r=>{if(!Z(r))return[];let o=Ze(r,"name");if(o===void 0||o==="")return[];let l=J(r,"isDefault"),d=J(r,"permissions");return[{name:o,description:Ze(r,"description"),isDefault:(Ts(l)?Aa(l):null)??!1,permissions:Array.isArray(d)?d.filter(p=>typeof p=="string"&&p!==""):[]}]}),s=wn(n,r=>r.name);if(s.length===0)return"";let a=[];a.push(""),a.push("// Roles and permissions (generated \u2014 do not edit)"),a.push("//"),a.push("// The roles this environment defines and the permissions they grant. A name"),a.push("// typed by hand is a string the server answers 403 to; a name typed here is a"),a.push("// compile error. Regenerated by `palbase spec` \u2014 a role withdrawn upstream"),a.push("// disappears from this file, so code still naming it stops building rather"),a.push("// than silently losing access."),a.push("enum class PalbaseRole(val key: String) {"),Em(a,s.map(r=>({key:r.name,doc:r.description??(r.isDefault?"Assigned to every new user at signup.":void 0)}))),a.push("}"),a.push(""),a.push("enum class PalbasePermission(val key: String) {");let i=[...new Set(s.flatMap(r=>r.permissions))].sort(Es);return Em(a,i.map(r=>({key:r,doc:void 0}))),a.push("}"),a.join(`
|
|
539
539
|
`)+`
|
|
540
|
-
`}function Em(e,t){let n=new Map;for(let{key:s,doc:a}of t){let i=b$(s),r=n.get(i);if(r!==void 0){e.push(` // codegen: skipped duplicate key ${be(s)} \u2014 collides with ${be(r)}`);continue}n.set(i,s),a!==void 0&&e.push(` /** ${m$(a)} */`),e.push(` ${i}(${be(s)}),`)}}function b$(e){return Bm(e)}var pl=new Map([["AEBuildError","CoreServices"],["AppleEvent","CoreServices"],["AuthEvent","Palbase"],["BackendError","Palbe"],["CFError","CoreFoundation"],["CFHTTPMessage","CFNetwork"],["CFNetServicesError","CFNetwork"],["CFSocketError","CoreFoundation"],["CFStreamError","CoreFoundation"],["CSIdentityQuery","CoreServices"],["CSIdentityQueryEvent","CoreServices"],["CachedURLResponse","Foundation"],["CancellationError","_Concurrency"],["CocoaError","Foundation"],["ConfigurationError","Palbase"],["CustomNSError","Foundation"],["DecodingError","Swift"],["EncodingError","Swift"],["FieldError","Palbe"],["HTTPURLResponse","Foundation"],["LocalizedError","Foundation"],["MDQuery","CoreServices"],["MachError","Foundation"],["MutableURLRequest","Foundation"],["NSBundleResourceRequest","Foundation"],["NSError","Foundation"],["NSMetadataQuery","Foundation"],["NSMutableURLRequest","Foundation"],["NSURLRequest","Foundation"],["NSXPCListenerEndpoint","Foundation"],["PBEndpoint","Palbe"],["PBError","Palbe"],["PBGatewayError","Palbe"],["PBRequest","Palbe"],["PBSseEndpoint","Palbe"],["PBUploadEndpoint","Palbe"],["PBVoidEndpoint","Palbe"],["POSIXError","Foundation"],["PalbaseError","Palbase"],["PalbaseReply","Palbase"],["PortMessage","Foundation"],["PredicateError","Foundation"],["RecoverableError","Foundation"],["SecKeychainEvent","Security"],["SessionChangedError","Palbase"],["URLError","Foundation"],["URLRequest","Foundation"],["URLResponse","Foundation"],["XPCEndpoint","XPC"],["XPCReceivedMessage","XPC"],["XPCRichError","XPC"]]);function Zm(e,t){_$(t);let n=new It,s=R$(e,n),a=N$(e,n),i="PB"
|
|
540
|
+
`}function Em(e,t){let n=new Map;for(let{key:s,doc:a}of t){let i=b$(s),r=n.get(i);if(r!==void 0){e.push(` // codegen: skipped duplicate key ${be(s)} \u2014 collides with ${be(r)}`);continue}n.set(i,s),a!==void 0&&e.push(` /** ${m$(a)} */`),e.push(` ${i}(${be(s)}),`)}}function b$(e){return Bm(e)}var pl=new Map([["AEBuildError","CoreServices"],["AppleEvent","CoreServices"],["AuthEvent","Palbase"],["BackendError","Palbe"],["CFError","CoreFoundation"],["CFHTTPMessage","CFNetwork"],["CFNetServicesError","CFNetwork"],["CFSocketError","CoreFoundation"],["CFStreamError","CoreFoundation"],["CSIdentityQuery","CoreServices"],["CSIdentityQueryEvent","CoreServices"],["CachedURLResponse","Foundation"],["CancellationError","_Concurrency"],["CocoaError","Foundation"],["ConfigurationError","Palbase"],["CustomNSError","Foundation"],["DecodingError","Swift"],["EncodingError","Swift"],["FieldError","Palbe"],["HTTPURLResponse","Foundation"],["LocalizedError","Foundation"],["MDQuery","CoreServices"],["MachError","Foundation"],["MutableURLRequest","Foundation"],["NSBundleResourceRequest","Foundation"],["NSError","Foundation"],["NSMetadataQuery","Foundation"],["NSMutableURLRequest","Foundation"],["NSURLRequest","Foundation"],["NSXPCListenerEndpoint","Foundation"],["PBEndpoint","Palbe"],["PBError","Palbe"],["PBGatewayError","Palbe"],["PBRequest","Palbe"],["PBSseEndpoint","Palbe"],["PBUploadEndpoint","Palbe"],["PBVoidEndpoint","Palbe"],["POSIXError","Foundation"],["PalbaseError","Palbase"],["PalbaseReply","Palbase"],["PortMessage","Foundation"],["PredicateError","Foundation"],["RecoverableError","Foundation"],["SecKeychainEvent","Security"],["SessionChangedError","Palbase"],["URLError","Foundation"],["URLRequest","Foundation"],["URLResponse","Foundation"],["XPCEndpoint","XPC"],["XPCReceivedMessage","XPC"],["XPCRichError","XPC"]]);function Zm(e,t){_$(t);let n=new It,s=R$(e,n),a=N$(e,n),i="PB"+Pt(t.client)+"Backend",r=new Map;k$(s,t.client,i,r);let o="";for(let d of t.header)o+="// "+d+`
|
|
541
541
|
`;o+=`import Foundation
|
|
542
542
|
`,o+=`import Palbase
|
|
543
543
|
`,o+=`import Palbe
|
|
@@ -559,12 +559,12 @@ public typealias JSONValue = JsonElement
|
|
|
559
559
|
// MARK: - Gateways (@Gateway)
|
|
560
560
|
|
|
561
561
|
`;for(let d of a)o+=oP(d,r)+`
|
|
562
|
-
`}return o}function w$(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: "+Ne(e.transit.projectId)+", signer: "+Ne(e.transit.signer)+")"}var v$=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 _$(e){if(!/^[a-z][A-Za-z0-9]*$/.test(e.client)||v$.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 qi(e,t){let n=pl.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 k$(e,t,n,s){qi(`client ${JSON.stringify(t)}`,n),s.set(he(n),`client ${JSON.stringify(t)}`);for(let a of e){let i=Bi(a.operationID);for(let r=1;r<i.length;r++){let o=`operation ${JSON.stringify(a.operationID)}, in namespace ${JSON.stringify(i.slice(0,r).join("."))},`,l=hl(i.slice(0,r),n);qi(o,l),s.has(he(l))||s.set(he(l),`namespace ${JSON.stringify(i.slice(0,r).join("."))}`)}}}function S$(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 $$=new Intl.Segmenter("en",{granularity:"grapheme"});function Pt(e){return Array.from($$.segment(e),t=>t.segment)}function he(e){return e.normalize("NFC")}function Re(e,t){return he(e)===he(t)}function xt(e,t){let n=Array.from(he(e)),s=Array.from(he(t));for(let a=0;a<n.length&&a<s.length;a++){let i=n[a].codePointAt(0)-s[a].codePointAt(0);if(i!==0)return i}return n.length-s.length}var Qm=e=>[...e].sort(xt);function zn(e,t,n){let s=[],a="";for(let i of Pt(e))Re(i,t)?((!n||a!=="")&&s.push(a),a=""):a+=i;return(!n||a!=="")&&s.push(a),s}function js(e,t,n){let s=Pt(e),a=Pt(t),i="";for(let r=0;r<s.length;)r+a.length<=s.length&&a.every((o,l)=>Re(s[r+l],o))?(i+=n,r+=a.length):i+=s[r++];return i}var Fm=new WeakMap;function ml(e){let t=Fm.get(e);if(t===void 0){t=new Map;for(let n of Object.keys(e))e[n]!==void 0&&(t.delete(he(n)),t.set(he(n),[n,e[n]]));Fm.set(e,t)}return t}var K=(e,t)=>ml(e).get(he(t))?.[1],vn=(e,t)=>ml(e).has(he(t)),Nt=e=>[...ml(e).values()],gl=e=>Nt(e).map(([t])=>t);function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function St(e){return Array.isArray(e)?e:void 0}function Ce(e){return typeof e=="string"?e:void 0}function Ui(e){if(typeof e=="boolean")return e;if(e===1)return!0;if(e===0)return!1}function P$(e){if(typeof e=="number")return e;if(typeof e=="boolean")return e?1:0}var Bn=(e,t=!1)=>({kind:e,nullable:t,props:[],enumVals:[]}),eg=2n**63n-1n,tg=-(2n**63n);function A$(e){return Number.isNaN(e)?0n:e>=2**63?eg:e<=-(2**63)?tg:BigInt(Math.trunc(e))}function R$(e,t=new It){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(K(n,"paths"));if(s===void 0)throw new Error("openapi.json has no `paths`");let a=[];for(let[i,r]of Nt(s)){let o=H(r);if(o!==void 0)for(let[l,d]of Nt(o)){let p=H(d);if(p===void 0)continue;let u=Ce(K(p,"operationId"))??"";if(u==="")continue;let g={where:`operation ${JSON.stringify(u)}`,budget:t,through:u.length,path:new Set};a.push({operationID:u,method:l.toUpperCase(),path:i,pathParams:M$(i),input:j$(p,g),output:I$(p,g),headers:Vm(p,"header",g),query:Vm(p,"query",g),errors:T$(p,g),upload:E$(p),sse:vn(p,"x-palbase-sse"),idempotent:O$(p),attests:K(p,"x-palbase-attest")===!0,...tP(Zt(e,p,`${l.toUpperCase()} ${i}`))})}}return a.sort((i,r)=>xt(i.operationID,r.operationID)),a}function T$(e,t){let n=H(K(e,"x-palbase-errors"));if(n===void 0)return[];let s=H(K(e,"responses")),a=[];for(let[i,r]of Nt(n)){let o=H(r);if(o===void 0)continue;let l=P$(K(o,"status"))??0,d=Ce(K(o,"code"))??"",p=Ce(K(o,"description"))??"",u=Ui(K(o,"hasData"))??!1;if(d===""||l===0)continue;let g={name:i,code:d,status:A$(l),description:p};u&&(g.data=C$(s,g.status,d,{...t,through:t.through+i.length})),a.push(g)}return a.sort((i,r)=>xt(i.name,r.name)),a}function E$(e){let t=H(K(e,"x-palbase-upload"));if(t===void 0||Nt(t).length===0)return;let n=Ce(K(t,"bucket"))??"",s=Ce(K(t,"pathTemplate"))??"";if(!(n===""||s===""))return{bucket:n,pathTemplate:s}}function C$(e,t,n,s){if(e===void 0)return;let a=H(K(e,t.toString()));if(a===void 0)return;let i=H(K(a,"content"));if(i===void 0)return;let r=H(K(i,"application/json"));if(r===void 0)return;let o=H(K(r,"schema"));if(o===void 0)return;let l=St(K(o,"oneOf"));if(l!==void 0){for(let d of l){let p=H(d);if(p===void 0)continue;let u=H(K(p,"properties")),g=u===void 0?void 0:H(K(u,"error"));if(g===void 0)continue;let y=Ce(K(g,"const"));if(y!==void 0&&Re(y,n))return Jm(p,s)}return}return Jm(o,s)}function Jm(e,t){let n=H(K(e,"properties"));if(n===void 0)return;let s=H(K(n,"data"));if(s!==void 0)return _n(s,s,t)}function j$(e,t){let n=H(K(e,"requestBody"));if(n!==void 0)return sg(K(n,"content"),t)}var ng=e=>he(e).toLowerCase()==="idempotency-key";function O$(e){return(St(K(e,"parameters"))??[]).some(t=>{let n=H(t);return n!==void 0&&Re(Ce(K(n,"in"))??"","header")&&ng(Ce(K(n,"name"))??"")})}function Vm(e,t,n){let s=St(K(e,"parameters"));if(s===void 0||s.length===0)return;let a=[];for(let i of s){let r=H(i);if(r===void 0||!Re(Ce(K(r,"in"))??"",t))continue;let o=Ce(K(r,"name"))??"";if(o===""||t==="header"&&ng(o))continue;let l=Ui(K(r,"required"))??!1,d=H(K(r,"schema"));a.push({name:o,schema:d===void 0?Bn("string"):_n(d,d,{...n,through:n.through+o.length}),required:l})}if(a.length!==0)return a.sort((i,r)=>xt(i.name,r.name)),{kind:"object",nullable:!1,props:a,enumVals:[]}}function M$(e){let t=[],n=e;for(;;){let s=n.indexOf("{");if(s<0)break;let a=n.indexOf("}",s);if(a<0)break;let i=n.slice(s+1,a);i!==""&&t.push(i),n=n.slice(a+1)}return t}function I$(e,t){let n=H(K(e,"responses"));if(n===void 0)return;let s=gl(n).filter(a=>Re(Pt(a)[0]??"","2")&&!Re(a,"200")&&!Re(a,"201"));for(let a of["200","201",...Qm(s)]){let i=H(K(n,a));if(i===void 0)continue;let r=sg(K(i,"content"),t);if(r!==void 0)return r}}function sg(e,t){let n=H(e);if(n===void 0)return;let s=H(K(n,"application/json"));if(s===void 0)return;let a=H(K(s,"schema"));if(a!==void 0&&!vn(a,"$ref"))return _n(a,a,t)}function _n(e,t,n,s=0,a=n.through){let i=e,r=x$(i,t);if(r!==void 0&&s<16){if(n.path.has(r))throw new Error(`${n.where}: the $ref ${JSON.stringify(Ce(K(i,"$ref")))} points back into a schema it is part of, a recursive schema, which no Swift type is written for: refused`);i=r}else if(vn(i,"$ref"))return Bn("any");let o=H(K(i,"properties")),l=(o===void 0?0:Hm(gl(o)))+Hm(St(K(i,"enum"))??[]);n.budget.charge(n.where,s,a,l),n.path.add(i);try{return L$(i,t,n,s,a)}finally{n.path.delete(i)}}var Hm=e=>e.reduce((t,n)=>t+(Ce(n)?.length??0),0);function L$(e,t,n,s,a){let i=Ui(K(e,"nullable"))??!1,r=St(K(e,"type"));if(r!==void 0)for(let p of r)Ce(p)==="null"&&(i=!0);let o=St(K(e,"anyOf"))??St(K(e,"oneOf"));if(o!==void 0){let p=o.map(H).filter(g=>g!==void 0),u=p.filter(g=>!D$(g));if(p.length===o.length&&u.length===1&&p.length>u.length){let g=_n(u[0],t,n,s+1,a);return g.nullable=!0,g}}let l=St(K(e,"enum"));if(l!==void 0){let p=[],u=!0;for(let g of l){let y=Ce(g);if(y===void 0){u=!1;break}p.push(y)}if(u&&p.length>0)return{kind:"enum",nullable:i,props:[],enumVals:p}}let d=Ce(K(e,"type"))??"";if(d===""&&r!==void 0)for(let p of r){let u=Ce(p);u!==void 0&&(u==="null"?i=!0:d===""&&(d=u))}switch(d){case"string":case"number":case"integer":case"boolean":return Bn(d,i);case"array":{let p=H(K(e,"items"));return{kind:"array",nullable:i,props:[],elem:p===void 0?Bn("any"):_n(p,t,n,s+1,a),enumVals:[]}}case"object":return Ym(e,i,t,n,s,a);default:return vn(e,"properties")||vn(e,"additionalProperties")?Ym(e,i,t,n,s,a):Bn("any",i)}}function Ym(e,t,n,s,a,i){let r=H(K(e,"properties"))??{},o=K(e,"additionalProperties"),l,d=H(o);if(d!==void 0?l=_n(d,n,s,a+1,i):(Ui(o)===!0||Nt(r).length===0&&!vn(e,"additionalProperties"))&&(l=Bn("any")),l!==void 0)return{kind:Nt(r).length===0?"map":"mixedObject",nullable:t,props:[],elem:l,enumVals:[]};let p=new Set;for(let g of St(K(e,"required"))??[]){let y=Ce(g);y!==void 0&&p.add(he(y))}let u=[];for(let g of Qm(gl(r))){let y=H(K(r,g));u.push({name:g,schema:y===void 0?Bn("any"):_n(y,n,s,a+1,i+g.length),required:p.has(he(g))})}return{kind:"object",nullable:t,props:u,enumVals:[]}}function D$(e){let t=K(e,"type");if(typeof t=="string")return t==="null";let n=St(t);if(n!==void 0){let s=n.filter(a=>typeof a=="string");return s.length===1&&s[0]==="null"}return!1}function x$(e,t){let n=Ce(K(e,"$ref"));if(n===void 0)return;let s=Pt(n);if(!Re(s[0]??"","#")||!Re(s[1]??"","/"))return;let a=t;for(let i of zn(s.slice(2).join(""),"/",!0)){let r=js(js(i,"~1","/"),"~0","~"),o=H(a),l=St(a),d=W$(r);if(o!==void 0&&vn(o,r))a=K(o,r);else if(l!==void 0&&d!==void 0&&d>=0n&&d<BigInt(l.length))a=l[Number(d)];else return}return H(a)}function N$(e,t=new It){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(K(n,"x-palbase-gateways"));if(s===void 0)return[];let a=[];for(let[i,r]of Nt(s)){let o=H(r),l=o===void 0?void 0:Ce(K(o,"pattern"));if(o===void 0||l===void 0||l===""||!q$(i))continue;let d={where:ag(i,l),budget:t,through:i.length,path:new Set},p=K(o,"durable");a.push({name:i,pattern:l,params:G$(l),durable:typeof p=="number"&&p>0,chat:K(o,"chat")===!0,events:U$(K(o,"events"),n,d),messages:B$(K(o,"messages"),n,d)})}return a.sort((i,r)=>xt(i.name,r.name)),a}var ag=(e,t)=>`gateway ${e} (${JSON.stringify(t)})`;function q$(e){return/^(?:[A-Za-z][A-Za-z0-9_]*|_[A-Za-z0-9_]+)$/.test(e)&&!K$.has(e)&&!pl.has(e)}var K$=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 ig(e){let t=Pt(e);return t.length>2&&Re(t[0],"{")&&Re(t[t.length-1],"}")?t.slice(1,-1).join(""):void 0}function G$(e){return zn(e,":",!1).flatMap(t=>ig(t)??[])}function cl(e,t,n,s){let a=z$(e,t)??e;return _n(a,a,{...n,through:n.through+s.length})}function U$(e,t,n){let s=H(e);if(s===void 0)return[];let a=[];for(let[i,r]of Nt(s)){let o=H(r);o!==void 0&&a.push({name:i,schema:cl(o,t,n,i)})}return a.sort((i,r)=>xt(i.name,r.name)),a}function B$(e,t,n){let s=H(e);if(s===void 0)return[];let a=[];for(let[i,r]of Nt(s)){let o=H(r),l=o===void 0?void 0:H(K(o,"payload"));if(o===void 0||l===void 0)continue;let d={name:i,schema:cl(l,t,n,i)},p=H(K(o,"reply"));p!==void 0&&(d.reply=cl(p,t,n,i)),a.push(d)}return a.sort((i,r)=>xt(i.name,r.name)),a}function z$(e,t){let n=Ce(K(e,"$ref"));if(n===void 0)return;let s=Pt(n);if(!Re(s[0]??"","#")||!Re(s[1]??"","/"))return;let a=t;for(let i of zn(s.slice(2).join(""),"/",!0)){let r=js(js(i,"~1","/"),"~0","~"),o=H(a);if(o===void 0||!vn(o,r))return;a=K(o,r)}return H(a)}function W$(e){if(!/^[+-]?[0-9]+$/.test(e))return;let t=BigInt(e);return t>eg||t<tg?void 0:t}function Ne(e){let t='"';for(let n of e){let s=n.codePointAt(0);if(n==='"')t+='\\"';else if(n==="\\")t+="\\\\";else if(n===`
|
|
563
|
-
`)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||F$.has(s)?t+="\\u{"+s.toString(16)+"}":t+=n}}return t+'"'}var F$=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Bi=e=>zn(e,".",!0)
|
|
564
|
-
`)}function og(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 Fi=e=>Ms(e)+"Endpoint";function lg(e){let t=[];for(let n of zn(e,"/",!1)){if(n==="")continue;let s=
|
|
565
|
-
`).join("")}var pg=e=>[...e.children.values()].sort((t,n)=>xt(t[0],n[0]));function hl(e,t){return e.length===0?t:"PB"+e.map(
|
|
562
|
+
`}return o}function w$(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: "+Ne(e.transit.projectId)+", signer: "+Ne(e.transit.signer)+")"}var v$=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 _$(e){if(!/^[a-z][A-Za-z0-9]*$/.test(e.client)||v$.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 qi(e,t){let n=pl.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 k$(e,t,n,s){qi(`client ${JSON.stringify(t)}`,n),s.set(he(n),`client ${JSON.stringify(t)}`);for(let a of e){let i=Bi(a.operationID);for(let r=1;r<i.length;r++){let o=`operation ${JSON.stringify(a.operationID)}, in namespace ${JSON.stringify(i.slice(0,r).join("."))},`,l=hl(i.slice(0,r),n);qi(o,l),s.has(he(l))||s.set(he(l),`namespace ${JSON.stringify(i.slice(0,r).join("."))}`)}}}function S$(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 $$=new Intl.Segmenter("en",{granularity:"grapheme"});function At(e){return Array.from($$.segment(e),t=>t.segment)}function he(e){return e.normalize("NFC")}function Re(e,t){return he(e)===he(t)}function xt(e,t){let n=Array.from(he(e)),s=Array.from(he(t));for(let a=0;a<n.length&&a<s.length;a++){let i=n[a].codePointAt(0)-s[a].codePointAt(0);if(i!==0)return i}return n.length-s.length}var Qm=e=>[...e].sort(xt);function zn(e,t,n){let s=[],a="";for(let i of At(e))Re(i,t)?((!n||a!=="")&&s.push(a),a=""):a+=i;return(!n||a!=="")&&s.push(a),s}function js(e,t,n){let s=At(e),a=At(t),i="";for(let r=0;r<s.length;)r+a.length<=s.length&&a.every((o,l)=>Re(s[r+l],o))?(i+=n,r+=a.length):i+=s[r++];return i}var Fm=new WeakMap;function ml(e){let t=Fm.get(e);if(t===void 0){t=new Map;for(let n of Object.keys(e))e[n]!==void 0&&(t.delete(he(n)),t.set(he(n),[n,e[n]]));Fm.set(e,t)}return t}var K=(e,t)=>ml(e).get(he(t))?.[1],vn=(e,t)=>ml(e).has(he(t)),Nt=e=>[...ml(e).values()],gl=e=>Nt(e).map(([t])=>t);function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function $t(e){return Array.isArray(e)?e:void 0}function Ce(e){return typeof e=="string"?e:void 0}function Ui(e){if(typeof e=="boolean")return e;if(e===1)return!0;if(e===0)return!1}function P$(e){if(typeof e=="number")return e;if(typeof e=="boolean")return e?1:0}var Bn=(e,t=!1)=>({kind:e,nullable:t,props:[],enumVals:[]}),eg=2n**63n-1n,tg=-(2n**63n);function A$(e){return Number.isNaN(e)?0n:e>=2**63?eg:e<=-(2**63)?tg:BigInt(Math.trunc(e))}function R$(e,t=new It){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(K(n,"paths"));if(s===void 0)throw new Error("openapi.json has no `paths`");let a=[];for(let[i,r]of Nt(s)){let o=H(r);if(o!==void 0)for(let[l,d]of Nt(o)){let p=H(d);if(p===void 0)continue;let u=Ce(K(p,"operationId"))??"";if(u==="")continue;let g={where:`operation ${JSON.stringify(u)}`,budget:t,through:u.length,path:new Set};a.push({operationID:u,method:l.toUpperCase(),path:i,pathParams:M$(i),input:j$(p,g),output:I$(p,g),headers:Vm(p,"header",g),query:Vm(p,"query",g),errors:T$(p,g),upload:E$(p),sse:vn(p,"x-palbase-sse"),idempotent:O$(p),attests:K(p,"x-palbase-attest")===!0,...tP(Zt(e,p,`${l.toUpperCase()} ${i}`))})}}return a.sort((i,r)=>xt(i.operationID,r.operationID)),a}function T$(e,t){let n=H(K(e,"x-palbase-errors"));if(n===void 0)return[];let s=H(K(e,"responses")),a=[];for(let[i,r]of Nt(n)){let o=H(r);if(o===void 0)continue;let l=P$(K(o,"status"))??0,d=Ce(K(o,"code"))??"",p=Ce(K(o,"description"))??"",u=Ui(K(o,"hasData"))??!1;if(d===""||l===0)continue;let g={name:i,code:d,status:A$(l),description:p};u&&(g.data=C$(s,g.status,d,{...t,through:t.through+i.length})),a.push(g)}return a.sort((i,r)=>xt(i.name,r.name)),a}function E$(e){let t=H(K(e,"x-palbase-upload"));if(t===void 0||Nt(t).length===0)return;let n=Ce(K(t,"bucket"))??"",s=Ce(K(t,"pathTemplate"))??"";if(!(n===""||s===""))return{bucket:n,pathTemplate:s}}function C$(e,t,n,s){if(e===void 0)return;let a=H(K(e,t.toString()));if(a===void 0)return;let i=H(K(a,"content"));if(i===void 0)return;let r=H(K(i,"application/json"));if(r===void 0)return;let o=H(K(r,"schema"));if(o===void 0)return;let l=$t(K(o,"oneOf"));if(l!==void 0){for(let d of l){let p=H(d);if(p===void 0)continue;let u=H(K(p,"properties")),g=u===void 0?void 0:H(K(u,"error"));if(g===void 0)continue;let y=Ce(K(g,"const"));if(y!==void 0&&Re(y,n))return Jm(p,s)}return}return Jm(o,s)}function Jm(e,t){let n=H(K(e,"properties"));if(n===void 0)return;let s=H(K(n,"data"));if(s!==void 0)return _n(s,s,t)}function j$(e,t){let n=H(K(e,"requestBody"));if(n!==void 0)return sg(K(n,"content"),t)}var ng=e=>he(e).toLowerCase()==="idempotency-key";function O$(e){return($t(K(e,"parameters"))??[]).some(t=>{let n=H(t);return n!==void 0&&Re(Ce(K(n,"in"))??"","header")&&ng(Ce(K(n,"name"))??"")})}function Vm(e,t,n){let s=$t(K(e,"parameters"));if(s===void 0||s.length===0)return;let a=[];for(let i of s){let r=H(i);if(r===void 0||!Re(Ce(K(r,"in"))??"",t))continue;let o=Ce(K(r,"name"))??"";if(o===""||t==="header"&&ng(o))continue;let l=Ui(K(r,"required"))??!1,d=H(K(r,"schema"));a.push({name:o,schema:d===void 0?Bn("string"):_n(d,d,{...n,through:n.through+o.length}),required:l})}if(a.length!==0)return a.sort((i,r)=>xt(i.name,r.name)),{kind:"object",nullable:!1,props:a,enumVals:[]}}function M$(e){let t=[],n=e;for(;;){let s=n.indexOf("{");if(s<0)break;let a=n.indexOf("}",s);if(a<0)break;let i=n.slice(s+1,a);i!==""&&t.push(i),n=n.slice(a+1)}return t}function I$(e,t){let n=H(K(e,"responses"));if(n===void 0)return;let s=gl(n).filter(a=>Re(At(a)[0]??"","2")&&!Re(a,"200")&&!Re(a,"201"));for(let a of["200","201",...Qm(s)]){let i=H(K(n,a));if(i===void 0)continue;let r=sg(K(i,"content"),t);if(r!==void 0)return r}}function sg(e,t){let n=H(e);if(n===void 0)return;let s=H(K(n,"application/json"));if(s===void 0)return;let a=H(K(s,"schema"));if(a!==void 0&&!vn(a,"$ref"))return _n(a,a,t)}function _n(e,t,n,s=0,a=n.through){let i=e,r=x$(i,t);if(r!==void 0&&s<16){if(n.path.has(r))throw new Error(`${n.where}: the $ref ${JSON.stringify(Ce(K(i,"$ref")))} points back into a schema it is part of, a recursive schema, which no Swift type is written for: refused`);i=r}else if(vn(i,"$ref"))return Bn("any");let o=H(K(i,"properties")),l=(o===void 0?0:Hm(gl(o)))+Hm($t(K(i,"enum"))??[]);n.budget.charge(n.where,s,a,l),n.path.add(i);try{return L$(i,t,n,s,a)}finally{n.path.delete(i)}}var Hm=e=>e.reduce((t,n)=>t+(Ce(n)?.length??0),0);function L$(e,t,n,s,a){let i=Ui(K(e,"nullable"))??!1,r=$t(K(e,"type"));if(r!==void 0)for(let p of r)Ce(p)==="null"&&(i=!0);let o=$t(K(e,"anyOf"))??$t(K(e,"oneOf"));if(o!==void 0){let p=o.map(H).filter(g=>g!==void 0),u=p.filter(g=>!D$(g));if(p.length===o.length&&u.length===1&&p.length>u.length){let g=_n(u[0],t,n,s+1,a);return g.nullable=!0,g}}let l=$t(K(e,"enum"));if(l!==void 0){let p=[],u=!0;for(let g of l){let y=Ce(g);if(y===void 0){u=!1;break}p.push(y)}if(u&&p.length>0)return{kind:"enum",nullable:i,props:[],enumVals:p}}let d=Ce(K(e,"type"))??"";if(d===""&&r!==void 0)for(let p of r){let u=Ce(p);u!==void 0&&(u==="null"?i=!0:d===""&&(d=u))}switch(d){case"string":case"number":case"integer":case"boolean":return Bn(d,i);case"array":{let p=H(K(e,"items"));return{kind:"array",nullable:i,props:[],elem:p===void 0?Bn("any"):_n(p,t,n,s+1,a),enumVals:[]}}case"object":return Ym(e,i,t,n,s,a);default:return vn(e,"properties")||vn(e,"additionalProperties")?Ym(e,i,t,n,s,a):Bn("any",i)}}function Ym(e,t,n,s,a,i){let r=H(K(e,"properties"))??{},o=K(e,"additionalProperties"),l,d=H(o);if(d!==void 0?l=_n(d,n,s,a+1,i):(Ui(o)===!0||Nt(r).length===0&&!vn(e,"additionalProperties"))&&(l=Bn("any")),l!==void 0)return{kind:Nt(r).length===0?"map":"mixedObject",nullable:t,props:[],elem:l,enumVals:[]};let p=new Set;for(let g of $t(K(e,"required"))??[]){let y=Ce(g);y!==void 0&&p.add(he(y))}let u=[];for(let g of Qm(gl(r))){let y=H(K(r,g));u.push({name:g,schema:y===void 0?Bn("any"):_n(y,n,s,a+1,i+g.length),required:p.has(he(g))})}return{kind:"object",nullable:t,props:u,enumVals:[]}}function D$(e){let t=K(e,"type");if(typeof t=="string")return t==="null";let n=$t(t);if(n!==void 0){let s=n.filter(a=>typeof a=="string");return s.length===1&&s[0]==="null"}return!1}function x$(e,t){let n=Ce(K(e,"$ref"));if(n===void 0)return;let s=At(n);if(!Re(s[0]??"","#")||!Re(s[1]??"","/"))return;let a=t;for(let i of zn(s.slice(2).join(""),"/",!0)){let r=js(js(i,"~1","/"),"~0","~"),o=H(a),l=$t(a),d=W$(r);if(o!==void 0&&vn(o,r))a=K(o,r);else if(l!==void 0&&d!==void 0&&d>=0n&&d<BigInt(l.length))a=l[Number(d)];else return}return H(a)}function N$(e,t=new It){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(K(n,"x-palbase-gateways"));if(s===void 0)return[];let a=[];for(let[i,r]of Nt(s)){let o=H(r),l=o===void 0?void 0:Ce(K(o,"pattern"));if(o===void 0||l===void 0||l===""||!q$(i))continue;let d={where:ag(i,l),budget:t,through:i.length,path:new Set},p=K(o,"durable");a.push({name:i,pattern:l,params:G$(l),durable:typeof p=="number"&&p>0,chat:K(o,"chat")===!0,events:U$(K(o,"events"),n,d),messages:B$(K(o,"messages"),n,d)})}return a.sort((i,r)=>xt(i.name,r.name)),a}var ag=(e,t)=>`gateway ${e} (${JSON.stringify(t)})`;function q$(e){return/^(?:[A-Za-z][A-Za-z0-9_]*|_[A-Za-z0-9_]+)$/.test(e)&&!K$.has(e)&&!pl.has(e)}var K$=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 ig(e){let t=At(e);return t.length>2&&Re(t[0],"{")&&Re(t[t.length-1],"}")?t.slice(1,-1).join(""):void 0}function G$(e){return zn(e,":",!1).flatMap(t=>ig(t)??[])}function cl(e,t,n,s){let a=z$(e,t)??e;return _n(a,a,{...n,through:n.through+s.length})}function U$(e,t,n){let s=H(e);if(s===void 0)return[];let a=[];for(let[i,r]of Nt(s)){let o=H(r);o!==void 0&&a.push({name:i,schema:cl(o,t,n,i)})}return a.sort((i,r)=>xt(i.name,r.name)),a}function B$(e,t,n){let s=H(e);if(s===void 0)return[];let a=[];for(let[i,r]of Nt(s)){let o=H(r),l=o===void 0?void 0:H(K(o,"payload"));if(o===void 0||l===void 0)continue;let d={name:i,schema:cl(l,t,n,i)},p=H(K(o,"reply"));p!==void 0&&(d.reply=cl(p,t,n,i)),a.push(d)}return a.sort((i,r)=>xt(i.name,r.name)),a}function z$(e,t){let n=Ce(K(e,"$ref"));if(n===void 0)return;let s=At(n);if(!Re(s[0]??"","#")||!Re(s[1]??"","/"))return;let a=t;for(let i of zn(s.slice(2).join(""),"/",!0)){let r=js(js(i,"~1","/"),"~0","~"),o=H(a);if(o===void 0||!vn(o,r))return;a=K(o,r)}return H(a)}function W$(e){if(!/^[+-]?[0-9]+$/.test(e))return;let t=BigInt(e);return t>eg||t<tg?void 0:t}function Ne(e){let t='"';for(let n of e){let s=n.codePointAt(0);if(n==='"')t+='\\"';else if(n==="\\")t+="\\\\";else if(n===`
|
|
563
|
+
`)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||F$.has(s)?t+="\\u{"+s.toString(16)+"}":t+=n}}return t+'"'}var F$=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Bi=e=>zn(e,".",!0),Pt=e=>rg(e,!0);function ae(e){let t=rg(e,!1);if(H$.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 X$(t)}var Ms=e=>Bi(e).map(Pt).join(""),zi=e=>Ms(e)+"Request",Os=e=>Ms(e)+"Response",Wi=e=>Ms(e)+"Error",fl=e=>Ms(e)+"Headers",Ta=e=>Ms(e)+"Query";function J$(e){let t=(n,s)=>xt(e,n)>=0&&xt(e,s)<=0;return t("a","z")||t("A","Z")||t("0","9")}function rg(e,t){let n=[],s=[];for(let r of At(e))J$(r)?s.push(r):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((r,o)=>{a+=(o===0&&!t?r[0].toLowerCase():r[0].toUpperCase())+r.slice(1).join("")});let i=a.codePointAt(0);if(i>=48&&i<=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 V$=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"]),H$=new Set(["break","continue","fallthrough","fileprivate","inout","precedencegroup","rethrows","static","subscript","super","typealias"]),Y$=new Set(["Any","Self","Type","Protocol"]);function X$(e){return V$.has(he(e))?"`"+e+"`":e}var Dt=e=>js(e,"`","");function Xm(e,t){if(Re(e,t))return!0;let n=At(t);if(!n.some(l=>Re(l,"_")))return!1;let s=0;for(;s<n.length&&Re(n[s],"_");)s++;let a=0;for(;a<n.length-s&&Re(n[n.length-1-a],"_");)a++;let i=n.slice(s,n.length-a).join("");if(i==="")return!1;let r=n.slice(0,s).join(""),o=zn(i,"_",!1);for(let l=0;l<o.length;l++){if(o[l]==="")return!1;if(l===0)r+=o[l].toLowerCase();else{let d=At(o[l]);r+=d[0].toUpperCase()+d.slice(1).join("").toLowerCase()}}return r+=n.slice(n.length-a).join(""),Re(r,e)}var C=e=>" ".repeat(e);function Lt(e,t){for(let n of t)e.push(n)}function Z$(e,t){let n=[];for(let s of e){let a=n.length,i=!1;if(s.input!==void 0&&(Lt(n,Cs(zi(s.operationID),s.input,!0)),i=!0),s.output!==void 0?(i&&n.push(""),Lt(n,Cs(Os(s.operationID),s.output)),i=!0):s.upload!==void 0&&(i&&n.push(""),n.push("public nonisolated struct "+Os(s.operationID)+": Codable, Sendable {"),n.push("}"),i=!0),s.headers!==void 0){for(let r of s.headers.props)if(!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(r.name))throw new Error(`operation ${JSON.stringify(s.operationID)}: the header ${JSON.stringify(r.name)} is no HTTP field name (RFC 9110's token): rename it in the backend`);i&&n.push(""),Lt(n,sP(fl(s.operationID),s.headers)),i=!0}s.query!==void 0&&(i&&n.push(""),Lt(n,Ji(Ta(s.operationID),s.query.props,0)),i=!0),i&&n.push(""),Lt(n,aP(Wi(s.operationID),s.errors)),n.push(""),Lt(n,Q$(s)),n.push("");for(let r of og(n.slice(a)))qi(`operation ${JSON.stringify(s.operationID)}`,r),t.has(he(r))||t.set(he(r),`operation ${JSON.stringify(s.operationID)}`)}return n.join(`
|
|
564
|
+
`)}function og(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 Fi=e=>Ms(e)+"Endpoint";function lg(e){let t=[];for(let n of zn(e,"/",!1)){if(n==="")continue;let s=At(n);if(s.length>=2&&Re(s[0],"{")&&Re(s[s.length-1],"}")){let a=s.slice(1,s.length-1).join("");if(a==="")continue;t.push(".param("+ae(a)+")")}else t.push(Ne(n))}return"["+t.join(", ")+"]"}function dg(e){return e.path===""?"/"+js(e.operationID,".","/"):e.path}function Q$(e){if(e.upload!==void 0)return nP(e);let t=Fi(e.operationID),n=[];e.sse?(n.push("public nonisolated struct "+t+": PBSseEndpoint {"),n.push(C(1)+"public typealias Element = "+Os(e.operationID))):e.output!==void 0?(n.push("public nonisolated struct "+t+": PBEndpoint {"),n.push(C(1)+"public typealias Response = "+Os(e.operationID))):n.push("public nonisolated struct "+t+": PBVoidEndpoint {"),n.push(C(1)+"public typealias Failure = "+Wi(e.operationID));for(let i of e.pathParams)n.push(C(1)+"let "+ae(i)+": String");e.input!==void 0&&n.push(C(1)+"let input: "+zi(e.operationID)),e.query!==void 0&&n.push(C(1)+"let query: "+Ta(e.operationID)),e.headers!==void 0&&n.push(C(1)+"let headers: "+fl(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(),lg(dg(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(C(1)+"public var pbRequest: PBRequest { PBRequest("+a.join(", ")+") }"),e.idempotent&&!e.sse){if(e.pathParams.some(i=>Dt(ae(i))==="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(C(1)+"public var idempotent: Bool { true }")}if(e.attests){if(e.pathParams.some(i=>Dt(ae(i))==="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(C(1)+"public var attests: Bool { true }")}if(e.encryption){if(e.pathParams.some(i=>Dt(ae(i))==="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(C(1)+"public var encryption: PBEncryption? { "+eP(e.encryption)+" }")}return n.push("}"),n}function eP(e){let t=n=>"["+n.map(Ne).join(", ")+"]";return"PBEncryption(request: "+t(e.request)+", response: "+t(e.response)+")"}function tP(e){return e?{encryption:e}:{}}function nP(e){let t=[];t.push("public nonisolated struct "+Fi(e.operationID)+": PBUploadEndpoint {"),t.push(C(1)+"public typealias Response = "+Os(e.operationID)),t.push(C(1)+"public typealias Failure = "+Wi(e.operationID));for(let s of e.pathParams)t.push(C(1)+"let "+ae(s)+": String");e.input!==void 0&&t.push(C(1)+"let input: "+zi(e.operationID)),e.query!==void 0&&t.push(C(1)+"let query: "+Ta(e.operationID));let n=[".post",lg(dg(e))];return e.input!==void 0&&n.push("body: Palbe.PBWireValue(input)"),e.query!==void 0&&n.push("query: query"),t.push(C(1)+"public var authorizeRequest: PBRequest { PBRequest("+n.join(", ")+") }"),t.push("}"),t}function Cs(e,t,n=!1,s=0){if(t.kind==="object")return Ji(e,t.props,s,n);let[a,i]=t.kind==="enum"?["String",[]]:Gi(t,e,s,n),r=[...i];return r.length>0&&r.push(""),r.push(C(s)+"public typealias "+e+" = "+a+(t.nullable?"?":"")),r}function sP(e,t){let n=Ji(e,t.props,0);n[n.length-1].trim()==="}"&&n.pop(),n.push(C(1)+"public func asHeaderDict() -> [String: String] {"),n.push(C(2)+"var out: [String: String] = [:]");for(let s of t.props){let a=ae(s.name),i=Ne(s.name),r=s.schema.kind==="enum";!s.required||s.schema.nullable?n.push(C(2)+"if let v = "+a+" { out["+i+"] = "+(r?"v.rawValue":"v")+" }"):n.push(C(2)+"out["+i+"] = "+a+(r?".rawValue":""))}return n.push(C(2)+"return out"),n.push(C(1)+"}"),n.push("}"),n}function aP(e,t){let n=["public nonisolated enum "+e+": PBError {"],s=1,a=new Map([["other","the other(BackendError) fallback"]]),i=[];for(let r of t){let o=Dt(ae(r.name)),l=a.get(he(o));if(l!==void 0){n.push(C(s)+"#error("+Ne("palbase: "+e+" declares error "+r.name+" ("+r.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(he(o),r.name+" ("+r.code+")"),i.push(r)}for(let r of i)r.data!==void 0&&Lt(n,Cs(Pt(r.name)+"Data",r.data,!1,s));for(let r of i)n.push(C(s)+"case "+ae(r.name)+(r.data!==void 0?"("+Pt(r.name)+"Data)":""));if(n.push(C(s)+"case other(BackendError)"),i.length===0)return n.push(C(s)+"public nonisolated init(_ backend: BackendError) { self = .other(backend) }"),n.push("}"),n;n.push(C(s)+"public nonisolated init(_ backend: BackendError) {"),n.push(C(s+1)+"guard let f = backend.failure else { self = .other(backend); return }"),n.push(C(s+1)+"switch f.code {");for(let r of i){let o=ae(r.name);r.data!==void 0?(n.push(C(s+1)+"case "+Ne(r.code)+":"),n.push(C(s+2)+"if let data = f.decodeData("+Pt(r.name)+"Data.self) { self = ."+o+"(data) } else { self = .other(backend) }")):n.push(C(s+1)+"case "+Ne(r.code)+": self = ."+o)}return n.push(C(s+1)+"default: self = .other(backend)"),n.push(C(s+1)+"}"),n.push(C(s)+"}"),n.push("}"),n}function Ji(e,t,n,s=!1){let a=[C(n)+"public nonisolated struct "+e+": Codable, Sendable {"],i=n+1,r=[],o=new Ki,l=new Map;for(let p of t){let u=ae(p.name),g=l.get(he(u));if(g!==void 0){a.push(C(i)+"#error("+Ne("palbase: "+e+" has colliding Swift property `"+Dt(u)+"` for wire keys "+g+" and "+p.name+". This schema is unsupported; use distinct property names and regenerate the client.")+")");continue}l.set(he(u),p.name);let y=!p.required||p.schema.nullable,[w,_]=Gi(p.schema,p.name,i,s,o);s&&!p.required&&p.schema.nullable&&(w="Nullable<"+w+">"),Lt(a,_),r.push({ident:u,key:p.name,typ:w,optional:y,required:p.required})}for(let p of r)a.push(C(i)+"public let "+p.ident+": "+p.typ+(p.optional?"?":""));let d=r.map(p=>p.ident+": "+p.typ+(p.optional?"? = nil":""));a.push(C(i)+"public init("+d.join(", ")+") {");for(let p of r)a.push(C(i+1)+"self."+p.ident+" = "+p.ident);if(a.push(C(i)+"}"),s){a.push(C(i)+"public func encode(to encoder: any Swift.Encoder) throws {"),a.push(C(i+1)+(r.length===0?"let":"var")+" fields: [Swift.String: Palbe.PBWireValue] = [:]");for(let p of r){let u="fields["+Ne(p.key)+"] = Palbe.PBWireValue(";p.required?a.push(C(i+1)+u+"self."+p.ident+")"):a.push(C(i+1)+"if let value = self."+p.ident+" { "+u+"value) }")}a.push(C(i+1)+"var container = encoder.singleValueContainer()"),a.push(C(i+1)+"try container.encode(fields)"),a.push(C(i)+"}")}if(r.some(p=>!Xm(Dt(p.ident),p.key))){a.push(C(i)+"enum CodingKeys: String, CodingKey {");for(let p of r)Xm(Dt(p.ident),p.key)?a.push(C(i+1)+"case "+p.ident):a.push(C(i+1)+"case "+p.ident+" = "+Ne(p.key));a.push(C(i)+"}")}return a.push(C(n)+"}"),a}var Ki=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(he(n));s++)n=t+s;return this.used.add(he(n)),n}};function Gi(e,t,n,s=!1,a=new Ki){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 i=a.allocate(Pt(t)+"Value"),r=[C(n)+"public nonisolated enum "+i+": String, Codable, Sendable {"];for(let o of e.enumVals)r.push(C(n+1)+"case "+ae(o)+" = "+Ne(o));return r.push(C(n)+"}"),[i,r]}case"array":{let i=e.elem,[r,o]=Gi(i,t+"Item",n,s,a);return["["+r+(i.nullable?"?":"")+"]",o]}case"map":{let i=e.elem,[r,o]=Gi(i,t+"Value",n,s,a);return["[String: "+r+(i.nullable?"?":"")+"]",o]}case"mixedObject":return["AnyCodableValue",[C(n)+"#error("+Ne("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(Y$.has(Pt(t)))throw new Error(`the name ${JSON.stringify(t)} becomes the type ${Pt(t)}, a name Swift gives no type of a program's: rename it in the backend`);let i=a.allocate(Pt(t));return[i,Ji(i,e.props,n,s)]}default:return["AnyCodableValue",[]]}}function iP(e,t){let n={path:[],children:new Map,methods:[]};for(let i of e){let r=Bi(i.operationID),o=n;for(let l of r.slice(0,Math.max(r.length-1,0))){let d=o.children.get(he(l));d===void 0&&(d=[l,{path:[...o.path,l],children:new Map,methods:[]}],o.children.set(he(l),d)),o=d[1]}o.methods.push(i)}let s=[],a=[n];for(;a.length>0;){let i=a.shift();s.push(i),a.push(...pg(i).map(([,r])=>r))}return s.map(i=>rP(i,t)+`
|
|
565
|
+
`).join("")}var pg=e=>[...e.children.values()].sort((t,n)=>xt(t[0],n[0]));function hl(e,t){return e.length===0?t:"PB"+e.map(Pt).join("")+"Namespace"}function rP(e,t){let n=e.path.length===0,s=[];n?s.push("public extension "+t+" {"):(s.push("public nonisolated struct "+hl(e.path,t)+": Sendable {"),s.push(" let _pb: PalBackendClient"));let a=n?"":"public ",i="_pb";for(let[,r]of pg(e)){let o=hl(r.path,t);s.push(C(1)+a+"nonisolated var "+ae(r.path[r.path.length-1])+": "+o+" { "+o+"(_pb: "+i+") }")}for(let r of e.methods){let o=Bi(r.operationID);if(o.length===0)throw new Error(`operationId ${JSON.stringify(r.operationID)} names no method`);let l=ae(o[o.length-1]),d=zi(r.operationID),p=Os(r.operationID),u="throws("+Wi(r.operationID)+")";if(r.upload!==void 0){Lt(s,lP(r,l,d,p,u,a,i));continue}let g=r.pathParams.map(_=>ae(_)+": String");r.input!==void 0&&g.push("_ input: "+d),r.query!==void 0&&g.push("query: "+Ta(r.operationID)),r.headers!==void 0&&g.push("headers: "+fl(r.operationID));let y=r.pathParams.map(_=>ae(_)+": "+ae(_));r.input!==void 0&&y.push("input: input"),r.query!==void 0&&y.push("query: query"),r.headers!==void 0&&y.push("headers: headers");let w=Fi(r.operationID)+"("+y.join(", ")+")";r.sse?(s.push(C(1)+a+"func "+l+"("+g.join(", ")+") async throws -> AsyncThrowingStream<"+p+", Error> {"),s.push(C(2)+"return try await "+i+".stream("+w+")")):r.output!==void 0?(s.push(C(1)+"@discardableResult"),s.push(C(1)+a+"func "+l+"("+g.join(", ")+") async "+u+" -> "+p+" {"),s.push(C(2)+"return try await "+i+".call("+w+")")):(s.push(C(1)+a+"func "+l+"("+g.join(", ")+") async "+u+" {"),s.push(C(2)+"try await "+i+".call("+w+")")),s.push(C(1)+"}")}return s.push("}"),s.join(`
|
|
566
566
|
`)+`
|
|
567
|
-
`}var ul=(e,t,n)=>e
|
|
567
|
+
`}var ul=(e,t,n)=>e+Pt(t)+n;function Ni(e,t,n){let s=e.get(he(t));if(s!==void 0)throw new Error(`${s} and ${n} both become ${t} in Swift: rename one in the backend`);e.set(he(t),n)}function oP(e,t){let n=ag(e.name,e.pattern),s=new Map([["topic","the gateway's topic"]]);for(let p of e.params){let u=Dt(ae(p));if(Ni(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 g=new Map;for(let y of u)Ni(g,Dt(ae(y.name)),`${n}'s ${p} ${JSON.stringify(y.name)}`)}let a=[],i=(p,u)=>{for(let g of og(p))Ni(t,g,u),qi(u,g);Lt(a,p),a.push("")},r=p=>ul(e.name,p,"Event"),o=p=>ul(e.name,p,"Message"),l=p=>p.reply===void 0?"JSONValue":ul(e.name,p.name,"Reply");for(let p of e.events)i(Cs(r(p.name),p.schema),`${n}'s event ${JSON.stringify(p.name)}`);for(let p of e.messages)i(Cs(o(p.name),p.schema,!0),`${n}'s message ${JSON.stringify(p.name)}`),p.reply!==void 0&&i(Cs(l(p),p.reply),`${n}'s ack of ${JSON.stringify(p.name)}`);Ni(t,e.name,n),a.push("public nonisolated struct "+e.name+": "+(e.chat?"PBChatGateway":"PBGateway")+" {"),a.push(C(1)+"public static let pattern = "+Ne(e.pattern)),a.push(C(1)+"public static let durable = "+String(e.durable));for(let p of e.params)a.push(C(1)+"public let "+ae(p)+": String");if(e.params.length===0)a.push(C(1)+"public init() {}");else{a.push(C(1)+"public init("+e.params.map(p=>ae(p)+": String").join(", ")+") {");for(let p of e.params)a.push(C(2)+"self."+Dt(ae(p))+" = "+ae(p));a.push(C(1)+"}")}a.push(C(1)+"public var topic: String {");let d="";for(let p of zn(e.pattern,":",!1)){d!==""&&(d+=":");let u=ig(p);d+=u!==void 0?"\\("+ae(u)+")":Ne(p).slice(1,-1)}a.push(C(2)+'return "'+d+'"'),a.push(C(1)+"}"),a.push(""),a.push(C(1)+"public enum Event: Sendable {");for(let p of e.events)a.push(C(2)+"case "+ae(p.name)+"("+r(p.name)+")");if(e.events.length===0&&a.push(C(2)+"// this gateway declares no events"),a.push(C(1)+"}"),a.push(""),a.push(C(1)+"public static let eventNames: [String] = ["+e.events.map(p=>Ne(p.name)).join(", ")+"]"),a.push(""),a.push(C(1)+"public static func decode(event: String, data: Data) throws -> Event? {"),e.events.length===0)a.push(C(2)+"_ = (event, data)"),a.push(C(2)+"return nil");else{a.push(C(2)+"switch event {");for(let p of e.events)a.push(C(2)+"case "+Ne(p.name)+":"),a.push(C(3)+"return ."+ae(p.name)+"(try JSONDecoder.palbaseDefault.decode("+r(p.name)+".self, from: data))");a.push(C(2)+"default:"),a.push(C(3)+"return nil"),a.push(C(2)+"}")}a.push(C(1)+"}"),a.push(""),a.push(C(1)+"public enum Send: Sendable {");for(let p of e.messages)a.push(C(2)+"case "+ae(p.name)+"("+o(p.name)+")");if(e.messages.length===0&&a.push(C(2)+"// this gateway takes no messages"),a.push(C(1)+"}"),a.push(""),a.push(C(1)+"public static func encode(_ message: Send) throws -> (event: String, data: Data) {"),e.messages.length===0)a.push(C(2)+"// this gateway takes no messages: there is none to encode");else{a.push(C(2)+"switch message {");for(let p of e.messages)a.push(C(2)+"case ."+ae(p.name)+"(let value):"),a.push(C(3)+"return ("+Ne(p.name)+", try JSONEncoder.palbaseDefault.encode(value))");a.push(C(2)+"}")}a.push(C(1)+"}"),a.push(""),a.push(C(1)+"public enum Reply: Sendable {");for(let p of e.messages)a.push(C(2)+"case "+ae(p.name)+"("+l(p)+")");if(e.messages.length===0&&a.push(C(2)+"// this gateway takes no messages"),a.push(C(1)+"}"),a.push(""),a.push(C(1)+"public static func decode(reply data: Data, to message: Send) throws -> Reply {"),e.messages.length===0)a.push(C(2)+"// this gateway takes no messages: there is no ack to read");else{a.push(C(2)+"switch message {");for(let p of e.messages)a.push(C(2)+"case ."+ae(p.name)+":"),a.push(C(3)+"return ."+ae(p.name)+"(try JSONDecoder.palbaseDefault.decode("+l(p)+".self, from: data))");a.push(C(2)+"}")}return a.push(C(1)+"}"),a.push("}"),a.join(`
|
|
568
568
|
`)+`
|
|
569
569
|
`}function lP(e,t,n,s,a,i,r){let o=e.pathParams.map(p=>ae(p)+": String");o.push("file: PBFileSource"),e.input!==void 0&&o.push("input: "+n),e.query!==void 0&&o.push("query: "+Ta(e.operationID)),o.push("onProgress: (@Sendable (BackendUploadProgress) -> Void)? = nil");let l=e.pathParams.map(p=>ae(p)+": "+ae(p));e.input!==void 0&&l.push("input: input"),e.query!==void 0&&l.push("query: query");let d=Fi(e.operationID)+"("+l.join(", ")+")";return[C(1)+"@discardableResult",C(1)+i+"func "+t+"("+o.join(", ")+") async "+a+" -> "+s+" {",C(2)+"return try await "+r+".call("+d+", file: file, onProgress: onProgress)",C(1)+"}"]}var Vi=/^[A-Za-z_$][A-Za-z0-9_$]*$/,yl=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__"]),dP=new Set(yl),pP=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function Hi(e){return e==="then"||e==="toJSON"||pP.has(e)}function ug(e){return e==="call"||e==="join"||Hi(e)}function Yi(e){return typeof e=="string"&&Vi.test(e)&&!dP.has(e)&&!Hi(e)}function cg(e){return typeof e=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(e)}function hg(e){Qa(e)}function mg(e){return Qa(e).origin}function Y(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function dt(e){return typeof e=="string"?e:""}function uP(e,t=new Ea){let n=Y(Y(e)?.paths);if(!n)throw new Error("the contract has no `paths`");let s=[];for(let[a,i]of Object.entries(n)){let r=Y(i);if(r)for(let[o,l]of Object.entries(r)){let d=Y(l);if(!d)continue;let p=dt(d.operationId);p!==""&&s.push({operationId:p,method:o.toUpperCase(),path:_g(a),pathParams:bP(a),input:gP(d,t),output:wP(d,t),headers:fg(d,"header",t),query:fg(d,"query",t),errors:hP(d,t),sse:d["x-palbase-sse"]!==void 0,idempotent:yP(d),upload:fP(d),...cP(Zt(e,d,`${o.toUpperCase()} ${a}`))})}}return s.sort((a,i)=>a.operationId<i.operationId?-1:a.operationId>i.operationId?1:0),s}function cP(e){return e?{encryption:e}:{}}function hP(e,t){let n=Y(e["x-palbase-errors"]);if(!n)return[];let s=Y(e.responses),a=[];for(let[i,r]of Object.entries(n)){let o=Y(r);if(!o)continue;let l=typeof o.status=="number"&&Number.isFinite(o.status)?Math.trunc(o.status):0,d=dt(o.code),p=dt(o.description),u=o.hasData===!0;if(d===""||l===0)continue;let g={name:i,code:d,status:l,description:p};u&&(g.data=mP(s,l,d,t)),a.push(g)}return a.sort((i,r)=>i.name<r.name?-1:i.name>r.name?1:0),a}function mP(e,t,n,s){let a=Y(e?.[String(t)]),i=Y(Y(a?.content)?.["application/json"]),r=Y(i?.schema);if(!r)return;let o=r.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&&dt(p.const)===n)return gg(d,s)}return}return gg(r,s)}function gg(e,t){let n=Y(Y(e.properties)?.data);if(n)return ht(n,t)}function gP(e,t){let n=Y(e.requestBody);if(n)return kg(n.content,t)}function fg(e,t,n){let s=e.parameters;if(!Array.isArray(s)||s.length===0)return;let a=[];for(let i of s){let r=Y(i);if(!r||dt(r.in)!==t)continue;let o=dt(r.name);if(o===""||t==="header"&&vg(o))continue;let l=r.required===!0,d=Y(r.schema),p=d?ht(d,n):Qe("string");a.push({name:o,schema:p,required:l})}if(a.length!==0)return a.sort((i,r)=>i.name<r.name?-1:i.name>r.name?1:0),{...Qe("object"),props:a}}function vg(e){return e.toLowerCase()==="idempotency-key"}function fP(e){let t=Y(e["x-palbase-upload"]);return dt(t?.bucket)!==""&&dt(t?.pathTemplate)!==""}function yP(e){let t=e.parameters;return Array.isArray(t)&&t.some(n=>dt(Y(n)?.in)==="header"&&vg(dt(Y(n)?.name)))}function _g(e){return e.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g,"{$1}")}function bP(e){let t=_g(e),n=[],s=t;for(;;){let a=s.indexOf("{");if(a<0)break;let i=s.indexOf("}",a);if(i<0)break;let r=s.slice(a+1,i);r!==""&&n.push(r),s=s.slice(i+1)}return n}function wP(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 i=Y(n[a]);if(!i)continue;let r=kg(i.content,t);if(r)return r}}function kg(e,t){let n=Y(Y(e)?.["application/json"]),s=Y(n?.schema);if(s&&!("$ref"in s))return ht(s,t)}function Qe(e){return{kind:e,nullable:!1,props:[],enumVals:[]}}var yg=2e5,Ea=class{left=yg;spend(){if(--this.left<0)throw new Error(`the contract's schemas make more than ${yg} 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 ht(e,t){t.spend();let n=e.nullable===!0||Array.isArray(e.type)&&e.type.includes("null");if(e.const===null)return Qe("null");if(["string","number","boolean"].includes(typeof e.const))return{...Qe("literal"),nullable:n,literal:e.const};let s=e.anyOf??e.oneOf;if(Array.isArray(s)&&s.length>0){let r=s.map(l=>ht(Y(l)??{},t));n||=r.some(l=>l.kind==="null");let o=r.filter(l=>l.kind!=="null");return o.length===0?Qe("null"):o.length===1?{...o[0],nullable:n||o[0].nullable}:{...Qe("union"),nullable:n,members:o}}let a=e.enum;if(Array.isArray(a)){let r=[],o=!0;for(let l of a)if(typeof l=="string")r.push(l);else{o=!1;break}if(o&&r.length>0)return{...Qe("enum"),nullable:n,enumVals:r};if(a.length>0&&a.every(l=>l===null||["string","number","boolean"].includes(typeof l)))return ht({anyOf:a.map(l=>({const:l})),nullable:n},t)}let i=dt(e.type);if(i===""&&Array.isArray(e.type)){let r=[...new Set(e.type)];if(r.filter(l=>typeof l=="string"&&l!=="null").length>1)return ht({anyOf:r.map(l=>({...e,type:l})),nullable:n},t);for(let l of r)typeof l=="string"&&(l==="null"?n=!0:i===""&&(i=l))}switch(i){case"null":return Qe("null");case"string":case"number":case"integer":case"boolean":return{...Qe(i),nullable:n};case"array":{let r=Y(e.items),o=r?ht(r,t):Qe("any");return{...Qe("array"),nullable:n,elem:o,...e.maxItems===0?{empty:!0}:{}}}case"object":return bg(e,n,t);default:return"properties"in e?bg(e,n,t):{...Qe("any"),nullable:n}}}function bg(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 i=Object.keys(s).sort(),r=[];for(let l of i){let d=Y(s[l]),p=d?ht(d,n):Qe("any");r.push({name:l,schema:p,required:a.has(l)})}let o=Y(e.additionalProperties);return{...Qe("object"),nullable:t,props:r,...o?{additional:ht(o,n)}:e.additionalProperties===!1?{additional:!1}:{}}}function vP(e,t=new Ea){let n=Y(e),s=Y(n?.["x-palbase-gateways"]);if(!s||!n)return[];let a=[];for(let[i,r]of Object.entries(s)){let o=Y(r),l=dt(o?.pattern);!o||l===""||!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(i)||Eg.has(i)||KP.has(i)||a.push({name:i,pattern:l,params:_P(l),durable:typeof o.durable=="number"&&o.durable>0,chat:o.chat===!0,events:kP(o.events,n,t),messages:SP(o.messages,n,t)})}return a.sort((i,r)=>i.name<r.name?-1:i.name>r.name?1:0),a}function _P(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 kP(e,t,n){let s=Y(e);if(!s)return[];let a=[];for(let[i,r]of Object.entries(s)){let o=Y(r);if(!o)continue;let l=bl(o,t)??o;a.push({name:i,schema:ht(l,n)})}return a.sort((i,r)=>i.name<r.name?-1:i.name>r.name?1:0),a}function SP(e,t,n){let s=Y(e);if(!s)return[];let a=[];for(let[i,r]of Object.entries(s)){let o=Y(r),l=Y(o?.payload);if(!o||!l)continue;let d=Y(o.reply);a.push({name:i,schema:ht(bl(l,t)??l,n),...d?{reply:ht(bl(d,t)??d,n)}:{}})}return a.sort((i,r)=>i.name<r.name?-1:i.name>r.name?1:0),a}function bl(e,t){let n=dt(e.$ref);if(!n.startsWith("#/"))return;let s=t;for(let a of n.slice(2).split("/")){let i=a.replace(/~1/g,"/").replace(/~0/g,"~"),r=Y(s);if(!r||!Object.hasOwn(r,i))return;s=r[i]}return Y(s)}function tr(e){return e.split(".").filter(t=>t!=="")}function lt(e){return Qi(e,!0)}function nr(e){return tr(e).map(lt).join("")}function Qi(e,t){let n=[],s="";for(let i of e)/^[A-Za-z0-9]$/.test(i)?s+=i: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((i,r)=>{a+=r===0&&!t?i.charAt(0).toLowerCase()+i.slice(1):i.charAt(0).toUpperCase()+i.slice(1)}),a.charAt(0)>="0"&&a.charAt(0)<="9"&&(a=`_${a}`),!Vi.test(a))throw new Error(`${JSON.stringify(e)} does not make an identifier`);return a}function Sg(e,t){if(!Yi(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{mg(t.project)}catch(T){throw new Error(`the project's address ${JSON.stringify(t.project)}: ${T instanceof Error?T.message:String(T)}`)}if(!cg(t.machine))throw new Error(`${JSON.stringify(t.machine)} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);try{hg(t.url)}catch(T){throw new Error(`the machine's address ${JSON.stringify(t.url)}: ${T instanceof Error?T.message:String(T)}`)}let n=new Ea,s=uP(e,n),a=vP(e,n),i=$P(e),r=[],o=[],l=new Set;for(let T of s){let[D]=tr(T.operationId);if(D!==void 0){if(ug(D)){let U=D.toLowerCase();l.has(U)||(l.add(U),o.push(D));continue}r.push(T)}}o.sort();let[d,p]=PP(r),u=new wl,[g,y,w]=RP(d,u),_=d.filter(T=>!w.has(T.operationId)),[P,S]=OP(_,u),$="";for(let T of t.header)$+=T===""?`//
|
|
570
570
|
`:`// ${Te(T)}
|
|
@@ -583,15 +583,15 @@ public typealias JSONValue = JsonElement
|
|
|
583
583
|
`;for(let T of a)$+=BP(T,u)}return i!==void 0&&($+=WP(i)),$}var wl=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}},Zi=e=>`operation ${JSON.stringify(e.operationId)}`,$g=(e,t)=>`${Zi(e)}'s error ${JSON.stringify(t.name)}`,Xi=e=>`gateway ${e.name} (${JSON.stringify(e.pattern)})`;function $P(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 PP(e){let t=[],n=[],s=new er;for(let a of e){let i=tr(a.operationId),r=i[i.length-1];if(r===void 0)continue;let o=!1;for(let d of i.slice(1))if(Hi(d)){n.push(`// codegen: skipped operation "${Te(a.operationId)}" (reserved segment "${Te(d)}")`),o=!0;break}if(o)continue;if(a.input&&a.query){n.push(`// codegen: skipped operation "${Te(a.operationId)}" (both body and query declared \u2014 unsupported)`);continue}if(a.sse&&a.query){n.push(`// codegen: skipped operation "${Te(a.operationId)}" (streaming with query parameters \u2014 unsupported)`);continue}if(a.upload&&(a.method!=="POST"||a.sse)){n.push(`// codegen: skipped operation "${Te(a.operationId)}" (an upload that is not one POST answered once \u2014 unsupported)`);continue}if(a.query){let d=AP(a.query);if(d!==void 0){n.push(`// codegen: skipped operation "${Te(a.operationId)}" (non-primitive query parameter "${Te(d)}")`);continue}}let l=s;for(let d of i.slice(0,-1))if(l=l.childNode(d),!l)break;if(!l?.addMethod(r,a)){n.push(`// codegen: skipped operation "${Te(a.operationId)}" (key collides with existing namespace/method)`);continue}t.push(a)}return[t,n]}function AP(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 RP(e,t){let n=new Set,s=new Map,a=[],i=[];for(let o of e){let l=nr(o.operationId),d=s.get(l);if(d!==void 0){a.push(`// codegen: skipped type "${Te(l)}" (collides with operation "${Te(d)}")`),n.add(o.operationId);continue}s.set(l,o.operationId),o.input&&i.push(...Wn(t.claim(`${l}Request`,Zi(o)),o.input)),o.query&&i.push(...Wn(t.claim(`${l}Query`,Zi(o)),o.query)),o.output&&i.push(...TP(l,o.output,u=>t.claim(u,Zi(o))));let p=vl(o);for(let u of p){if(!u.data)continue;let g=t.claim(`${l}${lt(u.name)}Data`,$g(o,u));i.push(`/** ${Te(u.code)} (${u.status}): ${Te(u.description)} */`),i.push(...Wn(g,u.data))}}if(i.length===0)return["",a,n];let r=`// \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
|
|
584
584
|
|
|
585
585
|
`;for(let o of i)r+=`${o}
|
|
586
|
-
`;return[r,a,n]}function Wn(e,t){return t.kind==="object"&&!t.nullable&&t.props.length>0&&!t.additional?Pg(e,t):[`export type ${e} = ${Jn(t)};`,""]}function TP(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?[...Pg(n(`${e}ResponseItem`),t.elem),`export type ${n(`${e}Response`)} = ${e}ResponseItem[]${t.nullable?" | null":""};`,""]:Wn(n(`${e}Response`),t)}function Pg(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(` ${
|
|
586
|
+
`;return[r,a,n]}function Wn(e,t){return t.kind==="object"&&!t.nullable&&t.props.length>0&&!t.additional?Pg(e,t):[`export type ${e} = ${Jn(t)};`,""]}function TP(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?[...Pg(n(`${e}ResponseItem`),t.elem),`export type ${n(`${e}Response`)} = ${e}ResponseItem[]${t.nullable?" | null":""};`,""]:Wn(n(`${e}Response`),t)}function Pg(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(` ${Rt(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"?we(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(we).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=EP(e);return e.nullable?`${t} | null`:t}default:return e.nullable?"unknown | null":"unknown"}}function EP(e){let t=[];for(let n of e.props){if(n.name==="__proto__")continue;let s=n.required?"":"?";t.push(`${Rt(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 CP=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"]),jP=/^http_\d+$/;function vl(e){if(e.errors.length===0)return[];let t=i=>{throw new Error(`${e.operationId}: ${i} \u2014 rename the error in the backend and push again`)},n=[...e.errors].sort((i,r)=>i.code<r.code?-1:i.code>r.code?1:0),s=new Set,a=new Map;for(let i of n){i.code==="__proto__"&&t('declares the error code "__proto__", which no lookup can hold'),(CP.has(i.code)||jP.test(i.code))&&t(`declares the error "${i.code}", a code the web client produces itself \u2014 the two could not be told apart`),s.has(i.code)&&t(`declares the error code "${i.code}" twice`);let r=lt(i.name),o=a.get(r);o!==void 0&&t(`declares errors "${o}" and "${i.name}", which both become the class ${r}`),s.add(i.code),a.set(r,i.name)}return n}function OP(e,t){let n=0,s=[];for(let i of e){let r=nr(i.operationId),o=vl(i);for(let l of o){let d=t.claim(`${r}${lt(l.name)}Error`,$g(i,l)),p=l.data!==void 0;s.push(`export class ${d} extends Error {`),s.push(` readonly name = ${we(d)};`),s.push(` readonly code = ${we(l.code)};`),s.push(` readonly status = ${l.status};`),p&&s.push(` readonly data: ${r}${lt(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 ${r}${lt(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
|
|
587
587
|
|
|
588
588
|
`;for(let i of s)a+=`${i}
|
|
589
589
|
`;return[a,n]}var er=class e{entries=[];index=new Map;childNode(t){let n=this.index.get(t);if(n)return n.child;let s=new e,a={key:t,child:s};return this.entries.push(a),this.index.set(t,a),s}addMethod(t,n){if(this.index.has(t))return!1;let s={key:t,op:n};return this.entries.push(s),this.index.set(t,s),!0}};function Ag(e){let t=new er;for(let n of e){let s=tr(n.operationId),a=s[s.length-1];if(a===void 0)continue;let i=t;for(let r of s.slice(0,-1))if(i=i.childNode(r),!i)break;i&&i.addMethod(a,n)}return t}function MP(e,t){let n=`__registerBackend(${we(t.project)}, ${we(t.client)}, ${we(t.machine)}, ${we(t.url)}, `,s=e.some(i=>i.encryption)?`, ${IP(t)})`:")";if(e.length===0)return`${n}{}${s};
|
|
590
590
|
`;let a=`${n}{
|
|
591
591
|
`;return a+=Rg(Ag(e),2),a+=`}${s};
|
|
592
|
-
`,a}function IP(e){if(!e.transit)throw new Error("the contract marks encrypted fields: the module needs the project's id and signing key (palbase apps:sync gives them)");return`{ projectId: ${we(e.transit.projectId)}, signer: ${we(e.transit.signer)} }`}function Rg(e,t){let n=" ".repeat(t),s="";for(let a of e.entries){if(a.child){s+=`${n}${
|
|
592
|
+
`,a}function IP(e){if(!e.transit)throw new Error("the contract marks encrypted fields: the module needs the project's id and signing key (palbase apps:sync gives them)");return`{ projectId: ${we(e.transit.projectId)}, signer: ${we(e.transit.signer)} }`}function Rg(e,t){let n=" ".repeat(t),s="";for(let a of e.entries){if(a.child){s+=`${n}${Rt(a.key)}: {
|
|
593
593
|
`,s+=Rg(a.child,t+2),s+=`${n}},
|
|
594
|
-
`;continue}a.op&&(s+=LP(a.op,a.key,t))}return s}function LP(e,t,n){let s=" ".repeat(n),a=
|
|
594
|
+
`;continue}a.op&&(s+=LP(a.op,a.key,t))}return s}function LP(e,t,n){let s=" ".repeat(n),a=Rt(t),i=vl(e),r=i.length>0,o=e.pathParams.length>0,l=e.input!==void 0,d=e.query!==void 0,p="";!l&&!d?p="none":d&&(p="query");let u="";if(!r){let y=[`method: ${we(e.method)}`,`path: ${we(e.path)}`];return o&&y.push(`pathParams: [${Fn(e.pathParams)}]`),p!==""&&y.push(`input: ${we(p)}`),e.upload&&y.push("upload: true"),e.sse&&y.push("sse: true"),e.idempotent&&!e.upload&&y.push("idempotent: true"),e.encryption&&y.push(`encryption: ${wg(e.encryption)}`),u+=`${s}${a}: { ${y.join(", ")} },
|
|
595
595
|
`,u}let g=" ".repeat(n+2);return u+=`${s}${a}: {
|
|
596
596
|
`,u+=`${g}method: ${we(e.method)},
|
|
597
597
|
`,u+=`${g}path: ${we(e.path)},
|
|
@@ -601,16 +601,16 @@ public typealias JSONValue = JsonElement
|
|
|
601
601
|
`),e.sse&&(u+=`${g}sse: true,
|
|
602
602
|
`),e.idempotent&&!e.upload&&(u+=`${g}idempotent: true,
|
|
603
603
|
`),e.encryption&&(u+=`${g}encryption: ${wg(e.encryption)},
|
|
604
|
-
`),u+=`${g}errors: { `,i.forEach((y,w)=>{w>0&&(u+=", ");let _=`${nr(e.operationId)}${lt(y.name)}Error`;u+=`${
|
|
604
|
+
`),u+=`${g}errors: { `,i.forEach((y,w)=>{w>0&&(u+=", ");let _=`${nr(e.operationId)}${lt(y.name)}Error`;u+=`${Rt(y.code)}: (e) => new ${_}(e)`}),u+=` },
|
|
605
605
|
`,u+=`${s}},
|
|
606
606
|
`,u}function wg(e){let t=[];return e.request.length>0&&t.push(`request: [${Fn(e.request)}]`),e.response.length>0&&t.push(`response: [${Fn(e.response)}]`),`{ ${t.join(", ")} }`}function Fn(e){return e.map(we).join(", ")}function DP(e){if(e.length===0)return`export interface Backend extends BackendBase {}
|
|
607
607
|
`;let t=`export interface Backend extends BackendBase {
|
|
608
608
|
`;return t+=Tg(Ag(e),2),t+=`}
|
|
609
|
-
`,t}function Tg(e,t){let n=" ".repeat(t),s="";for(let a of e.entries){if(a.child){s+=`${n}${
|
|
609
|
+
`,t}function Tg(e,t){let n=" ".repeat(t),s="";for(let a of e.entries){if(a.child){s+=`${n}${Rt(a.key)}: {
|
|
610
610
|
`,s+=Tg(a.child,t+2),s+=`${n}};
|
|
611
611
|
`;continue}a.op&&(s+=`${n}${GP(a.key)}${xP(a.op)};
|
|
612
|
-
`)}return s}function xP(e){let t=nr(e.operationId),n=[],s=new Set;for(let i of e.pathParams)n.push(`${qP(i,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(NP(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 NP(e){if(!e||e.props.length===0)return"options?: CallOptions";let t=e.props.some(a=>a.required),s=`{ ${e.props.map(a=>{let i=a.required?"":"?";return`${
|
|
613
|
-
`:return"\\n";case"\r":return"\\r";case"'":return t?"\\'":e}return e.length===1&&UP.test(e)?`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`:e}function we(e){let t="'";for(let n of e)t+=Cg(n,!0);return`${t}'`}function Te(e){let t="";for(let n of e)t+=n==="@"?"\\u0040":n==="#"?"\\u0023":Cg(n,!1);return t.replaceAll("*/","*\\/")}function BP(e,t){let n=e.name,s=[];for(let i of e.events)s.push(...Wn(t.claim(`${n}${lt(i.name)}Event`,`${Xi(e)}'s event ${JSON.stringify(i.name)}`),i.schema));for(let i of e.messages)s.push(...Wn(t.claim(`${n}${lt(i.name)}Message`,`${Xi(e)}'s message ${JSON.stringify(i.name)}`),i.schema)),i.reply&&s.push(...Wn(t.claim(`${n}${lt(i.name)}Reply`,`${Xi(e)}'s ack of ${JSON.stringify(i.name)}`),i.reply));for(let i of[`${n}Event`,`${n}Params`,n])t.claim(i,Xi(e));if(e.events.length>0){s.push(`export type ${n}Event =`);for(let i of e.events)s.push(` | { event: ${we(i.name)}; payload: ${n}${lt(i.name)}Event }`);s[s.length-1]+=";"}else s.push(`export type ${n}Event = never;`);s.push("");let a=e.params.map(i=>`${
|
|
612
|
+
`)}return s}function xP(e){let t=nr(e.operationId),n=[],s=new Set;for(let i of e.pathParams)n.push(`${qP(i,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(NP(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 NP(e){if(!e||e.props.length===0)return"options?: CallOptions";let t=e.props.some(a=>a.required),s=`{ ${e.props.map(a=>{let i=a.required?"":"?";return`${Rt(a.name)}${i}: ${Jn(a.schema)}`}).join("; ")} }`;return t?`options: CallOptions & { headers: ${s} }`:`options?: CallOptions & { headers?: ${s} }`}function qP(e,t){let n=Qi(e,!1);(Eg.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 KP=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(" ")),Eg=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 Rt(e){return Vi.test(e)?e:we(e)}function GP(e){return e==="new"?we(e):Rt(e)}var UP=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069\ud800-\udfff]/;function Cg(e,t){switch(e){case"\\":return"\\\\";case`
|
|
613
|
+
`:return"\\n";case"\r":return"\\r";case"'":return t?"\\'":e}return e.length===1&&UP.test(e)?`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`:e}function we(e){let t="'";for(let n of e)t+=Cg(n,!0);return`${t}'`}function Te(e){let t="";for(let n of e)t+=n==="@"?"\\u0040":n==="#"?"\\u0023":Cg(n,!1);return t.replaceAll("*/","*\\/")}function BP(e,t){let n=e.name,s=[];for(let i of e.events)s.push(...Wn(t.claim(`${n}${lt(i.name)}Event`,`${Xi(e)}'s event ${JSON.stringify(i.name)}`),i.schema));for(let i of e.messages)s.push(...Wn(t.claim(`${n}${lt(i.name)}Message`,`${Xi(e)}'s message ${JSON.stringify(i.name)}`),i.schema)),i.reply&&s.push(...Wn(t.claim(`${n}${lt(i.name)}Reply`,`${Xi(e)}'s ack of ${JSON.stringify(i.name)}`),i.reply));for(let i of[`${n}Event`,`${n}Params`,n])t.claim(i,Xi(e));if(e.events.length>0){s.push(`export type ${n}Event =`);for(let i of e.events)s.push(` | { event: ${we(i.name)}; payload: ${n}${lt(i.name)}Event }`);s[s.length-1]+=";"}else s.push(`export type ${n}Event = never;`);s.push("");let a=e.params.map(i=>`${Rt(i)}: string`).join("; ");return s.push(`export interface ${n}Params { ${a} }`),s.push(`export const ${n} = {`),s.push(` name: ${we(n)},`),s.push(` pattern: ${we(e.pattern)},`),s.push(` params: [${Fn(e.params)}] as const,`),s.push(` durable: ${e.durable},`),e.chat&&s.push(" chat: true,"),s.push(` events: [${Fn(e.events.map(i=>i.name))}] as const,`),s.push(` messages: [${Fn(e.messages.map(i=>i.name))}] as const,`),s.push(` send: {} as { ${e.messages.map(i=>`${Rt(i.name)}: ${n}${lt(i.name)}Message`).join("; ")} },`),s.push(` reply: {} as { ${e.messages.map(i=>`${Rt(i.name)}: ${i.reply?`${n}${lt(i.name)}Reply`:"unknown"}`).join("; ")} },`),s.push(` event: {} as ${n}Event,`),s.push("} as const;"),s.push(""),s.join(`
|
|
614
614
|
`)}function zP(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 r of t.permissions){if(typeof r!="string")throw new Error(`role "${s}" lists a permission that is not a name`);a.push(r)}let i={name:s,isDefault:t.isDefault,permissions:a};return"description"in t&&typeof t.description=="string"&&t.description!==""&&(i.description=t.description),i})}function WP(e){let t=zP(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=Qi(d.name,!1),u=a.get(p);if(u!==void 0){s.push(` // codegen: skipped duplicate role "${Te(d.name)}" \u2014 collides with "${Te(u)}" (both map to \`${Te(p)}\`)`);continue}a.set(p,d.name),d.description!==void 0&&s.push(` /** ${Te(d.description)} */`),d.isDefault&&s.push(" /** Assigned to every new user at signup. */"),s.push(` ${p}: ${we(d.name)},`)}let i=[],r=new Map;for(let d of n){let p=Qi(d,!1),u=r.get(p);if(u!==void 0){i.push(` // codegen: skipped duplicate permission "${Te(d)}" \u2014 collides with "${Te(u)}" (both map to \`${Te(p)}\`)`);continue}r.set(p,d),i.push(` ${p}: ${we(d)},`)}let o="";if(a.size>0&&(o+=`export const Roles = {
|
|
615
615
|
`,o+=`${s.join(`
|
|
616
616
|
`)}
|
|
@@ -637,14 +637,14 @@ public typealias JSONValue = JsonElement
|
|
|
637
637
|
`,l+o}var FP=/^[a-z][A-Za-z0-9]{0,62}$/,JP=new Set(["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","let","static","implements","interface","package","private","protected","public","await","async","associatedtype","deinit","extension","fileprivate","func","init","inout","internal","operator","precedencegroup","protocol","rethrows","struct","subscript","typealias","defer","fallthrough","guard","repeat","where","as","is","nil","self","throws","some","any","open","fun","object","typeof","val","when","interface","package","throw","try"]);function _l(e){return e.replace(/-([a-z0-9])/g,(t,n)=>n.toUpperCase())}function VP(e){if(!FP.test(e))return`${JSON.stringify(e)} is not a name of one: a letter a\u2013z, then letters and digits (shopApi), at most 63`;if(yl.includes(e))return`${e} is the client's own (pb.${e}) on one of the platforms \u2014 the backend is named another way`;if(JP.has(e))return`${e} is a word TypeScript, Swift or Kotlin keeps`;if(!Yi(e))return`${e} is a name every object has (pb.${e}) \u2014 the backend is named another way`}function jg(e,t,n){let s=new Map,a=new Map;for(let i of[...new Set(e)].sort()){let r=Object.hasOwn(t,i)?t[i]:void 0,o=r??_l(i),l=VP(o);if(l)throw new Error(r!==void 0?`--as ${i}=${o}: ${l}`:`${i}'s name in the apps, ${o}: ${l} \u2014 name it (palbase apps:sync --as ${i}=<name>)`);let d=a.get(o);if(d!==void 0)throw new Error(`${d} and ${i} would both be pb.${o}${n===void 0?"":` in ${n}`}: name one of them (palbase apps:sync --as ${i}=<name>)`);a.set(o,i),s.set(i,o)}return s}function nA(e){let t=e.paths;return typeof t!="object"||t===null?!1:Object.values(t).some(n=>typeof n=="object"&&n!==null&&Object.values(n).some(s=>typeof s=="object"&&s!==null&&s["x-palbase-attest"]===!0))}var z="palbase",Ca="// Code generated by palbase apps:sync",Is=e=>`${JSON.stringify(e,null,2)}
|
|
638
638
|
`,sA={environment:/^[A-Za-z][A-Za-z0-9-]{0,38}$/,app:/^[a-z][a-z0-9-]{0,38}[a-z0-9]$/,appId:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,machine:/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/,digest:/^[0-9a-f]{64}$/};function Ls(e,t){if(typeof t!="string"||!sA[e].test(t))throw new f("unexpected_answer",`the project answered ${e} ${JSON.stringify(t)}, which is not one`);return t}function kl(e){return String(e).replace(/[\u0000-\u001f\u007f\u061c\u200e\u200f\u2028-\u202e\u2066-\u2069]/g," ")}function aA(e){return e==="web"?"ts":e==="ios"?"swift":e==="android"?"kotlin":null}var Mg=e=>e.charAt(0).toUpperCase()+e.slice(1);function iA(e,t,n=[]){let s={url:t.url,publishableKey:t.publishable_key,environment:t.environment.slug,app:e.slug,appId:Ls("appId",t.app.id)},a=[...n].sort((i,r)=>i.client.localeCompare(r.client));return[`${Ca} \u2014 DO NOT EDIT.`,`// The settings of ${e.slug} (${kl(e.name)}) in ${t.environment.slug} (${kl(t.environment.name)}): what it is built with. Digest: ${kl(t.digest)}`,"import { createClient, type ClientOptions, type PalbaseClient } from 'palbase/web';",...a.flatMap(i=>[`import './palbe/${i.machine}';`,`import type { Backend as ${Mg(i.client)}Backend } from './palbe/${i.machine}';`]),...a.length===1?[`export * from './palbe/${a[0]?.machine}';`]:[],"",`export const settings = ${JSON.stringify(s,null,2)} as const;`,"",`/** The app's client: its project's modules (pb.auth, \u2026) and its backends${a.map(i=>`, pb.${i.client}`).join("")}. */`,`export type Client = PalbaseClient${a.length>0?` & { ${a.map(i=>`${i.client}: ${Mg(i.client)}Backend`).join("; ")} }`:""};`,"","let client: Client | undefined;","","/**"," * The app's client, made once with these settings \u2014 and with options, when"," * connect(options) is called before anything uses the client (pb)."," */","export function connect(options: Omit<ClientOptions, 'url' | 'publishableKey'> = {}): Client {"," if (client) {"," if (Object.keys(options).length > 0) throw new Error('palbase: connect(options) comes before the client is first used \u2014 call it as the app starts');"," return client;"," }"," client = createClient({ ...options, url: settings.url, publishableKey: settings.publishableKey, appId: settings.appId }) as Client;"," return client;","}","","/** The app's client, made when it is first used: pb.<backend>.<controller>.<method>(), pb.auth, \u2026 */","export const pb: Client = new Proxy({} as Client, {"," get(_, key) {"," const c = connect();"," const value: unknown = Reflect.get(c, key, c);"," return typeof value === 'function' ? value.bind(c) : value;"," },"," has: (_, key) => Reflect.has(connect(), key),","});",""].join(`
|
|
639
639
|
`)}async function rA(e,t){let n=await XP(pt(eA(),"palbase-contract-")),s=pt(n,"openapi.json");try{let a=await e.io.run("bun",["--no-env-file","run","src/main.ts"],{cwd:t,env:{PALBASE_CONTRACT_OUT:s},envOnly:!0}),i;try{i=await ja(s,"utf8")}catch{throw new f("no_contract",`the backend in ${t} wrote no contract (bun run src/main.ts exited ${a.code})`,{hint:`${(a.stderr||a.stdout).trim().split(`
|
|
640
|
-
`).slice(-3).join(" ").slice(0,300)||"is it a palbase/backend app, started from src/main.ts?"}`})}return JSON.parse(i)}finally{await Dg(n,{recursive:!0,force:!0})}}function oA(e,t){if(typeof e!="string"||e==="")return;let n=e.indexOf("=");return n>0&&/^[a-z][a-z0-9-]{0,62}$/.test(e.slice(0,n))?{machine:e.slice(0,n),dir:Og(t,e.slice(n+1))}:{dir:Og(t,e)}}async function lA(e,t){let n=await kn(e);if(t&&t.project.id!==n.id)throw new f("another_project",`this checkout's ${z}/ is ${t.project.name}'s, not ${n.name}'s`,{hint:`run it for ${t.project.name} (-P), or in that project's own checkout`});let s=await et(e,n.id),a=[...new Set([...t?.apps.map(O=>O.id)??[],...e.args])];if(a.length===0)throw m("name the app(s) this checkout builds: palbase apps:sync <app>",`the project's apps: ${s.map(O=>O.slug).join(", ")||"none \u2014 palbase apps:create"}`);let i=[];for(let O of a){let V=mt(s,O);if(Ls("app",V.slug),V.deleted_at)throw new f("app_deleted",`${V.name} is deleted (restorable until ${V.purge_after})`,{hint:`palbase apps:restore ${V.slug} \u2014 the sync writes nothing meanwhile`});i.some(G=>G.id===V.id)||i.push(V)}let r=new Map,o=[],l=new Map,d=new Map,p=new Map,u=oA(e.flags.backend,e.io.cwd),g=new Map,y=new Map,w=new Map,_=new Map,P=new Map,S=new Map,$=new Set;for(let O of i){let V=aA(O.platform);O.environments.length===0&&o.push(`${O.name} is in no environment yet: palbase apps:env:set ${O.slug} -E <env> \u2026`);for(let G of O.environments){if(G.suspended)continue;let ee=await e.studio.get(`/environments/${G.ref}/apps/${O.id}/config`),re=Ls("environment",ee.environment.slug),$e=[...l.keys()].find(le=>le!==re&&le.toLowerCase()===re.toLowerCase());if($e!==void 0)throw new f("environments_collide",`${$e} and ${re} differ only in case: their files under ${z}/environments/ would be one directory's on macOS and Windows`,{hint:"rename one of the environments"});l.set(re,ee.environment),d.set(re,ee.url),r.set(`${z}/environments/${re}/${O.slug}.json`,Is(ee)),O.platform==="ios"&&_.set(O,(_.get(O)??new Map).set(re,Is(ee))),O.platform==="android"&&S.set(O,(S.get(O)??new Set).add(re)),O.platform==="ios"&&typeof ee.keychain_group=="string"&&P.set(O,(P.get(O)??new Set).add(ee.keychain_group)),O.platform==="web"&&(y.set(O,(y.get(O)??new Map).set(re,ee)),w.set(O.slug,(w.get(O.slug)??new Set).add(re))),V&&g.set(re,(g.get(re)??new Set).add(V));for(let le of ee.backends){Ls("machine",le.machine),le.contract_digest!==void 0&&Ls("digest",le.contract_digest);let ln=p.get(re)??new Map;if(!le.contract_digest&&!(u&&(u.machine??le.machine)===le.machine)){let{body:
|
|
640
|
+
`).slice(-3).join(" ").slice(0,300)||"is it a palbase/backend app, started from src/main.ts?"}`})}return JSON.parse(i)}finally{await Dg(n,{recursive:!0,force:!0})}}function oA(e,t){if(typeof e!="string"||e==="")return;let n=e.indexOf("=");return n>0&&/^[a-z][a-z0-9-]{0,62}$/.test(e.slice(0,n))?{machine:e.slice(0,n),dir:Og(t,e.slice(n+1))}:{dir:Og(t,e)}}async function lA(e,t){let n=await kn(e);if(t&&t.project.id!==n.id)throw new f("another_project",`this checkout's ${z}/ is ${t.project.name}'s, not ${n.name}'s`,{hint:`run it for ${t.project.name} (-P), or in that project's own checkout`});let s=await et(e,n.id),a=[...new Set([...t?.apps.map(O=>O.id)??[],...e.args])];if(a.length===0)throw m("name the app(s) this checkout builds: palbase apps:sync <app>",`the project's apps: ${s.map(O=>O.slug).join(", ")||"none \u2014 palbase apps:create"}`);let i=[];for(let O of a){let V=mt(s,O);if(Ls("app",V.slug),V.deleted_at)throw new f("app_deleted",`${V.name} is deleted (restorable until ${V.purge_after})`,{hint:`palbase apps:restore ${V.slug} \u2014 the sync writes nothing meanwhile`});i.some(G=>G.id===V.id)||i.push(V)}let r=new Map,o=[],l=new Map,d=new Map,p=new Map,u=oA(e.flags.backend,e.io.cwd),g=new Map,y=new Map,w=new Map,_=new Map,P=new Map,S=new Map,$=new Set;for(let O of i){let V=aA(O.platform);O.environments.length===0&&o.push(`${O.name} is in no environment yet: palbase apps:env:set ${O.slug} -E <env> \u2026`);for(let G of O.environments){if(G.suspended)continue;let ee=await e.studio.get(`/environments/${G.ref}/apps/${O.id}/config`),re=Ls("environment",ee.environment.slug),$e=[...l.keys()].find(le=>le!==re&&le.toLowerCase()===re.toLowerCase());if($e!==void 0)throw new f("environments_collide",`${$e} and ${re} differ only in case: their files under ${z}/environments/ would be one directory's on macOS and Windows`,{hint:"rename one of the environments"});l.set(re,ee.environment),d.set(re,ee.url),r.set(`${z}/environments/${re}/${O.slug}.json`,Is(ee)),O.platform==="ios"&&_.set(O,(_.get(O)??new Map).set(re,Is(ee))),O.platform==="android"&&S.set(O,(S.get(O)??new Set).add(re)),O.platform==="ios"&&typeof ee.keychain_group=="string"&&P.set(O,(P.get(O)??new Set).add(ee.keychain_group)),O.platform==="web"&&(y.set(O,(y.get(O)??new Map).set(re,ee)),w.set(O.slug,(w.get(O.slug)??new Set).add(re))),V&&g.set(re,(g.get(re)??new Set).add(V));for(let le of ee.backends){Ls("machine",le.machine),le.contract_digest!==void 0&&Ls("digest",le.contract_digest);let ln=p.get(re)??new Map;if(!le.contract_digest&&!(u&&(u.machine??le.machine)===le.machine)){let{body:ft}=await _e(e.studio,l.get(re)?.ref,"GET",`/machines/${x("the machine's name",le.machine)}`);if(ft.contract_state==="none"){o.push(`${le.machine} in ${re} serves no contract (its app writes none): no Palbe client for it`);continue}let Cn=ft.contract_state==="refused"?`its contract was refused \u2014 ${As(ft.contract_error??"its app wrote none")}`:"its build's is still being written",yt=await dA(e.io.cwd,re,le.machine);if(!yt){o.push(ft.contract_state==="refused"?`${le.machine} in ${re}: ${Cn}: no Palbe client for it (palbase machines:get ${le.machine} says why)`:`${le.machine} in ${re} has no contract kept yet \u2014 it is read once its build's version alone serves (a palbase/backend app, or one given --openapi-path): no Palbe client for it`);continue}o.push(`${le.machine} in ${re} has no contract kept \u2014 ${Cn}: its client stays the one made from ${z}/environments/${re}/contracts/${le.machine}.openapi.json; palbase apps:sync again once it is kept`),ln.set(le.machine,{url:le.url,digest:yt.digest,last:yt.doc}),p.set(re,ln);continue}ln.set(le.machine,{url:le.url,digest:le.contract_digest??""}),p.set(re,ln)}}}let R=new Set([...p.values()].flatMap(O=>[...O.keys()]));if(u&&u.machine===void 0){if(R.size!==1)throw m(`--backend ${String(e.flags.backend)}: name the machine it is (--backend <machine>=<dir>)`,`this checkout's apps reach ${[...R].join(", ")||"no backend"}`);u.machine=[...R][0]}if(u&&!R.has(u.machine))throw m(`--backend: ${u.machine} is not a backend this checkout's apps reach`,`they reach ${[...R].join(", ")||"none"}`);let T=u?await rA(e,u.dir):void 0;for(let[O,V]of P)o.push(`${O.slug}: its entitlements must list keychain-access-groups $(AppIdentifierPrefix)$(PRODUCT_BUNDLE_IDENTIFIER).palbase (${[...V].sort().join(", ")}) \u2014 without it the SDK keeps no session and sign-in fails with keychain_unavailable`);u&&o.push(`${u.machine}'s Palbe is made from the backend in ${u.dir}, not from what its machine serves: sync again without --backend once it is deployed`);let D={...t?.clients??{}};for(let O of e.flags.as??[]){let V=O.indexOf("="),G=V>0?O.slice(0,V):"";if(!/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/.test(G))throw m(`--as ${O}: it is <machine>=<name>`,"palbase apps:sync --as shop-api=shop");if(!R.has(G))throw m(`--as ${O}: ${G} is not a backend this checkout's apps reach`,`they reach ${[...R].join(", ")||"none"}`);let ee=O.slice(V+1);ee===""||ee===_l(G)?delete D[G]:D[G]=ee}let U=new Map;try{for(let[O,V]of p)U.set(O,jg(V.keys(),D,O))}catch(O){throw new f("invalid_backend_name",O.message,{hint:"a name is a letter a\u2013z, then letters and digits; not one of the client's own (auth, flags, storage, \u2026) or a word a language keeps"})}for(let O of Object.keys(D))R.has(O)||delete D[O];let W=new Map,I=new Map,F=(O,V,G)=>[`${Ca.slice(3)} \u2014 DO NOT EDIT.`,`${O}'s client in ${V}, from its contract (contracts/${O}.openapi.json, sha256 ${G||"of this checkout"}): palbase apps:sync makes it again`],pe=new Map,Se=O=>{let V=pe.get(O);return V||(V=(async()=>{let G=await e.studio.get(`/environments/${x("the environment's ref",O)}`),{body:ee}=await _e(e.studio,O,"GET","/secrets/transit");return{projectId:G.platform_id,signer:ee.signer}})(),pe.set(O,V)),V};for(let[O,V]of[...p].sort(([G],[ee])=>G.localeCompare(ee))){let G=l.get(O)?.ref,ee=g.get(O)??new Set,re=new Map([["swift",new Map],["kotlin",new Map]]);for(let[$e,le]of[...V].sort(([ln],[ft])=>ln.localeCompare(ft))){let ln=le.url,ft=U.get(O)?.get($e),Cn=T!==void 0&&$e===u?.machine,yt=Cn?T:le.last??(await _e(e.studio,G,"GET",`/machines/${x("the machine's name",$e)}/openapi`)).body;if(!Cn&&!le.last){let{body:Ct}=await _e(e.studio,G,"GET",`/machines/${x("the machine's name",$e)}`);Ct.failed_build&&o.push(`${$e} in ${O}: ${sh(Ct.failed_build)}; its client is made from the contract of the build it serves`)}let Fw=Cn?Lg("sha256").update(Is(yt)).digest("hex"):le.digest;r.set(`${z}/environments/${O}/contracts/${$e}.openapi.json`,Is(yt));let Jr=F($e,O,Fw),ds=cm(yt)?await Se(G):void 0;nA(yt)&&$.add(O);let Vr=(Ct,Jw)=>{try{return Jw()}catch(Vw){throw new f("unusable_contract",`${$e}'s contract in ${O} makes no ${Ct} client: ${Vw.message}`,{hint:`fix the backend, deploy it, and sync again${Cn?"":` (palbase machines:builds ${$e} says what its build wrote)`}`})}};if(ee.has("ts")&&r.set(`${z}/environments/${O}/palbe/${$e}.ts`,Vr("TypeScript",()=>Sg(yt,{project:d.get(O),client:ft,machine:$e,url:ln,header:Jr,...ds?{transit:ds}:{}}))),ee.has("swift")){let Ct=Vr("Swift",()=>Zm(yt,{client:ft,machine:$e,header:Jr,...ds?{transit:ds}:{}}));Ig(re.get("swift"),pA(Ct),$e,O,"Swift"),I.set(O,[...I.get(O)??[],Ct])}if(ee.has("kotlin")){let Ct=Vr("Kotlin",()=>xm(yt,{client:ft,machine:$e,header:Jr,...ds?{transit:ds}:{}}));Ig(re.get("kotlin"),uA(Ct),$e,O,"Kotlin"),r.set(`${z}/environments/${O}/palbe/${$e}.kt`,Ct)}W.set(O,[...W.get(O)??[],{machine:$e,client:ft}])}}for(let[O,V]of y)for(let[G,ee]of V)r.set(`${z}/environments/${G}/${O.slug}.ts`,iA(O,ee,W.get(G)??[]));for(let[O,V]of _){let G={};for(let[ee,re]of[...V].sort(([$e],[le])=>$e.localeCompare(le)))G[ee]={swift:ym({environment:ee,document:re,backends:I.get(ee)??[]})};r.set(`${z}/${O.slug}.palbase`,Is({schema:1,app:O.slug,environments:G}))}let os=O=>[...O].filter(V=>$.has(V)).sort();for(let[O,V]of _){let G=os(V.keys());G.length>0&&o.push(`${O.slug}: its backends in ${G.join(", ")} have routes marked attest: true \u2014 its entitlements must list com.apple.developer.devicecheck.appattest-environment (Xcode's App Attest capability: development for a build run from Xcode; a TestFlight or App Store build uses Apple's production environment whatever the value says, so one entitlements file serves Debug and Release); without it its calls there are refused once App Attest is enforced`)}for(let[O,V]of S){let G=os(V);G.length>0&&o.push(`${O.slug}: its backends in ${G.join(", ")} have routes marked attest: true \u2014 register the SHA-256 of the certificates its releases are signed with (Play's app signing key, your upload key) \u2014 not a debug key, whose build anyone with the phone can drive (adb) to sign requests: palbase apps:env:set ${O.slug} -E <env> --sha256 <label>=<fingerprint>; a device's key is taken only from the app signed with one of them`)}let nt=[...new Set([...w.values()].flatMap(O=>[...O]))].sort(),ve=e.flags.types??t?.types_environment;if(ve!==void 0&&Ls("environment",ve),ve!==void 0&&nt.length>0&&!nt.includes(ve))throw m(`--types ${ve}: this checkout's web apps are set in ${nt.join(", ")}`);if(ve===void 0&&nt.length>0&&(ve=nt.find(O=>!l.get(O)?.production)??nt[0]),ve!==void 0&&nt.length>0){let O=G=>`${Ca} \u2014 DO NOT EDIT. The editor's types are ${ve}'s; a build imports its mode's environment (palbase() in vite.config).
|
|
641
641
|
${G}`,V=(G,ee)=>`${Ca} \u2014 DO NOT EDIT. ${G}'s, which a build made for ${G} type-checks the app against (palbase() in vite.config).
|
|
642
642
|
${ee}`;for(let[G,ee]of w){ee.has(ve)?r.set(`${z}/${G}.ts`,O(`export * from './environments/${ve}/${G}';
|
|
643
643
|
`)):o.push(`${G} is not in ${ve}: the editor has no types for it (palbase apps:sync --types <env>)`);for(let re of ee)r.set(`${z}/${G}.${re}.ts`,V(re,`export * from './environments/${re}/${G}';
|
|
644
644
|
`))}for(let{machine:G}of W.get(ve)??[])r.set(`${z}/palbe/${G}.ts`,O(`export * from '../environments/${ve}/palbe/${G}';
|
|
645
645
|
`));for(let G of nt)for(let{machine:ee}of W.get(G)??[])r.set(`${z}/palbe/${ee}.${G}.ts`,V(G,`export * from '../environments/${G}/palbe/${ee}';
|
|
646
|
-
`))}let ls={schema:1,project:{id:n.id,name:n.name},apps:i.map(O=>({id:O.id,slug:O.slug,name:O.name,platform:O.platform})),...ve!==void 0&&nt.length>0?{types_environment:ve}:{},...Object.keys(D).length>0?{clients:Object.fromEntries(Object.entries(D).sort(([O],[V])=>O.localeCompare(V)))}:{}};return r.set(`${z}/project.json`,Is(ls)),{files:r,notes:o,project:ls}}async function dA(e,t,n){let s=`${z}/environments/${t}`,a;try{a=await ja(await ge(e,`${s}/contracts/${n}.openapi.json`),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let i=`contracts/${n}.openapi.json, sha256 `,r=Lg("sha256").update(a).digest("hex");for(let o of[`${s}/palbe/${n}.ts`,`${s}/palbe/${n}.kt`]){let l=await ja(pt(e,o),"utf8").catch(()=>""),d=l.indexOf(i);if(d>=0){r=l.slice(d+i.length,l.indexOf(")",d));break}}return{doc:JSON.parse(a),digest:r}}function pA(e){return[...e.matchAll(/^public (?:nonisolated )?(?:struct|enum|typealias|final class|class|protocol) ([A-Za-z_][A-Za-z0-9_]*)/gm)].map(t=>t[1])}function uA(e){return[...e.matchAll(/^(?:(?:data|sealed|enum|value|internal|private|public) )*(?:class|object|interface|typealias) ([A-Za-z_][A-Za-z0-9_]*)|^val ([A-Za-z_][A-Za-z0-9_.]*\.[A-Za-z_][A-Za-z0-9_]*):/gm)].map(t=>t[1]??t[2])}function Ig(e,t,n,s,a){for(let i of t){let r=e.get(i);if(r!==void 0&&r!==n)throw new f("backends_collide",`${r} and ${n} both declare ${i} in ${s}'s ${a} client, which one target cannot hold`,{hint:"rename the controller or route in one of them (it names the type), or reach them from different apps"});e.set(i,n)}}async function cA(e){let t=new Map,n=async s=>{let a;try{a=await Sl(pt(e,s),{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of a){let r=`${s}/${i.name}`;if(i.isDirectory()){(s!==z||i.name==="environments"||i.name==="palbe")&&await n(r);continue}if(!i.isFile()||i.name.endsWith(".storekit"))continue;let o=await ja(pt(e,r),"utf8");(s!==z||i.name==="project.json"||i.name.endsWith(".palbase")||o.startsWith(Ca))&&t.set(r,o)}};return await n(z),t}async function ir(e){try{return JSON.parse(await ja(pt(e,z,"project.json"),"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw new f("unreadable_project_file",`${z}/project.json is not what palbase apps:sync writes: ${t.message}`)}}async function xg(e){let t=e.io.cwd,n=e.flags.check===!0,s=await ir(t),a=await lA(e,s),i=await cA(t),r=[],o=[],l=[];for(let[u,g]of a.files){let y=i.get(u);y===void 0?r.push(u):y!==g&&o.push(u)}for(let u of i.keys())a.files.has(u)||l.push(u);let d=r.length+o.length+l.length>0;if(!n){for(let u of[...r,...o]){let g=await ge(t,u);await YP(tA(g),{recursive:!0}),await ge(t,u),await QP(g,a.files.get(u))}for(let u of l)await Dg(await ge(t,u));await Ng(t,pt(t,z))}let p={project:a.project.project.name,apps:a.project.apps.map(u=>u.slug),added:r,changed:o,removed:l,unchanged:a.files.size-r.length-o.length,check:n,differs:d};for(let u of a.notes)e.out.note(u);return e.out.result(p,()=>{let u=(g,y)=>y.forEach(w=>e.out.line(` ${g} ${w}`));if(!d){e.out.line(`${z}/ is what ${a.project.project.name} gives now (${a.files.size} files)`);return}e.out.line(n?`${z}/ differs from what ${a.project.project.name} gives now:`:`${z}/ written for ${a.project.apps.map(g=>g.slug).join(", ")}:`),u(n?"missing":"added",r),u(n?"differs":"changed",o),u(n?"not given":"removed",l),n&&e.out.note("palbase apps:sync brings it up to date")}),n&&d?1:void 0}async function ge(e,t){let n=pt(e,z),s=pt(e,...t.split("/")),a=ar(n,s);if(a===""||a.startsWith(`..${sr}`)||a===".."||a.split(sr).some(r=>r===".."||r===""))throw new f("outside_palbase",`${t} is not under ${z}/`);let i=e;for(let r of[z,...a.split(sr)]){i=pt(i,r);try{if((await HP(i)).isSymbolicLink())throw new f("linked_path",`${ar(e,i)} is a link: palbase writes only into ${z}/ itself`,{hint:"remove the link, and run it again"})}catch(o){if(o.code==="ENOENT")break;throw o}}return s}async function Ng(e,t){let n;try{n=await Sl(t,{withFileTypes:!0})}catch{return}for(let s of n)s.isDirectory()&&await Ng(e,pt(t,s.name));ar(pt(e,z),t)===""||ar(pt(e,z),t).startsWith(`..${sr}`)||(await Sl(t)).length===0&&await ZP(t)}async function kn(e){let t=await Yt(e);return{id:t[0].project_id,name:t[0].project_name,org:t[0].org_name}}async function et(e,t){return(await e.studio.get(`/projects/${t}/apps`)).apps}function mt(e,t){let n=e.find(s=>s.slug===t||s.id===t);if(!n)throw new f("no_such_app",`the project has no app ${t}`,{hint:`its apps: ${e.map(s=>s.slug).join(", ")||"none \u2014 palbase apps:create"}`});return n}function rr(e){let t=e.ios?[e.ios.bundle,e.ios.app_clip&&`App Clip ${e.ios.app_clip}`,e.ios.watch&&`watch ${e.ios.watch}`].filter(Boolean).join(", "):e.android?`${e.android.package} (${e.android.fingerprints.map(n=>n.label).join(", ")||"no certificate"})`:e.web?.origins.join(", ")??"";return e.suspended?`${t} \u2014 suspended`:t}var qg={name:"apps:list",summary:"the project's apps, and what each is in every environment it is set in",scope:"environment",async run(e){let t=await kn(e),n=await et(e,t.id);e.out.result({apps:n},()=>{if(n.length===0)return e.out.note(`${t.name} has no app yet: palbase apps:create ios|android|web <name>`);e.out.table(n,[{header:"slug",value:s=>s.slug},{header:"platform",value:s=>s.platform},{header:"name",value:s=>s.deleted_at?`${s.name} (deleted; restorable until ${s.purge_after?.slice(0,10)})`:s.name},{header:"environments",value:s=>s.environments.map(a=>`${a.slug}: ${rr(a)}`).join("; ")||"\u2014"}])})}},Kg={name:"apps:create",summary:"register an app of the project (an iOS app names its Apple team); then set it in each environment (apps:env:set)",usage:"ios|android|web <name> [--slug <slug>] [--team-id <id>] [--app-id-prefix <prefix>]",details:["An app is one product on one platform: its widgets, notification service and other extensions are not apps of their own \u2014 Apple gives them bundles under the app's, and they share its sign-in.","The slug is the app's file in a checkout: palbase/environments/<env>/<slug>.json."],args:{min:2,max:2},flags:{slug:{type:"string",value:"slug",description:"its name in a checkout (default: from the name)"},"team-id":{type:"string",value:"id",description:"an iOS app's Apple team: 10 characters, Apple Developer \u203A Membership"},"app-id-prefix":{type:"string",value:"prefix",description:"an iOS app's App ID prefix when it is not the team's (an app made before 2011, or moved from another team)"}},scope:"environment",async run(e){let[t,n]=e.args;if(t!=="ios"&&t!=="android"&&t!=="web")throw m("the platform is ios, android or web");let s=await kn(e),a=await e.studio.post(`/projects/${s.id}/apps`,{platform:t,name:n,...e.flags.slug?{slug:e.flags.slug}:{},...e.flags["team-id"]?{team_id:e.flags["team-id"]}:{},...e.flags["app-id-prefix"]?{app_id_prefix:e.flags["app-id-prefix"]}:{}});e.out.result(a,()=>{e.out.line(`${s.name} \u203A ${a.name} (${a.platform}, ${a.slug})`),e.out.note(`set it in each environment: palbase apps:env:set ${a.slug} -E <env> ${t==="ios"?"--bundle <bundle id>":t==="android"?"--package <application id> --sha256 <label>=<fingerprint>":"--origin <https://\u2026>"}`)})}},Gg={name:"apps:get",summary:"an app of the project, with what it is and its key in every environment it is set in",usage:"<app>",args:{min:1,max:1},scope:"environment",async run(e){let t=await kn(e),n=mt(await et(e,t.id),e.args[0]);e.out.result(n,()=>{if(e.out.line(`${n.name} \u2014 ${n.platform}, ${n.slug}${n.team_id?`, team ${n.team_id}${n.app_id_prefix?` (App ID prefix ${n.app_id_prefix})`:""}`:""}`),n.deleted_at&&e.out.note(`deleted; restorable until ${n.purge_after} (palbase apps:restore ${n.slug})`),n.environments.length===0)return e.out.note(`in no environment yet: palbase apps:env:set ${n.slug} -E <env> \u2026`);e.out.table(n.environments,[{header:"environment",value:s=>s.slug},{header:"is",value:s=>rr(s)},{header:"publishable key",value:s=>s.key?.key??"\u2014"}])})}},Ug={name:"apps:update",summary:"rename an app, or change an iOS app's Apple team: every environment it is in is told",usage:'<app> [--name <name>] [--team-id <id>] [--app-id-prefix <prefix>|""]',args:{min:1,max:1},flags:{name:{type:"string",value:"name",description:"what it is called"},"team-id":{type:"string",value:"id",description:"an iOS app's Apple team"},"app-id-prefix":{type:"string",value:"prefix",description:`its App ID prefix; "" for the team's`}},scope:"environment",async run(e){let t=await kn(e),n=mt(await et(e,t.id),e.args[0]),s={};if(e.flags.name!==void 0&&(s.name=e.flags.name),e.flags["team-id"]!==void 0&&(s.team_id=e.flags["team-id"]),e.flags["app-id-prefix"]!==void 0&&(s.app_id_prefix=e.flags["app-id-prefix"]===""?null:e.flags["app-id-prefix"]),Object.keys(s).length===0)throw m("nothing to change: --name, --team-id or --app-id-prefix");let a=await e.studio.request("PATCH",`/projects/${t.id}/apps/${n.id}`,s);e.out.result(a,()=>e.out.line(`${a.name} (${a.slug}) \u2014 told to ${a.environments.length} environment(s)`))}},Bg={name:"apps:delete",summary:"delete an app: suspended in every environment for 30 days \u2014 its builds stop reaching the project \u2014 then removed for good",usage:"<app>",args:{min:1,max:1},scope:"environment",async run(e){let t=await kn(e),n=mt(await et(e,t.id),e.args[0]);if(!e.global.yes){if(!e.interactive)throw new f("confirmation_needed",`deleting ${n.name} stops every build of it reaching the project`,{hint:"confirm with -y"});let a=(await e.io.prompt(`Every build of ${n.name} stops reaching ${t.name} at once (restorable for 30 days). Delete it? [y/N] `)).trim().toLowerCase();if(a!=="y"&&a!=="yes")throw new f("cancelled","nothing was changed")}let s=await e.studio.request("DELETE",`/projects/${t.id}/apps/${n.id}`);e.out.result(s,()=>e.out.line(`${s.name} is deleted; palbase apps:restore ${s.slug} brings it back as it was until ${s.purge_after}`))}},zg={name:"apps:restore",summary:"bring a deleted app back as it was, with its keys, in every environment",usage:"<app>",args:{min:1,max:1},scope:"environment",async run(e){let t=await kn(e),n=mt(await et(e,t.id),e.args[0]),s=await e.studio.post(`/projects/${t.id}/apps/${n.id}/restore`);e.out.result(s,()=>e.out.line(`${s.name} is back in ${s.environments.length} environment(s)`))}},hA=/^([a-z][a-z0-9_-]{0,31})=(.+)$/,Wg={name:"apps:env:set",summary:"what an app is in the environment: its bundle (iOS), package and signing certificates (Android) or origins (web)",usage:"<app> [--bundle <id> [--app-clip <id>] [--watch <id>]] [--package <id> --sha256 <label>=<fingerprint>\u2026] [--origin <url>\u2026 --redirect <url>\u2026]",details:["iOS: the app's bundle in this environment; its App Clip and watch app are the bundle followed by one more part. Its extensions are not set: they share the app's.","Android: its application ID and the SHA-256 of each certificate it is signed with \u2014 Play Console \u203A App signing (Google's app signing key, not the upload key), ./gradlew signingReport for a debug key. Label each: debug, play_signing, upload\u2026","Web: the origins its pages are served from (https; http only on this computer) and the addresses a sign-in may return to.","The platform publishes it to Apple and Google for the environment: a device sees a change in a day or so (Apple caches its file; Android 15 re-checks within a week)."],args:{min:1,max:1},flags:{bundle:{type:"string",value:"id",description:"an iOS app's bundle identifier here"},"app-clip":{type:"string",value:"id",description:"its App Clip's bundle (the bundle followed by one more part)"},watch:{type:"string",value:"id",description:"its watch app's bundle (the bundle followed by one more part)"},package:{type:"string",value:"id",description:"an Android app's application ID here"},sha256:{type:"string",multiple:!0,value:"label=fingerprint",description:"a signing certificate's SHA-256, labelled (play_signing=AB:CD:\u2026); every one the app is signed with"},origin:{type:"string",multiple:!0,value:"url",description:"a web app's origin"},redirect:{type:"string",multiple:!0,value:"url",description:"an address a sign-in may return to"}},scope:"environment",async run(e){let t=await b(e),n=mt(await et(e,t.project_id),e.args[0]),s=r=>(e.flags[r]??[]).flatMap(o=>o.split(",")).map(o=>o.trim()).filter(Boolean),a;if(n.platform==="ios"){if(!e.flags.bundle)throw m(`${n.name} is an iOS app: give its bundle here (--bundle)`);a={ios:{bundle:e.flags.bundle,...e.flags["app-clip"]?{app_clip:e.flags["app-clip"]}:{},...e.flags.watch?{watch:e.flags.watch}:{}}}}else if(n.platform==="android"){if(!e.flags.package)throw m(`${n.name} is an Android app: give its package here (--package)`);let r=(e.flags.sha256??[]).map(o=>{let l=hA.exec(o.trim());if(!l)throw m(`--sha256 ${JSON.stringify(o)}: label=fingerprint, like play_signing=AB:CD:\u2026`);return{label:l[1],sha256:l[2]}});a={android:{package:e.flags.package,fingerprints:r}}}else{let r=s("origin");if(r.length===0)throw m(`${n.name} is a web app: give its origins here (--origin)`);let o=s("redirect");a={web:{origins:r,...o.length?{redirects:o}:{}}}}await v(e,t,`set ${n.name} (${n.slug}) here: ${rr(a)}`);let i=await e.studio.request("PUT",`/environments/${t.env_ref}/apps/${n.id}`,a);for(let r of i.warnings)e.out.warn(r);e.out.result(i,()=>{e.out.line(`${n.name} in ${t.env_name}: ${rr(i)}`),i.key&&e.out.line(`its publishable key here: ${i.key.key}`),e.out.note("palbase apps:sync writes its settings into this checkout")})}},Fg={name:"apps:env:unset",summary:"take an app out of the environment: its key there revoked, Apple's and Google's files no longer naming it",usage:"<app>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=mt(await et(e,t.project_id),e.args[0]);await v(e,t,`take ${n.name} out of here: builds of it stop reaching ${t.env_name}`),await e.studio.request("DELETE",`/environments/${t.env_ref}/apps/${n.id}`),e.out.result({app:n.slug,environment:t.env_slug,removed:!0},()=>e.out.line(`${n.name} is out of ${t.env_name}`))}},Jg={name:"apps:sdkconfig",summary:"an app's settings in the environment, as palbase apps:sync writes them: its address, its publishable key, what its modules tell it",usage:"<app> [--format json|env]",details:["The publishable key is public: it ships in the app. A secret key never does."],args:{min:1,max:1},flags:{format:{type:"string",value:"format",description:"json (default) or env"}},scope:"environment",async run(e){let t=await b(e),n=mt(await et(e,t.project_id),e.args[0]),s=e.flags.format??"json";if(s!=="json"&&s!=="env")throw m("--format is json or env");let a=await e.studio.get(`/environments/${t.env_ref}/apps/${n.id}/config`);e.out.result(a,()=>{s==="env"?(e.out.line(`PALBASE_URL=${a.url}`),e.out.line(`PALBASE_PUBLISHABLE_KEY=${a.publishable_key}`)):e.out.line(JSON.stringify(a,null,2))})}},Vg={name:"apps:sync",summary:"write each environment's settings and backend clients (Palbe) of this checkout's apps under palbase/ \u2014 nothing else is touched",usage:"[<app>\u2026] [--check] [--types <env>] [--backend [<machine>=]<dir>] [--as <machine>=<name>]\u2026",args:{min:0,max:20},details:["The apps named join this checkout's (palbase/project.json); with none named, its apps are synced.","palbase/environments/<env>/: each app's settings (<app>.json), each backend's contract (contracts/<machine>.openapi.json) and Palbe client made from it \u2014 TypeScript for a web app, Swift for an iOS app (in palbase/<app>.palbase), Kotlin for an Android app. A web app imports pb from palbase/<app>.ts: one environment's for the editor (--types), the build's mode's for the build (palbase() in vite.config), which type-checks the app against that environment.","--check writes nothing: it exits 1 naming what differs from the project now \u2014 for CI.","--backend makes a backend's Palbe from its checkout on this computer (its palbase/backend app writes its contract and exits; nothing is connected to), to try an endpoint before any machine serves it.","A backend is pb.<name> in the apps \u2014 pb.shopApi.rooms.create() for the machine shop-api \u2014 unless --as names it (--as shop-api=shop): the name is the checkout's, the same in every environment, and none of the client's own (auth, flags, storage, \u2026). Machines of different environments may take one name \u2014 Production's backend and Development's backend-dev both pb.backend with --as backend-dev=backend \u2014 so the app's code builds against either; two machines of one environment may not."],flags:{check:{type:"boolean",description:"write nothing; exit 1 when the checkout is not what the project gives now"},types:{type:"string",value:"env",description:"the environment the editor's types are of (remembered in palbase/project.json)"},backend:{type:"string",value:"[machine=]dir",description:"a backend's checkout here: its Palbe made from the contract it writes, not from its machine's"},as:{type:"string",multiple:!0,value:"machine=name",description:"a backend's name in the apps (pb.<name>): its machine's camelCased unless named; the same in every environment, and another environment's machine may take it too (remembered in palbase/project.json)"}},scope:"environment",async run(e){return xg(e)}};function or(e){let t=new URLSearchParams;for(let[s,a]of Object.entries(e))a!==void 0&&t.set(s,String(a));let n=t.toString();return n===""?"":`?${n}`}function lr(e,t){let n=se(e.flags.limit,"limit");if(n!==void 0&&(n<1||n>t))throw m(`--limit is a whole number from 1 to ${t}`);return n}function dr(e,t){return{limit:{type:"string",value:"n",description:`at most this many (1\u2013${e}, default ${t})`},cursor:{type:"string",value:"cursor",description:"the next page, as the last one said it"}}}var Qt=e=>e?e.slice(0,19).replace("T"," "):"",Vn=(e,t)=>e||t;function pr(e,t,n){t&&e.out.line(`More: palbase ${n} --cursor ${t}`)}function Yg(e){e.out.note("This read is in the project's access log (palbase messaging:access-log).")}function Xg(e){return e.map(t=>`${t.name?A(t.name):"a file"} (${A(t.content_type)}, ${t.size} bytes)`).join(", ")}var Hg="A report is deleted, with what it carries, 190 days after it is resolved; one never resolved, 2 years after it was made.",mA={name:"messaging:reports:list",summary:"the reports people made, newest first: why, whom, which messages (what they carry: messaging:reports:get)",usage:"[--status open|resolved] [--limit <n>] [--cursor <cursor>]",flags:{status:{type:"string",value:"status",description:"only the open ones, or only the resolved ones"},...dr(100,30)},scope:"environment",async run(e){let t=e.flags.status;if(t!==void 0&&t!=="open"&&t!=="resolved")throw m("--status is open or resolved");let n=lr(e,100),s=await b(e),a=await h(e,s,"GET",`/messaging/admin/reports${or({status:t,limit:n,cursor:e.flags.cursor})}`);e.out.result(a,()=>{a.data.length===0&&e.out.line(t===void 0?"No report yet.":`No ${t} report.`),e.out.table(a.data,[{header:"report",value:i=>i.id},{header:"made",value:i=>Qt(i.created_at)},{header:"status",value:i=>i.status==="resolved"?`resolved: ${i.resolution??""}`:"open"},{header:"reason",value:i=>i.reason},{header:"reported",value:i=>Vn(i.reported_user_id,"")},{header:"by",value:i=>Vn(i.reporter_id,"(deleted)")},{header:"messages",value:i=>String(i.message_ids.length)}]),pr(e,a.next_cursor,`messaging:reports:list${t?` --status ${t}`:""}`)})}},gA={name:"messaging:reports:get",summary:"one report with what it carries: the reporter's note, what the messages it names said when reported and before they were edited",usage:"<report id>",details:["An owner's or an admin's (a member lists the reports, without what they carry); the read is in the project's access log. --json carries the messages' files with the keys that open them.","A report of a group a person deleted says who deleted it and when; naming no message, it carries the last 30 messages the reporter saw in it.",Hg],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",`/messaging/admin/reports/${x("the report's id",e.args[0])}`);Yg(e),e.out.note(Hg),e.out.result(n,()=>{e.out.line(`report ${n.id} (${n.status==="resolved"?`resolved ${Qt(n.resolved_at)}: ${A(n.resolution??"")}`:"open"})`),e.out.line(`made ${Qt(n.created_at)} by ${Vn(n.reporter_id,"a user since deleted")}`),e.out.line(`reported ${Vn(n.reported_user_id,"no one in particular")}`),e.out.line(`reason ${A(n.reason)}`),e.out.line(`conversation ${n.conversation_id}${n.conversation_deleted_at?` (group deleted by ${Vn(n.conversation_deleted_by,"a user since deleted")} at ${Qt(n.conversation_deleted_at)})`:""}`),n.note&&e.out.line(`note ${A(n.note)}`);let s=n.messages??[];if(s.length!==0){e.out.line(),e.out.line("What the messages said when reported:");for(let a of s){e.out.line(` #${a.seq} ${Qt(a.created_at)} ${Vn(a.sender_id,"the server")} ${a.kind==="text"||a.text?A(a.text??""):`(${a.kind})`}`),a.attachments.length>0&&e.out.line(` files: ${Xg(a.attachments)}`);for(let i of a.earlier_versions)e.out.line(` before it was edited: ${A(i.text)}, until ${Qt(i.replaced_at)}`)}}})}},fA={name:"messaging:reports:resolve",summary:"resolve a report, saying what came of it in the project's own words",usage:"<report id> --resolution <text>",args:{min:1,max:1},flags:{resolution:{type:"string",value:"text",description:"what came of it: 1 to 64 characters (warned, removed, nothing found\u2026)"}},scope:"environment",async run(e){let t=e.flags.resolution?.trim();if(!t||[...t].length>64)throw m("--resolution says what came of it: 1 to 64 characters");let n=await b(e),s=x("the report's id",e.args[0]);await v(e,n,`resolve the report ${e.args[0]}: ${t}`);let a=await h(e,n,"POST",`/messaging/admin/reports/${s}/resolve`,{resolution:t});e.out.result(a,()=>e.out.line(`Resolved the report ${a.id}: ${A(a.resolution??t)}.`))}},yA={name:"messaging:access-log",summary:"each time people's messages were read or removed \u2014 by the project's server, or an owner or admin from Studio or the CLI \u2014 newest first: what, which conversation, whose, by whom (kept 400 days)",usage:"[--limit <n>] [--cursor <cursor>]",flags:dr(200,50),scope:"environment",async run(e){let t=lr(e,200),n=await b(e),s=await h(e,n,"GET",`/messaging/admin/access-log${or({limit:t,cursor:e.flags.cursor})}`);e.out.result(s,()=>{s.data.length===0&&e.out.line("No read or removal of people's messages yet."),e.out.table(s.data,[{header:"when",value:a=>Qt(a.at)},{header:"what",value:a=>a.action},{header:"messages",value:a=>String(a.count)},{header:"conversation",value:a=>a.conversation_id??""},{header:"person",value:a=>a.user_id??""},{header:"by",value:a=>a.actor},{header:"request",value:a=>a.request_id??""}]),pr(e,s.next_cursor,"messaging:access-log")})}},bA={name:"messaging:conversations:list",summary:"the project's conversations, or a person's with --user, or a space's with --space, the latest first: whose, how many people, when it last moved",usage:"[--user <user id>] [--space <space>] [--limit <n>] [--cursor <cursor>]",flags:{user:{type:"string",value:"user id",description:"only this person's conversations"},space:{type:"string",value:"space",description:"only the conversations of this space (as org:<id>)"},...dr(100,30)},scope:"environment",async run(e){let t=e.flags.user;if(t!==void 0&&t.trim()==="")throw m("--user is a person's id");let n=e.flags.space;if(n!==void 0&&!/^[A-Za-z0-9:_./@-]{1,128}$/.test(n))throw m("--space is 1 to 128 letters, digits and : _ . / @ - (as org:<id>)");let s=lr(e,100),a=await b(e),i=await h(e,a,"GET",`/messaging/admin/conversations${or({user_id:t,space:n,limit:s,cursor:e.flags.cursor})}`);e.out.result(i,()=>{i.data.length===0&&e.out.line(t===void 0?"No conversation yet.":`${t} is in no conversation.`),e.out.table(i.data,[{header:"conversation",value:r=>r.id},{header:"kind",value:r=>r.kind==="group"&&r.visibility==="open"?"group (open)":r.kind},{header:"space",value:r=>r.space??""},{header:"title",value:r=>r.kind==="group"?r.title??"":(r.members??[]).map(o=>o.user_id).join(" \xB7 ")},{header:"people",value:r=>String(r.member_count)},{header:"messages",value:r=>String(r.last_seq)},{header:"last moved",value:r=>Qt(r.last_message_at??r.created_at)}]),pr(e,i.next_cursor,`messaging:conversations:list${t!==void 0?` --user ${t}`:""}${n!==void 0?` --space ${n}`:""}`)})}},wA={name:"messaging:messages:list",summary:"what a conversation said, newest first \u2014 each read in the project's access log",usage:"<conversation id> [--limit <n>] [--cursor <cursor>]",details:["An owner's or an admin's: a member sees the conversations and the reports, not what was said.","--json carries the messages whole, their files with the keys that open them."],args:{min:1,max:1},flags:dr(100,50),scope:"environment",async run(e){let t=lr(e,100),n=await b(e),s=x("the conversation's id",e.args[0]),a=await h(e,n,"GET",`/messaging/admin/conversations/${s}/messages${or({limit:t,cursor:e.flags.cursor})}`);Yg(e),e.out.result(a,()=>{a.data.length===0&&e.out.line("The conversation has said nothing yet.");for(let i of a.data){let r=i.deleted?`(removed${i.removed_reason?`: ${i.removed_reason}`:""})`:i.kind==="system"?`(${i.system?.type??"system"})`:i.text!==null?A(i.text):`(${i.kind})`;e.out.line(`#${i.seq} ${Qt(i.created_at)} ${Vn(i.sender_id,"the server")} ${i.id} ${r}`),!i.deleted&&i.attachments.length>0&&e.out.line(` files: ${Xg(i.attachments)}`)}pr(e,a.next_cursor,`messaging:messages:list ${e.args[0]}`)})}},vA={name:"messaging:messages:delete",summary:"remove a message for everyone in its conversation: what it said and its files go (in the access log)",usage:"<conversation id> <message id>",details:["It is not undone: asked before it is done, whatever the environment (-y confirms)."],args:{min:2,max:2},scope:"environment",async run(e){let[t,n]=e.args,s=x("the conversation's id",t),a=x("the message's id",n),i=await b(e);await v(e,i,`remove the message ${n} of the conversation ${t} for everyone`,"It removes what the message said for everyone in the conversation, and it is not undone"),await h(e,i,"DELETE",`/messaging/admin/conversations/${s}/messages/${a}`),e.out.result({removed:{conversation_id:t,message_id:n}},()=>e.out.line(`Removed the message ${n} for everyone in ${N(i)}; the removal is in the access log.`))}},Zg=[mA,gA,fA,yA,bA,wA,vA];function _A(e){let t=new URLSearchParams;for(let[s,a]of Object.entries(e))a!==void 0&&t.set(s,String(a));let n=t.toString();return n===""?"":`?${n}`}function kA(e,t){let n=se(e.flags.limit,"limit");if(n!==void 0&&(n<1||n>t))throw m(`--limit is a whole number from 1 to ${t}`);return n}function SA(e,t){return{limit:{type:"string",value:"n",description:`at most this many (1\u2013${e}, default ${t})`},cursor:{type:"string",value:"cursor",description:"the next page, as the last one said it"}}}var ur=e=>e?e.slice(0,19).replace("T"," "):"";function $A(e,t,n){t&&e.out.line(`More: palbase ${n} --cursor ${t}`)}function $l(e){return!e.answered_at||!e.ended_at?"":String(Math.max(0,Math.round((Date.parse(e.ended_at)-Date.parse(e.answered_at))/1e3)))}var Qg=e=>e.video?"video":"voice";function PA(e){if(e<1e3)return`${e} B`;let t=["kB","MB","GB","TB"],n=e/1e3,s=0;for(;n>=1e3&&s<t.length-1;)n/=1e3,s+=1;return`${n>=100?Math.round(n):Math.round(n*10)/10} ${t[s]}`}var AA=["ringing","active","ended"],RA={name:"calls:list",summary:"the project's calls, or a person's with --user, newest first: kind, voice or video, state, why it ended, who called, how many were in it, how long",usage:"[--user <user id> [--missed]] [--state ringing|active|ended] [--limit <n>] [--cursor <cursor>]",details:["A call's length is from its answer to its end, in seconds: a group call, which no one answers, has its people's seconds in calls:get."],flags:{user:{type:"string",value:"user id",description:"only this person's calls"},missed:{type:"boolean",description:"with --user: only the calls they missed (or were busy for)"},state:{type:"string",value:"state",description:"only the calls ringing, going on (active), or over (ended)"},...SA(100,20)},scope:"environment",async run(e){let t=e.flags.user;if(t!==void 0&&t.trim()==="")throw m("--user is a person's id");let n=e.flags.missed===!0;if(n&&t===void 0)throw m("--missed says whose: give --user with it");let s=e.flags.state;if(s!==void 0&&!AA.includes(s))throw m("--state is ringing, active or ended");let a=kA(e,100),i=await b(e),r=await h(e,i,"GET",`/calls/admin/calls${_A({user_id:t,missed:n?"true":void 0,state:s,limit:a,cursor:e.flags.cursor})}`);e.out.result(r,()=>{r.calls.length===0&&e.out.line(`No ${n?"missed ":""}${s?`${s} `:""}call${t!==void 0?` of ${t}`:n||s?"":" yet"}.`),e.out.table(r.calls,[{header:"call",value:l=>l.id},{header:"started",value:l=>ur(l.created_at)},{header:"kind",value:l=>l.kind},{header:"media",value:Qg},{header:"state",value:l=>l.state},{header:"end reason",value:l=>l.end_reason??""},{header:"caller",value:l=>l.caller_id},{header:"people",value:l=>String(l.participants.length)},{header:"seconds",value:$l}]);let o=[t!==void 0?` --user ${t}`:"",n?" --missed":"",s?` --state ${s}`:""].join("");$A(e,r.next_cursor,`calls:list${o}`)})}},TA={name:"calls:get",summary:"one call with its people and bots: how each was in it (rung, joined, left, declined, missed, busy), for how many seconds, and what the media server sent them",usage:"<call id>",details:["Every call's media goes through the platform's media server, and a call is billed by the data it sent the call's people: each one's, in bytes, is as its meter last told it (up to a minute behind).","--json carries the call whole: its people's names and pictures, the caller's app's words about it (metadata), each one's bytes."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",`/calls/admin/calls/${x("the call's id",e.args[0])}`);e.out.result(n,()=>{e.out.line(`call ${n.id}`),e.out.line(`kind ${n.kind}, ${Qg(n)}${n.ring?"":", rings no one"}`),e.out.line(`state ${n.state}${n.end_reason?`: ${n.end_reason}${n.ended_by?` by ${n.ended_by}`:""}`:""}`),e.out.line(`caller ${n.caller_id}`),e.out.line(`started ${ur(n.created_at)}`),n.answered_at&&e.out.line(`answered ${ur(n.answered_at)}`),n.ended_at&&e.out.line(`ended ${ur(n.ended_at)}${$l(n)?`, after ${$l(n)} s`:""}`),n.conversation_id&&e.out.line(`conversation ${n.conversation_id}`),e.out.line(`holds at most ${n.max_participants}`),e.out.line(),e.out.table(n.participants,[{header:"user",value:s=>s.user_id},{header:"kind",value:s=>s.kind},{header:"role",value:s=>s.role},{header:"state",value:s=>s.state},{header:"seconds",value:s=>String(s.seconds)},{header:"data",value:s=>PA(s.bytes)}])})}},EA={name:"calls:end",summary:"end a call for everyone in it (asked before it is done, whatever the environment)",usage:"<call id>",details:["It is not undone: asked before it is done, whatever the environment (-y confirms). A call already over is left as it is."],args:{min:1,max:1},scope:"environment",async run(e){let t=x("the call's id",e.args[0]),n=await b(e);await v(e,n,`end the call ${e.args[0]} for everyone in it`,"It ends the call for everyone in it, and it is not undone");let s=await h(e,n,"POST",`/calls/admin/calls/${t}/end`);e.out.result(s,()=>e.out.line(s.end_reason&&s.end_reason!=="ended"?`The call ${s.id} was already over: ${s.end_reason}.`:`Ended the call ${s.id} for everyone in it in ${N(n)}.`))}},ef=[RA,TA,EA];var CA=/^[A-Z][A-Z0-9_]{0,127}$/;function Sn(e,t){return`/environments/${x("the environment's ref",e.env_ref)}/webhooks${t!==void 0?`/${x("the webhook's id",t)}`:""}`}function tf(e){return oe(e.flags.events)}function cr(e){let t=e.machine?`, the machine ${A(e.machine)}'s \u2014 kept by the platform to what its app takes`:"",n=e.created_by?`, made by ${A(e.created_by.name)}${e.created_by.id.startsWith("tok_")?" (access token)":e.created_by.id.startsWith("etk_")?" (environment token)":""}`:"";return`${A(e.url)} \u2014 ${e.events.length===0?"every event":A(e.events.join(", "))} (${A(e.id)}${t}${n})`}function jA(e,t){let n=t.find(a=>a.id===e.endpoint_id)?.url??`${e.endpoint_id} (no longer an endpoint)`,s=e.redelivered_at?`; redelivered ${A(e.redelivered_at)}`:e.redeliver_asked_at?"; redelivery asked":e.redelivery_error?`; redelivery failed: ${A(e.redelivery_error)}`:"";return`${A(e.id)} ${A(e.event_type)} ${A(e.event_id)} \u2192 ${A(n)} \u2014 ${A(e.last_error)} (${A(String(e.attempts))} tries, given up ${A(e.failed_at)})${s}`}var OA={name:"webhooks:list",summary:"the environment's webhook endpoints: where its events go, which (never their secrets)",scope:"environment",async run(e){let t=await b(e),{endpoints:n}=await e.studio.get(Sn(t));e.out.result({endpoints:n},()=>{n.length===0&&e.out.line("No webhook endpoint yet: palbase webhooks:create <url> makes one.");for(let s of n)e.out.line(cr(s))})}},MA={name:"webhooks:create",summary:"add a webhook endpoint; its signing secret is printed this once, or kept in a secret with --secret-to",usage:"<url> [--events <a,b>] [--secret-to <NAME> [--dev]]",details:["A machine is given its own endpoint and its secret (PALBASE_WEBHOOK_SECRET) by the platform, for the events its app takes: this is for another receiver. --secret-to keeps the secret in the environment's secrets (production; --dev: development) and prints it nowhere."],args:{min:1,max:1},flags:{events:{type:"string",value:"list",description:"the events it is sent, comma-separated (user.deleted, \u2026); none: every event"},"secret-to":{type:"string",value:"NAME",description:"keep its signing secret in the environment's secret NAME instead of printing it"},dev:{type:"boolean",description:"with --secret-to: the development secrets, not production"}},scope:"environment",async run(e){let t=await b(e),n=e.flags["secret-to"];if(n!==void 0&&!CA.test(n))throw m(`--secret-to ${JSON.stringify(n)} is not a secret's name: capital letters, digits and _, a letter first`);if(e.flags.dev===!0&&n===void 0)throw m("--dev goes with --secret-to <NAME>");let s=e.flags.dev===!0?"development":"production";await v(e,t,`add the webhook endpoint ${e.args[0]}${n?`, its secret kept in ${n} (${s})`:""}`);let a=await e.studio.post(Sn(t),{url:e.args[0],events:tf(e)??[]}),{secret:i,...r}=a;if(n!==void 0){let o=await h(e,t,"PUT",`/secrets/${s}/${n}`,{value:i});e.out.result({endpoint:r,secret_to:{set:s,name:n,version:o.version}},()=>e.out.line(`Added ${cr(r)}; its secret is ${n} (${s}, v${o.version}) in ${N(t)}.`));return}e.out.result(a,()=>{e.out.line(`Added ${cr(r)}.`),e.out.line(`signing secret (shown this once): ${i}`)})}},IA={name:"webhooks:update",summary:"change a webhook endpoint's address or events (its secret stays)",usage:'<id> [--url <url>] [--events <a,b>|""]',args:{min:1,max:1},flags:{url:{type:"string",value:"url",description:"where it is delivered now"},events:{type:"string",value:"list",description:'the events it is sent now, comma-separated; "" for every event'}},scope:"environment",async run(e){let t=await b(e);if(e.flags.url===void 0&&e.flags.events===void 0)throw m("nothing to change: --url or --events");let{endpoints:n}=await e.studio.get(Sn(t)),s=n.find(i=>i.id===e.args[0]);if(!s)throw m(`the environment has no webhook endpoint ${JSON.stringify(e.args[0])}`,"palbase webhooks:list shows them");await v(e,t,`change the webhook endpoint ${s.url}`);let a=await e.studio.request("PUT",Sn(t,s.id),{url:e.flags.url??s.url,events:tf(e)??s.events});e.out.result(a,()=>e.out.line(`Changed: ${cr(a)}.`))}},LA={name:"webhooks:delete",summary:"remove a webhook endpoint: its events are no longer delivered there",usage:"<id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e);await v(e,t,`remove the webhook endpoint ${e.args[0]}`),await e.studio.request("DELETE",Sn(t,e.args[0])),e.out.result({deleted:e.args[0]},()=>e.out.line(`Removed the webhook endpoint ${e.args[0]}.`))}},DA={name:"webhooks:deliveries:list",summary:"the deliveries the platform gave up on after its tries, still owed (--failed), or every one kept 30 days (--all)",usage:"[--failed] [--all]",flags:{failed:{type:"boolean",description:"those it gave up on and still owes (the default)"},all:{type:"boolean",description:"every one kept, those delivered again among them"}},scope:"environment",async run(e){let t=await b(e),[{deliveries:n},{endpoints:s}]=await Promise.all([e.studio.get(`${Sn(t)}/deliveries${e.flags.all===!0?"?all=true":"?failed=true"}`),e.studio.get(Sn(t))]);e.out.result({deliveries:n},()=>{n.length===0&&e.out.line("No failed delivery: every event reached its endpoints.");for(let a of n)e.out.line(jA(a,s))})}},xA={name:"webhooks:deliveries:redeliver",summary:"send a failed delivery again: the same event, its id and body, to the endpoint it failed at, within seconds",usage:"<id>",details:["As Stripe's Resend: the receiver takes an event more than once by its Palbase-Event-Id. An admin's; it is written to the organization's audit log."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e);await v(e,t,`send the failed delivery ${e.args[0]} again`);let n=await e.studio.post(`${Sn(t)}/deliveries/${x("the delivery's id",e.args[0])}/redeliver`,{});e.out.result(n,()=>e.out.line(`Asked: ${A(n.event_type)} ${A(n.event_id)} goes to its endpoint again within seconds (palbase webhooks:deliveries:list --all shows when it went).`))}},nf=[OA,MA,IA,LA,DA,xA];import{constants as hr,createReadStream as NA}from"node:fs";import{mkdir as qA,open as KA,readdir as GA,realpath as sf,stat as lf}from"node:fs/promises";import{dirname as af,extname as UA,join as df,relative as BA,resolve as rf,sep as mr}from"node:path";import{Readable as pf}from"node:stream";import{pipeline as zA}from"node:stream/promises";var uf=600;function Oa(e){let t=/^([a-z0-9][a-z0-9_-]{0,62}):(.*)$/.exec(e);return!t||e.startsWith("/")||e.startsWith(".")?null:{bucket:t[1],path:t[2].replace(/^\/+/,"")}}function gr(e){if(e.split("/").some(n=>n===""||n==="."||n===".."))throw new f("unsafe_path",`the object ${JSON.stringify(e)} has a name no request can carry`);return encodeURIComponent(e)}async function Pl(e,t,n,s){let a=[],i;do{let r=new URLSearchParams({limit:"1000",...s?{prefix:s}:{},...i?{cursor:i}:{}}),o=await h(e,t,"GET",`/storage/buckets/${x("the bucket",n)}/objects?${r}`);a.push(...o.objects),i=o.next_cursor}while(i);return a}async function cf(e,t,n,s){let a;try{a=await e.io.fetch(t,{...n,redirect:"manual"})}catch(i){throw new f("network_error",`${s}: ${i instanceof Error?i.message:String(i)}`)}if(!a.ok){let i=await a.json().catch(()=>({}));throw new f(i.error??`http_${a.status}`,`${s}: ${i.error_description??i.error??`answered ${a.status}`}`)}return a}var WA={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif",".avif":"image/avif",".svg":"image/svg+xml",".ico":"image/x-icon",".pdf":"application/pdf",".json":"application/json",".txt":"text/plain",".csv":"text/csv",".html":"text/html",".css":"text/css",".js":"text/javascript",".xml":"application/xml",".zip":"application/zip",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".m4a":"audio/mp4"};function of(e){return WA[UA(e).toLowerCase()]}async function Al(e,t,n,s,a,i){let r=(await lf(n)).size,o=await h(e,t,"POST",`/storage/buckets/${x("the bucket",s)}/upload-urls`,{path:a,expires_in:uf,...i?{owner_id:i}:{}});return await cf(e,o.url,{method:"PUT",body:pf.toWeb(NA(n)),headers:{"content-length":String(r),...of(n)?{"content-type":of(n)}:{}},duplex:"half"},`${n} \u2192 ${s}:${a}`),r}function FA(e,t){let n=t.split("/");if(t===""||n.some(a=>a===""||a==="."||a===".."||a.includes("\\")||a.includes("\0")))throw new f("unsafe_path",`the object ${JSON.stringify(t)} has a name no file here can take`);let s=df(e,...n);if(!s.startsWith(e+mr))throw new f("unsafe_path",`${t} would land outside ${e}`);return s}async function JA(e,t,n,s,a,i){let r=await h(e,t,"POST",`/storage/buckets/${x("the bucket",n)}/signed-urls`,{path:s,expires_in:uf}),o=await cf(e,r.url,{method:"GET"},`${n}:${s} \u2192 ${a}`);if(await qA(af(a),{recursive:!0}),i!==void 0){let[g,y]=await Promise.all([sf(i),sf(af(a))]);if(y!==g&&!y.startsWith(g+mr))throw new f("unsafe_path",`${s} would land outside ${i} (through a link)`)}let d=(await KA(a,hr.O_WRONLY|hr.O_CREAT|hr.O_TRUNC|hr.O_NOFOLLOW)).createWriteStream();if(!o.body)return await new Promise((g,y)=>d.on("error",y).end(g)),0;let p=0,u=pf.fromWeb(o.body).on("data",g=>{p+=g.length});return await zA(u,d),p}async function hf(e){let t=[];for(let n of await GA(e,{withFileTypes:!0})){let s=df(e,n.name);n.isDirectory()?t.push(...await hf(s)):n.isFile()&&t.push(s)}return t}var VA={name:"storage:ls",summary:"a bucket's objects, or those under a prefix: path, size, type",usage:"<bucket>[:prefix]",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=Oa(e.args[0].includes(":")?e.args[0]:`${e.args[0]}:`);if(!n)throw m(`${e.args[0]} is not a bucket (bucket or bucket:prefix)`);let s=await Pl(e,t,n.bucket,n.path);e.out.result({bucket:n.bucket,objects:s},()=>{s.length===0&&e.out.line(`Nothing in ${n.bucket}:${n.path}`);for(let a of s)e.out.line(`${a.path} ${a.size} ${a.content_type??""}`)})}},HA={name:"storage:cp",summary:"copy files between this computer and a bucket: a file, or a folder whole with -r",usage:"<from> <to> [-r] [--owner <user id>]",details:["bucket:path names an object of the environment; anything else is a path on this computer.","Up: a file to bucket:path (a path ending in / keeps the file name); with -r, a folder to bucket:prefix, its paths kept.","Down: bucket:path to a file; with -r, every object under bucket:prefix into a folder."],args:{min:2,max:2},flags:{recursive:{type:"boolean",short:"r",description:"a folder (up) or a prefix (down), whole"},owner:{type:"string",value:"user id",description:"the user uploaded objects belong to (deleted with them)"}},scope:"environment",async run(e){let t=await b(e),[n,s]=e.args,a=Oa(n),i=Oa(s),r=e.flags.recursive===!0,o=e.flags.owner;if(a&&i)throw m("one side is a bucket and the other this computer (bucket-to-bucket: the storage API copies within a bucket)");if(!a&&!i)throw m("one side is bucket:path");let l=0,d=0;if(i){let p=rf(e.io.cwd,n),u=r?await hf(p):[p];if(!r&&(await lf(p)).isDirectory())throw m(`${n} is a folder: copy it with -r`);await v(e,t,`upload ${u.length} file${u.length===1?"":"s"} to ${i.bucket}:${i.path} in ${N(t)}`);for(let g of u){let y=r?BA(p,g).split(mr).join("/"):g.split(mr).pop(),w=r||i.path===""||i.path.endsWith("/")?`${i.path.replace(/\/?$/,i.path?"/":"")}${y}`:i.path;d+=await Al(e,t,g,i.bucket,w,o),l++,u.length>1&&e.out.note(`${l}/${u.length} ${w}`)}}else if(a){let p=rf(e.io.cwd,s),u=r?await Pl(e,t,a.bucket,a.path):[{path:a.path,size:0}];for(let g of u){let y=r?g.path.slice(a.path.length).replace(/^\/+/,""):"",w=r?FA(p,y):p;d+=await JA(e,t,a.bucket,g.path,w,r?p:void 0),l++,u.length>1&&e.out.note(`${l}/${u.length} ${g.path}`)}}e.out.result({copied:l,bytes:d},()=>e.out.line(`Copied ${l} file${l===1?"":"s"} (${d} bytes).`))}},YA={name:"storage:rm",summary:"delete an object, or every object under a prefix with -r",usage:"<bucket:path> [-r]",args:{min:1,max:1},flags:{recursive:{type:"boolean",short:"r",description:"every object under the prefix"}},scope:"environment",async run(e){let t=await b(e),n=Oa(e.args[0]);if(!n||!n.path&&e.flags.recursive!==!0)throw m(`${e.args[0]} is not bucket:path`);let s=e.flags.recursive===!0?(await Pl(e,t,n.bucket,n.path)).map(a=>a.path):[n.path];await v(e,t,`delete ${s.length} object${s.length===1?"":"s"} from ${n.bucket} in ${N(t)}`);for(let a of s)await h(e,t,"DELETE",`/storage/buckets/${x("the bucket",n.bucket)}/objects/${gr(a)}`);e.out.result({deleted:s.length},()=>e.out.line(`Deleted ${s.length} object${s.length===1?"":"s"}.`))}},XA={name:"storage:url",summary:"a signed download URL for one object",usage:"<bucket:path> [--expires <seconds>]",args:{min:1,max:1},flags:{expires:{type:"string",value:"seconds",description:"how long it works (default 3600, at most 604800)"}},scope:"environment",async run(e){let t=await b(e),n=Oa(e.args[0]);if(!n||!n.path)throw m(`${e.args[0]} is not bucket:path`);let s=e.flags.expires===void 0?3600:Number(e.flags.expires);if(!Number.isInteger(s)||s<1||s>604800)throw m("--expires is 1 to 604800 seconds");let a=await h(e,t,"POST",`/storage/buckets/${x("the bucket",n.bucket)}/signed-urls`,{path:n.path,expires_in:s});e.out.result(a,()=>e.out.line(a.url))}},mf=[VA,HA,YA,XA];import{openAsBlob as ZA}from"node:fs";import{readFile as QA,stat as eR}from"node:fs/promises";import{resolve as vf}from"node:path";var wr=/^[a-z][a-z0-9_-]{0,63}$/,gf=["backend","client","https","mcp","platform"];function en(e,t,n=0){let s=e.args[n];if(!wr.test(s))throw m(`${JSON.stringify(s)} is not ${t}'s name: lowercase letters, digits, _ and -, a letter first, at most 64`);return s}function Rt(e,t){let n=se(e,t);if(n===0)throw m(`--${t} is a whole number from 1`);return n}function qt(e){let t=new URLSearchParams;for(let[s,a]of Object.entries(e))a!==void 0&&t.set(s,String(a));let n=t.toString();return n===""?"":`?${n}`}async function ff(e,t,n){let s;try{s=await QA(vf(e.io.cwd,t),"utf8")}catch(a){throw new f("unreadable_file",`${t} could not be read: ${a instanceof Error?a.message:String(a)}`)}return me(s,n)}var fr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yr=e=>`$${e<.01&&e>0?e.toPrecision(2):e.toFixed(e<1?4:2)}`,br=e=>`$${e.toFixed(2)}`,_f="or connect the environment's own key for the model's provider, which its provider bills: palbase ai:providers:set <provider>",Rl=`raise the budget in Studio \u203A AI \u203A Settings or with palbase ai:settings:set --monthly-budget <usd>; ${_f}`,Tl=`move its project to Pay as you go in Studio \u203A Billing or with palbase billing:project --plan pay_as_you_go (its organization paid for by a payment account with a card, not held); ${_f}`;function kf(e){if(!(e instanceof E))return e;switch(e.code){case"ai_budget_reached":return new f(e.code,"the environment's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or the budget is raised",{hint:Rl});case"ai_payment_required":return new f(e.code,"the month's free AI dollar is spent and the environment has nothing to pay for Palbase's models with: it is on Free, or its payment account is held",{hint:Tl});case"provider_key_required":return new f(e.code,"Palbase's models do not serve the environment, and it has no key of its own for the model's provider",{hint:"connect one: palbase ai:providers:set <provider> (palbase ai:spend says why)"});case"billing_unavailable":return new f(e.code,`Palbase's billing did not say whether its models serve the environment${e.retryAfter!==void 0?`: try again in ${e.retryAfter} s`:"; try again shortly"}`);default:return e}}function tR(e){if(e===void 0)return;let t={};for(let n of Array.isArray(e)?e:[e]){let s=String(n),a=s.indexOf("=");if(a<=0)throw m(`--metadata is key=value, not ${JSON.stringify(s)}`);Object.defineProperty(t,s.slice(0,a),{value:s.slice(a+1),enumerable:!0,writable:!0,configurable:!0})}return t}var nR={name:"ai:usage",summary:"the environment's uses of models, newest first: what each was, what it cost, and whose key it went out with",usage:"[--kind text|embedding|image] [--metadata key=value]\u2026 [--limit <n>] [--cursor <cursor>]",flags:{kind:{type:"string",value:"kind",description:"only uses of this kind: text, embedding or image"},metadata:{type:"string",multiple:!0,value:"key=value",description:"only uses carrying this label (repeat for several): a product's spend, a task's"},limit:{type:"string",value:"n",description:"at most this many (1\u2013500, default 50)"},cursor:{type:"string",value:"cursor",description:"the next page, as the last one said it"}},scope:"environment",async run(e){let t=e.flags.kind;if(t!==void 0&&!["text","embedding","image"].includes(t))throw m("--kind is text, embedding or image");let n=tR(e.flags.metadata),s=Rt(e.flags.limit,"limit"),a=await b(e),i=await h(e,a,"GET",`/ai/usage${qt({kind:t,limit:s,cursor:e.flags.cursor,metadata:n&&JSON.stringify(n)})}`);e.out.result(i,()=>{i.usage.length===0&&e.out.line("No use of a model yet."),e.out.table(i.usage,[{header:"when",value:r=>r.created_at},{header:"kind",value:r=>r.kind},{header:"model",value:r=>r.model},{header:"tokens",value:r=>`${r.kind==="image"?`${r.items} picture(s)`:`${r.input_tokens} in / ${r.output_tokens} out`}${r.estimated?" (estimate)":""}`},{header:"cost",value:r=>yr(r.cost_nano_usd/1e9)},{header:"key",value:r=>r.connection_owner==="project"?"project's":"platform's"},{header:"labels",value:r=>Object.entries(r.metadata??{}).map(([o,l])=>`${o}=${l}`).join(" ")}]),i.usage.some(r=>r.estimated)&&e.out.line("(estimate): a reasoning call cut before its answer \u2014 its provider never said what its hidden thinking came to, so it is billed as the time the model thought at its measured speed, rounded down."),i.next_cursor&&e.out.line(`More: palbase ai:usage --cursor ${i.next_cursor}`)})}},sR={name:"ai:models",summary:"the models the environment may name \u2014 every text model with its rungs, window and price, and the embedding and picture models",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/ai/models");e.out.result(n,()=>{e.out.line("Text models (an agent's or an answer's model by its name; none named is the default):"),n.chat.length===0?e.out.line("None listed for the environment just now: name none for the default, or connect a provider's key (ai:providers:set) to list its models."):e.out.table(n.chat,[{header:"name",value:s=>`${s.name}${s.default?" (default)":""}`},{header:"model",value:s=>s.display_name},{header:"deprecated",value:s=>s.deprecated?`since ${s.deprecated.since}: use ${s.deprecated.use_instead}`:"-"},{header:"efforts",value:s=>s.efforts.join(",")||"-"},{header:"window",value:s=>String(s.context_window)},{header:"$/M in",value:s=>String(s.price.input_usd_per_mtok)},{header:"$/M out",value:s=>String(s.price.output_usd_per_mtok)}]),e.out.line(),e.out.line("Embedding models:"),e.out.table(n.embeddings,[{header:"name",value:s=>`${s.name}${s.default?" (default)":""}`},{header:"dimensions",value:s=>String(s.dimensions)},{header:"$/M in",value:s=>String(s.input_usd_per_mtok)}]),e.out.line(),e.out.line("Picture models:"),e.out.table(n.images,[{header:"name",value:s=>`${s.name}${s.default?" (default)":""}`},{header:"$/M picture out",value:s=>String(s.image_output_usd_per_mtok)}]),n.unavailable.length>0&&e.out.line(`Not listed just now (their models are missing until they answer): ${n.unavailable.join(", ")}`)})}},aR={free:"Free \u2014 its project's free dollar a month, then its own provider keys",pay_as_you_go:"Pay as you go \u2014 past the project's free dollar, its payment account pays: the provider's price and 10%",exempt:"exempt \u2014 measured, not charged"},iR={name:"ai:spend",summary:"what Palbase's models cost the environment this month: its project's free dollar and what is left of it to it, the monthly budget, and whether they serve it now \u2014 and if not, why",details:["Palbase's models are the platform's provider keys. A month brings a project a dollar of them free, its environments together: what is left of it to this one is what its other environments have not spent. Past it a Free project's environments use their own provider keys (ai:providers:set); a Pay as you go project's payment account pays, at the provider's price and 10%.","Its own provider keys always serve it, and are not counted here: their provider bills them."],scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/ai/spend");e.out.result(n,()=>{if(e.out.line(`month ${n.month} (UTC; starts again ${n.resets_on})`),e.out.line(`plan ${aR[n.plan]??n.plan}`),e.out.line(`spent ${yr(n.spent_usd)} on Palbase's models, at what it is billed, before the free dollar`),e.out.line(`free ${br(n.free_usd)} this month: what its project's other environments left of its free dollar${n.free_left_usd===null?"":` \u2014 ${yr(n.free_left_usd)} left`}`),e.out.line(`monthly budget ${n.monthly_budget_usd===null?"none":br(n.monthly_budget_usd)}`),n.platform_keys){e.out.line("Palbase's models serve the environment now");return}n.reason==="budget"?(e.out.line(`Palbase's models do not serve the environment: its monthly budget is spent \u2014 until ${n.resets_on}, or until it is raised`),e.out.line(` ${Rl[0].toUpperCase()}${Rl.slice(1)}.`)):n.reason==="payment"?(e.out.line("Palbase's models do not serve the environment: its project's free dollar is spent and it has no paid rights now (it is on Free, at its month's limit, or its payment account has an unpaid charge)"),e.out.line(` ${Tl[0].toUpperCase()}${Tl.slice(1)}.`)):(e.out.line("Palbase's models do not serve the environment"),e.out.line(" Connect the environment's own key for a provider: palbase ai:providers:set <provider>."))})}},rR={name:"ai:providers:list",summary:"the providers the environment calls with its own key (never the keys): its calls go out with them instead of the platform's",scope:"environment",async run(e){let t=await b(e),{providers:n}=await h(e,t,"GET","/ai/providers");e.out.result({providers:n},()=>{n.length===0&&e.out.line("No key of the environment's own: its calls go out with the platform's."),e.out.table(n,[{header:"provider",value:s=>s.name},{header:"verified",value:s=>s.verified?"yes":"no"},{header:"key",value:()=>"set"}])})}},oR={name:"ai:providers:set",summary:"call a provider with the environment's own key: the key is piped in or typed unseen, never shown or put on the command line",usage:"<provider> [--key-stdin] < key.txt",details:["Without --key-stdin the key is asked for at the terminal, and not echoed as it is typed or pasted."],args:{min:1,max:1},flags:{"key-stdin":{type:"boolean",description:"read the key from stdin (a pipe, a file)"}},scope:"environment",async run(e){let t=e.args[0];if(!/^[a-z][a-z0-9-]{0,31}$/.test(t))throw m(`${JSON.stringify(t)} is not a provider's name (openai, anthropic, google\u2026)`);if(e.flags["key-stdin"]!==!0&&!e.interactive)throw m(`${t}'s key is read from stdin`,`pipe it in: palbase ai:providers:set ${t} --key-stdin < key.txt`);let n=await b(e),s=await Me(e,`${t}'s key`);await v(e,n,`call ${t} with the environment's own key`);let a=await h(e,n,"PUT",`/ai/providers/${k(t)}`,{key:s});e.out.result(a,()=>e.out.line(`${a.name}'s calls go out with the environment's own key from now on${a.verified?"":" (the provider did not confirm it: check the key)"}; it is kept sealed.`))}},lR={name:"ai:providers:remove",summary:"forget the environment's own key for a provider: its calls go out with the platform's again",usage:"<provider>",args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0],n=await b(e);await v(e,n,`forget the environment's own ${t} key`),await h(e,n,"DELETE",`/ai/providers/${k(t)}`),e.out.result({removed:t},()=>e.out.line(`${t}'s calls go out with the platform's key again.`))}};function Sf(e,t){e.out.line(`clients ${t.clients?"on: the app's users talk to the agents with their own session":"off: the server starts and writes every chat"}`),e.out.line(`messages per minute ${t.user_messages_per_minute} a user`),e.out.line(`history kept ${t.history_bytes} bytes of ${t.history_limit_bytes===null?"no fixed limit":`${t.history_limit_bytes} at most`}`);let n=t.monthly_budget_usd??null;e.out.line(`monthly budget ${n===null?"none: Palbase's models are not capped":`${br(n)} a month on Palbase's models`}`)}function dR(e){if(e===void 0)return;let t=String(e);if(t==="none")return null;let n=/^\d{1,7}(\.\d{1,2})?$/.test(t)?Number(t):NaN;if(!(n>=.01&&n<=1e6))throw m(`--monthly-budget is US dollars from 0.01 to 1000000, cents at most, or none \u2014 not ${JSON.stringify(t)}`,"palbase ai:settings:set --monthly-budget 25");return n}var pR={name:"ai:settings:get",summary:"what the environment allows its chats \u2014 whether the app's users talk to the agents, how often, how much history is kept \u2014 and its monthly AI budget",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/ai/settings");e.out.result(n,()=>Sf(e,n))}},uR={name:"ai:settings:set",summary:"change what the environment allows its chats, and its monthly AI budget: a setting left out is left as it is",usage:"[--clients on|off] [--messages-per-minute <n>] [--history-limit <bytes>|none] [--monthly-budget <usd>|none]",details:["--monthly-budget is the most the environment spends a month on Palbase's models (the platform's provider keys), at what it is billed: past it a call they would serve is refused (ai_budget_reached) until the month turns (UTC) or the budget is raised, and the organization's owners are emailed once. Its own provider keys are not counted: their provider bills them. palbase ai:spend says what is spent.","Only an owner or an admin of the organization sets it, as themselves: a member's change of it is refused, and so is a key's or a token's \u2014 what spends the money does not raise its own limit."],flags:{clients:{type:"string",value:"on|off",description:"the app's users talk to the agents of their chats with their own session"},"messages-per-minute":{type:"string",value:"n",description:"how many messages one user sends a minute (1\u2013600)"},"history-limit":{type:"string",value:"bytes|none",description:"the chat history kept at most, in bytes; none: the plan's"},"monthly-budget":{type:"string",value:"usd|none",description:"the most spent a month on Palbase's models, in US dollars (0.01\u20131000000, cents at most); none: no budget"}},scope:"environment",async run(e){let t={},n=e.flags.clients;if(n!==void 0){if(!["on","off"].includes(n))throw m("--clients is on or off");t.clients=n==="on"}let s=Rt(e.flags["messages-per-minute"],"messages-per-minute");s!==void 0&&(t.user_messages_per_minute=s);let a=e.flags["history-limit"];a!==void 0&&(a==="none"?t.history_limit_bytes=null:t.history_limit_bytes=Rt(a,"history-limit"));let i=dR(e.flags["monthly-budget"]);if(i!==void 0&&(t.monthly_budget_usd=i),Object.keys(t).length===0)throw m("nothing to change","pass --clients, --messages-per-minute, --history-limit or --monthly-budget");let r=await b(e),o=Object.keys(t).filter(p=>p!=="monthly_budget_usd"),l=[...o.length>0?[`change what the chats are allowed: ${o.join(", ")}`]:[],...i===void 0?[]:[i===null?"take away the monthly AI budget":`set the monthly AI budget to ${br(i)}`]];await v(e,r,l.join("; "));let d;try{d=await h(e,r,"PUT","/ai/settings",t)}catch(p){throw i===void 0?p:cR(p)}e.out.result(d,()=>Sf(e,d))}};function cR(e){return e instanceof E?e.status===403?new f(e.code,"only an owner or an admin of the organization sets the environment's monthly AI budget, as themselves: a member's change of it is refused, and so is a key's or a token's",{hint:"ask an owner or an admin to set it \u2014 in Studio \u203A AI \u203A Settings, or with palbase ai:settings:set --monthly-budget signed in as themselves (palbase login)"}):e.code==="no_billing"?new f(e.code,"this stack bills no AI, so it keeps no monthly AI budget: nothing was changed"):e.code==="registry_unavailable"?new f(e.code,"Palbase's billing did not answer: nothing was changed",{hint:"run the command again shortly"}):e:e}function El(e){return e.source==="code"?`the backend's code (machine ${e.machine??"backend"})`:e.published_version===null||e.published_version===void 0?`a draft (revision ${e.revision??"?"}), not published`:`version ${e.published_version} published${e.unpublished_changes?`, the draft (revision ${e.revision}) changed since`:""}`}var hR={name:"ai:agents:list",summary:"the environment's agents: its backend's (its build's contract names them) and those it keeps, a draft and published versions",scope:"environment",async run(e){let t=await b(e),{agents:n}=await h(e,t,"GET","/ai/agents");e.out.result({agents:n},()=>{n.length===0&&e.out.line("No agent yet: an ai.agent of the backend, or ai:agents:create <name>."),e.out.table(n,[{header:"name",value:s=>s.name},{header:"source",value:s=>s.source},{header:"published",value:s=>s.source==="code"?"-":s.published_version?`v${s.published_version}`:"no"},{header:"draft",value:s=>s.source==="code"?"-":s.unpublished_changes?`changed (r${s.revision})`:`r${s.revision}`},{header:"machine",value:s=>s.machine??"-"},{header:"description",value:s=>s.description??""}])})}};async function mR(e,t,n,s){let a;for(let i=0;i<100;i++){let r=await h(e,t,"GET",`/ai/agents/${k(n)}/versions${qt({limit:100,cursor:a})}`),o=r.versions.find(l=>l.version===s);if(o)return o;if(!r.next_cursor||r.versions.every(l=>l.version<s))break;a=r.next_cursor}throw new f("not_found",`${n} has no version ${s}`,{hint:`palbase ai:agents:versions ${n}`})}function Ds(e,t,n){if(e.out.line(t),n===void 0)e.out.line(" (none yet)");else for(let s of JSON.stringify(n,null,2).split(`
|
|
647
|
-
`))e.out.line(` ${s}`)}var gR={name:"ai:agents:show",summary:"one agent: where it stands and what it is \u2014 a kept one's published version (or its draft, or a version), a backend's last turn",usage:"<name> [--draft | --version <n>]",args:{min:1,max:1},flags:{draft:{type:"boolean",description:"the draft, as the next publish makes a version of it"},version:{type:"string",value:"n",description:"that version, as it was published"}},scope:"environment",async run(e){let t=en(e,"an agent"),n=Rt(e.flags.version,"version");if(n!==void 0&&e.flags.draft===!0)throw m("--draft or --version, not both");let s=await b(e);if(n!==void 0){let i=await mR(e,s,t,n);e.out.result(i,()=>Ds(e,`${t} version ${i.version}, published ${i.published_at} by ${i.published_by}:`,i.definition));return}let a=await h(e,s,"GET",`/ai/agents/${k(t)}`);if(e.flags.draft===!0&&a.source==="code")throw new f("agent_defined_in_code",`${t} is the backend's code's: it has no draft \u2014 it changes with the code`);e.out.result(a,()=>{e.out.line(`${a.name}: ${El(a)}`),a.description&&e.out.line(a.description),a.updated_at&&e.out.line(`Draft saved ${a.updated_at}${a.updated_by?` by ${a.updated_by}`:""}.`),e.out.line(),a.source==="code"?Ds(e,`Its last turn${a.defined_at?` (${a.defined_at})`:""} was defined as:`,a.definition):e.flags.draft===!0||a.published===void 0?Ds(e,`The draft (revision ${a.revision}):`,a.draft):Ds(e,`Version ${a.published_version}, the one its chats talk to:`,a.published)})}};function fR(e){let t=e.indexOf(":"),n=t>0?e.slice(0,t):"",s=e.slice(t+1);if(!gf.includes(n)||s==="")throw m(`--tool is source:name \u2014 ${gf.join(", ")} \u2014 not ${JSON.stringify(e)}`,"palbase ai:tools lists the tools an agent may be given");let a=n==="backend"?s.indexOf("/"):-1;if(a<0)return{source:n,name:s};let i=s.slice(0,a);if(s=s.slice(a+1),!wr.test(i)||s==="")throw m(`--tool backend:<machine>/<name> names one of the environment's machines and its tool, not ${JSON.stringify(e)}`);return{source:"backend",name:s,machine:i}}async function yR(e){let t={},n=e.flags.from;if(n!==void 0){let a=await ff(e,n,n),i=fr(a)&&fr(a.definition)&&typeof a.name=="string"?a.definition:a;if(!fr(i))throw m(`${n} is an agent's definition: a JSON object { instructions, model, tools, \u2026 }`);t=i}e.flags.instructions!==void 0&&(t.instructions=e.flags.instructions),e.flags.description!==void 0&&(t.description=e.flags.description),e.flags.model!==void 0&&(t.model=e.flags.model),e.flags.tool!==void 0&&(t.tools=e.flags.tool.map(fR));let s=e.flags["output-schema"];if(s!==void 0){let a=await ff(e,s,s);if(!fr(a)||a.type!=="object")throw m(`${s} is the JSON Schema of the agent's one-shot answers: an object's ({ "type": "object", "properties": \u2026 })`);t.output=a}if(t.backend!==void 0)throw m("an agent the environment keeps names no backend: a backend's agent is its code's (ai.agent)");return t}async function bR(e,t,n){try{let s=await h(e,t,"GET",`/ai/agents/${k(n)}`);return s.source==="platform"&&s.draft&&s.revision!==void 0?{draft:s.draft,revision:s.revision}:void 0}catch(s){if(s instanceof E&&s.status===404)return;throw s}}async function $f(e,t,n,s,a){return h(e,t,"PUT",`/ai/agents/${k(n)}${qt({revision:a})}`,s)}async function Cl(e,t,n,s){return h(e,t,"POST",`/ai/agents/${k(n)}/publish`,s!==void 0?{revision:s}:{})}var wR={name:"ai:agents:create",summary:"save the draft of an agent the environment keeps \u2014 a new one's, or a change of one's \u2014 and publish it with --publish",usage:"<name> [--from <file.json>] [--instructions <text>] [--description <text>] [--model <model>] [--tool <source:name>]\u2026 [--output-schema <file.json>] [--revision <n>] [--publish]",details:["Its chats talk to the version published: a draft changes nothing until it is published (ai:agents:publish, or --publish here).","A change of an agent it keeps is made on its draft: each flag given replaces its field, and the rest stays.",'--from is the whole definition as JSON ({ "instructions", "model", "tools": [{ "source", "name" }], "subagents", "output", \u2026 }) \u2014 or what ai:agents:generate --json printed; each flag given replaces its field.',"--tool is source:name: backend:<ai.tool> (backend:<machine>/<ai.tool> for another machine's), client:<ai.clientTool>, https:<endpoint>, mcp:<server>, platform:web.search|web.fetch|workspace.fetch_archive (palbase ai:tools lists them). Given, the tools are those; a backend or client tool goes by its name alone, and the platform takes what it does from the build that declares it.","--revision is the draft's revision as it was read (ai:agents:show): when another was saved since, the save is refused (draft_changed) and nothing is lost."],args:{min:1,max:1},flags:{from:{type:"string",value:"file.json",description:"the definition, as JSON"},instructions:{type:"string",value:"text",description:"what the agent is told to do"},description:{type:"string",value:"text",description:"what it is for, in a sentence or two"},model:{type:"string",value:"model",description:"the name of a model ai:models lists; left out, the default"},tool:{type:"string",multiple:!0,value:"source:name",description:"a tool it is given (repeat for several)"},"output-schema":{type:"string",value:"file.json",description:"the JSON Schema of its one-shot answers"},revision:{type:"string",value:"n",description:"the draft's revision the change is made on"},publish:{type:"boolean",description:"publish the draft as the next version once it is saved"}},scope:"environment",async run(e){let t=en(e,"an agent"),n=Rt(e.flags.revision,"revision"),s=await yR(e);if(Object.keys(s).length===0)throw m("the agent is empty","pass --from <file.json>, or --instructions, --model, --tool\u2026");let a=await b(e),i=e.flags.from===void 0?await bR(e,a,t):void 0,r={...i?.draft,...s},o=e.flags.publish===!0;await v(e,a,`save the draft of the agent ${t}${o?" and publish it":""}`);let l=await $f(e,a,t,r,n??i?.revision),d=o?await Cl(e,a,t,l.revision):l;e.out.result(d,()=>{e.out.line(`Saved the draft of ${t} (revision ${l.revision}).`),o?e.out.line(`Published ${t} as version ${d.published_version}: its chats talk to it from their next turn.`):e.out.line(`${El(d)[0].toUpperCase()}${El(d).slice(1)}: palbase ai:agents:publish ${t} makes its chats talk to it.`)})}},vR={name:"ai:agents:publish",summary:"make the draft of an agent the next version, the one its chats talk to from their next turn",usage:"<name> [--revision <n>]",args:{min:1,max:1},flags:{revision:{type:"string",value:"n",description:"the draft as it was read: refused when another was saved since"}},scope:"environment",async run(e){let t=en(e,"an agent"),n=Rt(e.flags.revision,"revision"),s=await b(e);await v(e,s,`publish the draft of the agent ${t}`);let a=await Cl(e,s,t,n);e.out.result(a,()=>e.out.line(`Published ${t} as version ${a.published_version}: its chats talk to it from their next turn.`))}},_R={name:"ai:agents:rollback",summary:"make a version an agent had the one its chats talk to again \u2014 and its draft that version",usage:"<name> <version>",args:{min:2,max:2},scope:"environment",async run(e){let t=en(e,"an agent"),n=Number(e.args[1]);if(!Number.isSafeInteger(n)||n<1)throw m(`the version is a version the agent had, a whole number from 1 (not ${JSON.stringify(e.args[1])})`,`palbase ai:agents:versions ${t}`);let s=await b(e);await v(e,s,`make version ${n} of the agent ${t} the one its chats talk to (a draft not published is dropped)`);let a=await h(e,s,"POST",`/ai/agents/${k(t)}/rollback`,{version:n});e.out.result(a,()=>e.out.line(`${t}'s chats talk to version ${a.published_version} again; its draft is that version.`))}},kR={name:"ai:agents:versions",summary:"the versions an agent the environment keeps was published as, newest first, and the one its chats talk to",usage:"<name> [--limit <n>] [--cursor <cursor>]",args:{min:1,max:1},flags:{limit:{type:"string",value:"n",description:"at most this many (1\u2013100, default 20)"},cursor:{type:"string",value:"cursor",description:"the next page, as the last one said it"}},scope:"environment",async run(e){let t=en(e,"an agent"),n=Rt(e.flags.limit,"limit"),s=await b(e),a=await h(e,s,"GET",`/ai/agents/${k(t)}/versions${qt({limit:n,cursor:e.flags.cursor})}`);e.out.result(a,()=>{a.versions.length===0&&e.out.line(`${t} has no version yet: palbase ai:agents:publish ${t}`),e.out.table(a.versions,[{header:"version",value:i=>`${i.version}${i.version===a.published_version?" (published)":""}`},{header:"published",value:i=>i.published_at},{header:"by",value:i=>i.published_by},{header:"model",value:i=>i.definition.model??"-"},{header:"description",value:i=>i.definition.description??""}]),a.next_cursor&&e.out.line(`More: palbase ai:agents:versions ${t} --cursor ${a.next_cursor}`)})}},SR={name:"ai:agents:generate",summary:"write an agent from a description \u2014 instructions, a model, the environment's tools that fit \u2014 and save it as a draft with --save",usage:'"<description>" [--name <name>] [--save] [--publish]',details:["Nothing is kept unless --save (or --publish) says so: the definition is printed, for ai:agents:create --from.","It is written as you \u2014 your sign-in, or PALBASE_TOKEN \u2014 20 an hour; the platform pays for it."],args:{min:1,max:1},flags:{name:{type:"string",value:"name",description:"the name it is to have (left out: one is suggested)"},save:{type:"boolean",description:"save it as the draft of an agent of that name"},publish:{type:"boolean",description:"save it and publish it as the next version"}},scope:"environment",async run(e){let t=e.args[0].trim();if(t===""||t.length>4e3)throw m("the description says the agent in words: 1 to 4000 characters");let n=e.flags.name;if(n!==void 0&&!wr.test(n))throw m(`${JSON.stringify(n)} is not an agent's name: lowercase letters, digits, _ and -, a letter first, at most 64`);let s=await b(e),a=await h(e,s,"POST","/ai/agent-drafts",{description:t,...n!==void 0?{name:n}:{}}),i=e.flags.publish===!0;if(e.flags.save!==!0&&!i){e.out.result(a,()=>{Ds(e,`${a.name}:`,a.definition),e.out.line(),e.out.line(`Nothing was kept. Save it: palbase ai:agents:generate "\u2026" --save, or palbase ai:agents:create ${a.name} --from <the definition, as ai:agents:generate --json prints it>`)});return}await v(e,s,`save the draft of the agent ${a.name}${i?" and publish it":""}`);let r=await $f(e,s,a.name,a.definition,void 0),o=i?await Cl(e,s,a.name,r.revision):r;e.out.result({...a,agent:o},()=>{Ds(e,`${a.name}:`,a.definition),e.out.line(),e.out.line(i?`Saved and published ${a.name} as version ${o.published_version}.`:`Saved the draft of ${a.name} (revision ${r.revision}): palbase ai:agents:publish ${a.name} makes its chats talk to it.`)})}},$R={name:"ai:agents:remove",summary:"forget an agent the environment keeps, its versions with it: its chats stay, and are refused a message until one of its name is there again",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=en(e,"an agent"),n=await b(e);await v(e,n,`forget the agent ${t} and its versions`),await h(e,n,"DELETE",`/ai/agents/${k(t)}`),e.out.result({removed:t},()=>e.out.line(`Forgot ${t} and its versions.`))}},PR={name:"ai:tools",summary:"the tools an agent may be given: the backend's (its build's contract), the environment's endpoints, and the platform's",scope:"environment",async run(e){let t=await b(e),{tools:n}=await h(e,t,"GET","/ai/tools");e.out.result({tools:n},()=>{e.out.table(n,[{header:"tool",value:s=>`${s.source}:${s.name}`},{header:"machine",value:s=>s.machine??"-"},{header:"approval",value:s=>s.approval?"yes":"no"},{header:"description",value:s=>s.description}]),e.out.line("An agent is given one as --tool source:name (ai:agents:create).")})}},AR={name:"ai:chats:list",summary:"the environment's chats, newest first \u2014 every one, or a member's",usage:"[--member <user id>] [--limit <n>] [--cursor <cursor>]",flags:{member:{type:"string",value:"user id",description:"only the chats this user is in"},limit:{type:"string",value:"n",description:"at most this many (1\u2013100, default 100)"},cursor:{type:"string",value:"cursor",description:"the next page, as the last one said it"}},scope:"environment",async run(e){let t=Rt(e.flags.limit,"limit"),n=await b(e),s=await h(e,n,"GET",`/ai/chats${qt({member:e.flags.member,limit:t,cursor:e.flags.cursor})}`);e.out.result(s,()=>{s.chats.length===0&&e.out.line("No chat."),e.out.table(s.chats,[{header:"id",value:a=>a.id},{header:"agent",value:a=>`${a.agent}${a.agent_version?`@${a.agent_version}`:""}`},{header:"title",value:a=>a.title},{header:"members",value:a=>String(a.members.length)},{header:"started",value:a=>a.created_at}]),s.next_cursor&&e.out.line(`More: palbase ai:chats:list --cursor ${s.next_cursor}`)})}},RR=/^chat_[0-9a-f]{32}$/;function Hn(e){let t=e.args[0];if(!RR.test(t))throw m(`${JSON.stringify(t)} is not a chat's id (chat_ and 32 hex digits)`,"palbase ai:chats:list");return t}var TR={name:"ai:chats:show",summary:"one chat: its agent and members, and what they wrote, newest last \u2014 with what each turn cost (--cost)",usage:"<chat id> [--limit <n>] [--cost]",args:{min:1,max:1},flags:{limit:{type:"string",value:"n",description:"its last this many messages (1\u2013100, default 50)"},cost:{type:"boolean",description:"what each turn a message started cost, its subagents counted"}},scope:"environment",async run(e){let t=Hn(e),n=Rt(e.flags.limit,"limit")??50,s=await b(e),a=await h(e,s,"GET",`/ai/chats/${k(t)}`),i=await h(e,s,"GET",`/ai/chats/${k(t)}/messages${qt({limit:n})}`),r=[...i.messages].reverse(),o=await ER(e,s,t,new Set(r.flatMap(p=>p.response_id?[p.response_id]:[]))),l=new Map;r.forEach((p,u)=>p.response_id&&l.set(p.response_id,u));let d=new Map;if(e.flags.cost===!0)for(let p of new Set(r.flatMap(u=>u.response_id?[u.response_id]:[])))d.set(p,await h(e,s,"GET",`/ai/chats/${k(t)}/turns/${k(p)}/cost`));e.out.result({chat:a,messages:r,answers:Object.fromEntries(o),...e.flags.cost===!0?{costs:Object.fromEntries(d)}:{}},()=>{e.out.line(`${a.id} ${a.title||"(untitled)"}`),e.out.line(`agent ${a.agent}${a.agent_version?` (stays on version ${a.agent_version})`:""}; started ${a.created_at}; ${a.history_bytes} bytes of history`),a.members.length>0&&e.out.line(`members: ${a.members.map(p=>`${p.name||p.user_id}${p.owner?" (owner)":""}`).join(", ")}`),e.out.line(),r.length===0&&e.out.line("Nothing written yet."),r.forEach((p,u)=>{if(e.out.line(`${p.created_at} ${p.author===null?"server":p.author_name||p.author}: ${p.text}${p.status==="failed"?` [failed: ${p.error??""}]`:""}`),!p.response_id||l.get(p.response_id)!==u)return;let g=o.get(p.response_id);g&&e.out.line(` ${a.agent}: ${g.replace(/\s*\n\s*/g," ")}`);let y=d.get(p.response_id);y&&e.out.line(` turn ${y.response_id}: ${yr(y.usd)}${y.unpriced?" at least":""}, ${y.input_tokens} in / ${y.output_tokens} out${y.final?"":" (still settling)"}`)}),i.next_cursor&&e.out.line(`(older messages are not shown: --limit ${Math.min(n*2,100)})`)})}};async function ER(e,t,n,s){let a=[],i;for(let o=0;o<20&&s.size>0;o++){let l=await h(e,t,"GET",`/ai/chats/${k(n)}/parts${qt({limit:1e3,cursor:i})}`);if(a.unshift(l.parts),!l.next_cursor)break;i=l.next_cursor}let r=new Map;for(let o of a.flat()){let l=o.data.response_id,d=o.data.offset;if(typeof l!="string"||!s.has(l)||typeof d!="number")continue;let p=(r.get(l)??Buffer.alloc(0)).subarray(0,d);r.set(l,o.type==="text"&&typeof o.data.text=="string"?Buffer.concat([p,Buffer.from(o.data.text)]):o.type==="reset"?p:r.get(l)??p)}return new Map([...r].map(([o,l])=>[o,l.toString("utf8").trim()]))}var CR={name:"ai:chats:remove",summary:"delete a chat: a turn still running is stopped, and its history no longer counts",usage:"<chat id>",args:{min:1,max:1},scope:"environment",async run(e){let t=Hn(e),n=await b(e);await v(e,n,`delete the chat ${t}`),await h(e,n,"DELETE",`/ai/chats/${k(t)}`),e.out.result({removed:t},()=>e.out.line(`Deleted the chat ${t}.`))}},jR=/^[a-z][a-z0-9_-]{0,63}(@[1-9][0-9]{0,8})?$/,Ma=/^[A-Za-z0-9_.:-]{1,160}$/;function OR(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).map(t=>{let n=String(t),s=n.indexOf("@"),a=s<0?n:n.slice(0,s),i=s<0?void 0:n.slice(s+1);if(!wr.test(a)||i==="")throw m(`--repo is one of the environment's repositories by name, at a branch with @ (shop@agent/x), not ${JSON.stringify(n)}`,"palbase ai:repos:list");return{repo:a,...i!==void 0?{branch:i}:{}}})}var MR={name:"ai:chats:create",summary:"start a chat with one of the environment's agents \u2014 on one of its runner pools, working in its repositories",usage:"--agent <name> [--pool <pool>] [--repo <name>[@<branch>]]\u2026 [--title <title>] [--auto-push]",details:["--agent is one of the environment's agents by name \u2014 its backend's, or one it keeps, whose published version each turn takes; name@N stays on version N.","--pool is one of its runner pools (ai:pools:list), by its id or its name: the chat's sessions run on the environment's own machines enrolled there. Left out, on the platform's own Linux machines. A chat on a pool works in a workspace.","--repo puts one of its repositories (ai:repos:list) in the chat's workspace, at a branch with @ (its default unless said); --auto-push lets the agent push its commits without a person's yes."],flags:{agent:{type:"string",value:"name",description:"the chat's agent, by name (name@N for a version)"},pool:{type:"string",value:"pool",description:"the runner pool its workspace runs on, by id or name"},repo:{type:"string",multiple:!0,value:"name[@branch]",description:"a repository its workspace works in (repeat for several)"},title:{type:"string",value:"title",description:"the chat's title"},"auto-push":{type:"boolean",description:"the agent pushes its commits without a person's yes"}},scope:"environment",async run(e){let t=e.flags.agent;if(t===void 0)throw m("--agent names the chat's agent","palbase ai:agents:list");if(!jR.test(t))throw m(`${JSON.stringify(t)} is not an agent's name (lowercase letters, digits, _ and -, a letter first, at most 64; name@N for a version)`);let n=e.flags.pool;if(n!==void 0&&!Ma.test(n))throw m(`${JSON.stringify(n)} is not a runner pool's id or name`,"palbase ai:pools:list");let s=OR(e.flags.repo),a=e.flags["auto-push"]===!0;if(a&&s.length===0)throw m("--auto-push is about the repositories the chat works in: give --repo");let i={agent:t};e.flags.title!==void 0&&(i.title=e.flags.title),n!==void 0&&(i.pool=n),s.length>0&&(i.workspace={repos:s,...a?{auto_push:!0}:{}});let r=await b(e);await v(e,r,`start a chat with the agent ${t}${n!==void 0?` on the pool ${n}`:""}`);let o=await h(e,r,"POST","/ai/chats",i);e.out.result(o,()=>{e.out.line(`Started the chat ${o.id} with ${o.agent}${o.pool?` on the pool ${o.pool}`:""}.`),s.length>0&&e.out.line(`Its workspace works in ${s.map(l=>l.branch?`${l.repo}@${l.branch}`:l.repo).join(", ")}${a?", its commits pushed without a yes":""}.`)})}};function Pf(e){if(e===""||Buffer.byteLength(e)>2048||e.startsWith("/")||e.split("/").some(t=>t===""||t==="."||t===".."||Buffer.byteLength(t)>255))throw m(`${JSON.stringify(e)} is not a file of the chat's workspace: relative to its root (app/src/config.json), 1 to 2048 bytes, each segment 1 to 255, no . or .. segment, no slash at either end`);return e}var IR=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/u,Af="128 bytes at most, no control, format (bidi, zero-width) or line-separator character",Rf=e=>Buffer.byteLength(e)<=128&&!IR.test(e),yf=64<<20,LR={name:"ai:chats:workspace:write",summary:"write one file of a chat's workspace \u2014 from a file here, or piped in: synced to every machine that holds it, the session's before the agent's next command",usage:"<chat id> <path> [--file <local file>] [< file]",details:["path is relative to the workspace's root (app/src/config.json). The write is published over whatever the workspace holds \u2014 deliberate, no conflict is made of it \u2014 and told as ai.workspace.published.","--file sends the file's bytes as they are (64 MiB at most); without it, the bytes piped in, as they are \u2014 a binary file too (64 MiB at most: no more is read)."],args:{min:2,max:2},flags:{file:{type:"string",value:"local file",description:"the file whose bytes are written (default: what is piped in)"}},scope:"environment",async run(e){let t=Hn(e),n=Pf(e.args[1]),s=e.flags.file,a;if(s!==void 0){let o=vf(e.io.cwd,s);try{let l=(await eR(o)).size;if(l>yf)throw new f("file_too_large",`${s} is ${l} bytes: a workspace's file is written up to 64 MiB`);a=await ZA(o)}catch(l){throw l instanceof f?l:new f("unreadable_file",`${s} could not be read: ${l instanceof Error?l.message:String(l)}`)}}else{if(e.interactive)throw m("the file's bytes are --file <local file>, or piped in",`palbase ai:chats:workspace:write ${t} ${n} --file <local file>`);let o=await e.io.readStdinBytes(yf);if(o===null)throw new f("file_too_large","more than 64 MiB was piped in: a workspace's file is written up to 64 MiB");if(o.byteLength===0)throw m("nothing was piped in","pipe the file in, or pass --file <local file>");a=new Blob([o])}let i=await b(e);await v(e,i,`write ${n} in the workspace of the chat ${t}`);let r=await h(e,i,"PUT",`/ai/chats/${k(t)}/workspace/files${qt({path:n})}`,new Wt(a,"application/octet-stream"));e.out.result(r,()=>e.out.line(`Wrote ${r.path} (${a.size} bytes): the workspace is at ${r.manifest_id}, seq ${r.seq}.`))}},DR={name:"ai:chats:workspace:rm",summary:"remove one file of a chat's workspace: synced to every machine that holds it",usage:"<chat id> <path>",args:{min:2,max:2},scope:"environment",async run(e){let t=Hn(e),n=Pf(e.args[1]),s=await b(e);await v(e,s,`remove ${n} from the workspace of the chat ${t}`);let a=await h(e,s,"DELETE",`/ai/chats/${k(t)}/workspace/files${qt({path:n})}`);e.out.result(a,()=>e.out.line(`Removed ${a.path}: the workspace is at ${a.manifest_id}, seq ${a.seq}.`))}},bf=604800,xR={name:"ai:chats:workspace:token",summary:"mint a token a machine of yours syncs a chat's workspace with (palai workspace sync): said once, here",usage:"<chat id> --access read|write [--ttl <seconds>] [--label <label>]",details:["write: the workspace is synced both ways, live; read: it is followed. The token lives --ttl seconds (an hour unless said, 7 days at most) \u2014 no longer than PALBASE_TOKEN when it is minted with one.","The token and its address are said once. On the machine: PALAI_WORKSPACE_TOKEN=<token> palai workspace sync --url <sync_url> <dir> \u2014 or the token on standard input, --token-file - \u2014 never on the command line: palai has no --token, a secret there is readable by every process on the machine.","A member's token (the project letting its app's users in) lives an hour at most, and stops working when they leave the chat or the project turns clients off.","--label is what it is for \u2014 the machine's name: a conflict names its writer by it."],args:{min:1,max:1},flags:{access:{type:"string",value:"read|write",description:"write: synced both ways; read: followed"},ttl:{type:"string",value:"seconds",description:"how long it lives (1\u2013604800, default 3600)"},label:{type:"string",value:"label",description:"what it is for \u2014 the machine's name"}},scope:"environment",async run(e){let t=Hn(e),n=e.flags.access;if(n!=="read"&&n!=="write")throw m("--access is read (the workspace followed) or write (synced both ways)");let s=Rt(e.flags.ttl,"ttl");if(s!==void 0&&s>bf)throw m(`--ttl is 1 to ${bf} seconds (7 days)`);let a=e.flags.label;if(a!==void 0&&!Rf(a))throw m(`--label is ${Af}`);let i={access:n};s!==void 0&&(i.ttl_seconds=s),a!==void 0&&(i.label=a);let r=await b(e);await v(e,r,`mint a ${n} token of the workspace of the chat ${t}`);let o=await h(e,r,"POST",`/ai/chats/${k(t)}/workspace/tokens`,i);e.out.result(o,()=>{e.out.line(`Minted ${o.id} (${o.access}${o.label?`, ${o.label}`:""}), until ${o.expires_at}. It is said this once:`),e.out.line(),e.out.line(` token ${o.token}`),e.out.line(` sync_url ${o.sync_url}`),e.out.line(),e.out.line("On the machine, the token in its environment (never on the command line):"),e.out.line(` PALAI_WORKSPACE_TOKEN=<the token> palai workspace sync --url ${o.sync_url} <dir>`),e.out.line("or on its standard input: palai workspace sync --url <sync_url> --token-file - <dir>"),e.out.line(`Revoke it: palbase ai:chats:workspace:revoke ${t} ${o.id}`)})}},NR={name:"ai:chats:workspace:tokens",summary:"the tokens of a chat's workspace \u2014 access, label, when each expires \u2014 none of them said again",usage:"<chat id>",args:{min:1,max:1},scope:"environment",async run(e){let t=Hn(e),n=await b(e),{tokens:s}=await h(e,n,"GET",`/ai/chats/${k(t)}/workspace/tokens`);e.out.result({tokens:s},()=>{s.length===0&&e.out.line(`No token: palbase ai:chats:workspace:token ${t} --access write`),e.out.table(s,[{header:"id",value:a=>a.id},{header:"access",value:a=>a.access},{header:"label",value:a=>a.label??""},{header:"expires",value:a=>a.expires_at}])})}},qR={name:"ai:chats:workspace:revoke",summary:"revoke a token of a chat's workspace at once: every sync with it is refused from then",usage:"<chat id> <token id>",args:{min:2,max:2},scope:"environment",async run(e){let t=Hn(e),n=e.args[1];if(!Ma.test(n))throw m(`${JSON.stringify(n)} is not a token's id`,`palbase ai:chats:workspace:tokens ${t}`);let s=await b(e);await v(e,s,`revoke the token ${n} of the workspace of the chat ${t}`),await h(e,s,"DELETE",`/ai/chats/${k(t)}/workspace/tokens/${k(n)}`),e.out.result({revoked:n},()=>e.out.line(`Revoked ${n}: every sync with it is refused from now.`))}},KR={name:"ai:endpoints:list",summary:"the environment's HTTPS tools and MCP servers an agent may be given by name (their signing secrets are never said again)",scope:"environment",async run(e){let t=await b(e),{endpoints:n}=await h(e,t,"GET","/ai/endpoints"),s=n.map(({signing_secret:a,...i})=>i);e.out.result({endpoints:s},()=>{s.length===0&&e.out.line("No endpoint."),e.out.table(s,[{header:"name",value:a=>a.name},{header:"kind",value:a=>a.kind},{header:"url",value:a=>a.url},{header:"approval",value:a=>a.approval?"yes":"no"},{header:"workspace",value:a=>a.workspace?"told":"not told"},{header:"description",value:a=>a.description}])})}},GR={name:"ai:endpoints:remove",summary:"forget an HTTPS tool or an MCP server: an agent that names it is given it no more",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=en(e,"an endpoint"),n=await b(e);await v(e,n,`forget the endpoint ${t}`),await h(e,n,"DELETE",`/ai/endpoints/${k(t)}`),e.out.result({removed:t},()=>e.out.line(`Forgot the endpoint ${t}.`))}},UR={name:"ai:repos:list",summary:"the repositories a chat's workspace works in, by name, and the machine that gives their tokens",usage:"[--limit <n>] [--cursor <cursor>]",flags:{limit:{type:"string",value:"n",description:"at most this many (1\u20131000, default 100)"},cursor:{type:"string",value:"cursor",description:"the next page, as the last one said it"}},scope:"environment",async run(e){let t=Rt(e.flags.limit,"limit"),n=await b(e),s=await h(e,n,"GET",`/ai/repos${qt({limit:t,cursor:e.flags.cursor})}`);e.out.result(s,()=>{s.repos.length===0&&e.out.line("No repository."),e.out.table(s.repos,[{header:"name",value:a=>a.name},{header:"repository",value:a=>a.repository},{header:"branch",value:a=>a.default_branch},{header:"tokens from",value:a=>a.backend}]),s.next_cursor&&e.out.line(`More: palbase ai:repos:list --cursor ${s.next_cursor}`)})}},BR={name:"ai:repos:remove",summary:"forget a repository: a chat's workspace checks it out no more",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=en(e,"a repository"),n=await b(e);await v(e,n,`forget the repository ${t}`),await h(e,n,"DELETE",`/ai/repos/${k(t)}`),e.out.result({removed:t},()=>e.out.line(`Forgot the repository ${t}.`))}};function vr(e){let t=e.args[0];if(!Ma.test(t))throw m(`${JSON.stringify(t)} is not a runner pool's id or name`,"palbase ai:pools:list");return t}function jl(e){let t=e.args[0];if(!Ma.test(t))throw m(`${JSON.stringify(t)} is not a machine's id`,"palbase ai:pools:state <pool> lists its machines");return t}function zR(e){if(!(e instanceof E))return e;switch(e.code){case"pool_not_empty":return new f(e.code,e.message,{hint:"palbase ai:pools:state <pool> lists its machines: ai:machines:cordon <id>, then ai:machines:delete <id> once it holds none"});case"machine_not_cordoned":return new f(e.code,e.message,{hint:"palbase ai:machines:cordon <id> first"});case"machine_busy":return new f(e.code,e.message,{hint:"delete it once ai:pools:state <pool> says it holds none (used 0)"});case"pool_exists":return new f(e.code,e.message,{hint:"palbase ai:pools:list"});default:return e}}async function Yn(e,t,n,s,a){try{return await h(e,t,n,s,a)}catch(i){throw zR(i)}}var WR={name:"ai:pools:create",summary:"make a runner pool of the environment's: machines of your own, of one type, that a chat's workspace runs on",usage:"<name> --os linux|macos --arch amd64|arm64",details:["A pool is of one type: its machines' operating system and architecture. Machines enrol into it with palai and a single-use key (ai:pools:keys:create); a chat runs on it when it names it (ai:chats:create --pool).","The environment scales it itself: ai:pools:state says what its machines hold and how many sessions wait."],args:{min:1,max:1},flags:{os:{type:"string",value:"linux|macos",description:"its machines' operating system"},arch:{type:"string",value:"amd64|arm64",description:"its machines' architecture"}},scope:"environment",async run(e){let t=en(e,"a pool"),n=e.flags.os,s=e.flags.arch;if(n!=="linux"&&n!=="macos")throw m("--os is the pool's machines' operating system: linux or macos");if(s!=="amd64"&&s!=="arm64")throw m("--arch is the pool's machines' architecture: amd64 or arm64");let a=await b(e);await v(e,a,`make the runner pool ${t} (${n}/${s})`);let i=await Yn(e,a,"POST","/ai/pools",{name:t,os:n,arch:s});e.out.result(i,()=>{e.out.line(`Made the pool ${i.name} (${i.id}), ${i.os}/${i.arch}.`),e.out.line(`Enrol a machine: palbase ai:pools:keys:create ${i.name}`)})}},FR={name:"ai:pools:list",summary:"the environment's runner pools: each one's type, its machines, the sessions they take and hold, and how many wait",scope:"environment",async run(e){let t=await b(e),{pools:n}=await h(e,t,"GET","/ai/pools");e.out.result({pools:n},()=>{n.length===0&&e.out.line("No pool: the environment's chats run on the platform's own Linux machines. Make one: palbase ai:pools:create <name> --os linux|macos --arch amd64|arm64"),e.out.table(n,[{header:"name",value:s=>s.name},{header:"id",value:s=>s.id},{header:"type",value:s=>`${s.os}/${s.arch}`},{header:"machines",value:s=>String(s.machines??0)},{header:"sessions",value:s=>`${s.capacity_used??0}/${s.capacity_total??0}`},{header:"waiting",value:s=>String(s.waiting??0)}])})}},JR={name:"ai:pools:delete",summary:"delete a runner pool with no machine left in it: cordon each machine, delete it once it holds no session, then the pool",usage:"<pool>",args:{min:1,max:1},scope:"environment",async run(e){let t=vr(e),n=await b(e);await v(e,n,`delete the runner pool ${t}`),await Yn(e,n,"DELETE",`/ai/pools/${k(t)}`),e.out.result({deleted:t},()=>e.out.line(`Deleted the pool ${t}.`))}},VR={name:"ai:pools:state",summary:"a runner pool's state, as a scaling loop reads it: its machines, the sessions they take and hold, and how many wait since when",usage:"<pool>",args:{min:1,max:1},scope:"environment",async run(e){let t=vr(e),n=await b(e),s=await h(e,n,"GET",`/ai/pools/${k(t)}/state`);e.out.result(s,()=>{e.out.line(`${s.pool.name} (${s.pool.id}), ${s.pool.os}/${s.pool.arch}`),e.out.line(`sessions ${s.capacity_used} held of ${s.capacity_total} its machines take at once`),e.out.line(`waiting ${s.waiting}${s.oldest_waiting_since?` (the oldest since ${s.oldest_waiting_since})`:""}`),e.out.line(),s.machines.length===0&&e.out.line(`No machine: palbase ai:pools:keys:create ${s.pool.name} mints a key one enrols with.`),e.out.table(s.machines,[{header:"id",value:a=>a.id},{header:"state",value:a=>a.state},{header:"sessions",value:a=>`${a.used}/${a.capacity}`},{header:"label",value:a=>a.label??""},{header:"last seen",value:a=>a.last_seen_at??"-"},{header:"idle since",value:a=>a.idle_since??"-"}])})}},HR={name:"ai:pools:keys:create",summary:"mint a single-use key a machine enrols into a runner pool with: said once, here",usage:"<pool> [--label <label>]",details:["Save the key to a file on the machine and enrol it: palai enroll --url <enroll_url> --key-file <file> --capacity <n> (with --server-name and --ca-file when the answer names a server name and a CA) \u2014 the key never goes on a command line, where any process on the machine could read it; n is how many sessions the machine runs at once (1 or more, default 1). The machine serves the environment's sessions once whoever minted the key is gone.","It is minted by a person signed in, never with an environment's token (PALBASE_TOKEN)."],args:{min:1,max:1},flags:{label:{type:"string",value:"label",description:"what it is for \u2014 the machine it enrols"}},scope:"environment",async run(e){let t=vr(e),n=e.flags.label;if(n!==void 0&&!Rf(n))throw m(`--label is ${Af}`);let s=await b(e);await v(e,s,`mint a key a machine enrols into the pool ${t} with`);let a=await Yn(e,s,"POST",`/ai/pools/${k(t)}/keys`,n!==void 0?{label:n}:{});if(typeof a.key!="string"||a.key==="")throw new f("no_key",`the key ${a.id} was minted but not said`,{hint:`revoke it (palbase ai:pools:keys:revoke ${a.id}) and mint another`});e.out.result(a,()=>{e.out.line(`Minted the key ${a.id}${a.label?` (${a.label})`:""}${a.expires_at?`, usable until ${a.expires_at}`:""}. It is said this once:`),e.out.line(),e.out.line(` ${a.key}`),e.out.line();let i=a.enroll_url??a.enroll?.url??"<enroll_url>",r=`${a.enroll?.server_name?` --server-name ${a.enroll.server_name}`:""}${a.enroll?.ca_certificate?" --ca-file <ca file>":""}`;e.out.line(`Save it to a file on the machine, then: palai enroll --url ${i} --key-file <file> --capacity <n>${r}`),a.enroll?.ca_certificate&&(e.out.line("The door's certificate is signed by this CA \u2014 save it as the <ca file>:"),e.out.line(),e.out.line(a.enroll.ca_certificate.trimEnd()),e.out.line()),e.out.line(`(n: how many sessions the machine runs at once, 1 or more, default 1; the key never goes on a command line.) Revoke it unused: palbase ai:pools:keys:revoke ${a.id}`)})}},YR={name:"ai:pools:keys:list",summary:"a runner pool's enrolment keys \u2014 when each was minted, last used, revoked \u2014 none of them said again",usage:"<pool>",args:{min:1,max:1},scope:"environment",async run(e){let t=vr(e),n=await b(e),{keys:s}=await h(e,n,"GET",`/ai/pools/${k(t)}/keys`),a=s.map(({key:i,...r})=>r);e.out.result({keys:a},()=>{a.length===0&&e.out.line(`No key: palbase ai:pools:keys:create ${t}`),e.out.table(a,[{header:"id",value:i=>i.id},{header:"label",value:i=>i.label??""},{header:"minted",value:i=>i.created_at??"-"},{header:"expires",value:i=>i.expires_at??"-"},{header:"last used",value:i=>i.last_used_at??"-"},{header:"revoked",value:i=>i.revoked_at??"-"}])})}},XR={name:"ai:pools:keys:revoke",summary:"revoke an enrolment key: no machine enrols with it any more",usage:"<key id>",args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0];if(!Ma.test(t))throw m(`${JSON.stringify(t)} is not a key's id`,"palbase ai:pools:keys:list <pool>");let n=await b(e);await v(e,n,`revoke the enrolment key ${t}`),await Yn(e,n,"POST",`/ai/pool-keys/${k(t)}/revoke`),e.out.result({revoked:t},()=>e.out.line(`Revoked ${t}: no machine enrols with it any more.`))}},ZR={name:"ai:machines:cordon",summary:"cordon a machine of a runner pool: it takes no new session, and the sessions it holds go on",usage:"<machine id>",args:{min:1,max:1},scope:"environment",async run(e){let t=jl(e),n=await b(e);await v(e,n,`cordon the machine ${t}`),await Yn(e,n,"POST",`/ai/machines/${k(t)}/cordon`),e.out.result({cordoned:t},()=>e.out.line(`Cordoned ${t}: it takes no new session. Delete it once it holds none: palbase ai:machines:delete ${t}`))}},QR={name:"ai:machines:resume",summary:"let a cordoned machine of a runner pool take sessions again",usage:"<machine id>",args:{min:1,max:1},scope:"environment",async run(e){let t=jl(e),n=await b(e);await v(e,n,`let the machine ${t} take sessions again`),await Yn(e,n,"POST",`/ai/machines/${k(t)}/resume`),e.out.result({resumed:t},()=>e.out.line(`${t} takes sessions again.`))}},eT={name:"ai:machines:delete",summary:"delete a cordoned machine that holds no session from its runner pool: its palai agent is refused from then",usage:"<machine id>",args:{min:1,max:1},scope:"environment",async run(e){let t=jl(e),n=await b(e);await v(e,n,`delete the machine ${t} from its pool`),await Yn(e,n,"DELETE",`/ai/machines/${k(t)}`),e.out.result({deleted:t},()=>e.out.line(`Deleted ${t}: its palai agent is refused from now.`))}},tT=/^[A-Z][A-Z0-9_]{0,127}$/,wf=32768;function Tf(e){let t=e.args[0];if(!tT.test(t)||t.startsWith("PALAI_"))throw m(`${JSON.stringify(t)} is not a variable's name: upper-case letters, digits and _, a letter first, at most 128 \u2014 and not PALAI_\u2026, the engine's own`);return t}var nT={name:"ai:env:set",summary:"set a variable every session of the environment's agents has: its value piped in or typed unseen, never shown or put on the command line",usage:"<KEY> [--value-stdin] [--not-secret] < value.txt",details:["Every command of every session its agents begin from now has it \u2014 on the platform's machines and on its own pools \u2014 beside an agent's own (its definition's env), masked in a transcript. The value is sealed where the sessions run: never answered, never logged.","Without --value-stdin the value is asked for at the terminal, and not echoed as it is typed or pasted.","--not-secret says it is no secret in ai:env:list; its value is masked and never shown either way."],args:{min:1,max:1},flags:{"value-stdin":{type:"boolean",description:"read the value from stdin (a pipe, a file)"},"not-secret":{type:"boolean",description:"list it as no secret (its value is never shown either way)"}},scope:"environment",async run(e){let t=Tf(e);if(e.flags["value-stdin"]!==!0&&!e.interactive)throw m(`${t}'s value is read from stdin`,`pipe it in: palbase ai:env:set ${t} --value-stdin < value.txt`);let n=await b(e),s=await Me(e,`${t}'s value`);if(Buffer.byteLength(s)>wf||s.includes("\0"))throw m(`${t}'s value is 1 to ${wf} bytes, no NUL`);let a=e.flags["not-secret"]!==!0;await v(e,n,`set the variable ${t} for every session of the environment's agents`);let i=await h(e,n,"PUT",`/ai/env/${k(t)}`,{value:s,...a?{}:{secret:!1}});e.out.result(i,()=>e.out.line(`Set ${i.key}${i.secret?" (a secret)":""}: every session begun from now has it. Its value is kept sealed, never shown.`))}},sT={name:"ai:env:unset",summary:"remove a variable: sessions of the environment's agents begun from now no longer have it",usage:"<KEY>",args:{min:1,max:1},scope:"environment",async run(e){let t=Tf(e),n=await b(e);await v(e,n,`remove the variable ${t}`),await h(e,n,"DELETE",`/ai/env/${k(t)}`),e.out.result({removed:t},()=>e.out.line(`Removed ${t}: sessions begun from now no longer have it.`))}},aT={name:"ai:env:list",summary:"the variables every session of the environment's agents has: their names, whether each is a secret, when each was set \u2014 never a value",scope:"environment",async run(e){let t=await b(e),{variables:n}=await h(e,t,"GET","/ai/env");e.out.result({variables:n},()=>{n.length===0&&e.out.line("No variable: palbase ai:env:set <KEY>"),e.out.table(n,[{header:"key",value:s=>s.key},{header:"secret",value:s=>s.secret?"yes":"no"},{header:"value",value:()=>"set"},{header:"updated",value:s=>s.updated_at}])})}},Ef=[nR,iR,sR,rR,oR,lR,pR,uR,hR,gR,wR,vR,_R,kR,SR,$R,PR,AR,TR,MR,CR,LR,DR,xR,NR,qR,KR,GR,UR,BR,WR,FR,JR,VR,HR,YR,XR,ZR,QR,eT,nT,sT,aT];var iT={name:"docs:search",summary:"search Palbase's documentation by meaning: the sections that answer it, each with its address and its text",usage:'"<what you need>" [--limit <n>]',details:["Ask in English, the docs' language: a question finds the section it means by its meaning and by its words \u2014 say what you need, not the words of a heading.","Each result is a section of a page: its title, its address with the section's anchor, and its text (the first 4000 characters of a longer one \u2014 the address has the rest).","Anyone may search, signed in or not: 10 searches in ten seconds, 30 a minute, 300 an hour. A sign-in or PALBASE_TOKEN is sent when there is one and is counted as itself; with none, your address is. When many search at once, a search waits its turn for a few seconds, or is told to search again in a moment."],args:{min:1,max:1},flags:{limit:{type:"string",value:"n",description:"how many sections (1 to 10, default 5)"}},scope:"none",async run(e){let t=e.args[0].trim();if([...t].length<2||[...t].length>500)throw m("say what you need from the docs: 2 to 500 characters");let n=e.flags.limit,s=n===void 0?5:Number(n);if(!Number.isInteger(s)||s<1||s>10)throw m("--limit is how many sections: 1 to 10");let{results:a}=await e.studio.open(`/docs/search?q=${encodeURIComponent(t)}&limit=${s}`);e.out.result(a,()=>{if(a.length===0){e.out.line('No section of the docs answers it: say it another way, or ask Palbase: palbase support:ask "<question>"');return}a.forEach((i,r)=>{r>0&&e.out.line(),e.out.line(`${r+1}. ${i.title===i.heading?i.title:`${i.title} \u203A ${i.heading}`}`),e.out.line(` ${i.url}`),e.out.line(),e.out.line(i.text)})})}},Cf=[iT];var jf=3e4,Ol=3,rT=80;async function oT(e,t){let n=[],s;try{s=(await h(e,t,"GET",`/machines?limit=100&environment=${encodeURIComponent(t.env_ref)}`)).machines}catch{return"machines: not readable with this sign-in or token"}if(s.length===0)return"machines: none";for(let i of s.slice(0,Ol)){n.push(`machine ${i.name}: ${i.state}, size ${i.size}, version ${i.running_version===i.version?i.version:`${i.running_version} \u2192 ${i.version}`}`);let r;try{r=(await h(e,t,"GET",`/machines/${x("a machine's name",i.name)}/builds?limit=3`)).builds}catch{n.push(" builds: not readable with this sign-in or token");continue}for(let l of r)n.push(` build ${l.id} ${l.commit.slice(0,7)} ${l.state}${l.running?" (serving)":""}${l.reason?` \u2014 ${l.reason}`:""} ${l.created_at} "${l.message.split(`
|
|
646
|
+
`))}let ls={schema:1,project:{id:n.id,name:n.name},apps:i.map(O=>({id:O.id,slug:O.slug,name:O.name,platform:O.platform})),...ve!==void 0&&nt.length>0?{types_environment:ve}:{},...Object.keys(D).length>0?{clients:Object.fromEntries(Object.entries(D).sort(([O],[V])=>O.localeCompare(V)))}:{}};return r.set(`${z}/project.json`,Is(ls)),{files:r,notes:o,project:ls}}async function dA(e,t,n){let s=`${z}/environments/${t}`,a;try{a=await ja(await ge(e,`${s}/contracts/${n}.openapi.json`),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let i=`contracts/${n}.openapi.json, sha256 `,r=Lg("sha256").update(a).digest("hex");for(let o of[`${s}/palbe/${n}.ts`,`${s}/palbe/${n}.kt`]){let l=await ja(pt(e,o),"utf8").catch(()=>""),d=l.indexOf(i);if(d>=0){r=l.slice(d+i.length,l.indexOf(")",d));break}}return{doc:JSON.parse(a),digest:r}}function pA(e){return[...e.matchAll(/^public (?:nonisolated )?(?:struct|enum|typealias|final class|class|protocol) ([A-Za-z_][A-Za-z0-9_]*)/gm)].map(t=>t[1])}function uA(e){return[...e.matchAll(/^(?:(?:data|sealed|enum|value|internal|private|public) )*(?:class|object|interface|typealias) ([A-Za-z_][A-Za-z0-9_]*)|^val ([A-Za-z_][A-Za-z0-9_.]*\.[A-Za-z_][A-Za-z0-9_]*):/gm)].map(t=>t[1]??t[2])}function Ig(e,t,n,s,a){for(let i of t){let r=e.get(i);if(r!==void 0&&r!==n)throw new f("backends_collide",`${r} and ${n} both declare ${i} in ${s}'s ${a} client, which one target cannot hold`,{hint:"rename the controller or route in one of them (it names the type), or reach them from different apps"});e.set(i,n)}}async function cA(e){let t=new Map,n=async s=>{let a;try{a=await Sl(pt(e,s),{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of a){let r=`${s}/${i.name}`;if(i.isDirectory()){(s!==z||i.name==="environments"||i.name==="palbe")&&await n(r);continue}if(!i.isFile()||i.name.endsWith(".storekit"))continue;let o=await ja(pt(e,r),"utf8");(s!==z||i.name==="project.json"||i.name.endsWith(".palbase")||o.startsWith(Ca))&&t.set(r,o)}};return await n(z),t}async function ir(e){try{return JSON.parse(await ja(pt(e,z,"project.json"),"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw new f("unreadable_project_file",`${z}/project.json is not what palbase apps:sync writes: ${t.message}`)}}async function xg(e){let t=e.io.cwd,n=e.flags.check===!0,s=await ir(t),a=await lA(e,s),i=await cA(t),r=[],o=[],l=[];for(let[u,g]of a.files){let y=i.get(u);y===void 0?r.push(u):y!==g&&o.push(u)}for(let u of i.keys())a.files.has(u)||l.push(u);let d=r.length+o.length+l.length>0;if(!n){for(let u of[...r,...o]){let g=await ge(t,u);await YP(tA(g),{recursive:!0}),await ge(t,u),await QP(g,a.files.get(u))}for(let u of l)await Dg(await ge(t,u));await Ng(t,pt(t,z))}let p={project:a.project.project.name,apps:a.project.apps.map(u=>u.slug),added:r,changed:o,removed:l,unchanged:a.files.size-r.length-o.length,check:n,differs:d};for(let u of a.notes)e.out.note(u);return e.out.result(p,()=>{let u=(g,y)=>y.forEach(w=>e.out.line(` ${g} ${w}`));if(!d){e.out.line(`${z}/ is what ${a.project.project.name} gives now (${a.files.size} files)`);return}e.out.line(n?`${z}/ differs from what ${a.project.project.name} gives now:`:`${z}/ written for ${a.project.apps.map(g=>g.slug).join(", ")}:`),u(n?"missing":"added",r),u(n?"differs":"changed",o),u(n?"not given":"removed",l),n&&e.out.note("palbase apps:sync brings it up to date")}),n&&d?1:void 0}async function ge(e,t){let n=pt(e,z),s=pt(e,...t.split("/")),a=ar(n,s);if(a===""||a.startsWith(`..${sr}`)||a===".."||a.split(sr).some(r=>r===".."||r===""))throw new f("outside_palbase",`${t} is not under ${z}/`);let i=e;for(let r of[z,...a.split(sr)]){i=pt(i,r);try{if((await HP(i)).isSymbolicLink())throw new f("linked_path",`${ar(e,i)} is a link: palbase writes only into ${z}/ itself`,{hint:"remove the link, and run it again"})}catch(o){if(o.code==="ENOENT")break;throw o}}return s}async function Ng(e,t){let n;try{n=await Sl(t,{withFileTypes:!0})}catch{return}for(let s of n)s.isDirectory()&&await Ng(e,pt(t,s.name));ar(pt(e,z),t)===""||ar(pt(e,z),t).startsWith(`..${sr}`)||(await Sl(t)).length===0&&await ZP(t)}async function kn(e){let t=await Yt(e);return{id:t[0].project_id,name:t[0].project_name,org:t[0].org_name}}async function et(e,t){return(await e.studio.get(`/projects/${t}/apps`)).apps}function mt(e,t){let n=e.find(s=>s.slug===t||s.id===t);if(!n)throw new f("no_such_app",`the project has no app ${t}`,{hint:`its apps: ${e.map(s=>s.slug).join(", ")||"none \u2014 palbase apps:create"}`});return n}function rr(e){let t=e.ios?[e.ios.bundle,e.ios.app_clip&&`App Clip ${e.ios.app_clip}`,e.ios.watch&&`watch ${e.ios.watch}`].filter(Boolean).join(", "):e.android?`${e.android.package} (${e.android.fingerprints.map(n=>n.label).join(", ")||"no certificate"})`:e.web?.origins.join(", ")??"";return e.suspended?`${t} \u2014 suspended`:t}var qg={name:"apps:list",summary:"the project's apps, and what each is in every environment it is set in",scope:"environment",async run(e){let t=await kn(e),n=await et(e,t.id);e.out.result({apps:n},()=>{if(n.length===0)return e.out.note(`${t.name} has no app yet: palbase apps:create ios|android|web <name>`);e.out.table(n,[{header:"slug",value:s=>s.slug},{header:"platform",value:s=>s.platform},{header:"name",value:s=>s.deleted_at?`${s.name} (deleted; restorable until ${s.purge_after?.slice(0,10)})`:s.name},{header:"environments",value:s=>s.environments.map(a=>`${a.slug}: ${rr(a)}`).join("; ")||"\u2014"}])})}},Kg={name:"apps:create",summary:"register an app of the project (an iOS app names its Apple team); then set it in each environment (apps:env:set)",usage:"ios|android|web <name> [--slug <slug>] [--team-id <id>] [--app-id-prefix <prefix>]",details:["An app is one product on one platform: its widgets, notification service and other extensions are not apps of their own \u2014 Apple gives them bundles under the app's, and they share its sign-in.","The slug is the app's file in a checkout: palbase/environments/<env>/<slug>.json."],args:{min:2,max:2},flags:{slug:{type:"string",value:"slug",description:"its name in a checkout (default: from the name)"},"team-id":{type:"string",value:"id",description:"an iOS app's Apple team: 10 characters, Apple Developer \u203A Membership"},"app-id-prefix":{type:"string",value:"prefix",description:"an iOS app's App ID prefix when it is not the team's (an app made before 2011, or moved from another team)"}},scope:"environment",async run(e){let[t,n]=e.args;if(t!=="ios"&&t!=="android"&&t!=="web")throw m("the platform is ios, android or web");let s=await kn(e),a=await e.studio.post(`/projects/${s.id}/apps`,{platform:t,name:n,...e.flags.slug?{slug:e.flags.slug}:{},...e.flags["team-id"]?{team_id:e.flags["team-id"]}:{},...e.flags["app-id-prefix"]?{app_id_prefix:e.flags["app-id-prefix"]}:{}});e.out.result(a,()=>{e.out.line(`${s.name} \u203A ${a.name} (${a.platform}, ${a.slug})`),e.out.note(`set it in each environment: palbase apps:env:set ${a.slug} -E <env> ${t==="ios"?"--bundle <bundle id>":t==="android"?"--package <application id> --sha256 <label>=<fingerprint>":"--origin <https://\u2026>"}`)})}},Gg={name:"apps:get",summary:"an app of the project, with what it is and its key in every environment it is set in",usage:"<app>",args:{min:1,max:1},scope:"environment",async run(e){let t=await kn(e),n=mt(await et(e,t.id),e.args[0]);e.out.result(n,()=>{if(e.out.line(`${n.name} \u2014 ${n.platform}, ${n.slug}${n.team_id?`, team ${n.team_id}${n.app_id_prefix?` (App ID prefix ${n.app_id_prefix})`:""}`:""}`),n.deleted_at&&e.out.note(`deleted; restorable until ${n.purge_after} (palbase apps:restore ${n.slug})`),n.environments.length===0)return e.out.note(`in no environment yet: palbase apps:env:set ${n.slug} -E <env> \u2026`);e.out.table(n.environments,[{header:"environment",value:s=>s.slug},{header:"is",value:s=>rr(s)},{header:"publishable key",value:s=>s.key?.key??"\u2014"}])})}},Ug={name:"apps:update",summary:"rename an app, or change an iOS app's Apple team: every environment it is in is told",usage:'<app> [--name <name>] [--team-id <id>] [--app-id-prefix <prefix>|""]',args:{min:1,max:1},flags:{name:{type:"string",value:"name",description:"what it is called"},"team-id":{type:"string",value:"id",description:"an iOS app's Apple team"},"app-id-prefix":{type:"string",value:"prefix",description:`its App ID prefix; "" for the team's`}},scope:"environment",async run(e){let t=await kn(e),n=mt(await et(e,t.id),e.args[0]),s={};if(e.flags.name!==void 0&&(s.name=e.flags.name),e.flags["team-id"]!==void 0&&(s.team_id=e.flags["team-id"]),e.flags["app-id-prefix"]!==void 0&&(s.app_id_prefix=e.flags["app-id-prefix"]===""?null:e.flags["app-id-prefix"]),Object.keys(s).length===0)throw m("nothing to change: --name, --team-id or --app-id-prefix");let a=await e.studio.request("PATCH",`/projects/${t.id}/apps/${n.id}`,s);e.out.result(a,()=>e.out.line(`${a.name} (${a.slug}) \u2014 told to ${a.environments.length} environment(s)`))}},Bg={name:"apps:delete",summary:"delete an app: suspended in every environment for 30 days \u2014 its builds stop reaching the project \u2014 then removed for good",usage:"<app>",args:{min:1,max:1},scope:"environment",async run(e){let t=await kn(e),n=mt(await et(e,t.id),e.args[0]);if(!e.global.yes){if(!e.interactive)throw new f("confirmation_needed",`deleting ${n.name} stops every build of it reaching the project`,{hint:"confirm with -y"});let a=(await e.io.prompt(`Every build of ${n.name} stops reaching ${t.name} at once (restorable for 30 days). Delete it? [y/N] `)).trim().toLowerCase();if(a!=="y"&&a!=="yes")throw new f("cancelled","nothing was changed")}let s=await e.studio.request("DELETE",`/projects/${t.id}/apps/${n.id}`);e.out.result(s,()=>e.out.line(`${s.name} is deleted; palbase apps:restore ${s.slug} brings it back as it was until ${s.purge_after}`))}},zg={name:"apps:restore",summary:"bring a deleted app back as it was, with its keys, in every environment",usage:"<app>",args:{min:1,max:1},scope:"environment",async run(e){let t=await kn(e),n=mt(await et(e,t.id),e.args[0]),s=await e.studio.post(`/projects/${t.id}/apps/${n.id}/restore`);e.out.result(s,()=>e.out.line(`${s.name} is back in ${s.environments.length} environment(s)`))}},hA=/^([a-z][a-z0-9_-]{0,31})=(.+)$/,Wg={name:"apps:env:set",summary:"what an app is in the environment: its bundle (iOS), package and signing certificates (Android) or origins (web)",usage:"<app> [--bundle <id> [--app-clip <id>] [--watch <id>]] [--package <id> --sha256 <label>=<fingerprint>\u2026] [--origin <url>\u2026 --redirect <url>\u2026]",details:["iOS: the app's bundle in this environment; its App Clip and watch app are the bundle followed by one more part. Its extensions are not set: they share the app's.","Android: its application ID and the SHA-256 of each certificate it is signed with \u2014 Play Console \u203A App signing (Google's app signing key, not the upload key), ./gradlew signingReport for a debug key. Label each: debug, play_signing, upload\u2026","Web: the origins its pages are served from (https; http only on this computer) and the addresses a sign-in may return to.","The platform publishes it to Apple and Google for the environment: a device sees a change in a day or so (Apple caches its file; Android 15 re-checks within a week)."],args:{min:1,max:1},flags:{bundle:{type:"string",value:"id",description:"an iOS app's bundle identifier here"},"app-clip":{type:"string",value:"id",description:"its App Clip's bundle (the bundle followed by one more part)"},watch:{type:"string",value:"id",description:"its watch app's bundle (the bundle followed by one more part)"},package:{type:"string",value:"id",description:"an Android app's application ID here"},sha256:{type:"string",multiple:!0,value:"label=fingerprint",description:"a signing certificate's SHA-256, labelled (play_signing=AB:CD:\u2026); every one the app is signed with"},origin:{type:"string",multiple:!0,value:"url",description:"a web app's origin"},redirect:{type:"string",multiple:!0,value:"url",description:"an address a sign-in may return to"}},scope:"environment",async run(e){let t=await b(e),n=mt(await et(e,t.project_id),e.args[0]),s=r=>(e.flags[r]??[]).flatMap(o=>o.split(",")).map(o=>o.trim()).filter(Boolean),a;if(n.platform==="ios"){if(!e.flags.bundle)throw m(`${n.name} is an iOS app: give its bundle here (--bundle)`);a={ios:{bundle:e.flags.bundle,...e.flags["app-clip"]?{app_clip:e.flags["app-clip"]}:{},...e.flags.watch?{watch:e.flags.watch}:{}}}}else if(n.platform==="android"){if(!e.flags.package)throw m(`${n.name} is an Android app: give its package here (--package)`);let r=(e.flags.sha256??[]).map(o=>{let l=hA.exec(o.trim());if(!l)throw m(`--sha256 ${JSON.stringify(o)}: label=fingerprint, like play_signing=AB:CD:\u2026`);return{label:l[1],sha256:l[2]}});a={android:{package:e.flags.package,fingerprints:r}}}else{let r=s("origin");if(r.length===0)throw m(`${n.name} is a web app: give its origins here (--origin)`);let o=s("redirect");a={web:{origins:r,...o.length?{redirects:o}:{}}}}await v(e,t,`set ${n.name} (${n.slug}) here: ${rr(a)}`);let i=await e.studio.request("PUT",`/environments/${t.env_ref}/apps/${n.id}`,a);for(let r of i.warnings)e.out.warn(r);e.out.result(i,()=>{e.out.line(`${n.name} in ${t.env_name}: ${rr(i)}`),i.key&&e.out.line(`its publishable key here: ${i.key.key}`),e.out.note("palbase apps:sync writes its settings into this checkout")})}},Fg={name:"apps:env:unset",summary:"take an app out of the environment: its key there revoked, Apple's and Google's files no longer naming it",usage:"<app>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=mt(await et(e,t.project_id),e.args[0]);await v(e,t,`take ${n.name} out of here: builds of it stop reaching ${t.env_name}`),await e.studio.request("DELETE",`/environments/${t.env_ref}/apps/${n.id}`),e.out.result({app:n.slug,environment:t.env_slug,removed:!0},()=>e.out.line(`${n.name} is out of ${t.env_name}`))}},Jg={name:"apps:sdkconfig",summary:"an app's settings in the environment, as palbase apps:sync writes them: its address, its publishable key, what its modules tell it",usage:"<app> [--format json|env]",details:["The publishable key is public: it ships in the app. A secret key never does."],args:{min:1,max:1},flags:{format:{type:"string",value:"format",description:"json (default) or env"}},scope:"environment",async run(e){let t=await b(e),n=mt(await et(e,t.project_id),e.args[0]),s=e.flags.format??"json";if(s!=="json"&&s!=="env")throw m("--format is json or env");let a=await e.studio.get(`/environments/${t.env_ref}/apps/${n.id}/config`);e.out.result(a,()=>{s==="env"?(e.out.line(`PALBASE_URL=${a.url}`),e.out.line(`PALBASE_PUBLISHABLE_KEY=${a.publishable_key}`)):e.out.line(JSON.stringify(a,null,2))})}},Vg={name:"apps:sync",summary:"write each environment's settings and backend clients (Palbe) of this checkout's apps under palbase/ \u2014 nothing else is touched",usage:"[<app>\u2026] [--check] [--types <env>] [--backend [<machine>=]<dir>] [--as <machine>=<name>]\u2026",args:{min:0,max:20},details:["The apps named join this checkout's (palbase/project.json); with none named, its apps are synced.","palbase/environments/<env>/: each app's settings (<app>.json), each backend's contract (contracts/<machine>.openapi.json) and Palbe client made from it \u2014 TypeScript for a web app, Swift for an iOS app (in palbase/<app>.palbase), Kotlin for an Android app. A web app imports pb from palbase/<app>.ts: one environment's for the editor (--types), the build's mode's for the build (palbase() in vite.config), which type-checks the app against that environment.","--check writes nothing: it exits 1 naming what differs from the project now \u2014 for CI.","--backend makes a backend's Palbe from its checkout on this computer (its palbase/backend app writes its contract and exits; nothing is connected to), to try an endpoint before any machine serves it.","A backend is pb.<name> in the apps \u2014 pb.shopApi.rooms.create() for the machine shop-api \u2014 unless --as names it (--as shop-api=shop): the name is the checkout's, the same in every environment, and none of the client's own (auth, flags, storage, \u2026). Machines of different environments may take one name \u2014 Production's backend and Development's backend-dev both pb.backend with --as backend-dev=backend \u2014 so the app's code builds against either; two machines of one environment may not."],flags:{check:{type:"boolean",description:"write nothing; exit 1 when the checkout is not what the project gives now"},types:{type:"string",value:"env",description:"the environment the editor's types are of (remembered in palbase/project.json)"},backend:{type:"string",value:"[machine=]dir",description:"a backend's checkout here: its Palbe made from the contract it writes, not from its machine's"},as:{type:"string",multiple:!0,value:"machine=name",description:"a backend's name in the apps (pb.<name>): its machine's camelCased unless named; the same in every environment, and another environment's machine may take it too (remembered in palbase/project.json)"}},scope:"environment",async run(e){return xg(e)}};function or(e){let t=new URLSearchParams;for(let[s,a]of Object.entries(e))a!==void 0&&t.set(s,String(a));let n=t.toString();return n===""?"":`?${n}`}function lr(e,t){let n=se(e.flags.limit,"limit");if(n!==void 0&&(n<1||n>t))throw m(`--limit is a whole number from 1 to ${t}`);return n}function dr(e,t){return{limit:{type:"string",value:"n",description:`at most this many (1\u2013${e}, default ${t})`},cursor:{type:"string",value:"cursor",description:"the next page, as the last one said it"}}}var Qt=e=>e?e.slice(0,19).replace("T"," "):"",Vn=(e,t)=>e||t;function pr(e,t,n){t&&e.out.line(`More: palbase ${n} --cursor ${t}`)}function Yg(e){e.out.note("This read is in the project's access log (palbase messaging:access-log).")}function Xg(e){return e.map(t=>`${t.name?A(t.name):"a file"} (${A(t.content_type)}, ${t.size} bytes)`).join(", ")}var Hg="A report is deleted, with what it carries, 190 days after it is resolved; one never resolved, 2 years after it was made.",mA={name:"messaging:reports:list",summary:"the reports people made, newest first: why, whom, which messages (what they carry: messaging:reports:get)",usage:"[--status open|resolved] [--limit <n>] [--cursor <cursor>]",flags:{status:{type:"string",value:"status",description:"only the open ones, or only the resolved ones"},...dr(100,30)},scope:"environment",async run(e){let t=e.flags.status;if(t!==void 0&&t!=="open"&&t!=="resolved")throw m("--status is open or resolved");let n=lr(e,100),s=await b(e),a=await h(e,s,"GET",`/messaging/admin/reports${or({status:t,limit:n,cursor:e.flags.cursor})}`);e.out.result(a,()=>{a.data.length===0&&e.out.line(t===void 0?"No report yet.":`No ${t} report.`),e.out.table(a.data,[{header:"report",value:i=>i.id},{header:"made",value:i=>Qt(i.created_at)},{header:"status",value:i=>i.status==="resolved"?`resolved: ${i.resolution??""}`:"open"},{header:"reason",value:i=>i.reason},{header:"reported",value:i=>Vn(i.reported_user_id,"")},{header:"by",value:i=>Vn(i.reporter_id,"(deleted)")},{header:"messages",value:i=>String(i.message_ids.length)}]),pr(e,a.next_cursor,`messaging:reports:list${t?` --status ${t}`:""}`)})}},gA={name:"messaging:reports:get",summary:"one report with what it carries: the reporter's note, what the messages it names said when reported and before they were edited",usage:"<report id>",details:["An owner's or an admin's (a member lists the reports, without what they carry); the read is in the project's access log. --json carries the messages' files with the keys that open them.","A report of a group a person deleted says who deleted it and when; naming no message, it carries the last 30 messages the reporter saw in it.",Hg],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",`/messaging/admin/reports/${x("the report's id",e.args[0])}`);Yg(e),e.out.note(Hg),e.out.result(n,()=>{e.out.line(`report ${n.id} (${n.status==="resolved"?`resolved ${Qt(n.resolved_at)}: ${A(n.resolution??"")}`:"open"})`),e.out.line(`made ${Qt(n.created_at)} by ${Vn(n.reporter_id,"a user since deleted")}`),e.out.line(`reported ${Vn(n.reported_user_id,"no one in particular")}`),e.out.line(`reason ${A(n.reason)}`),e.out.line(`conversation ${n.conversation_id}${n.conversation_deleted_at?` (group deleted by ${Vn(n.conversation_deleted_by,"a user since deleted")} at ${Qt(n.conversation_deleted_at)})`:""}`),n.note&&e.out.line(`note ${A(n.note)}`);let s=n.messages??[];if(s.length!==0){e.out.line(),e.out.line("What the messages said when reported:");for(let a of s){e.out.line(` #${a.seq} ${Qt(a.created_at)} ${Vn(a.sender_id,"the server")} ${a.kind==="text"||a.text?A(a.text??""):`(${a.kind})`}`),a.attachments.length>0&&e.out.line(` files: ${Xg(a.attachments)}`);for(let i of a.earlier_versions)e.out.line(` before it was edited: ${A(i.text)}, until ${Qt(i.replaced_at)}`)}}})}},fA={name:"messaging:reports:resolve",summary:"resolve a report, saying what came of it in the project's own words",usage:"<report id> --resolution <text>",args:{min:1,max:1},flags:{resolution:{type:"string",value:"text",description:"what came of it: 1 to 64 characters (warned, removed, nothing found\u2026)"}},scope:"environment",async run(e){let t=e.flags.resolution?.trim();if(!t||[...t].length>64)throw m("--resolution says what came of it: 1 to 64 characters");let n=await b(e),s=x("the report's id",e.args[0]);await v(e,n,`resolve the report ${e.args[0]}: ${t}`);let a=await h(e,n,"POST",`/messaging/admin/reports/${s}/resolve`,{resolution:t});e.out.result(a,()=>e.out.line(`Resolved the report ${a.id}: ${A(a.resolution??t)}.`))}},yA={name:"messaging:access-log",summary:"each time people's messages were read or removed \u2014 by the project's server, or an owner or admin from Studio or the CLI \u2014 newest first: what, which conversation, whose, by whom (kept 400 days)",usage:"[--limit <n>] [--cursor <cursor>]",flags:dr(200,50),scope:"environment",async run(e){let t=lr(e,200),n=await b(e),s=await h(e,n,"GET",`/messaging/admin/access-log${or({limit:t,cursor:e.flags.cursor})}`);e.out.result(s,()=>{s.data.length===0&&e.out.line("No read or removal of people's messages yet."),e.out.table(s.data,[{header:"when",value:a=>Qt(a.at)},{header:"what",value:a=>a.action},{header:"messages",value:a=>String(a.count)},{header:"conversation",value:a=>a.conversation_id??""},{header:"person",value:a=>a.user_id??""},{header:"by",value:a=>a.actor},{header:"request",value:a=>a.request_id??""}]),pr(e,s.next_cursor,"messaging:access-log")})}},bA={name:"messaging:conversations:list",summary:"the project's conversations, or a person's with --user, or a space's with --space, the latest first: whose, how many people, when it last moved",usage:"[--user <user id>] [--space <space>] [--limit <n>] [--cursor <cursor>]",flags:{user:{type:"string",value:"user id",description:"only this person's conversations"},space:{type:"string",value:"space",description:"only the conversations of this space (as org:<id>)"},...dr(100,30)},scope:"environment",async run(e){let t=e.flags.user;if(t!==void 0&&t.trim()==="")throw m("--user is a person's id");let n=e.flags.space;if(n!==void 0&&!/^[A-Za-z0-9:_./@-]{1,128}$/.test(n))throw m("--space is 1 to 128 letters, digits and : _ . / @ - (as org:<id>)");let s=lr(e,100),a=await b(e),i=await h(e,a,"GET",`/messaging/admin/conversations${or({user_id:t,space:n,limit:s,cursor:e.flags.cursor})}`);e.out.result(i,()=>{i.data.length===0&&e.out.line(t===void 0?"No conversation yet.":`${t} is in no conversation.`),e.out.table(i.data,[{header:"conversation",value:r=>r.id},{header:"kind",value:r=>r.kind==="group"&&r.visibility==="open"?"group (open)":r.kind},{header:"space",value:r=>r.space??""},{header:"title",value:r=>r.kind==="group"?r.title??"":(r.members??[]).map(o=>o.user_id).join(" \xB7 ")},{header:"people",value:r=>String(r.member_count)},{header:"messages",value:r=>String(r.last_seq)},{header:"last moved",value:r=>Qt(r.last_message_at??r.created_at)}]),pr(e,i.next_cursor,`messaging:conversations:list${t!==void 0?` --user ${t}`:""}${n!==void 0?` --space ${n}`:""}`)})}},wA={name:"messaging:messages:list",summary:"what a conversation said, newest first \u2014 each read in the project's access log",usage:"<conversation id> [--limit <n>] [--cursor <cursor>]",details:["An owner's or an admin's: a member sees the conversations and the reports, not what was said.","--json carries the messages whole, their files with the keys that open them."],args:{min:1,max:1},flags:dr(100,50),scope:"environment",async run(e){let t=lr(e,100),n=await b(e),s=x("the conversation's id",e.args[0]),a=await h(e,n,"GET",`/messaging/admin/conversations/${s}/messages${or({limit:t,cursor:e.flags.cursor})}`);Yg(e),e.out.result(a,()=>{a.data.length===0&&e.out.line("The conversation has said nothing yet.");for(let i of a.data){let r=i.deleted?`(removed${i.removed_reason?`: ${i.removed_reason}`:""})`:i.kind==="system"?`(${i.system?.type??"system"})`:i.text!==null?A(i.text):`(${i.kind})`;e.out.line(`#${i.seq} ${Qt(i.created_at)} ${Vn(i.sender_id,"the server")} ${i.id} ${r}`),!i.deleted&&i.attachments.length>0&&e.out.line(` files: ${Xg(i.attachments)}`)}pr(e,a.next_cursor,`messaging:messages:list ${e.args[0]}`)})}},vA={name:"messaging:messages:delete",summary:"remove a message for everyone in its conversation: what it said and its files go (in the access log)",usage:"<conversation id> <message id>",details:["It is not undone: asked before it is done, whatever the environment (-y confirms)."],args:{min:2,max:2},scope:"environment",async run(e){let[t,n]=e.args,s=x("the conversation's id",t),a=x("the message's id",n),i=await b(e);await v(e,i,`remove the message ${n} of the conversation ${t} for everyone`,"It removes what the message said for everyone in the conversation, and it is not undone"),await h(e,i,"DELETE",`/messaging/admin/conversations/${s}/messages/${a}`),e.out.result({removed:{conversation_id:t,message_id:n}},()=>e.out.line(`Removed the message ${n} for everyone in ${N(i)}; the removal is in the access log.`))}},Zg=[mA,gA,fA,yA,bA,wA,vA];function _A(e){let t=new URLSearchParams;for(let[s,a]of Object.entries(e))a!==void 0&&t.set(s,String(a));let n=t.toString();return n===""?"":`?${n}`}function kA(e,t){let n=se(e.flags.limit,"limit");if(n!==void 0&&(n<1||n>t))throw m(`--limit is a whole number from 1 to ${t}`);return n}function SA(e,t){return{limit:{type:"string",value:"n",description:`at most this many (1\u2013${e}, default ${t})`},cursor:{type:"string",value:"cursor",description:"the next page, as the last one said it"}}}var ur=e=>e?e.slice(0,19).replace("T"," "):"";function $A(e,t,n){t&&e.out.line(`More: palbase ${n} --cursor ${t}`)}function $l(e){return!e.answered_at||!e.ended_at?"":String(Math.max(0,Math.round((Date.parse(e.ended_at)-Date.parse(e.answered_at))/1e3)))}var Qg=e=>e.video?"video":"voice";function PA(e){if(e<1e3)return`${e} B`;let t=["kB","MB","GB","TB"],n=e/1e3,s=0;for(;n>=1e3&&s<t.length-1;)n/=1e3,s+=1;return`${n>=100?Math.round(n):Math.round(n*10)/10} ${t[s]}`}var AA=["ringing","active","ended"],RA={name:"calls:list",summary:"the project's calls, or a person's with --user, newest first: kind, voice or video, state, why it ended, who called, how many were in it, how long",usage:"[--user <user id> [--missed]] [--state ringing|active|ended] [--limit <n>] [--cursor <cursor>]",details:["A call's length is from its answer to its end, in seconds: a group call, which no one answers, has its people's seconds in calls:get."],flags:{user:{type:"string",value:"user id",description:"only this person's calls"},missed:{type:"boolean",description:"with --user: only the calls they missed (or were busy for)"},state:{type:"string",value:"state",description:"only the calls ringing, going on (active), or over (ended)"},...SA(100,20)},scope:"environment",async run(e){let t=e.flags.user;if(t!==void 0&&t.trim()==="")throw m("--user is a person's id");let n=e.flags.missed===!0;if(n&&t===void 0)throw m("--missed says whose: give --user with it");let s=e.flags.state;if(s!==void 0&&!AA.includes(s))throw m("--state is ringing, active or ended");let a=kA(e,100),i=await b(e),r=await h(e,i,"GET",`/calls/admin/calls${_A({user_id:t,missed:n?"true":void 0,state:s,limit:a,cursor:e.flags.cursor})}`);e.out.result(r,()=>{r.calls.length===0&&e.out.line(`No ${n?"missed ":""}${s?`${s} `:""}call${t!==void 0?` of ${t}`:n||s?"":" yet"}.`),e.out.table(r.calls,[{header:"call",value:l=>l.id},{header:"started",value:l=>ur(l.created_at)},{header:"kind",value:l=>l.kind},{header:"media",value:Qg},{header:"state",value:l=>l.state},{header:"end reason",value:l=>l.end_reason??""},{header:"caller",value:l=>l.caller_id},{header:"people",value:l=>String(l.participants.length)},{header:"seconds",value:$l}]);let o=[t!==void 0?` --user ${t}`:"",n?" --missed":"",s?` --state ${s}`:""].join("");$A(e,r.next_cursor,`calls:list${o}`)})}},TA={name:"calls:get",summary:"one call with its people and bots: how each was in it (rung, joined, left, declined, missed, busy), for how many seconds, and what the media server sent them",usage:"<call id>",details:["Every call's media goes through the platform's media server, and a call is billed by the data it sent the call's people: each one's, in bytes, is as its meter last told it (up to a minute behind).","--json carries the call whole: its people's names and pictures, the caller's app's words about it (metadata), each one's bytes."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",`/calls/admin/calls/${x("the call's id",e.args[0])}`);e.out.result(n,()=>{e.out.line(`call ${n.id}`),e.out.line(`kind ${n.kind}, ${Qg(n)}${n.ring?"":", rings no one"}`),e.out.line(`state ${n.state}${n.end_reason?`: ${n.end_reason}${n.ended_by?` by ${n.ended_by}`:""}`:""}`),e.out.line(`caller ${n.caller_id}`),e.out.line(`started ${ur(n.created_at)}`),n.answered_at&&e.out.line(`answered ${ur(n.answered_at)}`),n.ended_at&&e.out.line(`ended ${ur(n.ended_at)}${$l(n)?`, after ${$l(n)} s`:""}`),n.conversation_id&&e.out.line(`conversation ${n.conversation_id}`),e.out.line(`holds at most ${n.max_participants}`),e.out.line(),e.out.table(n.participants,[{header:"user",value:s=>s.user_id},{header:"kind",value:s=>s.kind},{header:"role",value:s=>s.role},{header:"state",value:s=>s.state},{header:"seconds",value:s=>String(s.seconds)},{header:"data",value:s=>PA(s.bytes)}])})}},EA={name:"calls:end",summary:"end a call for everyone in it (asked before it is done, whatever the environment)",usage:"<call id>",details:["It is not undone: asked before it is done, whatever the environment (-y confirms). A call already over is left as it is."],args:{min:1,max:1},scope:"environment",async run(e){let t=x("the call's id",e.args[0]),n=await b(e);await v(e,n,`end the call ${e.args[0]} for everyone in it`,"It ends the call for everyone in it, and it is not undone");let s=await h(e,n,"POST",`/calls/admin/calls/${t}/end`);e.out.result(s,()=>e.out.line(s.end_reason&&s.end_reason!=="ended"?`The call ${s.id} was already over: ${s.end_reason}.`:`Ended the call ${s.id} for everyone in it in ${N(n)}.`))}},ef=[RA,TA,EA];var CA=/^[A-Z][A-Z0-9_]{0,127}$/;function Sn(e,t){return`/environments/${x("the environment's ref",e.env_ref)}/webhooks${t!==void 0?`/${x("the webhook's id",t)}`:""}`}function tf(e){return oe(e.flags.events)}function cr(e){let t=e.machine?`, the machine ${A(e.machine)}'s \u2014 kept by the platform to what its app takes`:"",n=e.created_by?`, made by ${A(e.created_by.name)}${e.created_by.id.startsWith("tok_")?" (access token)":e.created_by.id.startsWith("etk_")?" (environment token)":""}`:"";return`${A(e.url)} \u2014 ${e.events.length===0?"every event":A(e.events.join(", "))} (${A(e.id)}${t}${n})`}function jA(e,t){let n=t.find(a=>a.id===e.endpoint_id)?.url??`${e.endpoint_id} (no longer an endpoint)`,s=e.redelivered_at?`; redelivered ${A(e.redelivered_at)}`:e.redeliver_asked_at?"; redelivery asked":e.redelivery_error?`; redelivery failed: ${A(e.redelivery_error)}`:"";return`${A(e.id)} ${A(e.event_type)} ${A(e.event_id)} \u2192 ${A(n)} \u2014 ${A(e.last_error)} (${A(String(e.attempts))} tries, given up ${A(e.failed_at)})${s}`}var OA={name:"webhooks:list",summary:"the environment's webhook endpoints: where its events go, which (never their secrets)",scope:"environment",async run(e){let t=await b(e),{endpoints:n}=await e.studio.get(Sn(t));e.out.result({endpoints:n},()=>{n.length===0&&e.out.line("No webhook endpoint yet: palbase webhooks:create <url> makes one.");for(let s of n)e.out.line(cr(s))})}},MA={name:"webhooks:create",summary:"add a webhook endpoint; its signing secret is printed this once, or kept in a secret with --secret-to",usage:"<url> [--events <a,b>] [--secret-to <NAME> [--dev]]",details:["A machine is given its own endpoint and its secret (PALBASE_WEBHOOK_SECRET) by the platform, for the events its app takes: this is for another receiver. --secret-to keeps the secret in the environment's secrets (production; --dev: development) and prints it nowhere."],args:{min:1,max:1},flags:{events:{type:"string",value:"list",description:"the events it is sent, comma-separated (user.deleted, \u2026); none: every event"},"secret-to":{type:"string",value:"NAME",description:"keep its signing secret in the environment's secret NAME instead of printing it"},dev:{type:"boolean",description:"with --secret-to: the development secrets, not production"}},scope:"environment",async run(e){let t=await b(e),n=e.flags["secret-to"];if(n!==void 0&&!CA.test(n))throw m(`--secret-to ${JSON.stringify(n)} is not a secret's name: capital letters, digits and _, a letter first`);if(e.flags.dev===!0&&n===void 0)throw m("--dev goes with --secret-to <NAME>");let s=e.flags.dev===!0?"development":"production";await v(e,t,`add the webhook endpoint ${e.args[0]}${n?`, its secret kept in ${n} (${s})`:""}`);let a=await e.studio.post(Sn(t),{url:e.args[0],events:tf(e)??[]}),{secret:i,...r}=a;if(n!==void 0){let o=await h(e,t,"PUT",`/secrets/${s}/${n}`,{value:i});e.out.result({endpoint:r,secret_to:{set:s,name:n,version:o.version}},()=>e.out.line(`Added ${cr(r)}; its secret is ${n} (${s}, v${o.version}) in ${N(t)}.`));return}e.out.result(a,()=>{e.out.line(`Added ${cr(r)}.`),e.out.line(`signing secret (shown this once): ${i}`)})}},IA={name:"webhooks:update",summary:"change a webhook endpoint's address or events (its secret stays)",usage:'<id> [--url <url>] [--events <a,b>|""]',args:{min:1,max:1},flags:{url:{type:"string",value:"url",description:"where it is delivered now"},events:{type:"string",value:"list",description:'the events it is sent now, comma-separated; "" for every event'}},scope:"environment",async run(e){let t=await b(e);if(e.flags.url===void 0&&e.flags.events===void 0)throw m("nothing to change: --url or --events");let{endpoints:n}=await e.studio.get(Sn(t)),s=n.find(i=>i.id===e.args[0]);if(!s)throw m(`the environment has no webhook endpoint ${JSON.stringify(e.args[0])}`,"palbase webhooks:list shows them");await v(e,t,`change the webhook endpoint ${s.url}`);let a=await e.studio.request("PUT",Sn(t,s.id),{url:e.flags.url??s.url,events:tf(e)??s.events});e.out.result(a,()=>e.out.line(`Changed: ${cr(a)}.`))}},LA={name:"webhooks:delete",summary:"remove a webhook endpoint: its events are no longer delivered there",usage:"<id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e);await v(e,t,`remove the webhook endpoint ${e.args[0]}`),await e.studio.request("DELETE",Sn(t,e.args[0])),e.out.result({deleted:e.args[0]},()=>e.out.line(`Removed the webhook endpoint ${e.args[0]}.`))}},DA={name:"webhooks:deliveries:list",summary:"the deliveries the platform gave up on after its tries, still owed (--failed), or every one kept 30 days (--all)",usage:"[--failed] [--all]",flags:{failed:{type:"boolean",description:"those it gave up on and still owes (the default)"},all:{type:"boolean",description:"every one kept, those delivered again among them"}},scope:"environment",async run(e){let t=await b(e),[{deliveries:n},{endpoints:s}]=await Promise.all([e.studio.get(`${Sn(t)}/deliveries${e.flags.all===!0?"?all=true":"?failed=true"}`),e.studio.get(Sn(t))]);e.out.result({deliveries:n},()=>{n.length===0&&e.out.line("No failed delivery: every event reached its endpoints.");for(let a of n)e.out.line(jA(a,s))})}},xA={name:"webhooks:deliveries:redeliver",summary:"send a failed delivery again: the same event, its id and body, to the endpoint it failed at, within seconds",usage:"<id>",details:["As Stripe's Resend: the receiver takes an event more than once by its Palbase-Event-Id. An admin's; it is written to the organization's audit log."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e);await v(e,t,`send the failed delivery ${e.args[0]} again`);let n=await e.studio.post(`${Sn(t)}/deliveries/${x("the delivery's id",e.args[0])}/redeliver`,{});e.out.result(n,()=>e.out.line(`Asked: ${A(n.event_type)} ${A(n.event_id)} goes to its endpoint again within seconds (palbase webhooks:deliveries:list --all shows when it went).`))}},nf=[OA,MA,IA,LA,DA,xA];import{constants as hr,createReadStream as NA}from"node:fs";import{mkdir as qA,open as KA,readdir as GA,realpath as sf,stat as lf}from"node:fs/promises";import{dirname as af,extname as UA,join as df,relative as BA,resolve as rf,sep as mr}from"node:path";import{Readable as pf}from"node:stream";import{pipeline as zA}from"node:stream/promises";var uf=600;function Oa(e){let t=/^([a-z0-9][a-z0-9_-]{0,62}):(.*)$/.exec(e);return!t||e.startsWith("/")||e.startsWith(".")?null:{bucket:t[1],path:t[2].replace(/^\/+/,"")}}function gr(e){if(e.split("/").some(n=>n===""||n==="."||n===".."))throw new f("unsafe_path",`the object ${JSON.stringify(e)} has a name no request can carry`);return encodeURIComponent(e)}async function Pl(e,t,n,s){let a=[],i;do{let r=new URLSearchParams({limit:"1000",...s?{prefix:s}:{},...i?{cursor:i}:{}}),o=await h(e,t,"GET",`/storage/buckets/${x("the bucket",n)}/objects?${r}`);a.push(...o.objects),i=o.next_cursor}while(i);return a}async function cf(e,t,n,s){let a;try{a=await e.io.fetch(t,{...n,redirect:"manual"})}catch(i){throw new f("network_error",`${s}: ${i instanceof Error?i.message:String(i)}`)}if(!a.ok){let i=await a.json().catch(()=>({}));throw new f(i.error??`http_${a.status}`,`${s}: ${i.error_description??i.error??`answered ${a.status}`}`)}return a}var WA={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif",".avif":"image/avif",".svg":"image/svg+xml",".ico":"image/x-icon",".pdf":"application/pdf",".json":"application/json",".txt":"text/plain",".csv":"text/csv",".html":"text/html",".css":"text/css",".js":"text/javascript",".xml":"application/xml",".zip":"application/zip",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".m4a":"audio/mp4"};function of(e){return WA[UA(e).toLowerCase()]}async function Al(e,t,n,s,a,i){let r=(await lf(n)).size,o=await h(e,t,"POST",`/storage/buckets/${x("the bucket",s)}/upload-urls`,{path:a,expires_in:uf,...i?{owner_id:i}:{}});return await cf(e,o.url,{method:"PUT",body:pf.toWeb(NA(n)),headers:{"content-length":String(r),...of(n)?{"content-type":of(n)}:{}},duplex:"half"},`${n} \u2192 ${s}:${a}`),r}function FA(e,t){let n=t.split("/");if(t===""||n.some(a=>a===""||a==="."||a===".."||a.includes("\\")||a.includes("\0")))throw new f("unsafe_path",`the object ${JSON.stringify(t)} has a name no file here can take`);let s=df(e,...n);if(!s.startsWith(e+mr))throw new f("unsafe_path",`${t} would land outside ${e}`);return s}async function JA(e,t,n,s,a,i){let r=await h(e,t,"POST",`/storage/buckets/${x("the bucket",n)}/signed-urls`,{path:s,expires_in:uf}),o=await cf(e,r.url,{method:"GET"},`${n}:${s} \u2192 ${a}`);if(await qA(af(a),{recursive:!0}),i!==void 0){let[g,y]=await Promise.all([sf(i),sf(af(a))]);if(y!==g&&!y.startsWith(g+mr))throw new f("unsafe_path",`${s} would land outside ${i} (through a link)`)}let d=(await KA(a,hr.O_WRONLY|hr.O_CREAT|hr.O_TRUNC|hr.O_NOFOLLOW)).createWriteStream();if(!o.body)return await new Promise((g,y)=>d.on("error",y).end(g)),0;let p=0,u=pf.fromWeb(o.body).on("data",g=>{p+=g.length});return await zA(u,d),p}async function hf(e){let t=[];for(let n of await GA(e,{withFileTypes:!0})){let s=df(e,n.name);n.isDirectory()?t.push(...await hf(s)):n.isFile()&&t.push(s)}return t}var VA={name:"storage:ls",summary:"a bucket's objects, or those under a prefix: path, size, type",usage:"<bucket>[:prefix]",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=Oa(e.args[0].includes(":")?e.args[0]:`${e.args[0]}:`);if(!n)throw m(`${e.args[0]} is not a bucket (bucket or bucket:prefix)`);let s=await Pl(e,t,n.bucket,n.path);e.out.result({bucket:n.bucket,objects:s},()=>{s.length===0&&e.out.line(`Nothing in ${n.bucket}:${n.path}`);for(let a of s)e.out.line(`${a.path} ${a.size} ${a.content_type??""}`)})}},HA={name:"storage:cp",summary:"copy files between this computer and a bucket: a file, or a folder whole with -r",usage:"<from> <to> [-r] [--owner <user id>]",details:["bucket:path names an object of the environment; anything else is a path on this computer.","Up: a file to bucket:path (a path ending in / keeps the file name); with -r, a folder to bucket:prefix, its paths kept.","Down: bucket:path to a file; with -r, every object under bucket:prefix into a folder."],args:{min:2,max:2},flags:{recursive:{type:"boolean",short:"r",description:"a folder (up) or a prefix (down), whole"},owner:{type:"string",value:"user id",description:"the user uploaded objects belong to (deleted with them)"}},scope:"environment",async run(e){let t=await b(e),[n,s]=e.args,a=Oa(n),i=Oa(s),r=e.flags.recursive===!0,o=e.flags.owner;if(a&&i)throw m("one side is a bucket and the other this computer (bucket-to-bucket: the storage API copies within a bucket)");if(!a&&!i)throw m("one side is bucket:path");let l=0,d=0;if(i){let p=rf(e.io.cwd,n),u=r?await hf(p):[p];if(!r&&(await lf(p)).isDirectory())throw m(`${n} is a folder: copy it with -r`);await v(e,t,`upload ${u.length} file${u.length===1?"":"s"} to ${i.bucket}:${i.path} in ${N(t)}`);for(let g of u){let y=r?BA(p,g).split(mr).join("/"):g.split(mr).pop(),w=r||i.path===""||i.path.endsWith("/")?`${i.path.replace(/\/?$/,i.path?"/":"")}${y}`:i.path;d+=await Al(e,t,g,i.bucket,w,o),l++,u.length>1&&e.out.note(`${l}/${u.length} ${w}`)}}else if(a){let p=rf(e.io.cwd,s),u=r?await Pl(e,t,a.bucket,a.path):[{path:a.path,size:0}];for(let g of u){let y=r?g.path.slice(a.path.length).replace(/^\/+/,""):"",w=r?FA(p,y):p;d+=await JA(e,t,a.bucket,g.path,w,r?p:void 0),l++,u.length>1&&e.out.note(`${l}/${u.length} ${g.path}`)}}e.out.result({copied:l,bytes:d},()=>e.out.line(`Copied ${l} file${l===1?"":"s"} (${d} bytes).`))}},YA={name:"storage:rm",summary:"delete an object, or every object under a prefix with -r",usage:"<bucket:path> [-r]",args:{min:1,max:1},flags:{recursive:{type:"boolean",short:"r",description:"every object under the prefix"}},scope:"environment",async run(e){let t=await b(e),n=Oa(e.args[0]);if(!n||!n.path&&e.flags.recursive!==!0)throw m(`${e.args[0]} is not bucket:path`);let s=e.flags.recursive===!0?(await Pl(e,t,n.bucket,n.path)).map(a=>a.path):[n.path];await v(e,t,`delete ${s.length} object${s.length===1?"":"s"} from ${n.bucket} in ${N(t)}`);for(let a of s)await h(e,t,"DELETE",`/storage/buckets/${x("the bucket",n.bucket)}/objects/${gr(a)}`);e.out.result({deleted:s.length},()=>e.out.line(`Deleted ${s.length} object${s.length===1?"":"s"}.`))}},XA={name:"storage:url",summary:"a signed download URL for one object",usage:"<bucket:path> [--expires <seconds>]",args:{min:1,max:1},flags:{expires:{type:"string",value:"seconds",description:"how long it works (default 3600, at most 604800)"}},scope:"environment",async run(e){let t=await b(e),n=Oa(e.args[0]);if(!n||!n.path)throw m(`${e.args[0]} is not bucket:path`);let s=e.flags.expires===void 0?3600:Number(e.flags.expires);if(!Number.isInteger(s)||s<1||s>604800)throw m("--expires is 1 to 604800 seconds");let a=await h(e,t,"POST",`/storage/buckets/${x("the bucket",n.bucket)}/signed-urls`,{path:n.path,expires_in:s});e.out.result(a,()=>e.out.line(a.url))}},mf=[VA,HA,YA,XA];import{openAsBlob as ZA}from"node:fs";import{readFile as QA,stat as eR}from"node:fs/promises";import{resolve as vf}from"node:path";var wr=/^[a-z][a-z0-9_-]{0,63}$/,gf=["backend","client","https","mcp","platform"];function en(e,t,n=0){let s=e.args[n];if(!wr.test(s))throw m(`${JSON.stringify(s)} is not ${t}'s name: lowercase letters, digits, _ and -, a letter first, at most 64`);return s}function Tt(e,t){let n=se(e,t);if(n===0)throw m(`--${t} is a whole number from 1`);return n}function qt(e){let t=new URLSearchParams;for(let[s,a]of Object.entries(e))a!==void 0&&t.set(s,String(a));let n=t.toString();return n===""?"":`?${n}`}async function ff(e,t,n){let s;try{s=await QA(vf(e.io.cwd,t),"utf8")}catch(a){throw new f("unreadable_file",`${t} could not be read: ${a instanceof Error?a.message:String(a)}`)}return me(s,n)}var fr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yr=e=>`$${e<.01&&e>0?e.toPrecision(2):e.toFixed(e<1?4:2)}`,br=e=>`$${e.toFixed(2)}`,_f="or connect the environment's own key for the model's provider, which its provider bills: palbase ai:providers:set <provider>",Rl=`raise the budget in Studio \u203A AI \u203A Settings or with palbase ai:settings:set --monthly-budget <usd>; ${_f}`,Tl=`move its project to Pay as you go in Studio \u203A Billing or with palbase billing:project --plan pay_as_you_go (its organization paid for by a payment account with a card, not held); ${_f}`;function kf(e){if(!(e instanceof E))return e;switch(e.code){case"ai_budget_reached":return new f(e.code,"the environment's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or the budget is raised",{hint:Rl});case"ai_payment_required":return new f(e.code,"the month's free AI dollar is spent and the environment has nothing to pay for Palbase's models with: it is on Free, or its payment account is held",{hint:Tl});case"provider_key_required":return new f(e.code,"Palbase's models do not serve the environment, and it has no key of its own for the model's provider",{hint:"connect one: palbase ai:providers:set <provider> (palbase ai:spend says why)"});case"billing_unavailable":return new f(e.code,`Palbase's billing did not say whether its models serve the environment${e.retryAfter!==void 0?`: try again in ${e.retryAfter} s`:"; try again shortly"}`);default:return e}}function tR(e){if(e===void 0)return;let t={};for(let n of Array.isArray(e)?e:[e]){let s=String(n),a=s.indexOf("=");if(a<=0)throw m(`--metadata is key=value, not ${JSON.stringify(s)}`);Object.defineProperty(t,s.slice(0,a),{value:s.slice(a+1),enumerable:!0,writable:!0,configurable:!0})}return t}var nR={name:"ai:usage",summary:"the environment's uses of models, newest first: what each was, what it cost, and whose key it went out with",usage:"[--kind text|embedding|image] [--metadata key=value]\u2026 [--limit <n>] [--cursor <cursor>]",flags:{kind:{type:"string",value:"kind",description:"only uses of this kind: text, embedding or image"},metadata:{type:"string",multiple:!0,value:"key=value",description:"only uses carrying this label (repeat for several): a product's spend, a task's"},limit:{type:"string",value:"n",description:"at most this many (1\u2013500, default 50)"},cursor:{type:"string",value:"cursor",description:"the next page, as the last one said it"}},scope:"environment",async run(e){let t=e.flags.kind;if(t!==void 0&&!["text","embedding","image"].includes(t))throw m("--kind is text, embedding or image");let n=tR(e.flags.metadata),s=Tt(e.flags.limit,"limit"),a=await b(e),i=await h(e,a,"GET",`/ai/usage${qt({kind:t,limit:s,cursor:e.flags.cursor,metadata:n&&JSON.stringify(n)})}`);e.out.result(i,()=>{i.usage.length===0&&e.out.line("No use of a model yet."),e.out.table(i.usage,[{header:"when",value:r=>r.created_at},{header:"kind",value:r=>r.kind},{header:"model",value:r=>r.model},{header:"tokens",value:r=>`${r.kind==="image"?`${r.items} picture(s)`:`${r.input_tokens} in / ${r.output_tokens} out`}${r.estimated?" (estimate)":""}`},{header:"cost",value:r=>yr(r.cost_nano_usd/1e9)},{header:"key",value:r=>r.connection_owner==="project"?"project's":"platform's"},{header:"labels",value:r=>Object.entries(r.metadata??{}).map(([o,l])=>`${o}=${l}`).join(" ")}]),i.usage.some(r=>r.estimated)&&e.out.line("(estimate): a reasoning call cut before its answer \u2014 its provider never said what its hidden thinking came to, so it is billed as the time the model thought at its measured speed, rounded down."),i.next_cursor&&e.out.line(`More: palbase ai:usage --cursor ${i.next_cursor}`)})}},sR={name:"ai:models",summary:"the models the environment may name \u2014 every text model with its rungs, window and price, and the embedding and picture models",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/ai/models");e.out.result(n,()=>{e.out.line("Text models (an agent's or an answer's model by its name; none named is the default):"),n.chat.length===0?e.out.line("None listed for the environment just now: name none for the default, or connect a provider's key (ai:providers:set) to list its models."):e.out.table(n.chat,[{header:"name",value:s=>`${s.name}${s.default?" (default)":""}`},{header:"model",value:s=>s.display_name},{header:"deprecated",value:s=>s.deprecated?`since ${s.deprecated.since}: use ${s.deprecated.use_instead}`:"-"},{header:"efforts",value:s=>s.efforts.join(",")||"-"},{header:"window",value:s=>String(s.context_window)},{header:"$/M in",value:s=>String(s.price.input_usd_per_mtok)},{header:"$/M out",value:s=>String(s.price.output_usd_per_mtok)}]),e.out.line(),e.out.line("Embedding models:"),e.out.table(n.embeddings,[{header:"name",value:s=>`${s.name}${s.default?" (default)":""}`},{header:"dimensions",value:s=>String(s.dimensions)},{header:"$/M in",value:s=>String(s.input_usd_per_mtok)}]),e.out.line(),e.out.line("Picture models:"),e.out.table(n.images,[{header:"name",value:s=>`${s.name}${s.default?" (default)":""}`},{header:"$/M picture out",value:s=>String(s.image_output_usd_per_mtok)}]),n.unavailable.length>0&&e.out.line(`Not listed just now (their models are missing until they answer): ${n.unavailable.join(", ")}`)})}},aR={free:"Free \u2014 its project's free dollar a month, then its own provider keys",pay_as_you_go:"Pay as you go \u2014 past the project's free dollar, its payment account pays: the provider's price and 10%",exempt:"exempt \u2014 measured, not charged"},iR={name:"ai:spend",summary:"what Palbase's models cost the environment this month: its project's free dollar and what is left of it to it, the monthly budget, and whether they serve it now \u2014 and if not, why",details:["Palbase's models are the platform's provider keys. A month brings a project a dollar of them free, its environments together: what is left of it to this one is what its other environments have not spent. Past it a Free project's environments use their own provider keys (ai:providers:set); a Pay as you go project's payment account pays, at the provider's price and 10%.","Its own provider keys always serve it, and are not counted here: their provider bills them."],scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/ai/spend");e.out.result(n,()=>{if(e.out.line(`month ${n.month} (UTC; starts again ${n.resets_on})`),e.out.line(`plan ${aR[n.plan]??n.plan}`),e.out.line(`spent ${yr(n.spent_usd)} on Palbase's models, at what it is billed, before the free dollar`),e.out.line(`free ${br(n.free_usd)} this month: what its project's other environments left of its free dollar${n.free_left_usd===null?"":` \u2014 ${yr(n.free_left_usd)} left`}`),e.out.line(`monthly budget ${n.monthly_budget_usd===null?"none":br(n.monthly_budget_usd)}`),n.platform_keys){e.out.line("Palbase's models serve the environment now");return}n.reason==="budget"?(e.out.line(`Palbase's models do not serve the environment: its monthly budget is spent \u2014 until ${n.resets_on}, or until it is raised`),e.out.line(` ${Rl[0].toUpperCase()}${Rl.slice(1)}.`)):n.reason==="payment"?(e.out.line("Palbase's models do not serve the environment: its project's free dollar is spent and it has no paid rights now (it is on Free, at its month's limit, or its payment account has an unpaid charge)"),e.out.line(` ${Tl[0].toUpperCase()}${Tl.slice(1)}.`)):(e.out.line("Palbase's models do not serve the environment"),e.out.line(" Connect the environment's own key for a provider: palbase ai:providers:set <provider>."))})}},rR={name:"ai:providers:list",summary:"the providers the environment calls with its own key (never the keys): its calls go out with them instead of the platform's",scope:"environment",async run(e){let t=await b(e),{providers:n}=await h(e,t,"GET","/ai/providers");e.out.result({providers:n},()=>{n.length===0&&e.out.line("No key of the environment's own: its calls go out with the platform's."),e.out.table(n,[{header:"provider",value:s=>s.name},{header:"verified",value:s=>s.verified?"yes":"no"},{header:"key",value:()=>"set"}])})}},oR={name:"ai:providers:set",summary:"call a provider with the environment's own key: the key is piped in or typed unseen, never shown or put on the command line",usage:"<provider> [--key-stdin] < key.txt",details:["Without --key-stdin the key is asked for at the terminal, and not echoed as it is typed or pasted."],args:{min:1,max:1},flags:{"key-stdin":{type:"boolean",description:"read the key from stdin (a pipe, a file)"}},scope:"environment",async run(e){let t=e.args[0];if(!/^[a-z][a-z0-9-]{0,31}$/.test(t))throw m(`${JSON.stringify(t)} is not a provider's name (openai, anthropic, google\u2026)`);if(e.flags["key-stdin"]!==!0&&!e.interactive)throw m(`${t}'s key is read from stdin`,`pipe it in: palbase ai:providers:set ${t} --key-stdin < key.txt`);let n=await b(e),s=await Me(e,`${t}'s key`);await v(e,n,`call ${t} with the environment's own key`);let a=await h(e,n,"PUT",`/ai/providers/${k(t)}`,{key:s});e.out.result(a,()=>e.out.line(`${a.name}'s calls go out with the environment's own key from now on${a.verified?"":" (the provider did not confirm it: check the key)"}; it is kept sealed.`))}},lR={name:"ai:providers:remove",summary:"forget the environment's own key for a provider: its calls go out with the platform's again",usage:"<provider>",args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0],n=await b(e);await v(e,n,`forget the environment's own ${t} key`),await h(e,n,"DELETE",`/ai/providers/${k(t)}`),e.out.result({removed:t},()=>e.out.line(`${t}'s calls go out with the platform's key again.`))}};function Sf(e,t){e.out.line(`clients ${t.clients?"on: the app's users talk to the agents with their own session":"off: the server starts and writes every chat"}`),e.out.line(`messages per minute ${t.user_messages_per_minute} a user`),e.out.line(`history kept ${t.history_bytes} bytes of ${t.history_limit_bytes===null?"no fixed limit":`${t.history_limit_bytes} at most`}`);let n=t.monthly_budget_usd??null;e.out.line(`monthly budget ${n===null?"none: Palbase's models are not capped":`${br(n)} a month on Palbase's models`}`)}function dR(e){if(e===void 0)return;let t=String(e);if(t==="none")return null;let n=/^\d{1,7}(\.\d{1,2})?$/.test(t)?Number(t):NaN;if(!(n>=.01&&n<=1e6))throw m(`--monthly-budget is US dollars from 0.01 to 1000000, cents at most, or none \u2014 not ${JSON.stringify(t)}`,"palbase ai:settings:set --monthly-budget 25");return n}var pR={name:"ai:settings:get",summary:"what the environment allows its chats \u2014 whether the app's users talk to the agents, how often, how much history is kept \u2014 and its monthly AI budget",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/ai/settings");e.out.result(n,()=>Sf(e,n))}},uR={name:"ai:settings:set",summary:"change what the environment allows its chats, and its monthly AI budget: a setting left out is left as it is",usage:"[--clients on|off] [--messages-per-minute <n>] [--history-limit <bytes>|none] [--monthly-budget <usd>|none]",details:["--monthly-budget is the most the environment spends a month on Palbase's models (the platform's provider keys), at what it is billed: past it a call they would serve is refused (ai_budget_reached) until the month turns (UTC) or the budget is raised, and the organization's owners are emailed once. Its own provider keys are not counted: their provider bills them. palbase ai:spend says what is spent.","Only an owner or an admin of the organization sets it, as themselves: a member's change of it is refused, and so is a key's or a token's \u2014 what spends the money does not raise its own limit."],flags:{clients:{type:"string",value:"on|off",description:"the app's users talk to the agents of their chats with their own session"},"messages-per-minute":{type:"string",value:"n",description:"how many messages one user sends a minute (1\u2013600)"},"history-limit":{type:"string",value:"bytes|none",description:"the chat history kept at most, in bytes; none: the plan's"},"monthly-budget":{type:"string",value:"usd|none",description:"the most spent a month on Palbase's models, in US dollars (0.01\u20131000000, cents at most); none: no budget"}},scope:"environment",async run(e){let t={},n=e.flags.clients;if(n!==void 0){if(!["on","off"].includes(n))throw m("--clients is on or off");t.clients=n==="on"}let s=Tt(e.flags["messages-per-minute"],"messages-per-minute");s!==void 0&&(t.user_messages_per_minute=s);let a=e.flags["history-limit"];a!==void 0&&(a==="none"?t.history_limit_bytes=null:t.history_limit_bytes=Tt(a,"history-limit"));let i=dR(e.flags["monthly-budget"]);if(i!==void 0&&(t.monthly_budget_usd=i),Object.keys(t).length===0)throw m("nothing to change","pass --clients, --messages-per-minute, --history-limit or --monthly-budget");let r=await b(e),o=Object.keys(t).filter(p=>p!=="monthly_budget_usd"),l=[...o.length>0?[`change what the chats are allowed: ${o.join(", ")}`]:[],...i===void 0?[]:[i===null?"take away the monthly AI budget":`set the monthly AI budget to ${br(i)}`]];await v(e,r,l.join("; "));let d;try{d=await h(e,r,"PUT","/ai/settings",t)}catch(p){throw i===void 0?p:cR(p)}e.out.result(d,()=>Sf(e,d))}};function cR(e){return e instanceof E?e.status===403?new f(e.code,"only an owner or an admin of the organization sets the environment's monthly AI budget, as themselves: a member's change of it is refused, and so is a key's or a token's",{hint:"ask an owner or an admin to set it \u2014 in Studio \u203A AI \u203A Settings, or with palbase ai:settings:set --monthly-budget signed in as themselves (palbase login)"}):e.code==="no_billing"?new f(e.code,"this stack bills no AI, so it keeps no monthly AI budget: nothing was changed"):e.code==="registry_unavailable"?new f(e.code,"Palbase's billing did not answer: nothing was changed",{hint:"run the command again shortly"}):e:e}function El(e){return e.source==="code"?`the backend's code (machine ${e.machine??"backend"})`:e.published_version===null||e.published_version===void 0?`a draft (revision ${e.revision??"?"}), not published`:`version ${e.published_version} published${e.unpublished_changes?`, the draft (revision ${e.revision}) changed since`:""}`}var hR={name:"ai:agents:list",summary:"the environment's agents: its backend's (its build's contract names them) and those it keeps, a draft and published versions",scope:"environment",async run(e){let t=await b(e),{agents:n}=await h(e,t,"GET","/ai/agents");e.out.result({agents:n},()=>{n.length===0&&e.out.line("No agent yet: an ai.agent of the backend, or ai:agents:create <name>."),e.out.table(n,[{header:"name",value:s=>s.name},{header:"source",value:s=>s.source},{header:"published",value:s=>s.source==="code"?"-":s.published_version?`v${s.published_version}`:"no"},{header:"draft",value:s=>s.source==="code"?"-":s.unpublished_changes?`changed (r${s.revision})`:`r${s.revision}`},{header:"machine",value:s=>s.machine??"-"},{header:"description",value:s=>s.description??""}])})}};async function mR(e,t,n,s){let a;for(let i=0;i<100;i++){let r=await h(e,t,"GET",`/ai/agents/${k(n)}/versions${qt({limit:100,cursor:a})}`),o=r.versions.find(l=>l.version===s);if(o)return o;if(!r.next_cursor||r.versions.every(l=>l.version<s))break;a=r.next_cursor}throw new f("not_found",`${n} has no version ${s}`,{hint:`palbase ai:agents:versions ${n}`})}function Ds(e,t,n){if(e.out.line(t),n===void 0)e.out.line(" (none yet)");else for(let s of JSON.stringify(n,null,2).split(`
|
|
647
|
+
`))e.out.line(` ${s}`)}var gR={name:"ai:agents:show",summary:"one agent: where it stands and what it is \u2014 a kept one's published version (or its draft, or a version), a backend's last turn",usage:"<name> [--draft | --version <n>]",args:{min:1,max:1},flags:{draft:{type:"boolean",description:"the draft, as the next publish makes a version of it"},version:{type:"string",value:"n",description:"that version, as it was published"}},scope:"environment",async run(e){let t=en(e,"an agent"),n=Tt(e.flags.version,"version");if(n!==void 0&&e.flags.draft===!0)throw m("--draft or --version, not both");let s=await b(e);if(n!==void 0){let i=await mR(e,s,t,n);e.out.result(i,()=>Ds(e,`${t} version ${i.version}, published ${i.published_at} by ${i.published_by}:`,i.definition));return}let a=await h(e,s,"GET",`/ai/agents/${k(t)}`);if(e.flags.draft===!0&&a.source==="code")throw new f("agent_defined_in_code",`${t} is the backend's code's: it has no draft \u2014 it changes with the code`);e.out.result(a,()=>{e.out.line(`${a.name}: ${El(a)}`),a.description&&e.out.line(a.description),a.updated_at&&e.out.line(`Draft saved ${a.updated_at}${a.updated_by?` by ${a.updated_by}`:""}.`),e.out.line(),a.source==="code"?Ds(e,`Its last turn${a.defined_at?` (${a.defined_at})`:""} was defined as:`,a.definition):e.flags.draft===!0||a.published===void 0?Ds(e,`The draft (revision ${a.revision}):`,a.draft):Ds(e,`Version ${a.published_version}, the one its chats talk to:`,a.published)})}};function fR(e){let t=e.indexOf(":"),n=t>0?e.slice(0,t):"",s=e.slice(t+1);if(!gf.includes(n)||s==="")throw m(`--tool is source:name \u2014 ${gf.join(", ")} \u2014 not ${JSON.stringify(e)}`,"palbase ai:tools lists the tools an agent may be given");let a=n==="backend"?s.indexOf("/"):-1;if(a<0)return{source:n,name:s};let i=s.slice(0,a);if(s=s.slice(a+1),!wr.test(i)||s==="")throw m(`--tool backend:<machine>/<name> names one of the environment's machines and its tool, not ${JSON.stringify(e)}`);return{source:"backend",name:s,machine:i}}async function yR(e){let t={},n=e.flags.from;if(n!==void 0){let a=await ff(e,n,n),i=fr(a)&&fr(a.definition)&&typeof a.name=="string"?a.definition:a;if(!fr(i))throw m(`${n} is an agent's definition: a JSON object { instructions, model, tools, \u2026 }`);t=i}e.flags.instructions!==void 0&&(t.instructions=e.flags.instructions),e.flags.description!==void 0&&(t.description=e.flags.description),e.flags.model!==void 0&&(t.model=e.flags.model),e.flags.tool!==void 0&&(t.tools=e.flags.tool.map(fR));let s=e.flags["output-schema"];if(s!==void 0){let a=await ff(e,s,s);if(!fr(a)||a.type!=="object")throw m(`${s} is the JSON Schema of the agent's one-shot answers: an object's ({ "type": "object", "properties": \u2026 })`);t.output=a}if(t.backend!==void 0)throw m("an agent the environment keeps names no backend: a backend's agent is its code's (ai.agent)");return t}async function bR(e,t,n){try{let s=await h(e,t,"GET",`/ai/agents/${k(n)}`);return s.source==="platform"&&s.draft&&s.revision!==void 0?{draft:s.draft,revision:s.revision}:void 0}catch(s){if(s instanceof E&&s.status===404)return;throw s}}async function $f(e,t,n,s,a){return h(e,t,"PUT",`/ai/agents/${k(n)}${qt({revision:a})}`,s)}async function Cl(e,t,n,s){return h(e,t,"POST",`/ai/agents/${k(n)}/publish`,s!==void 0?{revision:s}:{})}var wR={name:"ai:agents:create",summary:"save the draft of an agent the environment keeps \u2014 a new one's, or a change of one's \u2014 and publish it with --publish",usage:"<name> [--from <file.json>] [--instructions <text>] [--description <text>] [--model <model>] [--tool <source:name>]\u2026 [--output-schema <file.json>] [--revision <n>] [--publish]",details:["Its chats talk to the version published: a draft changes nothing until it is published (ai:agents:publish, or --publish here).","A change of an agent it keeps is made on its draft: each flag given replaces its field, and the rest stays.",'--from is the whole definition as JSON ({ "instructions", "model", "tools": [{ "source", "name" }], "subagents", "output", \u2026 }) \u2014 or what ai:agents:generate --json printed; each flag given replaces its field.',"--tool is source:name: backend:<ai.tool> (backend:<machine>/<ai.tool> for another machine's), client:<ai.clientTool>, https:<endpoint>, mcp:<server>, platform:web.search|web.fetch|workspace.fetch_archive (palbase ai:tools lists them). Given, the tools are those; a backend or client tool goes by its name alone, and the platform takes what it does from the build that declares it.","--revision is the draft's revision as it was read (ai:agents:show): when another was saved since, the save is refused (draft_changed) and nothing is lost."],args:{min:1,max:1},flags:{from:{type:"string",value:"file.json",description:"the definition, as JSON"},instructions:{type:"string",value:"text",description:"what the agent is told to do"},description:{type:"string",value:"text",description:"what it is for, in a sentence or two"},model:{type:"string",value:"model",description:"the name of a model ai:models lists; left out, the default"},tool:{type:"string",multiple:!0,value:"source:name",description:"a tool it is given (repeat for several)"},"output-schema":{type:"string",value:"file.json",description:"the JSON Schema of its one-shot answers"},revision:{type:"string",value:"n",description:"the draft's revision the change is made on"},publish:{type:"boolean",description:"publish the draft as the next version once it is saved"}},scope:"environment",async run(e){let t=en(e,"an agent"),n=Tt(e.flags.revision,"revision"),s=await yR(e);if(Object.keys(s).length===0)throw m("the agent is empty","pass --from <file.json>, or --instructions, --model, --tool\u2026");let a=await b(e),i=e.flags.from===void 0?await bR(e,a,t):void 0,r={...i?.draft,...s},o=e.flags.publish===!0;await v(e,a,`save the draft of the agent ${t}${o?" and publish it":""}`);let l=await $f(e,a,t,r,n??i?.revision),d=o?await Cl(e,a,t,l.revision):l;e.out.result(d,()=>{e.out.line(`Saved the draft of ${t} (revision ${l.revision}).`),o?e.out.line(`Published ${t} as version ${d.published_version}: its chats talk to it from their next turn.`):e.out.line(`${El(d)[0].toUpperCase()}${El(d).slice(1)}: palbase ai:agents:publish ${t} makes its chats talk to it.`)})}},vR={name:"ai:agents:publish",summary:"make the draft of an agent the next version, the one its chats talk to from their next turn",usage:"<name> [--revision <n>]",args:{min:1,max:1},flags:{revision:{type:"string",value:"n",description:"the draft as it was read: refused when another was saved since"}},scope:"environment",async run(e){let t=en(e,"an agent"),n=Tt(e.flags.revision,"revision"),s=await b(e);await v(e,s,`publish the draft of the agent ${t}`);let a=await Cl(e,s,t,n);e.out.result(a,()=>e.out.line(`Published ${t} as version ${a.published_version}: its chats talk to it from their next turn.`))}},_R={name:"ai:agents:rollback",summary:"make a version an agent had the one its chats talk to again \u2014 and its draft that version",usage:"<name> <version>",args:{min:2,max:2},scope:"environment",async run(e){let t=en(e,"an agent"),n=Number(e.args[1]);if(!Number.isSafeInteger(n)||n<1)throw m(`the version is a version the agent had, a whole number from 1 (not ${JSON.stringify(e.args[1])})`,`palbase ai:agents:versions ${t}`);let s=await b(e);await v(e,s,`make version ${n} of the agent ${t} the one its chats talk to (a draft not published is dropped)`);let a=await h(e,s,"POST",`/ai/agents/${k(t)}/rollback`,{version:n});e.out.result(a,()=>e.out.line(`${t}'s chats talk to version ${a.published_version} again; its draft is that version.`))}},kR={name:"ai:agents:versions",summary:"the versions an agent the environment keeps was published as, newest first, and the one its chats talk to",usage:"<name> [--limit <n>] [--cursor <cursor>]",args:{min:1,max:1},flags:{limit:{type:"string",value:"n",description:"at most this many (1\u2013100, default 20)"},cursor:{type:"string",value:"cursor",description:"the next page, as the last one said it"}},scope:"environment",async run(e){let t=en(e,"an agent"),n=Tt(e.flags.limit,"limit"),s=await b(e),a=await h(e,s,"GET",`/ai/agents/${k(t)}/versions${qt({limit:n,cursor:e.flags.cursor})}`);e.out.result(a,()=>{a.versions.length===0&&e.out.line(`${t} has no version yet: palbase ai:agents:publish ${t}`),e.out.table(a.versions,[{header:"version",value:i=>`${i.version}${i.version===a.published_version?" (published)":""}`},{header:"published",value:i=>i.published_at},{header:"by",value:i=>i.published_by},{header:"model",value:i=>i.definition.model??"-"},{header:"description",value:i=>i.definition.description??""}]),a.next_cursor&&e.out.line(`More: palbase ai:agents:versions ${t} --cursor ${a.next_cursor}`)})}},SR={name:"ai:agents:generate",summary:"write an agent from a description \u2014 instructions, a model, the environment's tools that fit \u2014 and save it as a draft with --save",usage:'"<description>" [--name <name>] [--save] [--publish]',details:["Nothing is kept unless --save (or --publish) says so: the definition is printed, for ai:agents:create --from.","It is written as you \u2014 your sign-in, or PALBASE_TOKEN \u2014 20 an hour; the platform pays for it."],args:{min:1,max:1},flags:{name:{type:"string",value:"name",description:"the name it is to have (left out: one is suggested)"},save:{type:"boolean",description:"save it as the draft of an agent of that name"},publish:{type:"boolean",description:"save it and publish it as the next version"}},scope:"environment",async run(e){let t=e.args[0].trim();if(t===""||t.length>4e3)throw m("the description says the agent in words: 1 to 4000 characters");let n=e.flags.name;if(n!==void 0&&!wr.test(n))throw m(`${JSON.stringify(n)} is not an agent's name: lowercase letters, digits, _ and -, a letter first, at most 64`);let s=await b(e),a=await h(e,s,"POST","/ai/agent-drafts",{description:t,...n!==void 0?{name:n}:{}}),i=e.flags.publish===!0;if(e.flags.save!==!0&&!i){e.out.result(a,()=>{Ds(e,`${a.name}:`,a.definition),e.out.line(),e.out.line(`Nothing was kept. Save it: palbase ai:agents:generate "\u2026" --save, or palbase ai:agents:create ${a.name} --from <the definition, as ai:agents:generate --json prints it>`)});return}await v(e,s,`save the draft of the agent ${a.name}${i?" and publish it":""}`);let r=await $f(e,s,a.name,a.definition,void 0),o=i?await Cl(e,s,a.name,r.revision):r;e.out.result({...a,agent:o},()=>{Ds(e,`${a.name}:`,a.definition),e.out.line(),e.out.line(i?`Saved and published ${a.name} as version ${o.published_version}.`:`Saved the draft of ${a.name} (revision ${r.revision}): palbase ai:agents:publish ${a.name} makes its chats talk to it.`)})}},$R={name:"ai:agents:remove",summary:"forget an agent the environment keeps, its versions with it: its chats stay, and are refused a message until one of its name is there again",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=en(e,"an agent"),n=await b(e);await v(e,n,`forget the agent ${t} and its versions`),await h(e,n,"DELETE",`/ai/agents/${k(t)}`),e.out.result({removed:t},()=>e.out.line(`Forgot ${t} and its versions.`))}},PR={name:"ai:tools",summary:"the tools an agent may be given: the backend's (its build's contract), the environment's endpoints, and the platform's",scope:"environment",async run(e){let t=await b(e),{tools:n}=await h(e,t,"GET","/ai/tools");e.out.result({tools:n},()=>{e.out.table(n,[{header:"tool",value:s=>`${s.source}:${s.name}`},{header:"machine",value:s=>s.machine??"-"},{header:"approval",value:s=>s.approval?"yes":"no"},{header:"description",value:s=>s.description}]),e.out.line("An agent is given one as --tool source:name (ai:agents:create).")})}},AR={name:"ai:chats:list",summary:"the environment's chats, newest first \u2014 every one, or a member's",usage:"[--member <user id>] [--limit <n>] [--cursor <cursor>]",flags:{member:{type:"string",value:"user id",description:"only the chats this user is in"},limit:{type:"string",value:"n",description:"at most this many (1\u2013100, default 100)"},cursor:{type:"string",value:"cursor",description:"the next page, as the last one said it"}},scope:"environment",async run(e){let t=Tt(e.flags.limit,"limit"),n=await b(e),s=await h(e,n,"GET",`/ai/chats${qt({member:e.flags.member,limit:t,cursor:e.flags.cursor})}`);e.out.result(s,()=>{s.chats.length===0&&e.out.line("No chat."),e.out.table(s.chats,[{header:"id",value:a=>a.id},{header:"agent",value:a=>`${a.agent}${a.agent_version?`@${a.agent_version}`:""}`},{header:"title",value:a=>a.title},{header:"members",value:a=>String(a.members.length)},{header:"started",value:a=>a.created_at}]),s.next_cursor&&e.out.line(`More: palbase ai:chats:list --cursor ${s.next_cursor}`)})}},RR=/^chat_[0-9a-f]{32}$/;function Hn(e){let t=e.args[0];if(!RR.test(t))throw m(`${JSON.stringify(t)} is not a chat's id (chat_ and 32 hex digits)`,"palbase ai:chats:list");return t}var TR={name:"ai:chats:show",summary:"one chat: its agent and members, and what they wrote, newest last \u2014 with what each turn cost (--cost)",usage:"<chat id> [--limit <n>] [--cost]",args:{min:1,max:1},flags:{limit:{type:"string",value:"n",description:"its last this many messages (1\u2013100, default 50)"},cost:{type:"boolean",description:"what each turn a message started cost, its subagents counted"}},scope:"environment",async run(e){let t=Hn(e),n=Tt(e.flags.limit,"limit")??50,s=await b(e),a=await h(e,s,"GET",`/ai/chats/${k(t)}`),i=await h(e,s,"GET",`/ai/chats/${k(t)}/messages${qt({limit:n})}`),r=[...i.messages].reverse(),o=await ER(e,s,t,new Set(r.flatMap(p=>p.response_id?[p.response_id]:[]))),l=new Map;r.forEach((p,u)=>p.response_id&&l.set(p.response_id,u));let d=new Map;if(e.flags.cost===!0)for(let p of new Set(r.flatMap(u=>u.response_id?[u.response_id]:[])))d.set(p,await h(e,s,"GET",`/ai/chats/${k(t)}/turns/${k(p)}/cost`));e.out.result({chat:a,messages:r,answers:Object.fromEntries(o),...e.flags.cost===!0?{costs:Object.fromEntries(d)}:{}},()=>{e.out.line(`${a.id} ${a.title||"(untitled)"}`),e.out.line(`agent ${a.agent}${a.agent_version?` (stays on version ${a.agent_version})`:""}; started ${a.created_at}; ${a.history_bytes} bytes of history`),a.members.length>0&&e.out.line(`members: ${a.members.map(p=>`${p.name||p.user_id}${p.owner?" (owner)":""}`).join(", ")}`),e.out.line(),r.length===0&&e.out.line("Nothing written yet."),r.forEach((p,u)=>{if(e.out.line(`${p.created_at} ${p.author===null?"server":p.author_name||p.author}: ${p.text}${p.status==="failed"?` [failed: ${p.error??""}]`:""}`),!p.response_id||l.get(p.response_id)!==u)return;let g=o.get(p.response_id);g&&e.out.line(` ${a.agent}: ${g.replace(/\s*\n\s*/g," ")}`);let y=d.get(p.response_id);y&&e.out.line(` turn ${y.response_id}: ${yr(y.usd)}${y.unpriced?" at least":""}, ${y.input_tokens} in / ${y.output_tokens} out${y.final?"":" (still settling)"}`)}),i.next_cursor&&e.out.line(`(older messages are not shown: --limit ${Math.min(n*2,100)})`)})}};async function ER(e,t,n,s){let a=[],i;for(let o=0;o<20&&s.size>0;o++){let l=await h(e,t,"GET",`/ai/chats/${k(n)}/parts${qt({limit:1e3,cursor:i})}`);if(a.unshift(l.parts),!l.next_cursor)break;i=l.next_cursor}let r=new Map;for(let o of a.flat()){let l=o.data.response_id,d=o.data.offset;if(typeof l!="string"||!s.has(l)||typeof d!="number")continue;let p=(r.get(l)??Buffer.alloc(0)).subarray(0,d);r.set(l,o.type==="text"&&typeof o.data.text=="string"?Buffer.concat([p,Buffer.from(o.data.text)]):o.type==="reset"?p:r.get(l)??p)}return new Map([...r].map(([o,l])=>[o,l.toString("utf8").trim()]))}var CR={name:"ai:chats:remove",summary:"delete a chat: a turn still running is stopped, and its history no longer counts",usage:"<chat id>",args:{min:1,max:1},scope:"environment",async run(e){let t=Hn(e),n=await b(e);await v(e,n,`delete the chat ${t}`),await h(e,n,"DELETE",`/ai/chats/${k(t)}`),e.out.result({removed:t},()=>e.out.line(`Deleted the chat ${t}.`))}},jR=/^[a-z][a-z0-9_-]{0,63}(@[1-9][0-9]{0,8})?$/,Ma=/^[A-Za-z0-9_.:-]{1,160}$/;function OR(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).map(t=>{let n=String(t),s=n.indexOf("@"),a=s<0?n:n.slice(0,s),i=s<0?void 0:n.slice(s+1);if(!wr.test(a)||i==="")throw m(`--repo is one of the environment's repositories by name, at a branch with @ (shop@agent/x), not ${JSON.stringify(n)}`,"palbase ai:repos:list");return{repo:a,...i!==void 0?{branch:i}:{}}})}var MR={name:"ai:chats:create",summary:"start a chat with one of the environment's agents \u2014 on one of its runner pools, working in its repositories",usage:"--agent <name> [--pool <pool>] [--repo <name>[@<branch>]]\u2026 [--title <title>] [--auto-push]",details:["--agent is one of the environment's agents by name \u2014 its backend's, or one it keeps, whose published version each turn takes; name@N stays on version N.","--pool is one of its runner pools (ai:pools:list), by its id or its name: the chat's sessions run on the environment's own machines enrolled there. Left out, on the platform's own Linux machines. A chat on a pool works in a workspace.","--repo puts one of its repositories (ai:repos:list) in the chat's workspace, at a branch with @ (its default unless said); --auto-push lets the agent push its commits without a person's yes."],flags:{agent:{type:"string",value:"name",description:"the chat's agent, by name (name@N for a version)"},pool:{type:"string",value:"pool",description:"the runner pool its workspace runs on, by id or name"},repo:{type:"string",multiple:!0,value:"name[@branch]",description:"a repository its workspace works in (repeat for several)"},title:{type:"string",value:"title",description:"the chat's title"},"auto-push":{type:"boolean",description:"the agent pushes its commits without a person's yes"}},scope:"environment",async run(e){let t=e.flags.agent;if(t===void 0)throw m("--agent names the chat's agent","palbase ai:agents:list");if(!jR.test(t))throw m(`${JSON.stringify(t)} is not an agent's name (lowercase letters, digits, _ and -, a letter first, at most 64; name@N for a version)`);let n=e.flags.pool;if(n!==void 0&&!Ma.test(n))throw m(`${JSON.stringify(n)} is not a runner pool's id or name`,"palbase ai:pools:list");let s=OR(e.flags.repo),a=e.flags["auto-push"]===!0;if(a&&s.length===0)throw m("--auto-push is about the repositories the chat works in: give --repo");let i={agent:t};e.flags.title!==void 0&&(i.title=e.flags.title),n!==void 0&&(i.pool=n),s.length>0&&(i.workspace={repos:s,...a?{auto_push:!0}:{}});let r=await b(e);await v(e,r,`start a chat with the agent ${t}${n!==void 0?` on the pool ${n}`:""}`);let o=await h(e,r,"POST","/ai/chats",i);e.out.result(o,()=>{e.out.line(`Started the chat ${o.id} with ${o.agent}${o.pool?` on the pool ${o.pool}`:""}.`),s.length>0&&e.out.line(`Its workspace works in ${s.map(l=>l.branch?`${l.repo}@${l.branch}`:l.repo).join(", ")}${a?", its commits pushed without a yes":""}.`)})}};function Pf(e){if(e===""||Buffer.byteLength(e)>2048||e.startsWith("/")||e.split("/").some(t=>t===""||t==="."||t===".."||Buffer.byteLength(t)>255))throw m(`${JSON.stringify(e)} is not a file of the chat's workspace: relative to its root (app/src/config.json), 1 to 2048 bytes, each segment 1 to 255, no . or .. segment, no slash at either end`);return e}var IR=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/u,Af="128 bytes at most, no control, format (bidi, zero-width) or line-separator character",Rf=e=>Buffer.byteLength(e)<=128&&!IR.test(e),yf=64<<20,LR={name:"ai:chats:workspace:write",summary:"write one file of a chat's workspace \u2014 from a file here, or piped in: synced to every machine that holds it, the session's before the agent's next command",usage:"<chat id> <path> [--file <local file>] [< file]",details:["path is relative to the workspace's root (app/src/config.json). The write is published over whatever the workspace holds \u2014 deliberate, no conflict is made of it \u2014 and told as ai.workspace.published.","--file sends the file's bytes as they are (64 MiB at most); without it, the bytes piped in, as they are \u2014 a binary file too (64 MiB at most: no more is read)."],args:{min:2,max:2},flags:{file:{type:"string",value:"local file",description:"the file whose bytes are written (default: what is piped in)"}},scope:"environment",async run(e){let t=Hn(e),n=Pf(e.args[1]),s=e.flags.file,a;if(s!==void 0){let o=vf(e.io.cwd,s);try{let l=(await eR(o)).size;if(l>yf)throw new f("file_too_large",`${s} is ${l} bytes: a workspace's file is written up to 64 MiB`);a=await ZA(o)}catch(l){throw l instanceof f?l:new f("unreadable_file",`${s} could not be read: ${l instanceof Error?l.message:String(l)}`)}}else{if(e.interactive)throw m("the file's bytes are --file <local file>, or piped in",`palbase ai:chats:workspace:write ${t} ${n} --file <local file>`);let o=await e.io.readStdinBytes(yf);if(o===null)throw new f("file_too_large","more than 64 MiB was piped in: a workspace's file is written up to 64 MiB");if(o.byteLength===0)throw m("nothing was piped in","pipe the file in, or pass --file <local file>");a=new Blob([o])}let i=await b(e);await v(e,i,`write ${n} in the workspace of the chat ${t}`);let r=await h(e,i,"PUT",`/ai/chats/${k(t)}/workspace/files${qt({path:n})}`,new Wt(a,"application/octet-stream"));e.out.result(r,()=>e.out.line(`Wrote ${r.path} (${a.size} bytes): the workspace is at ${r.manifest_id}, seq ${r.seq}.`))}},DR={name:"ai:chats:workspace:rm",summary:"remove one file of a chat's workspace: synced to every machine that holds it",usage:"<chat id> <path>",args:{min:2,max:2},scope:"environment",async run(e){let t=Hn(e),n=Pf(e.args[1]),s=await b(e);await v(e,s,`remove ${n} from the workspace of the chat ${t}`);let a=await h(e,s,"DELETE",`/ai/chats/${k(t)}/workspace/files${qt({path:n})}`);e.out.result(a,()=>e.out.line(`Removed ${a.path}: the workspace is at ${a.manifest_id}, seq ${a.seq}.`))}},bf=604800,xR={name:"ai:chats:workspace:token",summary:"mint a token a machine of yours syncs a chat's workspace with (palai workspace sync): said once, here",usage:"<chat id> --access read|write [--ttl <seconds>] [--label <label>]",details:["write: the workspace is synced both ways, live; read: it is followed. The token lives --ttl seconds (an hour unless said, 7 days at most) \u2014 no longer than PALBASE_TOKEN when it is minted with one.","The token and its address are said once. On the machine: PALAI_WORKSPACE_TOKEN=<token> palai workspace sync --url <sync_url> <dir> \u2014 or the token on standard input, --token-file - \u2014 never on the command line: palai has no --token, a secret there is readable by every process on the machine.","A member's token (the project letting its app's users in) lives an hour at most, and stops working when they leave the chat or the project turns clients off.","--label is what it is for \u2014 the machine's name: a conflict names its writer by it."],args:{min:1,max:1},flags:{access:{type:"string",value:"read|write",description:"write: synced both ways; read: followed"},ttl:{type:"string",value:"seconds",description:"how long it lives (1\u2013604800, default 3600)"},label:{type:"string",value:"label",description:"what it is for \u2014 the machine's name"}},scope:"environment",async run(e){let t=Hn(e),n=e.flags.access;if(n!=="read"&&n!=="write")throw m("--access is read (the workspace followed) or write (synced both ways)");let s=Tt(e.flags.ttl,"ttl");if(s!==void 0&&s>bf)throw m(`--ttl is 1 to ${bf} seconds (7 days)`);let a=e.flags.label;if(a!==void 0&&!Rf(a))throw m(`--label is ${Af}`);let i={access:n};s!==void 0&&(i.ttl_seconds=s),a!==void 0&&(i.label=a);let r=await b(e);await v(e,r,`mint a ${n} token of the workspace of the chat ${t}`);let o=await h(e,r,"POST",`/ai/chats/${k(t)}/workspace/tokens`,i);e.out.result(o,()=>{e.out.line(`Minted ${o.id} (${o.access}${o.label?`, ${o.label}`:""}), until ${o.expires_at}. It is said this once:`),e.out.line(),e.out.line(` token ${o.token}`),e.out.line(` sync_url ${o.sync_url}`),e.out.line(),e.out.line("On the machine, the token in its environment (never on the command line):"),e.out.line(` PALAI_WORKSPACE_TOKEN=<the token> palai workspace sync --url ${o.sync_url} <dir>`),e.out.line("or on its standard input: palai workspace sync --url <sync_url> --token-file - <dir>"),e.out.line(`Revoke it: palbase ai:chats:workspace:revoke ${t} ${o.id}`)})}},NR={name:"ai:chats:workspace:tokens",summary:"the tokens of a chat's workspace \u2014 access, label, when each expires \u2014 none of them said again",usage:"<chat id>",args:{min:1,max:1},scope:"environment",async run(e){let t=Hn(e),n=await b(e),{tokens:s}=await h(e,n,"GET",`/ai/chats/${k(t)}/workspace/tokens`);e.out.result({tokens:s},()=>{s.length===0&&e.out.line(`No token: palbase ai:chats:workspace:token ${t} --access write`),e.out.table(s,[{header:"id",value:a=>a.id},{header:"access",value:a=>a.access},{header:"label",value:a=>a.label??""},{header:"expires",value:a=>a.expires_at}])})}},qR={name:"ai:chats:workspace:revoke",summary:"revoke a token of a chat's workspace at once: every sync with it is refused from then",usage:"<chat id> <token id>",args:{min:2,max:2},scope:"environment",async run(e){let t=Hn(e),n=e.args[1];if(!Ma.test(n))throw m(`${JSON.stringify(n)} is not a token's id`,`palbase ai:chats:workspace:tokens ${t}`);let s=await b(e);await v(e,s,`revoke the token ${n} of the workspace of the chat ${t}`),await h(e,s,"DELETE",`/ai/chats/${k(t)}/workspace/tokens/${k(n)}`),e.out.result({revoked:n},()=>e.out.line(`Revoked ${n}: every sync with it is refused from now.`))}},KR={name:"ai:endpoints:list",summary:"the environment's HTTPS tools and MCP servers an agent may be given by name (their signing secrets are never said again)",scope:"environment",async run(e){let t=await b(e),{endpoints:n}=await h(e,t,"GET","/ai/endpoints"),s=n.map(({signing_secret:a,...i})=>i);e.out.result({endpoints:s},()=>{s.length===0&&e.out.line("No endpoint."),e.out.table(s,[{header:"name",value:a=>a.name},{header:"kind",value:a=>a.kind},{header:"url",value:a=>a.url},{header:"approval",value:a=>a.approval?"yes":"no"},{header:"workspace",value:a=>a.workspace?"told":"not told"},{header:"description",value:a=>a.description}])})}},GR={name:"ai:endpoints:remove",summary:"forget an HTTPS tool or an MCP server: an agent that names it is given it no more",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=en(e,"an endpoint"),n=await b(e);await v(e,n,`forget the endpoint ${t}`),await h(e,n,"DELETE",`/ai/endpoints/${k(t)}`),e.out.result({removed:t},()=>e.out.line(`Forgot the endpoint ${t}.`))}},UR={name:"ai:repos:list",summary:"the repositories a chat's workspace works in, by name, and the machine that gives their tokens",usage:"[--limit <n>] [--cursor <cursor>]",flags:{limit:{type:"string",value:"n",description:"at most this many (1\u20131000, default 100)"},cursor:{type:"string",value:"cursor",description:"the next page, as the last one said it"}},scope:"environment",async run(e){let t=Tt(e.flags.limit,"limit"),n=await b(e),s=await h(e,n,"GET",`/ai/repos${qt({limit:t,cursor:e.flags.cursor})}`);e.out.result(s,()=>{s.repos.length===0&&e.out.line("No repository."),e.out.table(s.repos,[{header:"name",value:a=>a.name},{header:"repository",value:a=>a.repository},{header:"branch",value:a=>a.default_branch},{header:"tokens from",value:a=>a.backend}]),s.next_cursor&&e.out.line(`More: palbase ai:repos:list --cursor ${s.next_cursor}`)})}},BR={name:"ai:repos:remove",summary:"forget a repository: a chat's workspace checks it out no more",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=en(e,"a repository"),n=await b(e);await v(e,n,`forget the repository ${t}`),await h(e,n,"DELETE",`/ai/repos/${k(t)}`),e.out.result({removed:t},()=>e.out.line(`Forgot the repository ${t}.`))}};function vr(e){let t=e.args[0];if(!Ma.test(t))throw m(`${JSON.stringify(t)} is not a runner pool's id or name`,"palbase ai:pools:list");return t}function jl(e){let t=e.args[0];if(!Ma.test(t))throw m(`${JSON.stringify(t)} is not a machine's id`,"palbase ai:pools:state <pool> lists its machines");return t}function zR(e){if(!(e instanceof E))return e;switch(e.code){case"pool_not_empty":return new f(e.code,e.message,{hint:"palbase ai:pools:state <pool> lists its machines: ai:machines:cordon <id>, then ai:machines:delete <id> once it holds none"});case"machine_not_cordoned":return new f(e.code,e.message,{hint:"palbase ai:machines:cordon <id> first"});case"machine_busy":return new f(e.code,e.message,{hint:"delete it once ai:pools:state <pool> says it holds none (used 0)"});case"pool_exists":return new f(e.code,e.message,{hint:"palbase ai:pools:list"});default:return e}}async function Yn(e,t,n,s,a){try{return await h(e,t,n,s,a)}catch(i){throw zR(i)}}var WR={name:"ai:pools:create",summary:"make a runner pool of the environment's: machines of your own, of one type, that a chat's workspace runs on",usage:"<name> --os linux|macos --arch amd64|arm64",details:["A pool is of one type: its machines' operating system and architecture. Machines enrol into it with palai and a single-use key (ai:pools:keys:create); a chat runs on it when it names it (ai:chats:create --pool).","The environment scales it itself: ai:pools:state says what its machines hold and how many sessions wait."],args:{min:1,max:1},flags:{os:{type:"string",value:"linux|macos",description:"its machines' operating system"},arch:{type:"string",value:"amd64|arm64",description:"its machines' architecture"}},scope:"environment",async run(e){let t=en(e,"a pool"),n=e.flags.os,s=e.flags.arch;if(n!=="linux"&&n!=="macos")throw m("--os is the pool's machines' operating system: linux or macos");if(s!=="amd64"&&s!=="arm64")throw m("--arch is the pool's machines' architecture: amd64 or arm64");let a=await b(e);await v(e,a,`make the runner pool ${t} (${n}/${s})`);let i=await Yn(e,a,"POST","/ai/pools",{name:t,os:n,arch:s});e.out.result(i,()=>{e.out.line(`Made the pool ${i.name} (${i.id}), ${i.os}/${i.arch}.`),e.out.line(`Enrol a machine: palbase ai:pools:keys:create ${i.name}`)})}},FR={name:"ai:pools:list",summary:"the environment's runner pools: each one's type, its machines, the sessions they take and hold, and how many wait",scope:"environment",async run(e){let t=await b(e),{pools:n}=await h(e,t,"GET","/ai/pools");e.out.result({pools:n},()=>{n.length===0&&e.out.line("No pool: the environment's chats run on the platform's own Linux machines. Make one: palbase ai:pools:create <name> --os linux|macos --arch amd64|arm64"),e.out.table(n,[{header:"name",value:s=>s.name},{header:"id",value:s=>s.id},{header:"type",value:s=>`${s.os}/${s.arch}`},{header:"machines",value:s=>String(s.machines??0)},{header:"sessions",value:s=>`${s.capacity_used??0}/${s.capacity_total??0}`},{header:"waiting",value:s=>String(s.waiting??0)}])})}},JR={name:"ai:pools:delete",summary:"delete a runner pool with no machine left in it: cordon each machine, delete it once it holds no session, then the pool",usage:"<pool>",args:{min:1,max:1},scope:"environment",async run(e){let t=vr(e),n=await b(e);await v(e,n,`delete the runner pool ${t}`),await Yn(e,n,"DELETE",`/ai/pools/${k(t)}`),e.out.result({deleted:t},()=>e.out.line(`Deleted the pool ${t}.`))}},VR={name:"ai:pools:state",summary:"a runner pool's state, as a scaling loop reads it: its machines, the sessions they take and hold, and how many wait since when",usage:"<pool>",args:{min:1,max:1},scope:"environment",async run(e){let t=vr(e),n=await b(e),s=await h(e,n,"GET",`/ai/pools/${k(t)}/state`);e.out.result(s,()=>{e.out.line(`${s.pool.name} (${s.pool.id}), ${s.pool.os}/${s.pool.arch}`),e.out.line(`sessions ${s.capacity_used} held of ${s.capacity_total} its machines take at once`),e.out.line(`waiting ${s.waiting}${s.oldest_waiting_since?` (the oldest since ${s.oldest_waiting_since})`:""}`),e.out.line(),s.machines.length===0&&e.out.line(`No machine: palbase ai:pools:keys:create ${s.pool.name} mints a key one enrols with.`),e.out.table(s.machines,[{header:"id",value:a=>a.id},{header:"state",value:a=>a.state},{header:"sessions",value:a=>`${a.used}/${a.capacity}`},{header:"label",value:a=>a.label??""},{header:"last seen",value:a=>a.last_seen_at??"-"},{header:"idle since",value:a=>a.idle_since??"-"}])})}},HR={name:"ai:pools:keys:create",summary:"mint a single-use key a machine enrols into a runner pool with: said once, here",usage:"<pool> [--label <label>]",details:["Save the key to a file on the machine and enrol it: palai enroll --url <enroll_url> --key-file <file> --capacity <n> (with --server-name and --ca-file when the answer names a server name and a CA) \u2014 the key never goes on a command line, where any process on the machine could read it; n is how many sessions the machine runs at once (1 or more, default 1). The machine serves the environment's sessions once whoever minted the key is gone.","It is minted by a person signed in, never with an environment's token (PALBASE_TOKEN)."],args:{min:1,max:1},flags:{label:{type:"string",value:"label",description:"what it is for \u2014 the machine it enrols"}},scope:"environment",async run(e){let t=vr(e),n=e.flags.label;if(n!==void 0&&!Rf(n))throw m(`--label is ${Af}`);let s=await b(e);await v(e,s,`mint a key a machine enrols into the pool ${t} with`);let a=await Yn(e,s,"POST",`/ai/pools/${k(t)}/keys`,n!==void 0?{label:n}:{});if(typeof a.key!="string"||a.key==="")throw new f("no_key",`the key ${a.id} was minted but not said`,{hint:`revoke it (palbase ai:pools:keys:revoke ${a.id}) and mint another`});e.out.result(a,()=>{e.out.line(`Minted the key ${a.id}${a.label?` (${a.label})`:""}${a.expires_at?`, usable until ${a.expires_at}`:""}. It is said this once:`),e.out.line(),e.out.line(` ${a.key}`),e.out.line();let i=a.enroll_url??a.enroll?.url??"<enroll_url>",r=`${a.enroll?.server_name?` --server-name ${a.enroll.server_name}`:""}${a.enroll?.ca_certificate?" --ca-file <ca file>":""}`;e.out.line(`Save it to a file on the machine, then: palai enroll --url ${i} --key-file <file> --capacity <n>${r}`),a.enroll?.ca_certificate&&(e.out.line("The door's certificate is signed by this CA \u2014 save it as the <ca file>:"),e.out.line(),e.out.line(a.enroll.ca_certificate.trimEnd()),e.out.line()),e.out.line(`(n: how many sessions the machine runs at once, 1 or more, default 1; the key never goes on a command line.) Revoke it unused: palbase ai:pools:keys:revoke ${a.id}`)})}},YR={name:"ai:pools:keys:list",summary:"a runner pool's enrolment keys \u2014 when each was minted, last used, revoked \u2014 none of them said again",usage:"<pool>",args:{min:1,max:1},scope:"environment",async run(e){let t=vr(e),n=await b(e),{keys:s}=await h(e,n,"GET",`/ai/pools/${k(t)}/keys`),a=s.map(({key:i,...r})=>r);e.out.result({keys:a},()=>{a.length===0&&e.out.line(`No key: palbase ai:pools:keys:create ${t}`),e.out.table(a,[{header:"id",value:i=>i.id},{header:"label",value:i=>i.label??""},{header:"minted",value:i=>i.created_at??"-"},{header:"expires",value:i=>i.expires_at??"-"},{header:"last used",value:i=>i.last_used_at??"-"},{header:"revoked",value:i=>i.revoked_at??"-"}])})}},XR={name:"ai:pools:keys:revoke",summary:"revoke an enrolment key: no machine enrols with it any more",usage:"<key id>",args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0];if(!Ma.test(t))throw m(`${JSON.stringify(t)} is not a key's id`,"palbase ai:pools:keys:list <pool>");let n=await b(e);await v(e,n,`revoke the enrolment key ${t}`),await Yn(e,n,"POST",`/ai/pool-keys/${k(t)}/revoke`),e.out.result({revoked:t},()=>e.out.line(`Revoked ${t}: no machine enrols with it any more.`))}},ZR={name:"ai:machines:cordon",summary:"cordon a machine of a runner pool: it takes no new session, and the sessions it holds go on",usage:"<machine id>",args:{min:1,max:1},scope:"environment",async run(e){let t=jl(e),n=await b(e);await v(e,n,`cordon the machine ${t}`),await Yn(e,n,"POST",`/ai/machines/${k(t)}/cordon`),e.out.result({cordoned:t},()=>e.out.line(`Cordoned ${t}: it takes no new session. Delete it once it holds none: palbase ai:machines:delete ${t}`))}},QR={name:"ai:machines:resume",summary:"let a cordoned machine of a runner pool take sessions again",usage:"<machine id>",args:{min:1,max:1},scope:"environment",async run(e){let t=jl(e),n=await b(e);await v(e,n,`let the machine ${t} take sessions again`),await Yn(e,n,"POST",`/ai/machines/${k(t)}/resume`),e.out.result({resumed:t},()=>e.out.line(`${t} takes sessions again.`))}},eT={name:"ai:machines:delete",summary:"delete a cordoned machine that holds no session from its runner pool: its palai agent is refused from then",usage:"<machine id>",args:{min:1,max:1},scope:"environment",async run(e){let t=jl(e),n=await b(e);await v(e,n,`delete the machine ${t} from its pool`),await Yn(e,n,"DELETE",`/ai/machines/${k(t)}`),e.out.result({deleted:t},()=>e.out.line(`Deleted ${t}: its palai agent is refused from now.`))}},tT=/^[A-Z][A-Z0-9_]{0,127}$/,wf=32768;function Tf(e){let t=e.args[0];if(!tT.test(t)||t.startsWith("PALAI_"))throw m(`${JSON.stringify(t)} is not a variable's name: upper-case letters, digits and _, a letter first, at most 128 \u2014 and not PALAI_\u2026, the engine's own`);return t}var nT={name:"ai:env:set",summary:"set a variable every session of the environment's agents has: its value piped in or typed unseen, never shown or put on the command line",usage:"<KEY> [--value-stdin] [--not-secret] < value.txt",details:["Every command of every session its agents begin from now has it \u2014 on the platform's machines and on its own pools \u2014 beside an agent's own (its definition's env), masked in a transcript. The value is sealed where the sessions run: never answered, never logged.","Without --value-stdin the value is asked for at the terminal, and not echoed as it is typed or pasted.","--not-secret says it is no secret in ai:env:list; its value is masked and never shown either way."],args:{min:1,max:1},flags:{"value-stdin":{type:"boolean",description:"read the value from stdin (a pipe, a file)"},"not-secret":{type:"boolean",description:"list it as no secret (its value is never shown either way)"}},scope:"environment",async run(e){let t=Tf(e);if(e.flags["value-stdin"]!==!0&&!e.interactive)throw m(`${t}'s value is read from stdin`,`pipe it in: palbase ai:env:set ${t} --value-stdin < value.txt`);let n=await b(e),s=await Me(e,`${t}'s value`);if(Buffer.byteLength(s)>wf||s.includes("\0"))throw m(`${t}'s value is 1 to ${wf} bytes, no NUL`);let a=e.flags["not-secret"]!==!0;await v(e,n,`set the variable ${t} for every session of the environment's agents`);let i=await h(e,n,"PUT",`/ai/env/${k(t)}`,{value:s,...a?{}:{secret:!1}});e.out.result(i,()=>e.out.line(`Set ${i.key}${i.secret?" (a secret)":""}: every session begun from now has it. Its value is kept sealed, never shown.`))}},sT={name:"ai:env:unset",summary:"remove a variable: sessions of the environment's agents begun from now no longer have it",usage:"<KEY>",args:{min:1,max:1},scope:"environment",async run(e){let t=Tf(e),n=await b(e);await v(e,n,`remove the variable ${t}`),await h(e,n,"DELETE",`/ai/env/${k(t)}`),e.out.result({removed:t},()=>e.out.line(`Removed ${t}: sessions begun from now no longer have it.`))}},aT={name:"ai:env:list",summary:"the variables every session of the environment's agents has: their names, whether each is a secret, when each was set \u2014 never a value",scope:"environment",async run(e){let t=await b(e),{variables:n}=await h(e,t,"GET","/ai/env");e.out.result({variables:n},()=>{n.length===0&&e.out.line("No variable: palbase ai:env:set <KEY>"),e.out.table(n,[{header:"key",value:s=>s.key},{header:"secret",value:s=>s.secret?"yes":"no"},{header:"value",value:()=>"set"},{header:"updated",value:s=>s.updated_at}])})}},Ef=[nR,iR,sR,rR,oR,lR,pR,uR,hR,gR,wR,vR,_R,kR,SR,$R,PR,AR,TR,MR,CR,LR,DR,xR,NR,qR,KR,GR,UR,BR,WR,FR,JR,VR,HR,YR,XR,ZR,QR,eT,nT,sT,aT];var iT={name:"docs:search",summary:"search Palbase's documentation by meaning: the sections that answer it, each with its address and its text",usage:'"<what you need>" [--limit <n>]',details:["Ask in English, the docs' language: a question finds the section it means by its meaning and by its words \u2014 say what you need, not the words of a heading.","Each result is a section of a page: its title, its address with the section's anchor, and its text (the first 4000 characters of a longer one \u2014 the address has the rest).","Anyone may search, signed in or not: 10 searches in ten seconds, 30 a minute, 300 an hour. A sign-in or PALBASE_TOKEN is sent when there is one and is counted as itself; with none, your address is. When many search at once, a search waits its turn for a few seconds, or is told to search again in a moment."],args:{min:1,max:1},flags:{limit:{type:"string",value:"n",description:"how many sections (1 to 10, default 5)"}},scope:"none",async run(e){let t=e.args[0].trim();if([...t].length<2||[...t].length>500)throw m("say what you need from the docs: 2 to 500 characters");let n=e.flags.limit,s=n===void 0?5:Number(n);if(!Number.isInteger(s)||s<1||s>10)throw m("--limit is how many sections: 1 to 10");let{results:a}=await e.studio.open(`/docs/search?q=${encodeURIComponent(t)}&limit=${s}`);e.out.result(a,()=>{if(a.length===0){e.out.line('No section of the docs answers it: say it another way, or ask Palbase: palbase support:ask "<question>"');return}a.forEach((i,r)=>{r>0&&e.out.line(),e.out.line(`${r+1}. ${i.title===i.heading?i.title:`${i.title} \u203A ${i.heading}`}`),e.out.line(` ${i.url}`),e.out.line(),e.out.line(i.text)})})}},Cf=[iT];var jf=3e4,Ol=3,rT=80;async function oT(e,t){let n=[],s;try{s=(await h(e,t,"GET",`/machines?limit=100&environment=${encodeURIComponent(t.env_ref)}`)).machines}catch{return"machines: not readable with this sign-in or token"}if(s.length===0)return"machines: none";for(let i of s.slice(0,Ol)){n.push(`machine ${i.name}: ${i.state}, size ${i.size}, version ${i.running_version===i.version?i.version:`${i.running_version} \u2192 ${i.version}`}`);let r;try{r=(await h(e,t,"GET",`/machines/${x("a machine's name",i.name)}/builds?limit=3`)).builds}catch{n.push(" builds: not readable with this sign-in or token");continue}for(let l of r)n.push(` build ${l.id} ${l.commit.slice(0,7)} ${l.state}${l.running?" (serving)":""}${l.reason?` \u2014 ${l.reason}`:""} ${l.created_at} "${l.message.split(`
|
|
648
648
|
`)[0].slice(0,80)}"`);let o=r.find(l=>l.state==="failed");if(o)try{let l=await h(e,t,"GET",`/machines/${x("a machine's name",i.name)}/builds/${x("a build's id",o.id)}/log`),d=typeof l=="string"?l:JSON.stringify(l);n.push(` the end of build ${o.id}'s log:`,...d.trimEnd().split(`
|
|
649
649
|
`).slice(-rT).map(p=>` ${p}`))}catch{n.push(` build ${o.id}'s log: not readable with this sign-in or token`)}}s.length>Ol&&n.push(`(${s.length-Ol} more machines not shown)`);let a=n.join(`
|
|
650
650
|
`);return a.length>jf?`${a.slice(0,jf)}
|
|
@@ -671,9 +671,9 @@ ${t}}`}var tn=e=>["",e.toUpperCase(),"-".repeat(e.length)],AT=[{title:"One packa
|
|
|
671
671
|
`)}
|
|
672
672
|
`}var Sr={$schema:"https://json-schema.org/draft/2020-12/schema",title:"Palbase paywall definition",description:"A paywall: a design system (the theme's colors, type scale, radii and spacing) and a free layout of components that name it \u2014 a fixed header and footer around the part that scrolls, and sheets it opens. Every component takes a style, a condition to be shown, a style for when it is selected, and an entrance animation. Prices are never in it: an app fills `{{price}}` and the other variables from its store. Its assets (asset:<id>) are the project's, given as https addresses in the app's answer and listed for the app to download before it shows the paywall. The server refuses what it does not know and holds a definition to bounds: 128 KiB of JSON, 400 components, 16 deep, 500 characters a text, 40 languages, 8 stops a gradient, 2 seconds an animation, 10 carousel pages, 5 tabs, 5 sheets.",$ref:"#/$defs/PaywallDefinition",$defs:{PaywallAction:{additionalProperties:!1,description:"What a button does.",properties:{package:{description:"Package.",pattern:"^([a-z][a-z0-9_]{0,39})\\.([a-z][a-z0-9_]{0,39})$",type:"string"},sheet:{description:"Sheet.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},type:{description:"Type.",enum:["close","restore","open_url","terms","privacy","offer_code","sheet","select_package"],type:"string"},url:{description:"Url.",maxLength:2048,pattern:"^https://.+$",type:"string"}},required:["type"],type:"object"},PaywallAnimation:{additionalProperties:!1,description:"How the component appears; a renderer skips it when the system asks to reduce motion.",properties:{delay_ms:{default:0,description:"Delay ms.",maximum:2e3,minimum:0,type:"integer"},duration_ms:{default:300,description:"Duration ms.",maximum:2e3,minimum:50,type:"integer"},easing:{default:"ease_out",description:"Easing.",enum:["ease_out","ease_in_out","spring"],type:"string"},type:{description:"Type.",enum:["fade","slide_up","slide_down","slide_leading","slide_trailing","scale"],type:"string"}},required:["type"],type:"object"},PaywallBorder:{additionalProperties:!1,description:"A border.",properties:{color:{description:"Color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},width:{description:"Width.",maximum:16,minimum:.5,type:"number"}},required:["color","width"],type:"object"},PaywallButton:{additionalProperties:!1,description:"A button that does an action: closes the paywall, restores purchases, opens an address, the terms or the privacy policy, the store's offer code sheet, one of the paywall's sheets, or selects a package.",properties:{action:{$ref:"#/$defs/PaywallAction"},animation:{$ref:"#/$defs/PaywallAnimation"},content:{$ref:"#/$defs/PaywallComponent"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},type:{description:"The component.",enum:["button"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["action","content","type"],type:"object"},PaywallCarousel:{additionalProperties:!1,description:"Pages the customer swipes through, the next peeking in, advancing on their own, with an indicator.",properties:{animation:{$ref:"#/$defs/PaywallAnimation"},auto_advance_ms:{description:"Auto advance ms.",maximum:3e4,minimum:1e3,type:"integer"},height:{description:"Height.",oneOf:[{$ref:"#/$defs/PaywallSizeKeyword"},{$ref:"#/$defs/PaywallLength"}]},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},indicator:{$ref:"#/$defs/PaywallIndicator"},loop:{default:!1,description:"Loop.",type:"boolean"},pages:{description:"Pages.",items:{$ref:"#/$defs/PaywallComponent"},maxItems:10,minItems:1,type:"array"},peek:{default:0,description:"Peek.",maximum:64,minimum:0,type:"integer"},spacing:{default:8,description:"Spacing.",maximum:64,minimum:0,type:"integer"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},type:{description:"The component.",enum:["carousel"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["pages","type"],type:"object"},PaywallColorValue:{description:"A color: a token of the theme's colors (the light or the dark value, as the app appears), or #RRGGBB / #RRGGBBAA.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},PaywallColors:{additionalProperties:!1,description:"The theme's colors by name, for each appearance; both name the same colors, at least background, surface, text, muted, accent and on_accent.",properties:{dark:{$ref:"#/$defs/PaywallPalette"},light:{$ref:"#/$defs/PaywallPalette"}},required:["dark","light"],type:"object"},PaywallComponent:{description:"A component, by its type. A newer schema adds components; an app never draws a definition with one it does not know.",oneOf:[{$ref:"#/$defs/PaywallButton"},{$ref:"#/$defs/PaywallCarousel"},{$ref:"#/$defs/PaywallCountdown"},{$ref:"#/$defs/PaywallCustomHtml"},{$ref:"#/$defs/PaywallDivider"},{$ref:"#/$defs/PaywallFeatures"},{$ref:"#/$defs/PaywallIcon"},{$ref:"#/$defs/PaywallImage"},{$ref:"#/$defs/PaywallPackage"},{$ref:"#/$defs/PaywallPurchaseButton"},{$ref:"#/$defs/PaywallSpacer"},{$ref:"#/$defs/PaywallStack"},{$ref:"#/$defs/PaywallSwitch"},{$ref:"#/$defs/PaywallTabs"},{$ref:"#/$defs/PaywallText"},{$ref:"#/$defs/PaywallTimeline"},{$ref:"#/$defs/PaywallVideo"}]},PaywallCondition:{additionalProperties:!1,description:"When the component is shown: every field named holds at once.",properties:{appearance:{description:"Appearance.",enum:["light","dark"],type:"string"},intro_eligible:{description:"Intro eligible.",type:"boolean"},locale:{description:"Locale.",items:{pattern:"^[a-z]{2,3}(-[A-Z][A-Za-z]{1,3})?$",type:"string"},maxItems:40,minItems:1,type:"array",uniqueItems:!0},offer_open:{description:"Holds while the package's offer (its package component's offer) is the customer's to take: the package the component is in, else the selected one.",type:"boolean"},platform:{description:"Platform.",items:{enum:["ios","android","web"],type:"string"},maxItems:3,minItems:1,type:"array",uniqueItems:!0},selected_package:{description:"Selected package.",items:{pattern:"^([a-z][a-z0-9_]{0,39})\\.([a-z][a-z0-9_]{0,39})$",type:"string"},maxItems:6,minItems:1,type:"array"},tab:{description:"Tab.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"}},type:"object"},PaywallCorners:{additionalProperties:!1,description:"Each corner its own, in points or a token of the theme's radii.",properties:{bottom_leading:{default:0,description:"Bottom leading.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"}]},bottom_trailing:{default:0,description:"Bottom trailing.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"}]},top_leading:{default:0,description:"Top leading.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"}]},top_trailing:{default:0,description:"Top trailing.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"}]}},type:"object"},PaywallCountdown:{additionalProperties:!1,description:"A countdown to an instant, or for a time from the moment the paywall opened: one content while it counts \u2014 its texts name {{countdown}}, {{days}}, {{hours}}, {{minutes}}, {{seconds}} \u2014, another once it ended.",properties:{animation:{$ref:"#/$defs/PaywallAnimation"},counting:{$ref:"#/$defs/PaywallComponent"},ended:{$ref:"#/$defs/PaywallComponent"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},target:{$ref:"#/$defs/PaywallTarget"},type:{description:"The component.",enum:["countdown"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["counting","target","type"],type:"object"},PaywallCustomHtml:{additionalProperties:!1,description:"A decorative HTML block from an archive the project uploaded (an animation, a Lottie or Rive scene): drawn in a sandbox of an origin of its own: it reaches neither the page around it, nor the app, nor the purchase, and loads only what came in its archive (a content security policy) \u2014 it may still navigate its own frame away and open a WebRTC connection (a content security policy does not cover WebRTC). It is told the selected package, the language and the appearance, and is hidden from screen readers. It cannot buy anything.",properties:{animation:{$ref:"#/$defs/PaywallAnimation"},height:{description:"Height.",oneOf:[{$ref:"#/$defs/PaywallSizeKeyword"},{$ref:"#/$defs/PaywallLength"}]},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},src:{description:"Src.",maxLength:2048,pattern:"^asset:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$",type:"string"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},type:{description:"The component.",enum:["custom_html"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["height","src","type"],type:"object"},PaywallDefinition:{additionalProperties:!1,description:"A paywall: a design system (the theme's colors, type scale, radii and spacing) and a free layout of components that name it \u2014 a fixed header and footer around the part that scrolls, and sheets it opens. Every component takes a style, a condition to be shown, a style for when it is selected, and an entrance animation. Prices are never in it: an app fills `{{price}}` and the other variables from its store. Its assets (asset:<id>) are the project's, given as https addresses in the app's answer and listed for the app to download before it shows the paywall. The server refuses what it does not know and holds a definition to bounds: 128 KiB of JSON, 400 components, 16 deep, 500 characters a text, 40 languages, 8 stops a gradient, 2 seconds an animation, 10 carousel pages, 5 tabs, 5 sheets.",properties:{$schema:{type:"string",description:"The JSON Schema an editor checks this file against. The CLI takes it out before the definition is sent."},default_locale:{description:"The language a text falls back to: a tag such as en or pt-BR.",pattern:"^[a-z]{2,3}(-[A-Z][A-Za-z]{1,3})?$",type:"string"},footer:{$ref:"#/$defs/PaywallComponent"},header:{$ref:"#/$defs/PaywallComponent"},locales:{$ref:"#/$defs/PaywallLocales"},name:{description:"The paywall's name, for the people who edit it (1 to 100 characters).",maxLength:100,minLength:1,type:"string"},root:{$ref:"#/$defs/PaywallComponent"},schema:{description:"The schema the definition is written in: 2. An app says the newest schema it draws (X-Palbase-Paywall-Schema) and is given the newest version written in it or an older one; an app that draws no schema this server takes is told to update (426).",maximum:2,minimum:2,type:"integer"},sheets:{$ref:"#/$defs/PaywallSheets"},theme:{$ref:"#/$defs/PaywallTheme"}},required:["schema","name","default_locale","theme","root"],type:"object"},PaywallDivider:{additionalProperties:!1,description:"A thin line across its stack.",properties:{animation:{$ref:"#/$defs/PaywallAnimation"},color:{default:"muted",description:"Color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},thickness:{default:1,description:"Thickness.",maximum:8,minimum:.5,type:"number"},type:{description:"The component.",enum:["divider"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["type"],type:"object"},PaywallEdges:{additionalProperties:!1,description:"Each edge its own, in points or a token of the theme's spacing.",properties:{bottom:{default:0,description:"Bottom.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"}]},leading:{default:0,description:"Leading.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"}]},top:{default:0,description:"Top.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"}]},trailing:{default:0,description:"Trailing.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"}]}},type:"object"},PaywallFeature:{additionalProperties:!1,description:"A feature.",properties:{icon:{$ref:"#/$defs/PaywallIconName"},text:{$ref:"#/$defs/PaywallString"}},required:["icon","text"],type:"object"},PaywallFeatures:{additionalProperties:!1,description:"What the purchase gives, each with an icon.",properties:{animation:{$ref:"#/$defs/PaywallAnimation"},color:{default:"text",description:"Color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},icon_color:{default:"accent",description:"Icon color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},items:{description:"Items.",items:{$ref:"#/$defs/PaywallFeature"},maxItems:12,minItems:1,type:"array"},spacing:{default:12,description:"Spacing.",maximum:64,minimum:0,type:"integer"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},type:{description:"The component.",enum:["features"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["items","type"],type:"object"},PaywallFontSize:{description:"A size in points, scaled with the platform's body style.",maximum:120,minimum:6,type:"number"},PaywallIcon:{additionalProperties:!1,description:"An icon every renderer draws.",properties:{animation:{$ref:"#/$defs/PaywallAnimation"},color:{default:"accent",description:"Color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},name:{$ref:"#/$defs/PaywallIconName"},size:{default:24,description:"Size.",maximum:128,minimum:8,type:"integer"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},type:{description:"The component.",enum:["icon"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["name","type"],type:"object"},PaywallIconName:{description:"An icon every renderer draws (SF Symbols on iOS).",enum:["ad_free","arrow_right","bell","bolt","book","calendar","chart","chat","check","check_circle","clock","close","cloud","crown","download","gift","globe","heart","infinity","lock","lock_open","music","people","person","photo","play","quote","shield","sparkles","star","trophy","video"],type:"string"},PaywallImage:{additionalProperties:!1,description:"An image the app downloads before it shows the paywall: an https address, or an image the project uploaded.",properties:{alt:{$ref:"#/$defs/PaywallString"},animation:{$ref:"#/$defs/PaywallAnimation"},aspect:{description:"Aspect.",maximum:10,minimum:.1,type:"number"},decorative:{default:!1,description:"Decorative.",type:"boolean"},fit:{default:"fit",description:"Fit.",enum:["fit","fill"],type:"string"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},mask:{$ref:"#/$defs/PaywallMask"},overlay:{description:"Overlay.",oneOf:[{$ref:"#/$defs/PaywallLinear"},{$ref:"#/$defs/PaywallRadial"}]},src:{description:"Src.",maxLength:2048,pattern:"^(https://.+|asset:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))$",type:"string"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},type:{description:"The component.",enum:["image"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["src","type"],type:"object"},PaywallImageFill:{additionalProperties:!1,description:"An image behind the component.",properties:{fit:{default:"fill",description:"Fit.",enum:["fit","fill"],type:"string"},src:{description:"Src.",maxLength:2048,pattern:"^(https://.+|asset:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))$",type:"string"},type:{description:"Type.",enum:["image"],type:"string"}},required:["src","type"],type:"object"},PaywallIndicator:{additionalProperties:!1,description:"A carousel's page indicator.",properties:{active_color:{default:"accent",description:"Active color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},color:{default:"muted",description:"Color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},size:{default:8,description:"Size.",maximum:16,minimum:2,type:"integer"},spacing:{default:6,description:"Spacing.",maximum:32,minimum:0,type:"integer"},style:{default:"dots",description:"Its style.",enum:["dots","bars","none"],type:"string"}},type:"object"},PaywallLength:{description:"A length in points.",maximum:4e3,minimum:0,type:"number"},PaywallLinear:{additionalProperties:!1,description:"A linear gradient: its angle (0 up, clockwise, 180 down) and 2 to 8 stops.",properties:{angle:{default:180,description:"Angle.",maximum:360,minimum:0,type:"number"},stops:{description:"Stops.",items:{$ref:"#/$defs/PaywallStop"},maxItems:8,minItems:2,type:"array"},type:{description:"Type.",enum:["linear"],type:"string"}},required:["stops","type"],type:"object"},PaywallLiteral:{description:"The text itself, in every language.",maxLength:500,type:"string"},PaywallLocales:{additionalProperties:{$ref:"#/$defs/PaywallTexts"},description:"The texts in each language (at most 40), by language tag: a component's `{\"t\": key}` is the app's language's, or the default locale's when it lacks the key.",type:"object"},PaywallMask:{additionalProperties:!1,description:"The image's shape: a rectangle with corners, a circle, or a rectangle whose bottom edge curves in (concave) or out (convex).",properties:{depth:{default:16,description:"Depth.",maximum:64,minimum:0,type:"number"},radius:{default:0,description:"Radius.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"}]},shape:{description:"Shape.",enum:["rect","circle","concave","convex"],type:"string"}},required:["shape"],type:"object"},PaywallPackage:{additionalProperties:!1,description:"A package on sale, laid out as the project likes: tapping it selects it; its content's styles for when it is selected apply while it is.",properties:{animation:{$ref:"#/$defs/PaywallAnimation"},children:{description:"The components.",items:{$ref:"#/$defs/PaywallComponent"},maxItems:50,type:"array"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},offer:{description:"One of the catalog's offers on the package: bought with it, and its texts' {{offer_price}} its price, while the customer may take it (GET /purchases/offers lists it).",pattern:"^[a-z][a-z0-9_]{0,39}$",type:"string"},plan:{description:"Plan.",pattern:"^[a-z][a-z0-9_]{0,39}$",type:"string"},product:{description:"Product.",pattern:"^[a-z][a-z0-9_]{0,39}$",type:"string"},selected:{default:!1,description:"Selected when the paywall opens (at most one).",type:"boolean"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},type:{description:"The component.",enum:["package"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["plan","product","type"],type:"object"},PaywallPalette:{additionalProperties:{pattern:"^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$",type:"string"},description:"Colors by token (lowercase letters, digits and _, at most 32), each #RRGGBB or #RRGGBBAA.",maxProperties:40,type:"object"},PaywallPoints:{description:"Points.",maximum:200,minimum:0,type:"number"},PaywallPurchaseButton:{additionalProperties:!1,description:"The button that buys the selected package \u2014 or its own package \u2014: the store's sheet (StoreKit) or checkout (Stripe) opens.",properties:{animation:{$ref:"#/$defs/PaywallAnimation"},content:{$ref:"#/$defs/PaywallComponent"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},package:{description:"Package.",pattern:"^([a-z][a-z0-9_]{0,39})\\.([a-z][a-z0-9_]{0,39})$",type:"string"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},type:{description:"The component.",enum:["purchase_button"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["content","type"],type:"object"},PaywallRadial:{additionalProperties:!1,description:"A radial gradient: its center and radius as shares of the component, and 2 to 8 stops.",properties:{center_x:{default:.5,description:"Center x.",maximum:1,minimum:0,type:"number"},center_y:{default:.5,description:"Center y.",maximum:1,minimum:0,type:"number"},radius:{default:.5,description:"Radius.",maximum:2,minimum:.01,type:"number"},stops:{description:"Stops.",items:{$ref:"#/$defs/PaywallStop"},maxItems:8,minItems:2,type:"array"},type:{description:"Type.",enum:["radial"],type:"string"}},required:["stops","type"],type:"object"},PaywallScale:{additionalProperties:{maximum:200,minimum:0,type:"number"},description:"Points by token (lowercase letters, digits and _, at most 32).",maxProperties:16,type:"object"},PaywallShadow:{additionalProperties:!1,description:"A shadow.",properties:{color:{description:"Color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},radius:{default:0,description:"Radius.",maximum:64,minimum:0,type:"number"},x:{default:0,description:"X.",maximum:64,minimum:-64,type:"number"},y:{default:0,description:"Y.",maximum:64,minimum:-64,type:"number"}},required:["color"],type:"object"},PaywallSheet:{additionalProperties:!1,description:"A second page a button opens over the paywall.",properties:{root:{$ref:"#/$defs/PaywallComponent"},title:{$ref:"#/$defs/PaywallString"}},required:["root"],type:"object"},PaywallSheets:{additionalProperties:{$ref:"#/$defs/PaywallSheet"},description:"The sheets by id (lowercase letters, digits, _ and -, starting with a letter).",maxProperties:5,type:"object"},PaywallSizeKeyword:{description:`fit: the content's size; fill: all the parent gives; a share of the parent ("50%").`,pattern:"^(fit|fill|([1-9][0-9]?|100)%)$",type:"string"},PaywallSpacer:{additionalProperties:!1,description:"Space: a fixed size, or all that is left along its stack when absent.",properties:{animation:{$ref:"#/$defs/PaywallAnimation"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},size:{description:"Size.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"}]},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},type:{description:"The component.",enum:["spacer"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["type"],type:"object"},PaywallSpan:{additionalProperties:!1,description:"A part of a text: bold, italic, underlined, struck through, colored, a link.",properties:{bold:{default:!1,description:"Bold.",type:"boolean"},color:{description:"Color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},italic:{default:!1,description:"Italic.",type:"boolean"},link:{description:"Link.",maxLength:2048,pattern:"^(terms|privacy|https://.+)$",type:"string"},strikethrough:{default:!1,description:"Strikethrough.",type:"boolean"},text:{$ref:"#/$defs/PaywallString"},underline:{default:!1,description:"Underline.",type:"boolean"}},required:["text"],type:"object"},PaywallStack:{additionalProperties:!1,description:"Components laid out one after another \u2014 down, across \u2014 or over each other (z). The root, the header and the footer are each one; the root scrolls between the fixed header and footer.",properties:{align:{default:"center",description:"Align.",enum:["start","center","end","stretch"],type:"string"},animation:{$ref:"#/$defs/PaywallAnimation"},axis:{default:"vertical",description:"Axis.",enum:["vertical","horizontal","z"],type:"string"},children:{description:"The components.",items:{$ref:"#/$defs/PaywallComponent"},maxItems:50,type:"array"},distribution:{default:"start",description:"Distribution.",enum:["start","center","end","space_between","space_around","space_evenly"],type:"string"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},scroll:{default:!1,description:"Scroll.",type:"boolean"},spacing:{default:0,description:"Spacing.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"}]},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},type:{description:"The component.",enum:["stack"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["type"],type:"object"},PaywallStates:{additionalProperties:!1,description:"The component's style while what it is in is selected: the package it is in (or is), the tab whose label it is.",properties:{selected:{$ref:"#/$defs/PaywallStyle"}},type:"object"},PaywallStop:{additionalProperties:!1,description:"A gradient's color at a point along it (0 to 1).",properties:{at:{description:"At.",maximum:1,minimum:0,type:"number"},color:{description:"Color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"}},required:["at","color"],type:"object"},PaywallString:{description:'A text: the string itself, or `{"t": key}` of the language table. Either may hold variables the app fills from its store \u2014 `{{price}}`, `{{price_per_month}}`, `{{period}}`, `{{trial}}`, `{{savings}}`, `{{product_name}}`, `{{offer_price}}` (the price of the package\'s offer while the customer may take it, its price otherwise) \u2014 of the package an item is, or of the selected package anywhere else. A text that names a variable its package has no value for (no trial, no savings) is not drawn.',oneOf:[{$ref:"#/$defs/PaywallLiteral"},{$ref:"#/$defs/PaywallTextKey"}]},PaywallStyle:{additionalProperties:!1,description:"What every component takes: padding and margin by edge, a size, a fill, a border, corners each their own, a shadow, an opacity. Points and colors name the theme's tokens or are given as they are.",properties:{background:{description:"Background.",oneOf:[{$ref:"#/$defs/PaywallColorValue"},{$ref:"#/$defs/PaywallLinear"},{$ref:"#/$defs/PaywallRadial"},{$ref:"#/$defs/PaywallImageFill"},{$ref:"#/$defs/PaywallVideoFill"}]},border:{$ref:"#/$defs/PaywallBorder"},corners:{description:"Corners.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"},{$ref:"#/$defs/PaywallCorners"}]},height:{description:"Height.",oneOf:[{$ref:"#/$defs/PaywallSizeKeyword"},{$ref:"#/$defs/PaywallLength"}]},margin:{description:"Margin.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"},{$ref:"#/$defs/PaywallEdges"}]},max_width:{description:"Max width.",maximum:4e3,minimum:1,type:"integer"},opacity:{default:1,description:"Opacity.",maximum:1,minimum:0,type:"number"},padding:{description:"Padding.",oneOf:[{$ref:"#/$defs/PaywallPoints"},{$ref:"#/$defs/PaywallToken"},{$ref:"#/$defs/PaywallEdges"}]},shadow:{$ref:"#/$defs/PaywallShadow"},width:{description:"Width.",oneOf:[{$ref:"#/$defs/PaywallSizeKeyword"},{$ref:"#/$defs/PaywallLength"}]}},type:"object"},PaywallSwitch:{additionalProperties:!1,description:"A switch between two contents \u2014 a yearly and a monthly offer \u2014, each selecting its own package when it is shown.",properties:{animation:{$ref:"#/$defs/PaywallAnimation"},default:{default:!1,description:"Default.",type:"boolean"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},label:{$ref:"#/$defs/PaywallString"},off:{$ref:"#/$defs/PaywallComponent"},off_package:{description:"Off package.",pattern:"^([a-z][a-z0-9_]{0,39})\\.([a-z][a-z0-9_]{0,39})$",type:"string"},on:{$ref:"#/$defs/PaywallComponent"},on_package:{description:"On package.",pattern:"^([a-z][a-z0-9_]{0,39})\\.([a-z][a-z0-9_]{0,39})$",type:"string"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},tint:{default:"accent",description:"Tint.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},type:{description:"The component.",enum:["switch"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["off","on","type"],type:"object"},PaywallTab:{additionalProperties:!1,description:"A tab: its label, its content, and the package it selects when it is shown.",properties:{content:{$ref:"#/$defs/PaywallComponent"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},label:{$ref:"#/$defs/PaywallComponent"},package:{description:"Package.",pattern:"^([a-z][a-z0-9_]{0,39})\\.([a-z][a-z0-9_]{0,39})$",type:"string"}},required:["content","id","label"],type:"object"},PaywallTabs:{additionalProperties:!1,description:"Tabs, each its own content and default package; the labels, in a bar, are components whose style when selected is the shown tab's.",properties:{animation:{$ref:"#/$defs/PaywallAnimation"},bar:{$ref:"#/$defs/PaywallStyle"},default:{description:"Default.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},tabs:{description:"Tabs.",items:{$ref:"#/$defs/PaywallTab"},maxItems:5,minItems:2,type:"array"},type:{description:"The component.",enum:["tabs"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["tabs","type"],type:"object"},PaywallTarget:{additionalProperties:!1,description:"What a countdown counts to: an instant (at), or a time from the moment the paywall opened (after_open_seconds) \u2014 one of them.",properties:{after_open_seconds:{description:"After open seconds.",maximum:604800,minimum:1,type:"integer"},at:{description:"At.",format:"date-time",type:"string"}},type:"object"},PaywallText:{additionalProperties:!1,description:"A text: one string, or spans \u2014 bold, italic, colored parts and links \u2014, in a type style of the theme or its own.",properties:{align:{default:"center",description:"Align.",enum:["start","center","end"],type:"string"},animation:{$ref:"#/$defs/PaywallAnimation"},color:{default:"text",description:"Color.",oneOf:[{$ref:"#/$defs/PaywallColorValue"},{$ref:"#/$defs/PaywallLinear"},{$ref:"#/$defs/PaywallRadial"}]},font:{description:"Font.",pattern:"^(system|rounded|serif|mono|asset:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))$",type:"string"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},letter_spacing:{description:"Letter spacing.",maximum:20,minimum:-5,type:"number"},line_height:{description:"Line height.",maximum:3,minimum:.5,type:"number"},max_lines:{description:"Max lines.",maximum:20,minimum:1,type:"integer"},size:{description:"Size.",oneOf:[{$ref:"#/$defs/PaywallFontSize"},{$ref:"#/$defs/PaywallToken"}]},spans:{description:"Spans.",items:{$ref:"#/$defs/PaywallSpan"},maxItems:20,minItems:1,type:"array"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},text:{$ref:"#/$defs/PaywallString"},type:{description:"The component.",enum:["text"],type:"string"},uppercase:{default:!1,description:"Uppercase.",type:"boolean"},visible:{$ref:"#/$defs/PaywallCondition"},weight:{description:"Weight.",enum:[100,200,300,400,500,600,700,800,900],type:"integer"}},required:["type"],type:"object"},PaywallTextKey:{additionalProperties:!1,description:"A text of the language table.",properties:{t:{description:"The text's key.",type:"string"}},required:["t"],type:"object"},PaywallTexts:{additionalProperties:{maxLength:500,type:"string"},description:"One language's texts, by key (lowercase letters, digits, `_` `.` `-`, at most 64): each at most 500 characters, with variables.",type:"object"},PaywallTheme:{additionalProperties:!1,description:"The paywall's design system: colors for light and dark, a type scale, radii and spacing; the components name them.",properties:{colors:{$ref:"#/$defs/PaywallColors"},radii:{$ref:"#/$defs/PaywallScale"},spacing:{$ref:"#/$defs/PaywallScale"},typography:{$ref:"#/$defs/PaywallTypeScale"}},required:["colors"],type:"object"},PaywallTimeline:{additionalProperties:!1,description:"Steps in time \u2014 a trial's today, its reminder, its first charge \u2014, each with an icon, joined by a line.",properties:{animation:{$ref:"#/$defs/PaywallAnimation"},color:{default:"text",description:"Color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},icon_color:{default:"on_accent",description:"Icon color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},items:{description:"Items.",items:{$ref:"#/$defs/PaywallTimelineItem"},maxItems:8,minItems:2,type:"array"},line_color:{default:"accent",description:"Line color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},line_width:{default:2,description:"Line width.",maximum:8,minimum:1,type:"integer"},spacing:{default:16,description:"Spacing.",maximum:64,minimum:0,type:"integer"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},type:{description:"The component.",enum:["timeline"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["items","type"],type:"object"},PaywallTimelineItem:{additionalProperties:!1,description:"A step of a timeline.",properties:{color:{description:"Color.",pattern:"^(#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})|[a-z][a-z0-9_]{0,31})$",type:"string"},icon:{$ref:"#/$defs/PaywallIconName"},text:{$ref:"#/$defs/PaywallString"},title:{$ref:"#/$defs/PaywallString"}},required:["icon","title"],type:"object"},PaywallToken:{description:"A token of the theme's scale.",pattern:"^[a-z][a-z0-9_]{0,31}$",type:"string"},PaywallTypeScale:{additionalProperties:{$ref:"#/$defs/PaywallTypography"},description:"Type styles by token (lowercase letters, digits and _, at most 32).",maxProperties:16,type:"object"},PaywallTypography:{additionalProperties:!1,description:"A type style of the theme: what a text whose size names it is drawn in. It scales with its text style (Dynamic Type on iOS, the root font size on the web).",properties:{font:{default:"system",description:"Font.",pattern:"^(system|rounded|serif|mono|asset:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))$",type:"string"},letter_spacing:{default:0,description:"Letter spacing.",maximum:20,minimum:-5,type:"number"},line_height:{description:"Line height.",maximum:3,minimum:.5,type:"number"},size:{description:"Size.",maximum:120,minimum:6,type:"number"},text_style:{default:"body",description:"Text style.",enum:["large_title","title","title2","title3","headline","body","callout","subheadline","footnote","caption"],type:"string"},weight:{default:400,description:"Weight.",enum:[100,200,300,400,500,600,700,800,900],type:"integer"}},required:["size"],type:"object"},PaywallVideo:{additionalProperties:!1,description:"A video the app downloads before it shows the paywall; muted and looping unless it says otherwise.",properties:{alt:{$ref:"#/$defs/PaywallString"},animation:{$ref:"#/$defs/PaywallAnimation"},aspect:{description:"Aspect.",maximum:10,minimum:.1,type:"number"},autoplay:{default:!0,description:"Autoplay.",type:"boolean"},controls:{default:!1,description:"Controls.",type:"boolean"},fit:{default:"fill",description:"Fit.",enum:["fit","fill"],type:"string"},id:{description:"Names the component, unique in the paywall: an app's code can draw its own part in its place.",pattern:"^[a-z][a-z0-9_-]{0,39}$",type:"string"},loop:{default:!0,description:"Loop.",type:"boolean"},mute:{default:!0,description:"Mute.",type:"boolean"},poster:{description:"Poster.",maxLength:2048,pattern:"^(https://.+|asset:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))$",type:"string"},src:{description:"Src.",maxLength:2048,pattern:"^(https://.+|asset:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))$",type:"string"},states:{$ref:"#/$defs/PaywallStates"},style:{$ref:"#/$defs/PaywallStyle"},type:{description:"The component.",enum:["video"],type:"string"},visible:{$ref:"#/$defs/PaywallCondition"}},required:["src","type"],type:"object"},PaywallVideoFill:{additionalProperties:!1,description:"A muted video behind the component.",properties:{loop:{default:!0,description:"Loop.",type:"boolean"},poster:{description:"Poster.",maxLength:2048,pattern:"^(https://.+|asset:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))$",type:"string"},src:{description:"Src.",maxLength:2048,pattern:"^(https://.+|asset:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))$",type:"string"},type:{description:"Type.",enum:["video"],type:"string"}},required:["src","type"],type:"object"}}};var Ie=`${z}/paywalls`,Ks=`${Ie}/paywall.schema.json`,$n="paywall-assets",xl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Rr=e=>`"${e}"`;function Gs(e,t,n){let s=e.args[t];if(s===void 0||s.trim()==="")throw m(`${n} is required`);return s}async function nn(e,t){return(await h(e,t,"GET","/purchases/paywalls")).paywalls}function Tr(e,t){if(xl.test(t))return e.find(a=>a.id===t.toLowerCase());let n=e.filter(a=>a.name===t),s=n.length>0?n:e.filter(a=>a.name.toLocaleLowerCase()===t.toLocaleLowerCase());if(s.length>1)throw new f("ambiguous_paywall",`${s.length} paywalls are named ${JSON.stringify(t)}`,{hint:`name one by its id: ${s.map(a=>a.id).join(", ")}`});return s[0]}async function Qn(e,t,n){let s=await nn(e,t),a=Tr(s,n);if(!a)throw new f("paywall_not_found",`no paywall ${JSON.stringify(n)}`,{hint:s.length>0?`the project's: ${s.map(i=>i.name).join(", ")}`:"the project has none yet: palbase purchases:paywalls:put <name> --file <file> --revision 0 makes one"});return a}function Ia(e){let t=e.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60);return t===""?"paywall":t}function He(e,t,n,s,a=`${Ie}/<name>${s}`){let i=MT(e.io.cwd,Zf(e.io.cwd,n)).split(IT).join("/");if(!i.startsWith(`${z}/`)||i.split("/").includes(".."))throw m(`--${t} ${n}: the file goes under ${z}/, as the CLI writes nothing else in the checkout`,`--${t} ${a}`);if(!i.endsWith(s))throw m(`--${t} ${n}: the file's name ends in ${s}`);return i}async function Pr(e,t,n){let s=await ge(e.io.cwd,t);await ET(OT(s),{recursive:!0}),await ge(e.io.cwd,t),await jT(s,n)}var Qf=`${JSON.stringify(Sr,null,2)}
|
|
673
673
|
`;async function Ar(e,t,n){await Pr(e,Ks,Qf);let s=Hf.relative(Hf.dirname(t),Ks);await Pr(e,t,`${JSON.stringify({$schema:s.startsWith(".")?s:`./${s}`,...n},null,2)}
|
|
674
|
-
`)}async function Er(e,t){let n=me(await ke(e,t,"the paywall"),"the paywall");if(typeof n!="object"||n===null||Array.isArray(n))throw m("a paywall is a JSON object: { schema, name, default_locale, theme, root, \u2026 }");if("draft"in n&&"draft_revision"in n)throw m('the file is a whole paywall (its draft, its revision, its problems): give its "draft" alone, as purchases:paywalls:get --out writes it');if("definition"in n&&!("root"in n))throw m('the file is a definition inside something else: give the "definition" alone, as purchases:paywalls:get --out writes it');let{$schema:s,...a}=n;return a}function Cr(e,t){for(let n of t)e.out.note(` ${n.path}: ${n.code} \u2014 ${n.message}${n.warning?" (warning)":""}`)}var ey=e=>e.filter(t=>!t.warning).length;function ty(e){if(!(!(e instanceof E)||e.code!=="invalid_paywall"))return(e.body??{}).problems??[]}function ny(e,t,n){let s=ty(t);throw s!==void 0?(s.length>0&&(e.out.note(`The paywall breaks ${ey(s)} rule(s):`),Cr(e,s)),new f("invalid_paywall",`${n}: ${t.message}`,{hint:"fix each problem in the file (palbase purchases:paywalls:validate --file <file> checks it without saving)"})):t}function sy(e,t,n){return new f("paywall_changed",`the draft of ${e} is no longer at revision ${t}: someone saved a newer one since it was read \u2014 nothing was ${n}`,{hint:`read it again (palbase purchases:paywalls:get ${JSON.stringify(e)}), make the edit on it, and save it with that revision`})}async function LT(e,t){let n=new Map,s=(o,l)=>{if(o===void 0)return;let d=n.get(o)??[];d.includes(l)||d.push(l),n.set(o,d)},{placements:a}=await h(e,t,"GET","/purchases/placements");for(let o of a)s(o.paywall_id,o.key);let i=a.filter(o=>o.rule_count>0);return(await Promise.all(i.map(o=>h(e,t,"GET",`/purchases/placements/${k(o.key)}/rules`)))).forEach((o,l)=>{for(let d of o.rules)s(d.target.paywall_id,`${i[l].key} (rule)`)}),n}var DT={name:"purchases:paywalls",summary:"the environment's paywalls: each one's draft revision, the version published, and the placements that show it",details:["A paywall is a JSON definition: purchases:paywalls:get writes one to a file, purchases:paywalls:put saves the edit as its draft, purchases:paywalls:publish makes the draft what the apps draw.","An app sees a paywall once it is published and a placement shows it.","How a definition is written \u2014 every component and field, and three to start from: palbase purchases:paywalls:guide"],scope:"environment",async run(e){let t=await b(e),[n,s]=await Promise.all([nn(e,t),LT(e,t)]),a=n.map(i=>({...i,placements:s.get(i.id)??[]}));e.out.result({paywalls:a},()=>{if(a.length===0){e.out.line("No paywall yet."),e.out.line(`Write a definition and save it: palbase purchases:paywalls:put <name> --file ${Ie}/<name>.json --revision 0`);return}e.out.table(a,[{header:"name",value:i=>i.name},{header:"id",value:i=>i.id},{header:"draft",value:i=>`revision ${i.draft_revision}`},{header:"published",value:i=>i.published_version===0?"never":`version ${i.published_version}, ${L(i.published_at)}`},{header:"shown at",value:i=>i.placements.length===0?"\u2014":i.placements.join(", ")}])})}},xT={name:"purchases:paywalls:get",summary:"write a paywall's draft \u2014 or a version published \u2014 to a file to edit, with the revision it is at",usage:`<name|id> [--out <${Ie}/name.json>] [--version <n>]`,details:[`The file is the definition alone, as purchases:paywalls:put takes it, under ${Ie}/. Its first line names its JSON Schema, written beside it (${Ks}), so an editor checks the file as it is edited.`,"The revision printed is the one an edit is saved on: purchases:paywalls:put --revision."],args:{min:1,max:1},flags:{out:{type:"string",value:"file",description:`where under ${z}/ (default: ${Ie}/<name>.json)`},version:{type:"string",value:"n",description:"a published version instead of the draft"}},scope:"environment",async run(e){let t=await b(e),n=se(e.flags.version,"version");if(n===0)throw m("--version is 1 or more: the versions published");let s=await Qn(e,t,Gs(e,0,"the paywall's name or id")),a=e.flags.out!==void 0?He(e,"out",e.flags.out,".json"):`${Ie}/${Ia(s.name)}${n===void 0?"":`.v${n}`}.json`;if(n!==void 0){let r;try{r=await h(e,t,"GET",`/purchases/paywalls/${k(s.id)}/versions/${n}`)}catch(o){throw o instanceof E&&o.status===404?new f("version_not_found",`${s.name} has no version ${n}${s.published_version===0?": it was never published":`: its newest is ${s.published_version} (the newest 50 are kept)`}`):o}if(!r.definition)throw new f("unexpected_answer",`the module answered version ${n} of ${s.name} without its definition`);await Ar(e,a,r.definition),e.out.result({file:a,paywall_id:s.id,name:s.name,version:r.version,published_at:r.published_at,draft_revision:s.draft_revision},()=>{e.out.line(`Wrote version ${r.version} of ${s.name} (published ${L(r.published_at)}) to ${a}.`),e.out.line(`Saved as the draft, it goes on the draft's revision: palbase purchases:paywalls:put ${JSON.stringify(s.name)} --file ${a} --revision ${s.draft_revision}`)});return}let i=await h(e,t,"GET",`/purchases/paywalls/${k(s.id)}`);await Ar(e,a,i.draft),e.out.result({file:a,paywall_id:i.id,name:i.name,revision:i.draft_revision,published_version:i.published_version,problems:i.problems},()=>{e.out.line(`Wrote draft revision ${i.draft_revision} of ${i.name} to ${a}${i.published_version===0?" (never published)":` (version ${i.published_version} is published)`}.`),i.problems.length>0&&(e.out.note("The module says of the draft:"),Cr(e,i.problems)),e.out.line(`Save an edit of it: palbase purchases:paywalls:put ${JSON.stringify(i.name)} --file ${a} --revision ${i.draft_revision}`)})}},NT={name:"purchases:paywalls:validate",summary:"check a paywall definition as publishing it would, without saving it: every problem, by its path",usage:"--file <paywall.json>",details:["Every rule of the schema is checked, and every package against the environment's catalog as it is. A warning (what App Review expects of a paywall, say) does not stop a save or a publish.","It exits 1 while a problem that is not a warning is left; --json prints { valid, problems } either way."],flags:{file:{type:"string",value:"paywall.json",description:"the definition ('-' or none: stdin)"}},scope:"environment",async run(e){let t=await b(e),n=await Er(e,e.flags.file),s;try{s={valid:!0,problems:(await h(e,t,"POST","/purchases/paywalls/validate",n,j())).problems??[]}}catch(a){let i=ty(a);if(i===void 0)throw a;s={valid:!1,problems:i}}return e.out.result(s,()=>{s.problems.length>0&&Cr(e,s.problems);let a=s.problems.filter(i=>i.warning).length;e.out.line(s.valid?`The paywall can be published${a>0?`, with ${a} warning(s)`:""}.`:`The paywall breaks ${ey(s.problems)} rule(s): it cannot be saved as it is.`)}),s.valid?void 0:1}};async function ay(e,t,n,s){try{let a=await qe(e,t,"POST",`/purchases/paywalls/${k(n.id)}/publish`,void 0,{"if-match":Rr(s),...j()});return{version:a.body,fresh:a.status===201}}catch(a){if(a instanceof E&&a.status===412)throw sy(n.name,s,"published");ny(e,a,`${n.name} was not published`)}}function iy(e,t,n){e.out.line(n.fresh?`Published version ${n.version.version} of ${t}: the apps asking for a placement that shows it get it at once.`:`The draft of ${t} is what version ${n.version.version} already is: nothing new was published.`)}var qT={name:"purchases:paywalls:put",summary:"save a definition as a paywall's draft, on the revision it was edited from \u2014 or make the paywall, at revision 0; --publish publishes it too",usage:"<name|id> --file <paywall.json> --revision <n> [--publish]",details:["The module checks it first: a definition that breaks a rule is refused with every problem, and nothing is saved.","Of two people editing at once, the second is told \u2014 the draft moved past the revision they edited \u2014 never overwritten.","What the apps draw changes only when the draft is published (--publish, or purchases:paywalls:publish). A new paywall takes the name its definition gives.","How a definition is written: palbase purchases:paywalls:guide"],args:{min:1,max:1},flags:{file:{type:"string",value:"paywall.json",description:"the definition, as purchases:paywalls:get wrote it ('-' or none: stdin)"},revision:{type:"string",value:"n",description:"the draft revision it was edited from, as purchases:paywalls:get printed it (0 makes a new paywall)"},publish:{type:"boolean",description:"publish the saved draft as the next version"}},scope:"environment",async run(e){let t=await b(e),n=Gs(e,0,"the paywall's name or id"),s=se(e.flags.revision,"revision");if(s===void 0)throw m("--revision is the draft revision the paywall was edited from (0 for a new one): of two edits at once, the second is told, not saved over the first");let a=await Er(e,e.flags.file),i=Tr(await nn(e,t),n),r=e.flags.publish===!0?" and publish it":"",o;try{if(i){if(s===0)throw new f("paywall_exists",`${i.name} is there already, at draft revision ${i.draft_revision}: an edit of it is saved on the revision it was read at`,{hint:`palbase purchases:paywalls:get ${JSON.stringify(i.name)} writes it and prints the revision`});await v(e,t,`save the draft of ${i.name} over revision ${s}${r}`),o=await h(e,t,"PUT",`/purchases/paywalls/${k(i.id)}/draft`,{definition:a},{"if-match":Rr(s),...j()})}else{if(xl.test(n))throw new f("paywall_not_found",`no paywall ${n}`);if(s!==0)throw new f("paywall_not_found",`no paywall ${JSON.stringify(n)} to save revision ${s} over`,{hint:"--revision 0 makes it"});if(typeof a.name!="string"||a.name.toLocaleLowerCase()!==n.toLocaleLowerCase())throw m(`the file names the paywall ${JSON.stringify(a.name)}, not ${JSON.stringify(n)}: a new paywall takes the name its definition gives`,`set "name" to ${JSON.stringify(n)} in the file, or: palbase purchases:paywalls:put ${JSON.stringify(a.name??"")} \u2026`);await v(e,t,`make the paywall ${a.name}${r}`),o=await h(e,t,"POST","/purchases/paywalls",{definition:a},j())}}catch(d){if(d instanceof E&&d.status===412)throw sy(i?.name??n,s,"saved");if(d instanceof E&&d.code==="too_many_paywalls")throw new f("too_many_paywalls","the project has 100 paywalls, the most it holds: nothing was made",{hint:"delete one no placement shows: palbase purchases:paywalls:delete <name>"});ny(e,d,"the paywall was not saved")}let l=e.flags.publish===!0?await ay(e,t,o,o.draft_revision):void 0;e.out.result({...o,...l?{published:l.version,published_new:l.fresh}:{}},()=>{e.out.line(`${i?"Saved":"Made"} ${o.name}: its draft is at revision ${o.draft_revision}.`),o.problems.length>0&&(e.out.note("The module says of the draft:"),Cr(e,o.problems)),l?iy(e,o.name,l):e.out.line(`The apps draw it once it is published: palbase purchases:paywalls:publish ${JSON.stringify(o.name)}`)})}},KT={name:"purchases:paywalls:publish",summary:"publish a paywall's draft as its next version: what the apps asking for a placement that shows it draw from then on",usage:"<name|id> [--revision <n>]",details:["It is checked as the apps will get it: every package must be sold by the catalog, every asset still what was registered.","--revision names the draft revision that was looked at: a draft saved since is not published in its place. Without it, the draft as it is now is published.","A draft the same as the newest version publishes nothing new."],args:{min:1,max:1},flags:{revision:{type:"string",value:"n",description:"the draft revision looked at (default: the draft as it is now)"}},scope:"environment",async run(e){let t=await b(e),n=await Qn(e,t,Gs(e,0,"the paywall's name or id")),s=se(e.flags.revision,"revision")??n.draft_revision;await v(e,t,`publish draft revision ${s} of ${n.name}`);let a=await ay(e,t,n,s);e.out.result({...a.version,published_new:a.fresh},()=>iy(e,n.name,a))}},GT={name:"purchases:paywalls:delete",summary:"delete a paywall and its versions; one a placement or a running experiment shows is not deleted",usage:"<name|id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=await Qn(e,t,Gs(e,0,"the paywall's name or id"));await v(e,t,`delete the paywall ${n.name}: its draft and every version of it`);try{await h(e,t,"DELETE",`/purchases/paywalls/${k(n.id)}`,void 0,j())}catch(s){throw s instanceof E&&s.code==="paywall_in_use"?new f("paywall_in_use",`${n.name} is shown \u2014 a placement shows it, as its default or by a rule, or a running experiment does \u2014 so it was not deleted`,{hint:"palbase purchases:paywalls says where; give those placements another paywall, or stop the experiment, first"}):s}e.out.result({deleted:n.id,name:n.name},()=>e.out.line(`Deleted ${n.name}.`))}},UT={name:"purchases:paywalls:schema",summary:"the JSON Schema of a paywall definition: every component, its fields and their bounds, for an editor or an agent to check a file against",usage:`[--out <${Ks}>]`,details:["It is the module's contract, as the CLI was built with it: a file that passes may still be refused for what only the module knows (the catalog's packages, the project's assets) \u2014 purchases:paywalls:validate asks it.",'purchases:paywalls:get writes it too, and names it on the first line of each file ("$schema").'],flags:{out:{type:"string",value:"file",description:`where under ${z}/ (default: ${Ks}); --json prints it instead`}},scope:"none",async run(e){if(e.global.json){e.out.result(Sr,()=>{});return}let t=e.flags.out!==void 0?He(e,"out",e.flags.out,".json"):Ks;await Pr(e,t,Qf),e.out.line(`Wrote the paywall definition's JSON Schema to ${t}.`)}},BT={name:"purchases:paywalls:guide",summary:"how a paywall definition is written by hand \u2014 for an agent or a person: the flow, every component and field in the contract's words, three definitions to start from",usage:`[--out <${Ie}/GUIDE.txt>]`,details:["It is made from the definition's JSON Schema the CLI carries (purchases:paywalls:schema), so it says what this version of the CLI checks."],flags:{out:{type:"string",value:"file",description:`write it to a file under ${z}/ instead of printing it`}},scope:"none",async run(e){let t=Vf(Sr),n=e.flags.out;if(n===void 0){e.out.result({guide:t},()=>e.io.stdout(t));return}let s=He(e,"out",n,".txt");await Pr(e,s,t),e.out.result({file:s},()=>e.out.line(`Wrote the guide to ${s}.`))}},Yf=["image","video","font","html"];function Dl(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(e<10*1024?1:0)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function Us(e,t){return(await h(e,t,"GET","/purchases/paywalls/assets")).assets??[]}var Xf={unsupported_asset:"it is no file a paywall takes: an image (PNG, JPEG or WebP, never SVG), a video (MP4 or MOV), a font (TTF, OTF or WOFF2), or an HTML block as a zip",asset_too_large:"it is too large for a paywall: an image is at most 2 MiB, a video 50 MiB, a font or an HTML block's zip 5 MiB",asset_kind_mismatch:"its bytes are not the kind --kind names",invalid_archive:"the zip could not be opened: an HTML block is a zip with index.html at its root",archive_too_many_files:"the HTML block holds too many files: at most 200",archive_too_large:"the HTML block is too large opened: at most 20 MiB of files",unsafe_archive_path:"the HTML block has a file whose path leaves the zip: every file stays under its root",archive_link:"the HTML block holds a link: a zip of plain files is taken",archive_no_index:"the HTML block has no index.html at its root",asset_unreadable:"the purchases module could not read it at its public address; trying again in a moment is safe",too_many_assets:"the project has 500 assets, the most it holds: delete one no paywall names first (palbase purchases:paywalls:assets:delete <id>)"};async function Nl(e,t){let n;try{n=await h(e,t,"GET",`/storage/buckets/${$n}`)}catch(s){if(!(s instanceof E)||s.status!==404)throw s}if(!n?.public){if(n)throw new f("asset_bucket_private",`the project's ${$n} bucket is private: an app downloads a paywall's assets at their public address, and the CLI does not open a bucket the project closed`,{hint:`if everything in it may be read by anyone: palbase storage:buckets:set ${$n} --public`});await h(e,t,"PUT",`/storage/buckets/${$n}`,{public:!0,file_size_limit:null,allowed_mime_types:[],variants:[]}),e.out.note(`Made the public bucket ${$n}: paywall assets are kept in the project's own storage.`)}}function zT(e){let t=$r(e).normalize("NFKD").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(-80).replace(/^\.+$/,"")||"file";return`paywalls/${TT()}/${t}`}async function ql(e,t,n,s){let a=zT(n);await Al(e,t,n,$n,a);try{return await h(e,t,"POST","/purchases/paywalls/assets",{path:a,...s?{kind:s}:{}},j())}catch(i){throw await h(e,t,"DELETE",`/storage/buckets/${$n}/objects/${gr(a)}`).catch(()=>{}),i instanceof E&&i.code!==void 0&&i.code in Xf?new f(i.code,`${$r(n)} was not registered: ${Xf[i.code]}`):i}}var WT={name:"purchases:paywalls:assets",summary:"the project's paywall assets: the images, videos, fonts and HTML blocks a definition names asset:<id>",scope:"environment",async run(e){let t=await b(e),n=await Us(e,t);e.out.result({assets:n},()=>{if(n.length===0){e.out.line("No paywall asset yet."),e.out.line("Upload one: palbase purchases:paywalls:assets:upload <file>");return}e.out.table(n,[{header:"ref",value:s=>s.ref},{header:"kind",value:s=>s.kind},{header:"size",value:s=>Dl(s.bytes)},{header:"file",value:s=>s.path.split("/").pop()??s.path},{header:"registered",value:s=>L(s.created_at)}])})}},FT={name:"purchases:paywalls:assets:upload",summary:"upload a file to the project's storage and register it for paywalls: it answers the asset:<id> a definition names",usage:"<file> [--kind image|video|font|html]",details:[`The file goes to the project's public bucket ${$n} (made when there is none; a private one is left as it is, and refuses). The module then reads it there, says what it is by its bytes, and keeps their SHA-256: an app draws what it downloads only when it is that.`,"An image is PNG, JPEG or WebP, at most 2 MiB; a video MP4 or MOV, 50 MiB; a font TTF, OTF or WOFF2, 5 MiB; an HTML block a zip with index.html at its root, 5 MiB."],args:{min:1,max:1},flags:{kind:{type:"string",value:"kind",description:"what the file is meant to be: one whose bytes are another kind is refused"}},scope:"environment",async run(e){let t=await b(e),n=Zf(e.io.cwd,Gs(e,0,"the file")),s=e.flags.kind;if(s!==void 0&&!Yf.includes(s))throw m(`--kind is one of ${Yf.join(", ")}`);let a;try{let r=await CT(n);if(!r.isFile())throw new Error("it is not a file");a=r.size}catch(r){throw new f("unreadable_file",`${e.args[0]} could not be read: ${r instanceof Error?r.message:String(r)}`)}if(a===0)throw new f("empty_file",`${e.args[0]} is empty`);await v(e,t,`upload ${$r(n)} (${Dl(a)}) as a paywall asset`),await Nl(e,t);let i=await ql(e,t,n,s);e.out.result(i,()=>{e.out.line(`Registered ${$r(n)} as ${i.ref} (${i.kind}, ${Dl(i.bytes)}).`),e.out.line(`A definition names it "${i.ref}" where it takes ${i.kind==="html"?"an HTML block":i.kind==="image"?"an image":`a ${i.kind}`}.`)})}},JT={name:"purchases:paywalls:assets:delete",summary:"forget a paywall asset no paywall names, and remove its file from the project's storage",usage:"<asset:id|id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=Gs(e,0,"the asset's id").replace(/^asset:/,"").toLowerCase();if(!xl.test(n))throw m(`${e.args[0]} is not an asset: asset:<id>, as purchases:paywalls:assets lists them`);let s=(await Us(e,t)).find(i=>i.id===n);if(!s)throw new f("asset_not_found",`the project has no asset ${n}`,{hint:"palbase purchases:paywalls:assets lists them"});await v(e,t,`delete the paywall asset ${s.ref} (${s.path.split("/").pop()})`);try{await h(e,t,"DELETE",`/purchases/paywalls/assets/${k(n)}`,void 0,j())}catch(i){throw i instanceof E&&i.code==="asset_in_use"?new f("asset_in_use",`${s.ref} is named by a paywall \u2014 in its draft, or in a version kept \u2014 so it was not deleted`,{hint:"take it out of the paywall (its draft, then publish) first"}):i}let a=!0;await h(e,t,"DELETE",`/storage/buckets/${k(s.bucket)}/objects/${gr(s.path)}`).catch(()=>{a=!1}),e.out.result({deleted:n,object_removed:a},()=>{e.out.line(`Deleted ${s.ref}.`),a||e.out.warn(`its file stays in the project's storage: palbase storage:rm ${s.bucket}:${s.path}`)})}},ry=[DT,xT,NT,qT,KT,GT,UT,BT,WT,FT,JT];var py=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,sE=/^AuthKey_([A-Z0-9]{10})\.p8$/,aE=8192,uy=["testflight","play_internal"],Kl=100,cy=5,iE=5,Sy=300,rE=5,jr=900,oE=["iphone_6_9","iphone_6_5","ipad_13"],hy=/^[0-9a-f]{64}$/i,lE=10*1024*1024,my=3,dE={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg"},sn=`${z}/store/listing.json`,Rn={beta_review:"Beta App Review",export_compliance:"the export compliance answer",expire_build:"expiring the build",apply_listing:"writing the App Store page",submit_review:"the App Review submission",withdraw_review:"the withdrawal from App Review",release_version:"the release",phased_release:"a phased release change"};function Bs(e){return e.package_id?`package ${e.package_id}`:`app ${e.app_id??"?"}`}var Bl=e=>e.charAt(0).toUpperCase()+e.slice(1);function L(e){return e?e.slice(0,19).replace("T"," "):"\u2014"}function X(e,t,n){let s=e.args[t];if(s===void 0||s.trim()==="")throw m(`${n} is required`);return s}function rn(e,t,n,s){let a=st(e.cloud,t.env_ref),i;try{i=new URL(n).origin}catch{throw new f("unexpected_address",`${s} is not a URL: nothing was sent`)}if(i!==a)throw new f("unexpected_address",`${s} names ${i}, not the environment's address ${a}: nothing was sent`);return a}async function Da(e,t,n,s){let a;try{a=await e.io.fetch(t,{...n,redirect:"manual"})}catch(l){throw new f("network_error",`${s}: ${t} could not be reached: ${l instanceof Error?l.message:String(l)}`)}let i=await a.text(),r;if(i!=="")try{r=JSON.parse(i)}catch{r=i}if(a.status>=200&&a.status<300)return r;let o=r??{};throw new E({op:s,status:a.status,code:typeof o.error=="string"?o.error:`http_${a.status}`,message:ci(r,a.status),requestId:typeof o.request_id=="string"?o.request_id:a.headers.get("x-request-id")??void 0,retryAfter:pE(a.headers.get("retry-after"),o.retry_after,e.io.now()),body:r})}function pE(e,t,n){if(e!==null&&e.trim()!==""){let s=Number(e);if(Number.isFinite(s)&&s>=0)return s;let a=Date.parse(e);if(Number.isFinite(a))return Math.max(0,Math.ceil((a-n)/1e3))}return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function zl(e,t){if(!t.connected){e.out.line("No Apple account is connected."),e.out.line("Connect one: palbase stores:apple:connect --key-file AuthKey_<KEYID>.p8 --issuer-id <issuer id>");return}e.out.line(`Apple account: issuer ${t.issuer_id??"?"}, key ${t.key_id??"?"}`),e.out.line(`status: ${t.status??"not checked"}${t.checked_at?` (checked ${L(t.checked_at)})`:""}`),t.capabilities&&e.out.line(`reaches: ${t.capabilities.length>0?t.capabilities.join(", "):"nothing"}`),t.connected_at&&e.out.line(`connected ${L(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.status==="agreement"?e.out.line(`Apple waits on the account holder: ${t.action??"accept the account's agreements in App Store Connect"}, then palbase stores:apple:check`):t.action&&e.out.line(`To do: ${t.action}`)}function Wl(e,t){if(!t.connected){e.out.line("No Apple ID is signed in (App Review messages, App Privacy and app records need one)."),e.out.line("Sign one in: palbase stores:apple:connect --apple-id <you@example.com>");return}e.out.line(`Apple ID: ${t.apple_id??"?"}${t.team?` in ${t.team.name}`:""}${t.roles&&t.roles.length>0?` (${t.roles.join(", ")})`:""}`),e.out.line(`session: ${t.status??"?"}${t.checked_at?` (checked ${L(t.checked_at)})`:""}`),t.connected_at&&e.out.line(`signed in ${L(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.shared_from&&e.out.line(`shared from ${t.shared_from.name||t.shared_from.ref||t.shared_from.project_id}, where it was signed in: used here too; signed out from either, it serves neither`),t.action&&e.out.line(`To do: ${t.action}`)}var uE={name:"stores:apple",summary:"the environment's Apple account and Apple ID: whether each is connected, what Apple last said of them, what the key reaches",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/stores/apple"),s=await h(e,t,"GET","/stores/apple/session").catch(a=>{if(!(a instanceof E&&a.status===404))throw a});e.out.result(s===void 0?n:{...n,apple_id_session:s},()=>{zl(e,n),s!==void 0&&(e.out.line(""),Wl(e,s))})}};async function cE(e,t){let n=new Uint8Array([...new TextEncoder().encode("palbase/stores/apple-id/password/1"),0,...new TextEncoder().encode(e.grant)]),{enc:s,ct:a}=await wo(Mt(e.seal_key),n,new TextEncoder().encode(t)),i=new Uint8Array(s.length+a.length);return i.set(s),i.set(a,s.length),ga(i)}async function hE(e,t,n){if(e.flags["key-file"]!==void 0)throw m("--apple-id or --key-file, not both");if(e.flags["print-link"]===!0){await v(e,t,"make a link that signs an Apple ID in");let p=await h(e,t,"POST","/stores/apple/session/grants",void 0,j());rn(e,t,p.connect_url,"the sign-in link"),e.out.result({connect_url:p.connect_url,expires_at:p.expires_at},()=>{e.out.line(p.connect_url),e.out.note(`Open it in a browser and sign in there; it works once, until ${L(p.expires_at)}.`)});return}if(!e.io.interactive)throw m("signing an Apple ID in asks for Apple's code at the terminal","or --print-link for a link a browser opens");await v(e,t,`sign the Apple ID ${n} in`);let s=await Me(e,`the password of ${n}`),a=await h(e,t,"POST","/stores/apple/session/grants",void 0,j()),i=rn(e,t,a.connect_url,"the sign-in link"),r=await cE(a,s),o=(p,u)=>Da(e,`${i}/stores/connect/apple-id${p}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({grant:a.grant,...u})},"signing the Apple ID in"),l=await o("",{apple_id:n,password_sealed:r});for(;l.step==="code";){let p=l.method==="phone"?`to ${l.destination??"your phone"}`:"to your trusted devices",u=(await e.io.prompt(`Apple sent a code ${p}. Code: `)).replace(/\s/g,"");try{l=await o("/code",{code:u})}catch(g){if(g instanceof E&&g.code==="apple_code_refused"){e.out.note("Apple did not accept this code.");continue}throw g}}if(l.step==="team"){let p=l.teams??[],u=e.flags.team,g=u===void 0?void 0:p.find(y=>y.id===u||y.name===u);if(u!==void 0&&g===void 0)throw new f("unknown_team",`${n} is not in the team ${u}: ${p.map(y=>y.name).join(", ")}`);for(;g===void 0;){p.forEach((w,_)=>e.out.note(` ${_+1}. ${w.name}`));let y=Number((await e.io.prompt(`${n} is in ${p.length} teams. The one this environment's apps are in [1-${p.length}]: `)).trim());g=p[y-1]}l=await o("/team",{team:g.id})}let d=l.session??{connected:!1};e.out.result(d,()=>{e.out.line(`Signed ${n} in to ${N(t)}.`),Wl(e,d)})}var mE={name:"stores:apple:connect",summary:"connect an App Store Connect API key, or sign an Apple ID in: either goes from this computer straight to the environment, never through Studio",usage:"--key-file <AuthKey_KEYID.p8> --issuer-id <issuer id> [--key-id <KEYID>] | --apple-id <email> [--team <team>] | [--apple-id <email>] --print-link",details:["App Store Connect \u2192 Users and Access \u2192 Integrations \u2192 App Store Connect API makes the key and shows the Issuer ID; stores:apple then says what its role reaches.","Studio is asked for a one-time grant alone; the key is posted with it to the environment's own address. --print-link prints a link that takes the key in a browser instead.","--apple-id signs an Apple ID in, for what Apple's API does not do: App Review's messages and the answer to them, App Privacy, making an app record. Its password is read here and handed to Apple through the environment, never kept; then Apple's code, and the team when the Apple ID is in more than one. An owner's or an admin's."],flags:{"apple-id":{type:"string",value:"email",description:"sign this Apple ID in instead of connecting a key"},team:{type:"string",value:"team",description:"the Apple ID's team, by name or id, when it is in more than one"},"key-file":{type:"string",value:"AuthKey_KEYID.p8",description:"the .p8 file Apple gave when the key was made"},"key-id":{type:"string",value:"KEYID",description:"the key's id (default: from the file's name)"},"issuer-id":{type:"string",value:"issuer id",description:"the account's issuer id"},"print-link":{type:"boolean",description:"only print a link that takes the key in a browser (valid 30 minutes, once)"}},scope:"environment",async run(e){let t=await b(e),n=e.flags["apple-id"];if(n!==void 0){if(n.trim()==="")throw m("--apple-id is the Apple ID: an email address");await hE(e,t,n.trim());return}if(e.flags["print-link"]===!0){if(e.flags["key-file"]!==void 0)throw m("--print-link or --key-file, not both");await v(e,t,"make a link that connects an Apple account");let g=await h(e,t,"POST","/stores/apple/grants",void 0,j());rn(e,t,g.connect_url,"the connect link"),e.out.result({connect_url:g.connect_url,expires_at:g.expires_at},()=>{e.out.line(g.connect_url),e.out.note(`Open it in a browser and pick the .p8 file; it works once, until ${L(g.expires_at)}.`)});return}let s=e.flags["key-file"],a=e.flags["issuer-id"];if(s===void 0)throw m("--key-file names the .p8 file","or --print-link for a link a browser opens");if(a===void 0||a.trim()==="")throw m("--issuer-id is the account's issuer id (App Store Connect \u2192 Users and Access \u2192 Integrations)");let i=ZT(s),r=e.flags["key-id"]??sE.exec(i)?.[1];if(r===void 0)throw m(`--key-id is needed: ${i} is not named AuthKey_<KEYID>.p8`);let o;try{let g=an(e.io.cwd,s);if((await Ul(g)).size>aE)throw new f("not_a_key",`${s} is larger than a .p8 key`);o=await HT(g,"utf8")}catch(g){throw g instanceof f?g:new f("unreadable_file",`${s} could not be read: ${g instanceof Error?g.message:String(g)}`)}if(!o.includes("-----BEGIN PRIVATE KEY-----"))throw new f("not_a_key",`${s} is not a .p8 key (no "BEGIN PRIVATE KEY")`);await v(e,t,`connect the Apple account of issuer ${a} with key ${r}`);let l=await h(e,t,"POST","/stores/apple/grants",void 0,j()),d=rn(e,t,l.connect_url,"the connect link"),p={grant:l.grant,issuer_id:a.trim(),key_id:r,private_key:o,file_name:i},u=await Da(e,`${d}/stores/connect`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(p)},"connecting the Apple key");e.out.result(u,()=>{e.out.line(`Connected key ${r} to ${N(t)}.`),zl(e,u)})}},gE={name:"stores:apple:check",summary:"ask Apple about the connected key again (after the account holder accepted its agreements, or its role changed), or with --apple-id about the Apple ID",flags:{"apple-id":{type:"boolean",description:"check the Apple ID's session instead: whether Apple still takes it, its team and roles"}},scope:"environment",async run(e){let t=await b(e);if(e.flags["apple-id"]===!0){let s=await h(e,t,"POST","/stores/apple/session/check",void 0,j());e.out.result(s,()=>Wl(e,s));return}let n=await h(e,t,"POST","/stores/apple/check",void 0,j());e.out.result(n,()=>zl(e,n))}},fE={name:"stores:apple:disconnect",summary:"take the environment's Apple key away (Apple keeps its apps and builds), or with --apple-id sign its Apple ID out",flags:{"apple-id":{type:"boolean",description:"sign the Apple ID out, at Apple too, and forget its session; the key stays"}},scope:"environment",async run(e){let t=await b(e);if(e.flags["apple-id"]===!0){let n=await h(e,t,"GET","/stores/apple/session"),s=n.shared_from?` (signed in for ${n.shared_from.name||n.shared_from.ref||n.shared_from.project_id}: every environment that uses it loses it)`:"";await v(e,t,`sign the Apple ID out${s}`),await h(e,t,"DELETE","/stores/apple/session",void 0,j()),e.out.result({disconnected:!0},()=>e.out.line(`Signed the Apple ID out of ${N(t)}, at Apple too.`));return}await v(e,t,"disconnect the Apple account (a key Palbase made is revoked at Apple)"),await h(e,t,"DELETE","/stores/apple",void 0,j()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected the Apple account from ${N(t)}.`))}},es={asc:"App Store Connect API key",apns:"APNs keys (one for production, one for the sandbox)",iap:"In-App Purchase key"},yE=2,bE=60;function Fl(e,t){let n=t.kind==="apns"?`APNs key (${t.environment??"?"})`:es[t.kind]??t.kind;e.out.line(` ${t.key_id} ${n}${t.module?` for ${t.module}`:""}: ${t.state}${t.bundles&&t.bundles.length>0?` \u2014 ${t.bundles.join(", ")}`:""}`),t.note&&e.out.line(` ${t.note}`)}async function $y(e,t,n){let s=o=>n.some(l=>l.kind===o&&l.state==="waiting"),a=await h(e,t,"GET","/stores/apple"),i=await h(e,t,"GET","/notify/providers"),r=await h(e,t,"GET","/purchases/apple");return{asc:!a.connected,apns:!i.providers.some(o=>o.channel==="push"&&o.provider==="apns")&&!s("apns"),iap:!r.connected&&!s("iap")}}var wE={name:"stores:apple:keys",summary:"the keys Palbase made at Apple for the environment with its Apple ID, where each stands, and which keys the environment lacks",details:["Palbase makes them with the Apple ID signed in for the environment (stores:apple:connect --apple-id): stores:apple:keys:make. No one downloads a .p8."],scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/stores/apple/keys"),s=await $y(e,t,n.keys);e.out.result({...n,lacking:Object.keys(s).filter(a=>s[a])},()=>{n.keys.length===0?e.out.line("Palbase made no key at Apple for this environment."):(e.out.line("Keys Palbase made at Apple:"),n.keys.forEach(i=>Fl(e,i)));let a=Object.keys(es).filter(i=>s[i]);if(a.length===0){e.out.line("The environment lacks no key.");return}e.out.line(`The environment lacks: ${a.map(i=>es[i]).join("; ")}.`),e.out.line("Make them at Apple: palbase stores:apple:keys:make")})}},vE={name:"stores:apple:keys:make",summary:"make at Apple, with the environment's Apple ID, the keys it lacks \u2014 App Store Connect API, APNs, In-App Purchase \u2014 and connect them: one confirmation",details:["With no flag, every key the environment lacks; a key it has is kept. The Apple ID is an Admin or the Account Holder of the team.","APNs: one key for production and one for the sandbox, scoped to the environment's iOS apps; notify takes them. In-App Purchase: for one iOS app (--bundle with more than one); purchases connects it."],flags:{asc:{type:"boolean",description:"the App Store Connect API key"},apns:{type:"boolean",description:"the APNs keys"},iap:{type:"boolean",description:"the In-App Purchase key"},bundle:{type:"string",description:"the iOS app the In-App Purchase key is for, when the environment has more than one"}},scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/stores/apple/keys"),s=await $y(e,t,n.keys),a=Object.keys(es).filter(p=>e.flags[p]===!0),i=a.length>0?a:Object.keys(es);for(let p of i.filter(u=>!s[u]))e.out.note(`The environment has its ${es[p]}: it is kept.`);let r=i.filter(p=>s[p]);if(r.length===0){e.out.result({keys:[]},()=>e.out.line("The environment lacks none of these keys: nothing to make."));return}await v(e,t,`make at Apple and connect: ${r.map(p=>es[p]).join("; ")}`);let o=[];for(let p of r){let u={kind:p};p==="iap"&&typeof e.flags.bundle=="string"&&(u.bundle=e.flags.bundle);let g=await h(e,t,"POST","/stores/apple/keys",u,j());o.push(...g.keys)}let l=e.io.now()+bE*1e3,d=o;for(;d.some(p=>p.state==="waiting")&&e.io.now()<l;){await e.io.sleep(yE*1e3);let p=await h(e,t,"GET","/stores/apple/keys");d=o.map(u=>p.keys.find(g=>g.key_id===u.key_id)??u)}e.out.result({keys:d},()=>{e.out.line(`Made at Apple for ${N(t)}:`),d.forEach(p=>Fl(e,p)),d.some(p=>p.state==="waiting")&&e.out.note("A module has not taken its key yet: palbase stores:apple:keys says when it has.")})}},_E={name:"stores:apple:keys:revoke",summary:"revoke at Apple an APNs or In-App Purchase key Palbase made for the environment (the App Store Connect key is revoked as stores:apple:disconnect takes it away)",usage:"<key-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=X(e,0,"the key id"),n=await b(e);await v(e,n,`revoke the key ${t} at Apple`);let s=await h(e,n,"DELETE",`/stores/apple/keys/${k(t)}`,void 0,j());e.out.result(s,()=>{e.out.line(`Revoked ${t} at Apple.`),Fl(e,s)})}};async function Py(e,t,n){let s=(await Pe(e.studio)).filter(i=>i.project_id===t.project_id),a=s.find(i=>i.slug===n||i.ref===n);if(!a)throw new f("no_such_environment",`${t.project_name} has no environment ${JSON.stringify(n)}`,{hint:`its environments: ${s.map(i=>i.slug).join(", ")}`});if(a.ref===t.env_ref)throw m("the environment uses its own session: name another environment of the project");return a}var kE={name:"stores:apple:share",summary:"share the environment's Apple ID session with another environment of the project, which uses it while it has none of its own",usage:"<environment>",details:["An environment of the same project alone: Palbase refuses another project's, of your organization or not (other_project).","You are an owner or an admin of both environments; a key or an environment token does not share.","Signed out, or signed in again, the session serves none it was shared with: share it again. stores:apple:unshare takes it back."],args:{min:1,max:1},scope:"environment",async run(e){let t=X(e,0,"the environment to share with"),n=await b(e),s=await Py(e,n,t);await v(e,n,`share its Apple ID session with ${s.name} (${s.slug})`);let a=await h(e,n,"PUT",`/stores/apple/session/shares/${k(s.ref)}`,void 0,j());e.out.result(a,()=>{e.out.line(`Shared with ${s.name} (${s.ref}): it uses this environment's Apple ID while it has none of its own.`)})}},SE={name:"stores:apple:unshare",summary:"take the environment's Apple ID session back from another environment of the project",usage:"<environment>",args:{min:1,max:1},scope:"environment",async run(e){let t=X(e,0,"the environment to take it back from"),n=await b(e),s=await Py(e,n,t);await v(e,n,`take its Apple ID session back from ${s.name} (${s.slug})`),await h(e,n,"DELETE",`/stores/apple/session/shares/${k(s.ref)}`,void 0,j()),e.out.result({unshared:s.ref},()=>{e.out.line(`Taken back from ${s.name} (${s.ref}): it uses this environment's Apple ID no more.`)})}};function Jl(e,t){if(!t.connected){e.out.line("Google Play is not connected."),e.out.line("Connect it: palbase stores:google:connect");return}e.out.line(`Play connection: ${t.service_account??"?"}`),e.out.line(`status: ${t.status??"not checked"}${t.checked_at?` (checked ${L(t.checked_at)})`:""}`),t.capabilities&&e.out.line(`reaches: ${t.capabilities.length>0?t.capabilities.join(", "):"nothing yet"}`);for(let n of t.apps??[])e.out.line(` ${n.package_name}: ${n.reached?`reached (${n.capabilities.join(", ")})`:`not reached \u2014 ${n.problem??"Play did not say why"}`}`);t.connected_at&&e.out.line(`connected ${L(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.action&&e.out.line(`To do: ${t.action}`)}var $E={name:"stores:google",summary:"the environment's Play connection: the service account Play Console invites, what Play let it reach",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/stores/google");e.out.result(n,()=>Jl(e,n))}},PE={name:"stores:google:connect",summary:"connect Google Play: Palbase makes a service account for the environment, which your Play Console invites",details:["No key changes hands: Palbase acts as the service account it made in its own Google Cloud project.","Then, in Play Console \u2192 Users and permissions, invite the service account with the app (Release to testing tracks; for purchases also View financial data and Manage orders and subscriptions), link the Android app (stores:apps:link) and check: stores:google:check."],scope:"environment",async run(e){let t=await b(e);await v(e,t,"connect Google Play (Palbase makes a service account for it)");let n=await h(e,t,"POST","/stores/google",void 0,j());e.out.result(n,()=>Jl(e,n))}},AE={name:"stores:google:check",summary:"ask Play what the environment's service account reaches of each Android app: after Play Console invited it",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"POST","/stores/google/check",void 0,j());e.out.result(n,()=>Jl(e,n))}},RE={name:"stores:google:disconnect",summary:"delete the environment's service account at Google: Play Console's invite of it reaches nothing any more",scope:"environment",async run(e){let t=await b(e);await v(e,t,"disconnect Google Play (its service account is deleted)"),await h(e,t,"DELETE","/stores/google",void 0,j()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected Google Play from ${N(t)}.`))}};function TE(e,t){t.asc_app_id===null&&e.out.line(`Apple has no App Store Connect record for ${t.bundle_id} yet: make it with palbase stores:apps:record ${t.app_id} --name <App Store name> (needs an Apple ID signed in), or on the website (App Store Connect \u2192 Apps \u2192 +), then link again.`)}var EE={name:"stores:apps",summary:"the environment's apps linked to their store",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/stores/apps");e.out.result(n,()=>{n.apps.length===0?e.out.line("No app is linked yet: palbase stores:apps:link <app id>"):e.out.table(n.apps,[{header:"app",value:s=>s.app_id},{header:"platform",value:s=>s.platform},{header:"name",value:s=>s.name},{header:"bundle id / package",value:s=>s.bundle_id},{header:"team",value:s=>s.team_id??""},{header:"app store connect",value:s=>s.platform==="ios"?s.asc_app_id??"no record yet":""}])})}},CE={name:"stores:apps:link",summary:"link an app of the project to its store: an iOS app to the App Store, an Android app to Google Play (with an upload key Palbase makes)",usage:"<app id> [--name <name in the store>]",args:{min:1,max:1},flags:{name:{type:"string",value:"name",description:"its name in the store (default: the bundle id or package)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=e.flags.name!==void 0?{name:e.flags.name}:{};await v(e,t,`link the app ${n} to its store`);let a=await h(e,t,"POST",`/stores/apps/${k(n)}/link`,s,j());e.out.result(a,()=>{if(a.platform==="android"){e.out.line(`Linked ${a.name} (${a.bundle_id}) to Google Play.`),a.upload_key&&e.out.line(`upload key: ${a.upload_key.fingerprint} (Palbase signs its builds with it)`),a.play?e.out.line(`Play: ${a.play.reached?`reached (${a.play.capabilities.join(", ")})`:`not reached \u2014 ${a.play.problem??"?"}`}`):e.out.line("Play was not asked \u2014 the project has no Play connection (stores:google:connect), or Google did not answer (a service account made just now answers after a minute): palbase stores:google:check asks it.");return}e.out.line(`Linked ${a.name} (${a.bundle_id}, team ${a.team_id}).`),TE(e,a)})}},jE={name:"stores:feedback",summary:"an app's TestFlight feedback: testers' screenshots and crashes",usage:"<app id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await h(e,t,"GET",`/stores/apps/${k(n)}/feedback`);e.out.result(s,()=>{s.feedback.length===0?e.out.line("No feedback yet."):e.out.table(s.feedback,[{header:"when",value:a=>L(a.created_at)},{header:"kind",value:a=>a.kind},{header:"tester",value:a=>a.email??""},{header:"comment",value:a=>a.comment??""},{header:"id",value:a=>a.id}]),s.feedback.length>0&&e.out.note(`Read one, with a crash's log: palbase stores:feedback:get ${n} <crash|screenshot> <id>`)})}},OE={name:"stores:feedback:get",summary:"one of an app's TestFlight feedback: the device, the build, and a crash's log",usage:"<app id> <crash|screenshot> <feedback id>",details:["A crash's log is cut at 32 KiB: the exception and the crashed thread come first. A screenshot's images are Apple's links, which expire."],args:{min:3,max:3},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=e.args[1];if(s!=="crash"&&s!=="screenshot")throw m("the kind is crash or screenshot");let a=X(e,2,"the feedback's id"),i=await h(e,t,"GET",`/stores/apps/${k(n)}/feedback/${s}/${k(a)}`);e.out.result(i,()=>{e.out.line(`${Bl(i.kind)} ${A(i.id)}, sent ${L(i.created_at)}${i.email?` by ${A(i.email)}`:""}`);let r=[i.device_model,i.os_version?`iOS ${i.os_version}`:void 0,i.locale].filter(Boolean).join(", ");r&&e.out.line(`from: ${A(r)}`),i.asc_build_id&&e.out.line(`build: ${A(i.asc_build_id)} (App Store Connect's id)`),i.comment&&e.out.line(`comment: ${A(i.comment)}`);for(let o of i.screenshots??[])e.out.line(`screenshot ${o.width}x${o.height}, until ${L(o.expires_at)}: ${A(o.url)}`);i.kind==="crash"&&(i.crash_log?(e.out.line(i.crash_log_cut?"crash log (cut at 32 KiB):":"crash log:"),e.out.line(i.crash_log)):e.out.line("Apple has no log of this crash."))})}};function gy(e,t,n){let s={on:"on: App Store Connect tells Palbase each change the moment it happens",refused:"refused: the connected key's role may not make it",failed:"failed: Apple refused it",none:"not made yet"};e.out.line(`App Store Connect webhook: ${s[n.state]??n.state}`),n.error&&e.out.line(`why: ${A(n.error)}`),n.url&&e.out.line(`reports to: ${A(n.url)}`),n.event_types.length>0&&e.out.line(`tells: ${n.event_types.join(", ")}`),n.installed_at&&e.out.line(`made ${L(n.installed_at)}${n.asc_webhook_id?` (App Store Connect's ${A(n.asc_webhook_id)})`:""}`),e.out.line(n.last_delivery_at?`last delivery: ${A(n.last_delivery_type??"?")}, ${L(n.last_delivery_at)}`:"last delivery: none yet"),n.pinged_at&&e.out.line(`last ping: ${L(n.pinged_at)}`),n.state!=="on"&&e.out.note(`Until it is on, Palbase reads Apple every few minutes. Make it again: palbase stores:webhook ${t} --make`)}var fy=30,yy=2,ME={name:"stores:webhook",summary:"an iOS app's App Store Connect webhook: whether Apple tells Palbase each change at once, and its last delivery",usage:"<app id> [--make] [--ping]",details:["Palbase makes the webhook when the app is linked (the key's role must be Admin or App Manager), and tries again every day while it is not on; meanwhile it reads Apple every few minutes.","--make points it at the environment again with a new secret; --ping asks Apple to send it a ping and waits for it to arrive."],args:{min:1,max:1},flags:{make:{type:"boolean",description:"make it again: a new secret, pointed at the environment"},ping:{type:"boolean",description:"ask Apple to send it a ping, and wait for it to arrive"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=`/stores/apps/${k(n)}/webhook`,a;if(e.flags.make?(await v(e,t,`make the App Store Connect webhook of ${n} again`),a=await h(e,t,"POST",s,{})):a=await h(e,t,"GET",s),e.flags.ping){let i=a.last_delivery_at;await h(e,t,"POST",`${s}/ping`,{});for(let o=0;o<fy&&(await e.io.sleep(yy*1e3),a=await h(e,t,"GET",s),!(a.pinged_at&&a.last_delivery_at&&a.last_delivery_at!==i));o+=yy);let r=!!(a.last_delivery_at&&a.last_delivery_at!==i);e.out.result({...a,ping_arrived:r},()=>{gy(e,n,a),e.out.line(r?"The ping arrived.":`Apple did not deliver the ping within ${fy} s: look again with palbase stores:webhook ${n}`)});return}e.out.result(a,()=>gy(e,n,a))}},La=e=>e==null?"\u2014":`${(e*100).toFixed(2)}%`,IE={ok:"App Store crash counts: the App Crashes report, last 30 days",none_yet:"App Store crash counts: Apple's report has no day yet",requested:"App Store crash counts: asked of Apple now; its first days come in a day or two",not_requested:"App Store crash counts: Palbase asks Apple for the report with its next round",admin_key_needed:"App Store crash counts: only an Admin key may read the App Crashes report \u2014 the connected key is not one"},LE={name:"stores:vitals",summary:"an app's health as its store has it: crashes, terminations and hangs, crash and ANR rates by version",usage:"<app id>",details:["An iOS app: the crashes testers sent from TestFlight, what TestFlight counted of its newest builds (installs, sessions, crashes, feedback), its App Store versions' terminations, hangs and launches, and App Store crashes by day (the App Crashes report, an Admin key's).","An Android app: Play's Android vitals \u2014 each version code's crash and ANR rates over seven days, its errors, and what Play flagged.","A new day of it is the environment's stores.vitals.changed event."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await h(e,t,"GET",`/stores/apps/${k(n)}/vitals`);e.out.result(s,()=>{if(e.out.line(`${s.platform==="android"?"Google Play":"App Store"} health of ${n}, read ${L(s.read_at)}`),e.out.line(s.through?`crash data through ${s.through}`:"no crash data yet"),s.apple){let a=s.apple;a.testflight_crashes.length===0?e.out.line("TestFlight crashes: none"):(e.out.line(`TestFlight crashes (palbase stores:feedback:get ${n} crash <id> reads one with its log):`),e.out.table(a.testflight_crashes,[{header:"when",value:i=>L(i.created_at)},{header:"id",value:i=>i.id},{header:"comment",value:i=>i.comment??""}])),a.testflight_builds.length>0&&(e.out.line("TestFlight builds, as Apple counts them:"),e.out.table(a.testflight_builds,[{header:"build",value:i=>`${i.version} (${i.build_number})${i.expired?", expired":""}`},{header:"days",value:i=>i.from?`${i.from} \u2013 ${i.to??i.from}`:"\u2014"},{header:"installs",value:i=>String(i.installs)},{header:"sessions",value:i=>String(i.sessions)},{header:"crashes",value:i=>String(i.crashes)},{header:"feedback",value:i=>String(i.feedback)},{header:"invites",value:i=>String(i.invites)}])),e.out.line(IE[a.crash_counts]??a.crash_counts),a.crash_days.length>0&&e.out.table(a.crash_days,[{header:"day",value:i=>i.date},{header:"version",value:i=>i.version},{header:"crashes",value:i=>String(i.crashes)},{header:"devices",value:i=>String(i.devices)}]),a.metrics.length===0?e.out.line("terminations, hangs, launches: Apple publishes none yet (enough people who share their data must run an App Store version)"):e.out.table(a.metrics,[{header:"what",value:i=>i.category},{header:"metric",value:i=>i.identifier},{header:"version",value:i=>i.version},{header:"value",value:i=>`${i.value}${i.unit?` ${i.unit}`:""}`},{header:"devices",value:i=>i.device??""}])}if(s.play){let a=s.play;a.versions.length===0?e.out.line("crash and ANR rates: Play has none yet (too few users)"):e.out.table(a.versions,[{header:"version code",value:i=>String(i.version_code)},{header:"crashes",value:i=>La(i.crash_rate)},{header:"crashes in use",value:i=>La(i.user_perceived_crash_rate)},{header:"ANRs",value:i=>La(i.anr_rate)},{header:"ANRs in use",value:i=>La(i.user_perceived_anr_rate)},{header:"users",value:i=>String(i.users)}]),a.issues.length>0&&e.out.table(a.issues,[{header:"error",value:i=>i.type},{header:"cause",value:i=>i.cause},{header:"where",value:i=>i.location},{header:"reports",value:i=>String(i.reports)},{header:"users",value:i=>String(i.users)}]);for(let i of a.anomalies)e.out.line(`Play flagged ${A(i.metric)}${i.version_code?` of version code ${i.version_code}`:""}${i.value!==null?`: ${La(i.value)}`:""}${i.from?` (${i.from}${i.to?` \u2013 ${i.to}`:""})`:""}`)}})}};function DE(e,t){e.out.line(`Package ${t.id} of ${t.app_id}: build ${t.build_number}${t.version?`, version ${t.version}`:""} \u2014 ${t.status==="uploaded"?`uploaded ${L(t.uploaded_at)}`:"waiting for its build"}`),t.size!==null&&e.out.line(`.ipa: ${t.size} bytes, sha256 ${t.sha256??"?"}`),t.bundles.length>0&&e.out.line(`bundles: ${t.bundles.map(n=>n.bundle_id+(n.path?` (${n.path})`:"")).join(", ")}`),t.notes&&e.out.line(`notes: ${t.notes}`),e.out.line(`made ${L(t.created_at)} by ${t.created_by} (command ${t.command_id})`);for(let n of t.deliveries)e.out.line(`${n.channel}: ${Ay(n)}`)}function Ay(e){let t=[e.status];return e.processing_state&&t.push(`Apple: ${e.processing_state}`),e.play_version_code!==void 0&&t.push(`Play: version code ${e.play_version_code}${e.play_release_status?`, ${e.play_release_status}`:""}`),e.groups.length>0&&t.push(`${e.groups.length} group${e.groups.length===1?"":"s"}`),e.error_code&&t.push(`${e.error_code}${e.error?` \u2014 ${e.error}`:""}`),t.join(", ")}var xE={name:"stores:packages",summary:"the packages handed to the stores, newest first",usage:"[--app <app id>] [--limit <n>]",flags:{app:{type:"string",value:"app id",description:"only this app's"},limit:{type:"string",value:"n",description:"how many (1\u2013200, default 20)"}},scope:"environment",async run(e){let t=await b(e),n=se(e.flags.limit,"limit")??20;if(n<1||n>200)throw m("--limit is a whole number from 1 to 200");let s=new URLSearchParams({limit:String(n),...e.flags.app?{app_id:e.flags.app}:{}}),a=await h(e,t,"GET",`/stores/packages?${s}`);e.out.result(a,()=>{a.packages.length===0?e.out.line("No package yet."):e.out.table(a.packages,[{header:"package",value:i=>i.id},{header:"app",value:i=>i.app_id},{header:"build",value:i=>String(i.build_number)},{header:"version",value:i=>i.version??""},{header:"status",value:i=>i.status},{header:"testflight",value:i=>i.deliveries.find(r=>r.channel==="testflight")?.status??""},{header:"made",value:i=>L(i.created_at)}]),a.next_cursor&&e.out.note(`More than ${n}: raise --limit to see older ones.`)})}},NE={name:"stores:packages:get",summary:"one package: its build, its bundles and its deliveries",usage:"<package id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",`/stores/packages/${k(X(e,0,"the package's id"))}`);e.out.result(n,()=>DE(e,n))}},qE={name:"stores:packages:create",summary:"make a package of an app: its build number, and the URL and token its .ipa is uploaded with",usage:"<app id> --command-id <id> [--notes <text>] [--entitlements-file <json>]",details:["The build is made with the build number it answers (CFBundleVersion), then uploaded: palbase stores:packages:upload.","The same --command-id again answers the same package, with a new upload token while it waits for its build: a build machine sends its run's id."],args:{min:1,max:1},flags:{"command-id":{type:"string",value:"id",description:"names the request (a CI run id): sent again, the same package"},notes:{type:"string",value:"text",description:"notes kept with it (a commit, a branch)"},"entitlements-file":{type:"string",value:"json",description:'what each bundle asks for, by bundle id ({"com.acme.app": {"aps-environment": "production"}})'}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=e.flags["command-id"];if(s===void 0||s.trim()==="")throw m("--command-id names the request: sent again, it answers the same package");let a={command_id:s};if(e.flags.notes!==void 0&&(a.notes=e.flags.notes),e.flags["entitlements-file"]!==void 0){let o=me(await ke(e,e.flags["entitlements-file"],"the entitlements"),"the entitlements"),l=d=>typeof d=="object"&&d!==null&&!Array.isArray(d);if(!l(o)||!Object.values(o).every(l))throw m("the entitlements are an object of bundle id \u2192 its entitlements object");a.entitlements=o}await v(e,t,`make a package of ${n}`);let i=await qe(e,t,"POST",`/stores/apps/${k(n)}/packages`,a,j()),r=i.body;e.out.result(r,()=>{if(e.out.line(`Package ${r.id} of ${r.app_id}: build number ${r.build_number}${i.status===200?" (made before by this command id)":""}.`),r.status==="uploaded"){e.out.line("Its build has arrived already.");return}e.out.line(`Build it with CFBundleVersion ${r.build_number}, then upload its .ipa:`),r.upload&&(e.out.line(` palbase stores:packages:upload ${r.id} --file <app.ipa> --token ${r.upload.token}`),e.out.line(`url: ${r.upload.url}`),e.out.line(`token: ${r.upload.token} (shown this once; it works until ${L(r.upload.expires_at)})`))})}},KE={name:"stores:packages:upload",summary:"hand a package its build: the .ipa or .aab goes straight to the environment's address with the upload token",usage:"<package id> --file <app.ipa|app.aab> --token <upload token>",details:["The token is the one stores:packages:create printed; PALBASE_UPLOAD_TOKEN stands in for --token, out of the process list.","The file goes with its Content-Length. While the module is busy with another upload it is sent again, after the wait the module names, five times at most; a package that has its build already (this token's upload arrived before) counts as uploaded."],args:{min:1,max:1},flags:{file:{type:"string",value:"app.ipa|app.aab",description:"the unsigned .ipa, or the Android App Bundle (unsigned, or signed with the app's upload key), the build machine made"},token:{type:"string",value:"upload token",description:"the package's upload token"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the package's id"),s=e.flags.file;if(s===void 0)throw m("--file names the .ipa or .aab");let a=e.flags.token??e.io.env.PALBASE_UPLOAD_TOKEN;if(a===void 0||a.trim()==="")throw m("--token is the package's upload token (stores:packages:create printed it)","or PALBASE_UPLOAD_TOKEN");let i=an(e.io.cwd,s),r;try{let p=await Ul(i);if(!p.isFile())throw new Error("not a file");r=p.size}catch(p){throw new f("unreadable_file",`${s} could not be read: ${p instanceof Error?p.message:String(p)}`)}await v(e,t,`upload ${s} (${r} bytes) as the build of package ${n}`);let o=`${st(e.cloud,t.env_ref)}/stores/packages/${k(n)}/artifact`,l;try{l=await vy(i)}catch(p){throw new f("unreadable_file",`${s} could not be read: ${p instanceof Error?p.message:String(p)}`)}let d=`${s} \u2192 package ${n}`;for(let p=1;;p++)try{let u=await Da(e,o,{method:"PUT",headers:{"palbase-upload-token":a,"content-type":"application/octet-stream","content-length":String(l.size),accept:"application/json"},body:l},d);e.out.result(u,()=>{e.out.line(`Package ${u.id}: build ${u.build_number}${u.version?`, version ${u.version}`:""} arrived (${u.size??l.size} bytes, sha256 ${u.sha256??"?"}).`),e.out.line(`Send it to testers: palbase stores:deliver ${u.id}`)});return}catch(u){if(!(u instanceof E))throw u;if(u.status===409&&u.code==="package_uploaded"){e.out.result({id:n,uploaded:!0,already:!0},()=>{e.out.line(`Package ${n} has its build already: an upload with this token arrived before, and this one was not taken.`),e.out.line(`Send it to testers: palbase stores:deliver ${n}`)});return}let g=u.status===409&&u.code==="upload_in_progress"||u.status===503&&u.code==="stores_busy",y=Math.max(u.retryAfter??iE,1);if(!g||p>=cy||y>Sy)throw u;e.out.note(`${d}: ${u.message}; trying again in ${y} s (${p+1} of ${cy})`),await e.io.sleep(y*1e3)}}},GE={name:"stores:apps:upload-key",summary:"an Android app's upload key: the certificate Palbase signs its builds with (never its private key)",usage:"<app id> [--out <file.pem>]",details:["Play Console shows an app's upload key by this fingerprint; asked to change an app's upload key to Palbase's, it takes this certificate (--out)."],args:{min:1,max:1},flags:{out:{type:"string",value:"file.pem",description:"write the certificate (PEM) to this file"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await h(e,t,"GET",`/stores/apps/${k(n)}/upload-key`),a=e.flags.out;if(a!==void 0){let i=await _y(an(e.io.cwd,a),An.O_WRONLY|An.O_CREAT|An.O_TRUNC|An.O_NOFOLLOW);try{await i.writeFile(s.certificate)}finally{await i.close()}}e.out.result(s,()=>{e.out.line(`upload key of ${n}: SHA-256 ${s.fingerprint} (made ${L(s.created_at)})`),a!==void 0&&e.out.line(`certificate written to ${a}`)})}},UE={name:"stores:packages:bundle",summary:"download a package's bundle as Palbase signed it for Play: to upload it in Play Console by hand",usage:"<package id> --out <file.aab> [--channel play_internal]",details:["stores:deliver sends every build to Play, an app's first too; when Play wants a release made in Play Console instead (Testing \u2192 Internal testing \u2192 Create new release), upload this file there: it is signed with the app's upload key.","The bytes come from the environment's address on a link the module sealed for this bundle, valid 15 minutes; Studio is asked for the link alone."],args:{min:1,max:1},flags:{out:{type:"string",value:"file.aab",description:"where to write it"},channel:{type:"string",value:"channel",description:"the Play delivery (play_internal)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the package's id"),s=e.flags.out;if(s===void 0)throw m("--out names the file to write");let a=e.flags.channel??"play_internal";if(a!=="play_internal")throw m("--channel is play_internal");let i=await h(e,t,"POST",`/stores/packages/${k(n)}/deliveries/${k(a)}/bundle-link`,void 0,j());rn(e,t,i.url,"the download link");let r;try{r=await e.io.fetch(i.url,{method:"GET",redirect:"manual"})}catch(g){throw new f("network_error",`the signed bundle could not be downloaded: ${g instanceof Error?g.message:String(g)}`)}if(r.status!==200||!r.body){let g=await r.text(),y=g;try{y=JSON.parse(g)}catch{}throw new f("download_failed",`the signed bundle: ${ci(y,r.status)}`)}let o=an(e.io.cwd,s),l=await _y(o,An.O_WRONLY|An.O_CREAT|An.O_TRUNC|An.O_NOFOLLOW),d=0,p=tE.fromWeb(r.body).on("data",g=>{d+=g.length}),u=Number(r.headers.get("content-length")??NaN);try{if(await nE(p,l.createWriteStream()),Number.isFinite(u)&&d!==u)throw new Error(`${d} of its ${u} bytes arrived`)}catch(g){throw await YT(o,{force:!0}),new f("download_failed",`the signed bundle did not arrive whole: ${g instanceof Error?g.message:String(g)}; ask again`)}e.out.result({file:s,bytes:d},()=>{e.out.line(`Wrote ${s} (${d} bytes): package ${n}, signed with the app's upload key.`),e.out.line("Upload it in Play Console \u2192 Testing \u2192 Internal testing \u2192 Create new release, once; then send the next package with stores:deliver.")})}};async function BE(e,t,n,s){if(s.every(r=>py.test(r)))return s;let a=await h(e,t,"GET",`/stores/packages/${k(n)}`),i=(await h(e,t,"GET",`/stores/apps/${k(a.app_id)}/groups`)).groups;return s.map(r=>{if(py.test(r))return r;let o=i.filter(d=>d.name===r),l=o.length>0?o:i.filter(d=>d.name.toLowerCase()===r.toLowerCase());if(l.length!==1)throw new f(l.length===0?"no_such_group":"ambiguous_group",`${a.app_id} has ${l.length===0?"no group":"more than one group"} named ${JSON.stringify(r)}`,{hint:`palbase stores:groups ${a.app_id} lists them`});return l[0].id})}async function zE(e,t,n){let s=await h(e,t,"GET",`/stores/packages/${k(n)}`);return(await h(e,t,"GET","/stores/apps")).apps.find(i=>i.app_id===s.app_id)?.platform==="android"?"play_internal":"testflight"}var WE={name:"stores:deliver",summary:"send a package to a channel's testers: signed, handed to Apple or Play, and given to the testers",usage:"<package id> [--channel testflight|play_internal] [--groups <group,\u2026>] [--what-to-test <text>] [--locale <locale>]",details:["An iOS app goes to TestFlight: processed, then given to the groups; an export compliance question is answered with stores:export-compliance.","An Android app goes to Play's internal testing track, to the testers it lists in Play Console. An invite given in Play Console just now takes a while to reach Play's API: a delivery Play refuses then (google_not_allowed) is sent again later.","palbase stores:deliveries <package id> follows it."],args:{min:1,max:1},flags:{channel:{type:"string",value:"channel",description:"where it goes: testflight, or play_internal (default: the app's platform's)"},groups:{type:"string",multiple:!0,value:"group,\u2026",description:"the groups it goes to once ready, by id or name"},"what-to-test":{type:"string",value:"text",description:"the note testers read"},locale:{type:"string",value:"locale",description:"the note's locale (default: the app's primary one)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the package's id"),s=e.flags.channel??await zE(e,t,n);if(!uy.includes(s))throw m(`--channel is one of ${uy.join(", ")}`);let a=e.flags["what-to-test"];if(e.flags.locale!==void 0&&a===void 0)throw m("--locale is the --what-to-test note's");let i={channel:s},r=oe(e.flags.groups);r&&r.length>0&&(i.groups=await BE(e,t,n,r)),a!==void 0&&(i.what_to_test={text:a,...e.flags.locale!==void 0?{locale:e.flags.locale}:{}}),await v(e,t,`send package ${n} to ${s}${i.groups?` (${i.groups.length} group${i.groups.length===1?"":"s"})`:""}`);let o=await h(e,t,"POST",`/stores/packages/${k(n)}/deliveries`,i,j());e.out.result(o,()=>{e.out.line(`Package ${n} \u2192 ${o.channel}: ${Ay(o)}.`),o.status!=="ready"&&o.status!=="failed"&&e.out.line(`Follow it: palbase stores:deliveries ${n}`)})}},FE={name:"stores:deliveries",summary:"a package's deliveries: where each is now, and what to do when one failed",usage:"<package id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the package's id"),s=await h(e,t,"GET",`/stores/packages/${k(n)}/deliveries`);e.out.result(s,()=>{s.deliveries.length===0?e.out.line(`Package ${n} has not been sent anywhere: palbase stores:deliver ${n}`):e.out.table(s.deliveries,[{header:"channel",value:a=>a.channel},{header:"status",value:a=>a.status},{header:"store",value:a=>a.processing_state??(a.play_version_code!==void 0?`version code ${a.play_version_code}${a.play_release_status?` ${a.play_release_status}`:""}`:"")},{header:"groups",value:a=>String(a.groups.length)},{header:"updated",value:a=>L(a.updated_at)},{header:"error",value:a=>a.error_code?`${a.error_code}${a.error?`: ${a.error}`:""}`:""}])})}},JE={name:"stores:what-to-test:set",summary:"change what testers read with a package's TestFlight build, once Apple holds the build",usage:"<package id> --text <text> [--locale <locale>]",details:["Apple's note on the build, and the delivery's own; before Apple holds the build the module says so (build_not_at_apple) \u2014 stores:deliver --what-to-test sets it with the delivery."],args:{min:1,max:1},flags:{text:{type:"string",value:"text",description:"the note testers read (4000 characters at most)"},locale:{type:"string",value:"locale",description:"its locale (default: the app's primary one)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the package's id"),s=e.flags.text;if(s===void 0||s.trim()==="")throw m("--text is the note testers read");if(s.length>4e3)throw m(`the note is 4000 characters at most (${s.length} were given)`);let a={text:s,...e.flags.locale!==void 0?{locale:e.flags.locale}:{}};await v(e,t,`change what testers read with package ${n}${a.locale?` (${a.locale})`:""}`);let i=await h(e,t,"PUT",`/stores/packages/${k(n)}/what-to-test`,a,j());e.out.result(i,()=>e.out.line(`Testers of package ${n} read${a.locale?` (${a.locale})`:""}: ${i.what_to_test??s}`))}};function Ry(e,t){let n=(e.args[t]??"").trim();if(n===""||n.length>40||/[\r\n]/.test(n))throw m("a group's name is 1 to 40 characters on one line");return n}var VE={name:"stores:groups",summary:"an app's groups of testers",usage:"<app id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await h(e,t,"GET",`/stores/apps/${k(n)}/groups`);e.out.result(s,()=>{s.groups.length===0?e.out.line(`${n} has no group: palbase stores:groups:create ${n} <name>`):e.out.table(s.groups,[{header:"group",value:a=>a.id},{header:"name",value:a=>a.name},{header:"testers",value:a=>String(a.testers)},{header:"updated",value:a=>L(a.updated_at)}])})}},HE={name:"stores:groups:create",summary:"make a group of testers for an app (in TestFlight an internal and an external group)",usage:"<app id> <name>",args:{min:2,max:2},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=Ry(e,1);await v(e,t,`make the group ${JSON.stringify(s)} of ${n}`);let a=await h(e,t,"POST",`/stores/apps/${k(n)}/groups`,{name:s},j());e.out.result(a,()=>e.out.line(`Made ${a.name} (${a.id}).`))}},YE={name:"stores:groups:rename",summary:"rename a group",usage:"<group id> <name>",args:{min:2,max:2},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the group's id"),s=Ry(e,1);await v(e,t,`rename the group ${n} to ${JSON.stringify(s)}`);let a=await h(e,t,"PATCH",`/stores/groups/${k(n)}`,{name:s},j());e.out.result(a,()=>e.out.line(`${a.id} is ${a.name}.`))}},XE={name:"stores:groups:delete",summary:"delete a group: its testers lose the builds it gave them",usage:"<group id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the group's id");await v(e,t,`delete the group ${n}`),await h(e,t,"DELETE",`/stores/groups/${k(n)}`,void 0,j()),e.out.result({id:n,deleted:!0},()=>e.out.line(`Deleted the group ${n}.`))}},ZE={name:"stores:groups:testers",summary:"a group's testers",usage:"<group id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the group's id"),s=await h(e,t,"GET",`/stores/groups/${k(n)}/testers`);e.out.result(s,()=>{s.testers.length===0?e.out.line("No tester in the group."):e.out.table(s.testers,[{header:"email",value:a=>a.email},{header:"name",value:a=>[a.first_name,a.last_name].filter(Boolean).join(" ")},{header:"side",value:a=>a.side},{header:"added",value:a=>L(a.added_at)}])})}};function QE(e){let t=e.trim();if(t.startsWith("[")){let n=me(t,"the testers");if(!Array.isArray(n)||!n.every(s=>typeof s=="object"&&s!==null&&typeof s.email=="string"))throw m('the testers are a JSON array of { "email": \u2026, "first_name": \u2026, "last_name": \u2026 }');return n}return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>n!==""&&!n.startsWith("#")).map(n=>{let[s,a,i]=n.split(",").map(r=>r.trim());return{email:s,...a?{first_name:a}:{},...i?{last_name:i}:{}}})}var eC={name:"stores:groups:testers:set",summary:"set who a group holds, whole: those not named leave it",usage:"<group id> (--emails <a@x,\u2026> | --file <testers.txt>)",details:[`A file names one tester a line \u2014 email, or email,First,Last \u2014 or is a JSON array; - reads it from stdin. ${Kl} at most.`],args:{min:1,max:1},flags:{emails:{type:"string",multiple:!0,value:"a@x,\u2026",description:"the testers' addresses"},file:{type:"string",value:"path",description:"the testers, one a line (- for stdin)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the group's id"),s=oe(e.flags.emails);if(s===void 0==(e.flags.file===void 0))throw m("the testers are named by --emails or --file, one of the two");let a=s?s.map(d=>({email:d})):QE(await ke(e,e.flags.file,"the testers"));for(let d of a)if(!/^[^@\s]+@[^@\s]+$/.test(d.email))throw m(`${JSON.stringify(d.email)} is not an email address`);if(a.length>Kl)throw m(`a group holds ${Kl} testers at most (${a.length} were named)`);let i=(await h(e,t,"GET",`/stores/groups/${k(n)}/testers`)).testers,r=new Set(a.map(d=>d.email.toLowerCase())),o=i.filter(d=>!r.has(d.email.toLowerCase())).map(d=>d.email);await v(e,t,`set the testers of ${n} to ${a.length}${o.length>0?`; ${o.length} leave: ${o.join(", ")}`:""}`);let l=await h(e,t,"PUT",`/stores/groups/${k(n)}/testers`,{testers:a},j());e.out.result({...l,left:o},()=>{e.out.line(`${n} holds ${l.testers.length} tester${l.testers.length===1?"":"s"}${o.length>0?`; ${o.join(", ")} left it`:""}.`)})}},tC={name:"stores:groups:add-build",summary:"give a group a package that TestFlight has (external testers get it after Beta App Review)",usage:"<group id> <package id>",args:{min:2,max:2},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the group's id"),s=X(e,1,"the package's id");await v(e,t,`give package ${s} to the group ${n}`),await h(e,t,"POST",`/stores/groups/${k(n)}/builds`,{package_id:s},j()),e.out.result({group_id:n,package_id:s},()=>e.out.line(`Gave package ${s} to ${n}.`))}},nC={description:"description","feedback-email":"feedback_email","contact-first-name":"contact_first_name","contact-last-name":"contact_last_name","contact-phone":"contact_phone","contact-email":"contact_email","demo-account-name":"demo_account_name",notes:"notes",locale:"locale"};function Tt(e){return e===""?"(not set)":e}var sC={name:"stores:review-info",summary:"an app's TestFlight test information as Apple holds it, in one locale, and what Beta App Review still lacks \u2014 the demo password only as set or not",usage:"<app id> [--locale <locale>]",args:{min:1,max:1},flags:{locale:{type:"string",value:"locale",description:"the locale to read (default: the app's primary one)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=e.flags.locale!==void 0?`?${new URLSearchParams({locale:e.flags.locale})}`:"",a=await h(e,t,"GET",`/stores/apps/${k(n)}/testflight/review-info${s}`);e.out.result(a,()=>{let i=a.locales.filter(p=>p!==a.locale);e.out.line(`Test information of ${n} in ${a.locale}${i.length>0?` (also in ${i.join(", ")})`:""}:`);let r=[`${a.contact_first_name} ${a.contact_last_name}`.trim(),a.contact_phone,a.contact_email].filter(p=>p!=="").join(", "),o=a.demo_account_required?`required: ${Tt(a.demo_account_name)}, password ${a.demo_account_password_set?"set":"not set"}`:"not required",l=[["what to test",Tt(a.description)],["feedback email",Tt(a.feedback_email)],["review contact",Tt(r)],["demo account",o],["notes",Tt(a.notes)]],d=Math.max(...l.map(([p])=>p.length));for(let[p,u]of l)e.out.line(` ${p.padEnd(d)} ${u}`);e.out.line(a.missing.length===0?"Beta App Review has what it needs.":`Beta App Review still lacks: ${a.missing.join(", ")} (palbase stores:review-info:set ${n} \u2026).`)})}},aC={name:"stores:review-info:set",summary:"what Beta App Review needs to know of an app: only the fields given are written; it answers what is still missing",usage:"<app id> [--description <text>] [--feedback-email <a@x>] [--contact-\u2026 <\u2026>] [--demo-account-name <name> --demo-password-stdin] [--notes <text>] [--locale <locale>]",args:{min:1,max:1},flags:{description:{type:"string",value:"text",description:"what testers should test"},"feedback-email":{type:"string",value:"a@x",description:"where testers send feedback"},"contact-first-name":{type:"string",value:"name",description:"whom Apple calls: first name"},"contact-last-name":{type:"string",value:"name",description:"last name"},"contact-phone":{type:"string",value:"phone",description:"phone"},"contact-email":{type:"string",value:"a@x",description:"email"},"demo-account-name":{type:"string",value:"name",description:"a sign-in for the reviewer, when the app needs one"},"demo-password-stdin":{type:"boolean",description:"read the demo account's password from stdin (never the command line)"},notes:{type:"string",value:"text",description:"notes to the reviewer"},locale:{type:"string",value:"locale",description:"the description's and feedback address's locale (default: the app's primary one)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s={};for(let[i,r]of Object.entries(nC))e.flags[i]!==void 0&&(s[r]=e.flags[i]);if(e.flags["demo-password-stdin"]===!0&&(s.demo_account_password=await Me(e,"the demo account's password")),Object.keys(s).length===0)throw m("nothing to write: name at least one field","palbase help stores:review-info:set");await v(e,t,`write ${Object.keys(s).join(", ")} of ${n}'s Beta App Review information`);let a=await h(e,t,"PUT",`/stores/apps/${k(n)}/testflight/review-info`,s,j());e.out.result(a,()=>{e.out.line(a.missing.length===0?"Beta App Review has what it needs.":`Beta App Review still lacks: ${a.missing.join(", ")}.`)})}};async function Vl(e,t){let n=dE[QT(t).toLowerCase()];if(n===void 0)throw m(`${e}: a screenshot is a .png or .jpg file`);let s;try{let a=await Ul(t);if(!a.isFile())throw new Error("not a file");s=a.size}catch(a){throw new f("unreadable_file",`${e} could not be read: ${a instanceof Error?a.message:String(a)}`)}if(s===0||s>lE)throw m(`${e}: a screenshot is 1 byte to 10 MB, and it is ${s} bytes`);return{file:e,path:t,contentType:n}}async function iC(e,t,n){let s=an(e.io.cwd,z),a=an(t,n),i=ly(s,a);if(i===""||i===".."||i.startsWith(`..${dy}`)||eE(i))throw m(`${n}: a screenshot the page names by its file is under ${z}/, and ${ly(e.io.cwd,a)||a} is not`,`move it under ${z}/, or name it by the SHA-256 palbase stores:screenshots:upload printed`);let r,o;try{[o,r]=await Promise.all([oy(s),oy(a)])}catch(l){throw new f("unreadable_file",`${n} could not be read: ${l instanceof Error?l.message:String(l)}`)}if(!r.startsWith(o+dy))throw new f("outside_palbase",`${n} is a link out of ${z}/: palbase reads only what is under it`);return Vl(n,r)}async function Hl(e,t,n,s,a="page"){let i;try{i=await vy(s.path,{type:s.contentType})}catch(r){throw new f("unreadable_file",`${s.file} could not be read: ${r instanceof Error?r.message:String(r)}`)}for(let r=1;;r++)try{let o=`/stores/apps/${k(n)}/screenshots${a==="review"?"?for=review":""}`;return await h(e,t,"PUT",o,new Wt(i,s.contentType))}catch(o){if(!(o instanceof E)||o.status!==503||o.code!=="stores_busy")throw o;let l=Math.max(o.retryAfter??60,1);if(r>=my||l>Sy)throw o;e.out.note(`${s.file}: ${o.message}; trying again in ${l} s (${r+1} of ${my})`),await e.io.sleep(l*1e3)}}var Pn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function rC(e){let t=Pn(e)&&"draft"in e&&"revision"in e?e.draft:e;if(!Pn(t)||!Pn(t.locales))throw m('a page is a JSON object that names its languages: { "primary_category": \u2026, "locales": { "en-US": { "name": \u2026, "screenshots": { "iphone_6_9": [ \u2026 ] } } } }',`as palbase stores:listing:get <app id> --out ${sn} writes it`);for(let[n,s]of Object.entries(t.locales)){if(!Pn(s))throw m(`locales.${n} is an object: { "name": \u2026, \u2026 }`);if(s.screenshots!==void 0){if(!Pn(s.screenshots))throw m(`locales.${n}.screenshots is an object of display \u2192 its screenshots (${oE.join(", ")})`);for(let[a,i]of Object.entries(s.screenshots))if(!Array.isArray(i)||!i.every(r=>typeof r=="string"&&r.trim()!==""))throw m(`locales.${n}.screenshots.${a} is a list of screenshots, each a SHA-256 or a file under ${z}/`)}}return t}function oC(e,t){let n=structuredClone(e);for(let s of Object.values(n.locales))for(let[a,i]of Object.entries(s.screenshots??{}))s.screenshots[a]=i.map(t);return n}var Kt=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`;function Ty(e,t,n,s,a){if(t instanceof E){if(t.code==="listing_moved")throw new f("listing_moved",`${n}'s draft page is no longer at revision ${a??"?"}: someone saved a newer one since it was read \u2014 ${s}`,{hint:`read it again (palbase stores:listing:get ${n} --out <file>), make the edit on it, and save with that revision`});if(t.code==="listing_invalid"){let i=t.message.split("; ").filter(r=>r!=="");e.out.note(`The page has ${Kt(i.length,"problem")}:`);for(let r of i)e.out.note(` ${r}`);throw new f("listing_invalid",`${s}: the page breaks ${Kt(i.length,"rule")} of the App Store's`,{hint:"fix each in the file, and save it again"})}if(t.code==="listing_empty")throw new f("listing_empty",`${n} has no draft App Store page yet: ${s}`,{hint:`write one: palbase stores:listing:get ${n} --out ${sn}, edit it, then palbase stores:listing:put ${n} --file ${sn} --revision 0`});if(t.code==="no_editable_version")throw new f("no_editable_version",`${n} has no App Store version whose page can change: ${s}`,{hint:`prepare the next one: palbase stores:version:prepare ${n} --version <x.y.z>`})}throw t}var lC={name:"stores:listing:get",summary:"an iOS app's draft App Store page \u2014 categories, age rating, each language's text and screenshots \u2014 and its revision",usage:`<app id> [--out <${sn}>]`,details:["--out writes the draft to a file to edit, under palbase/; stores:listing:put saves the edit on the revision printed. A screenshot can be named there by its file under palbase/ (relative to the draft's file) instead of its SHA-256: listing:put uploads it first.","Nothing of the draft is at Apple: stores:listing:plan compares it with App Store Connect, and the plan, once confirmed, writes it."],args:{min:1,max:1},flags:{out:{type:"string",value:"file",description:"write the draft to this file, under palbase/"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=e.flags.out,a=s!==void 0?He(e,"out",s,".json",sn):void 0,i=await h(e,t,"GET",`/stores/apps/${k(n)}/listing`);if(a!==void 0){let r=await ge(e.io.cwd,a);await VT(ky(r),{recursive:!0}),await ge(e.io.cwd,a),await XT(r,`${JSON.stringify(i.draft,null,2)}
|
|
674
|
+
`)}async function Er(e,t){let n=me(await ke(e,t,"the paywall"),"the paywall");if(typeof n!="object"||n===null||Array.isArray(n))throw m("a paywall is a JSON object: { schema, name, default_locale, theme, root, \u2026 }");if("draft"in n&&"draft_revision"in n)throw m('the file is a whole paywall (its draft, its revision, its problems): give its "draft" alone, as purchases:paywalls:get --out writes it');if("definition"in n&&!("root"in n))throw m('the file is a definition inside something else: give the "definition" alone, as purchases:paywalls:get --out writes it');let{$schema:s,...a}=n;return a}function Cr(e,t){for(let n of t)e.out.note(` ${n.path}: ${n.code} \u2014 ${n.message}${n.warning?" (warning)":""}`)}var ey=e=>e.filter(t=>!t.warning).length;function ty(e){if(!(!(e instanceof E)||e.code!=="invalid_paywall"))return(e.body??{}).problems??[]}function ny(e,t,n){let s=ty(t);throw s!==void 0?(s.length>0&&(e.out.note(`The paywall breaks ${ey(s)} rule(s):`),Cr(e,s)),new f("invalid_paywall",`${n}: ${t.message}`,{hint:"fix each problem in the file (palbase purchases:paywalls:validate --file <file> checks it without saving)"})):t}function sy(e,t,n){return new f("paywall_changed",`the draft of ${e} is no longer at revision ${t}: someone saved a newer one since it was read \u2014 nothing was ${n}`,{hint:`read it again (palbase purchases:paywalls:get ${JSON.stringify(e)}), make the edit on it, and save it with that revision`})}async function LT(e,t){let n=new Map,s=(o,l)=>{if(o===void 0)return;let d=n.get(o)??[];d.includes(l)||d.push(l),n.set(o,d)},{placements:a}=await h(e,t,"GET","/purchases/placements");for(let o of a)s(o.paywall_id,o.key);let i=a.filter(o=>o.rule_count>0);return(await Promise.all(i.map(o=>h(e,t,"GET",`/purchases/placements/${k(o.key)}/rules`)))).forEach((o,l)=>{for(let d of o.rules)s(d.target.paywall_id,`${i[l].key} (rule)`)}),n}var DT={name:"purchases:paywalls",summary:"the environment's paywalls: each one's draft revision, the version published, and the placements that show it",details:["A paywall is a JSON definition: purchases:paywalls:get writes one to a file, purchases:paywalls:put saves the edit as its draft, purchases:paywalls:publish makes the draft what the apps draw.","An app sees a paywall once it is published and a placement shows it.","How a definition is written \u2014 every component and field, and three to start from: palbase purchases:paywalls:guide"],scope:"environment",async run(e){let t=await b(e),[n,s]=await Promise.all([nn(e,t),LT(e,t)]),a=n.map(i=>({...i,placements:s.get(i.id)??[]}));e.out.result({paywalls:a},()=>{if(a.length===0){e.out.line("No paywall yet."),e.out.line(`Write a definition and save it: palbase purchases:paywalls:put <name> --file ${Ie}/<name>.json --revision 0`);return}e.out.table(a,[{header:"name",value:i=>i.name},{header:"id",value:i=>i.id},{header:"draft",value:i=>`revision ${i.draft_revision}`},{header:"published",value:i=>i.published_version===0?"never":`version ${i.published_version}, ${L(i.published_at)}`},{header:"shown at",value:i=>i.placements.length===0?"\u2014":i.placements.join(", ")}])})}},xT={name:"purchases:paywalls:get",summary:"write a paywall's draft \u2014 or a version published \u2014 to a file to edit, with the revision it is at",usage:`<name|id> [--out <${Ie}/name.json>] [--version <n>]`,details:[`The file is the definition alone, as purchases:paywalls:put takes it, under ${Ie}/. Its first line names its JSON Schema, written beside it (${Ks}), so an editor checks the file as it is edited.`,"The revision printed is the one an edit is saved on: purchases:paywalls:put --revision."],args:{min:1,max:1},flags:{out:{type:"string",value:"file",description:`where under ${z}/ (default: ${Ie}/<name>.json)`},version:{type:"string",value:"n",description:"a published version instead of the draft"}},scope:"environment",async run(e){let t=await b(e),n=se(e.flags.version,"version");if(n===0)throw m("--version is 1 or more: the versions published");let s=await Qn(e,t,Gs(e,0,"the paywall's name or id")),a=e.flags.out!==void 0?He(e,"out",e.flags.out,".json"):`${Ie}/${Ia(s.name)}${n===void 0?"":`.v${n}`}.json`;if(n!==void 0){let r;try{r=await h(e,t,"GET",`/purchases/paywalls/${k(s.id)}/versions/${n}`)}catch(o){throw o instanceof E&&o.status===404?new f("version_not_found",`${s.name} has no version ${n}${s.published_version===0?": it was never published":`: its newest is ${s.published_version} (the newest 50 are kept)`}`):o}if(!r.definition)throw new f("unexpected_answer",`the module answered version ${n} of ${s.name} without its definition`);await Ar(e,a,r.definition),e.out.result({file:a,paywall_id:s.id,name:s.name,version:r.version,published_at:r.published_at,draft_revision:s.draft_revision},()=>{e.out.line(`Wrote version ${r.version} of ${s.name} (published ${L(r.published_at)}) to ${a}.`),e.out.line(`Saved as the draft, it goes on the draft's revision: palbase purchases:paywalls:put ${JSON.stringify(s.name)} --file ${a} --revision ${s.draft_revision}`)});return}let i=await h(e,t,"GET",`/purchases/paywalls/${k(s.id)}`);await Ar(e,a,i.draft),e.out.result({file:a,paywall_id:i.id,name:i.name,revision:i.draft_revision,published_version:i.published_version,problems:i.problems},()=>{e.out.line(`Wrote draft revision ${i.draft_revision} of ${i.name} to ${a}${i.published_version===0?" (never published)":` (version ${i.published_version} is published)`}.`),i.problems.length>0&&(e.out.note("The module says of the draft:"),Cr(e,i.problems)),e.out.line(`Save an edit of it: palbase purchases:paywalls:put ${JSON.stringify(i.name)} --file ${a} --revision ${i.draft_revision}`)})}},NT={name:"purchases:paywalls:validate",summary:"check a paywall definition as publishing it would, without saving it: every problem, by its path",usage:"--file <paywall.json>",details:["Every rule of the schema is checked, and every package against the environment's catalog as it is. A warning (what App Review expects of a paywall, say) does not stop a save or a publish.","It exits 1 while a problem that is not a warning is left; --json prints { valid, problems } either way."],flags:{file:{type:"string",value:"paywall.json",description:"the definition ('-' or none: stdin)"}},scope:"environment",async run(e){let t=await b(e),n=await Er(e,e.flags.file),s;try{s={valid:!0,problems:(await h(e,t,"POST","/purchases/paywalls/validate",n,j())).problems??[]}}catch(a){let i=ty(a);if(i===void 0)throw a;s={valid:!1,problems:i}}return e.out.result(s,()=>{s.problems.length>0&&Cr(e,s.problems);let a=s.problems.filter(i=>i.warning).length;e.out.line(s.valid?`The paywall can be published${a>0?`, with ${a} warning(s)`:""}.`:`The paywall breaks ${ey(s.problems)} rule(s): it cannot be saved as it is.`)}),s.valid?void 0:1}};async function ay(e,t,n,s){try{let a=await qe(e,t,"POST",`/purchases/paywalls/${k(n.id)}/publish`,void 0,{"if-match":Rr(s),...j()});return{version:a.body,fresh:a.status===201}}catch(a){if(a instanceof E&&a.status===412)throw sy(n.name,s,"published");ny(e,a,`${n.name} was not published`)}}function iy(e,t,n){e.out.line(n.fresh?`Published version ${n.version.version} of ${t}: the apps asking for a placement that shows it get it at once.`:`The draft of ${t} is what version ${n.version.version} already is: nothing new was published.`)}var qT={name:"purchases:paywalls:put",summary:"save a definition as a paywall's draft, on the revision it was edited from \u2014 or make the paywall, at revision 0; --publish publishes it too",usage:"<name|id> --file <paywall.json> --revision <n> [--publish]",details:["The module checks it first: a definition that breaks a rule is refused with every problem, and nothing is saved.","Of two people editing at once, the second is told \u2014 the draft moved past the revision they edited \u2014 never overwritten.","What the apps draw changes only when the draft is published (--publish, or purchases:paywalls:publish). A new paywall takes the name its definition gives.","How a definition is written: palbase purchases:paywalls:guide"],args:{min:1,max:1},flags:{file:{type:"string",value:"paywall.json",description:"the definition, as purchases:paywalls:get wrote it ('-' or none: stdin)"},revision:{type:"string",value:"n",description:"the draft revision it was edited from, as purchases:paywalls:get printed it (0 makes a new paywall)"},publish:{type:"boolean",description:"publish the saved draft as the next version"}},scope:"environment",async run(e){let t=await b(e),n=Gs(e,0,"the paywall's name or id"),s=se(e.flags.revision,"revision");if(s===void 0)throw m("--revision is the draft revision the paywall was edited from (0 for a new one): of two edits at once, the second is told, not saved over the first");let a=await Er(e,e.flags.file),i=Tr(await nn(e,t),n),r=e.flags.publish===!0?" and publish it":"",o;try{if(i){if(s===0)throw new f("paywall_exists",`${i.name} is there already, at draft revision ${i.draft_revision}: an edit of it is saved on the revision it was read at`,{hint:`palbase purchases:paywalls:get ${JSON.stringify(i.name)} writes it and prints the revision`});await v(e,t,`save the draft of ${i.name} over revision ${s}${r}`),o=await h(e,t,"PUT",`/purchases/paywalls/${k(i.id)}/draft`,{definition:a},{"if-match":Rr(s),...j()})}else{if(xl.test(n))throw new f("paywall_not_found",`no paywall ${n}`);if(s!==0)throw new f("paywall_not_found",`no paywall ${JSON.stringify(n)} to save revision ${s} over`,{hint:"--revision 0 makes it"});if(typeof a.name!="string"||a.name.toLocaleLowerCase()!==n.toLocaleLowerCase())throw m(`the file names the paywall ${JSON.stringify(a.name)}, not ${JSON.stringify(n)}: a new paywall takes the name its definition gives`,`set "name" to ${JSON.stringify(n)} in the file, or: palbase purchases:paywalls:put ${JSON.stringify(a.name??"")} \u2026`);await v(e,t,`make the paywall ${a.name}${r}`),o=await h(e,t,"POST","/purchases/paywalls",{definition:a},j())}}catch(d){if(d instanceof E&&d.status===412)throw sy(i?.name??n,s,"saved");if(d instanceof E&&d.code==="too_many_paywalls")throw new f("too_many_paywalls","the project has 100 paywalls, the most it holds: nothing was made",{hint:"delete one no placement shows: palbase purchases:paywalls:delete <name>"});ny(e,d,"the paywall was not saved")}let l=e.flags.publish===!0?await ay(e,t,o,o.draft_revision):void 0;e.out.result({...o,...l?{published:l.version,published_new:l.fresh}:{}},()=>{e.out.line(`${i?"Saved":"Made"} ${o.name}: its draft is at revision ${o.draft_revision}.`),o.problems.length>0&&(e.out.note("The module says of the draft:"),Cr(e,o.problems)),l?iy(e,o.name,l):e.out.line(`The apps draw it once it is published: palbase purchases:paywalls:publish ${JSON.stringify(o.name)}`)})}},KT={name:"purchases:paywalls:publish",summary:"publish a paywall's draft as its next version: what the apps asking for a placement that shows it draw from then on",usage:"<name|id> [--revision <n>]",details:["It is checked as the apps will get it: every package must be sold by the catalog, every asset still what was registered.","--revision names the draft revision that was looked at: a draft saved since is not published in its place. Without it, the draft as it is now is published.","A draft the same as the newest version publishes nothing new."],args:{min:1,max:1},flags:{revision:{type:"string",value:"n",description:"the draft revision looked at (default: the draft as it is now)"}},scope:"environment",async run(e){let t=await b(e),n=await Qn(e,t,Gs(e,0,"the paywall's name or id")),s=se(e.flags.revision,"revision")??n.draft_revision;await v(e,t,`publish draft revision ${s} of ${n.name}`);let a=await ay(e,t,n,s);e.out.result({...a.version,published_new:a.fresh},()=>iy(e,n.name,a))}},GT={name:"purchases:paywalls:delete",summary:"delete a paywall and its versions; one a placement or a running experiment shows is not deleted",usage:"<name|id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=await Qn(e,t,Gs(e,0,"the paywall's name or id"));await v(e,t,`delete the paywall ${n.name}: its draft and every version of it`);try{await h(e,t,"DELETE",`/purchases/paywalls/${k(n.id)}`,void 0,j())}catch(s){throw s instanceof E&&s.code==="paywall_in_use"?new f("paywall_in_use",`${n.name} is shown \u2014 a placement shows it, as its default or by a rule, or a running experiment does \u2014 so it was not deleted`,{hint:"palbase purchases:paywalls says where; give those placements another paywall, or stop the experiment, first"}):s}e.out.result({deleted:n.id,name:n.name},()=>e.out.line(`Deleted ${n.name}.`))}},UT={name:"purchases:paywalls:schema",summary:"the JSON Schema of a paywall definition: every component, its fields and their bounds, for an editor or an agent to check a file against",usage:`[--out <${Ks}>]`,details:["It is the module's contract, as the CLI was built with it: a file that passes may still be refused for what only the module knows (the catalog's packages, the project's assets) \u2014 purchases:paywalls:validate asks it.",'purchases:paywalls:get writes it too, and names it on the first line of each file ("$schema").'],flags:{out:{type:"string",value:"file",description:`where under ${z}/ (default: ${Ks}); --json prints it instead`}},scope:"none",async run(e){if(e.global.json){e.out.result(Sr,()=>{});return}let t=e.flags.out!==void 0?He(e,"out",e.flags.out,".json"):Ks;await Pr(e,t,Qf),e.out.line(`Wrote the paywall definition's JSON Schema to ${t}.`)}},BT={name:"purchases:paywalls:guide",summary:"how a paywall definition is written by hand \u2014 for an agent or a person: the flow, every component and field in the contract's words, three definitions to start from",usage:`[--out <${Ie}/GUIDE.txt>]`,details:["It is made from the definition's JSON Schema the CLI carries (purchases:paywalls:schema), so it says what this version of the CLI checks."],flags:{out:{type:"string",value:"file",description:`write it to a file under ${z}/ instead of printing it`}},scope:"none",async run(e){let t=Vf(Sr),n=e.flags.out;if(n===void 0){e.out.result({guide:t},()=>e.io.stdout(t));return}let s=He(e,"out",n,".txt");await Pr(e,s,t),e.out.result({file:s},()=>e.out.line(`Wrote the guide to ${s}.`))}},Yf=["image","video","font","html"];function Dl(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(e<10*1024?1:0)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function Us(e,t){return(await h(e,t,"GET","/purchases/paywalls/assets")).assets??[]}var Xf={unsupported_asset:"it is no file a paywall takes: an image (PNG, JPEG or WebP, never SVG), a video (MP4 or MOV), a font (TTF, OTF or WOFF2), or an HTML block as a zip",asset_too_large:"it is too large for a paywall: an image is at most 2 MiB, a video 50 MiB, a font or an HTML block's zip 5 MiB",asset_kind_mismatch:"its bytes are not the kind --kind names",invalid_archive:"the zip could not be opened: an HTML block is a zip with index.html at its root",archive_too_many_files:"the HTML block holds too many files: at most 200",archive_too_large:"the HTML block is too large opened: at most 20 MiB of files",unsafe_archive_path:"the HTML block has a file whose path leaves the zip: every file stays under its root",archive_link:"the HTML block holds a link: a zip of plain files is taken",archive_no_index:"the HTML block has no index.html at its root",asset_unreadable:"the purchases module could not read it at its public address; trying again in a moment is safe",too_many_assets:"the project has 500 assets, the most it holds: delete one no paywall names first (palbase purchases:paywalls:assets:delete <id>)"};async function Nl(e,t){let n;try{n=await h(e,t,"GET",`/storage/buckets/${$n}`)}catch(s){if(!(s instanceof E)||s.status!==404)throw s}if(!n?.public){if(n)throw new f("asset_bucket_private",`the project's ${$n} bucket is private: an app downloads a paywall's assets at their public address, and the CLI does not open a bucket the project closed`,{hint:`if everything in it may be read by anyone: palbase storage:buckets:set ${$n} --public`});await h(e,t,"PUT",`/storage/buckets/${$n}`,{public:!0,file_size_limit:null,allowed_mime_types:[],variants:[]}),e.out.note(`Made the public bucket ${$n}: paywall assets are kept in the project's own storage.`)}}function zT(e){let t=$r(e).normalize("NFKD").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(-80).replace(/^\.+$/,"")||"file";return`paywalls/${TT()}/${t}`}async function ql(e,t,n,s){let a=zT(n);await Al(e,t,n,$n,a);try{return await h(e,t,"POST","/purchases/paywalls/assets",{path:a,...s?{kind:s}:{}},j())}catch(i){throw await h(e,t,"DELETE",`/storage/buckets/${$n}/objects/${gr(a)}`).catch(()=>{}),i instanceof E&&i.code!==void 0&&i.code in Xf?new f(i.code,`${$r(n)} was not registered: ${Xf[i.code]}`):i}}var WT={name:"purchases:paywalls:assets",summary:"the project's paywall assets: the images, videos, fonts and HTML blocks a definition names asset:<id>",scope:"environment",async run(e){let t=await b(e),n=await Us(e,t);e.out.result({assets:n},()=>{if(n.length===0){e.out.line("No paywall asset yet."),e.out.line("Upload one: palbase purchases:paywalls:assets:upload <file>");return}e.out.table(n,[{header:"ref",value:s=>s.ref},{header:"kind",value:s=>s.kind},{header:"size",value:s=>Dl(s.bytes)},{header:"file",value:s=>s.path.split("/").pop()??s.path},{header:"registered",value:s=>L(s.created_at)}])})}},FT={name:"purchases:paywalls:assets:upload",summary:"upload a file to the project's storage and register it for paywalls: it answers the asset:<id> a definition names",usage:"<file> [--kind image|video|font|html]",details:[`The file goes to the project's public bucket ${$n} (made when there is none; a private one is left as it is, and refuses). The module then reads it there, says what it is by its bytes, and keeps their SHA-256: an app draws what it downloads only when it is that.`,"An image is PNG, JPEG or WebP, at most 2 MiB; a video MP4 or MOV, 50 MiB; a font TTF, OTF or WOFF2, 5 MiB; an HTML block a zip with index.html at its root, 5 MiB."],args:{min:1,max:1},flags:{kind:{type:"string",value:"kind",description:"what the file is meant to be: one whose bytes are another kind is refused"}},scope:"environment",async run(e){let t=await b(e),n=Zf(e.io.cwd,Gs(e,0,"the file")),s=e.flags.kind;if(s!==void 0&&!Yf.includes(s))throw m(`--kind is one of ${Yf.join(", ")}`);let a;try{let r=await CT(n);if(!r.isFile())throw new Error("it is not a file");a=r.size}catch(r){throw new f("unreadable_file",`${e.args[0]} could not be read: ${r instanceof Error?r.message:String(r)}`)}if(a===0)throw new f("empty_file",`${e.args[0]} is empty`);await v(e,t,`upload ${$r(n)} (${Dl(a)}) as a paywall asset`),await Nl(e,t);let i=await ql(e,t,n,s);e.out.result(i,()=>{e.out.line(`Registered ${$r(n)} as ${i.ref} (${i.kind}, ${Dl(i.bytes)}).`),e.out.line(`A definition names it "${i.ref}" where it takes ${i.kind==="html"?"an HTML block":i.kind==="image"?"an image":`a ${i.kind}`}.`)})}},JT={name:"purchases:paywalls:assets:delete",summary:"forget a paywall asset no paywall names, and remove its file from the project's storage",usage:"<asset:id|id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=Gs(e,0,"the asset's id").replace(/^asset:/,"").toLowerCase();if(!xl.test(n))throw m(`${e.args[0]} is not an asset: asset:<id>, as purchases:paywalls:assets lists them`);let s=(await Us(e,t)).find(i=>i.id===n);if(!s)throw new f("asset_not_found",`the project has no asset ${n}`,{hint:"palbase purchases:paywalls:assets lists them"});await v(e,t,`delete the paywall asset ${s.ref} (${s.path.split("/").pop()})`);try{await h(e,t,"DELETE",`/purchases/paywalls/assets/${k(n)}`,void 0,j())}catch(i){throw i instanceof E&&i.code==="asset_in_use"?new f("asset_in_use",`${s.ref} is named by a paywall \u2014 in its draft, or in a version kept \u2014 so it was not deleted`,{hint:"take it out of the paywall (its draft, then publish) first"}):i}let a=!0;await h(e,t,"DELETE",`/storage/buckets/${k(s.bucket)}/objects/${gr(s.path)}`).catch(()=>{a=!1}),e.out.result({deleted:n,object_removed:a},()=>{e.out.line(`Deleted ${s.ref}.`),a||e.out.warn(`its file stays in the project's storage: palbase storage:rm ${s.bucket}:${s.path}`)})}},ry=[DT,xT,NT,qT,KT,GT,UT,BT,WT,FT,JT];var py=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,sE=/^AuthKey_([A-Z0-9]{10})\.p8$/,aE=8192,uy=["testflight","play_internal"],Kl=100,cy=5,iE=5,Sy=300,rE=5,jr=900,oE=["iphone_6_9","iphone_6_5","ipad_13"],hy=/^[0-9a-f]{64}$/i,lE=10*1024*1024,my=3,dE={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg"},sn=`${z}/store/listing.json`,Rn={beta_review:"Beta App Review",export_compliance:"the export compliance answer",expire_build:"expiring the build",apply_listing:"writing the App Store page",submit_review:"the App Review submission",withdraw_review:"the withdrawal from App Review",release_version:"the release",phased_release:"a phased release change"};function Bs(e){return e.package_id?`package ${e.package_id}`:`app ${e.app_id??"?"}`}var Bl=e=>e.charAt(0).toUpperCase()+e.slice(1);function L(e){return e?e.slice(0,19).replace("T"," "):"\u2014"}function X(e,t,n){let s=e.args[t];if(s===void 0||s.trim()==="")throw m(`${n} is required`);return s}function rn(e,t,n,s){let a=st(e.cloud,t.env_ref),i;try{i=new URL(n).origin}catch{throw new f("unexpected_address",`${s} is not a URL: nothing was sent`)}if(i!==a)throw new f("unexpected_address",`${s} names ${i}, not the environment's address ${a}: nothing was sent`);return a}async function Da(e,t,n,s){let a;try{a=await e.io.fetch(t,{...n,redirect:"manual"})}catch(l){throw new f("network_error",`${s}: ${t} could not be reached: ${l instanceof Error?l.message:String(l)}`)}let i=await a.text(),r;if(i!=="")try{r=JSON.parse(i)}catch{r=i}if(a.status>=200&&a.status<300)return r;let o=r??{};throw new E({op:s,status:a.status,code:typeof o.error=="string"?o.error:`http_${a.status}`,message:ci(r,a.status),requestId:typeof o.request_id=="string"?o.request_id:a.headers.get("x-request-id")??void 0,retryAfter:pE(a.headers.get("retry-after"),o.retry_after,e.io.now()),body:r})}function pE(e,t,n){if(e!==null&&e.trim()!==""){let s=Number(e);if(Number.isFinite(s)&&s>=0)return s;let a=Date.parse(e);if(Number.isFinite(a))return Math.max(0,Math.ceil((a-n)/1e3))}return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function zl(e,t){if(!t.connected){e.out.line("No Apple account is connected."),e.out.line("Connect one: palbase stores:apple:connect --key-file AuthKey_<KEYID>.p8 --issuer-id <issuer id>");return}e.out.line(`Apple account: issuer ${t.issuer_id??"?"}, key ${t.key_id??"?"}`),e.out.line(`status: ${t.status??"not checked"}${t.checked_at?` (checked ${L(t.checked_at)})`:""}`),t.capabilities&&e.out.line(`reaches: ${t.capabilities.length>0?t.capabilities.join(", "):"nothing"}`),t.connected_at&&e.out.line(`connected ${L(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.status==="agreement"?e.out.line(`Apple waits on the account holder: ${t.action??"accept the account's agreements in App Store Connect"}, then palbase stores:apple:check`):t.action&&e.out.line(`To do: ${t.action}`)}function Wl(e,t){if(!t.connected){e.out.line("No Apple ID is signed in (App Review messages, App Privacy and app records need one)."),e.out.line("Sign one in: palbase stores:apple:connect --apple-id <you@example.com>");return}e.out.line(`Apple ID: ${t.apple_id??"?"}${t.team?` in ${t.team.name}`:""}${t.roles&&t.roles.length>0?` (${t.roles.join(", ")})`:""}`),e.out.line(`session: ${t.status??"?"}${t.checked_at?` (checked ${L(t.checked_at)})`:""}`),t.connected_at&&e.out.line(`signed in ${L(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.shared_from&&e.out.line(`shared from ${t.shared_from.name||t.shared_from.ref||t.shared_from.project_id}, where it was signed in: used here too; signed out from either, it serves neither`),t.action&&e.out.line(`To do: ${t.action}`)}var uE={name:"stores:apple",summary:"the environment's Apple account and Apple ID: whether each is connected, what Apple last said of them, what the key reaches",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/stores/apple"),s=await h(e,t,"GET","/stores/apple/session").catch(a=>{if(!(a instanceof E&&a.status===404))throw a});e.out.result(s===void 0?n:{...n,apple_id_session:s},()=>{zl(e,n),s!==void 0&&(e.out.line(""),Wl(e,s))})}};async function cE(e,t){let n=new Uint8Array([...new TextEncoder().encode("palbase/stores/apple-id/password/1"),0,...new TextEncoder().encode(e.grant)]),{enc:s,ct:a}=await wo(Mt(e.seal_key),n,new TextEncoder().encode(t)),i=new Uint8Array(s.length+a.length);return i.set(s),i.set(a,s.length),ga(i)}async function hE(e,t,n){if(e.flags["key-file"]!==void 0)throw m("--apple-id or --key-file, not both");if(e.flags["print-link"]===!0){await v(e,t,"make a link that signs an Apple ID in");let p=await h(e,t,"POST","/stores/apple/session/grants",void 0,j());rn(e,t,p.connect_url,"the sign-in link"),e.out.result({connect_url:p.connect_url,expires_at:p.expires_at},()=>{e.out.line(p.connect_url),e.out.note(`Open it in a browser and sign in there; it works once, until ${L(p.expires_at)}.`)});return}if(!e.io.interactive)throw m("signing an Apple ID in asks for Apple's code at the terminal","or --print-link for a link a browser opens");await v(e,t,`sign the Apple ID ${n} in`);let s=await Me(e,`the password of ${n}`),a=await h(e,t,"POST","/stores/apple/session/grants",void 0,j()),i=rn(e,t,a.connect_url,"the sign-in link"),r=await cE(a,s),o=(p,u)=>Da(e,`${i}/stores/connect/apple-id${p}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({grant:a.grant,...u})},"signing the Apple ID in"),l=await o("",{apple_id:n,password_sealed:r});for(;l.step==="code";){let p=l.method==="phone"?`to ${l.destination??"your phone"}`:"to your trusted devices",u=(await e.io.prompt(`Apple sent a code ${p}. Code: `)).replace(/\s/g,"");try{l=await o("/code",{code:u})}catch(g){if(g instanceof E&&g.code==="apple_code_refused"){e.out.note("Apple did not accept this code.");continue}throw g}}if(l.step==="team"){let p=l.teams??[],u=e.flags.team,g=u===void 0?void 0:p.find(y=>y.id===u||y.name===u);if(u!==void 0&&g===void 0)throw new f("unknown_team",`${n} is not in the team ${u}: ${p.map(y=>y.name).join(", ")}`);for(;g===void 0;){p.forEach((w,_)=>e.out.note(` ${_+1}. ${w.name}`));let y=Number((await e.io.prompt(`${n} is in ${p.length} teams. The one this environment's apps are in [1-${p.length}]: `)).trim());g=p[y-1]}l=await o("/team",{team:g.id})}let d=l.session??{connected:!1};e.out.result(d,()=>{e.out.line(`Signed ${n} in to ${N(t)}.`),Wl(e,d)})}var mE={name:"stores:apple:connect",summary:"connect an App Store Connect API key, or sign an Apple ID in: either goes from this computer straight to the environment, never through Studio",usage:"--key-file <AuthKey_KEYID.p8> --issuer-id <issuer id> [--key-id <KEYID>] | --apple-id <email> [--team <team>] | [--apple-id <email>] --print-link",details:["App Store Connect \u2192 Users and Access \u2192 Integrations \u2192 App Store Connect API makes the key and shows the Issuer ID; stores:apple then says what its role reaches.","Studio is asked for a one-time grant alone; the key is posted with it to the environment's own address. --print-link prints a link that takes the key in a browser instead.","--apple-id signs an Apple ID in, for what Apple's API does not do: App Review's messages and the answer to them, App Privacy, making an app record. Its password is read here and handed to Apple through the environment, never kept; then Apple's code, and the team when the Apple ID is in more than one. An owner's or an admin's."],flags:{"apple-id":{type:"string",value:"email",description:"sign this Apple ID in instead of connecting a key"},team:{type:"string",value:"team",description:"the Apple ID's team, by name or id, when it is in more than one"},"key-file":{type:"string",value:"AuthKey_KEYID.p8",description:"the .p8 file Apple gave when the key was made"},"key-id":{type:"string",value:"KEYID",description:"the key's id (default: from the file's name)"},"issuer-id":{type:"string",value:"issuer id",description:"the account's issuer id"},"print-link":{type:"boolean",description:"only print a link that takes the key in a browser (valid 30 minutes, once)"}},scope:"environment",async run(e){let t=await b(e),n=e.flags["apple-id"];if(n!==void 0){if(n.trim()==="")throw m("--apple-id is the Apple ID: an email address");await hE(e,t,n.trim());return}if(e.flags["print-link"]===!0){if(e.flags["key-file"]!==void 0)throw m("--print-link or --key-file, not both");await v(e,t,"make a link that connects an Apple account");let g=await h(e,t,"POST","/stores/apple/grants",void 0,j());rn(e,t,g.connect_url,"the connect link"),e.out.result({connect_url:g.connect_url,expires_at:g.expires_at},()=>{e.out.line(g.connect_url),e.out.note(`Open it in a browser and pick the .p8 file; it works once, until ${L(g.expires_at)}.`)});return}let s=e.flags["key-file"],a=e.flags["issuer-id"];if(s===void 0)throw m("--key-file names the .p8 file","or --print-link for a link a browser opens");if(a===void 0||a.trim()==="")throw m("--issuer-id is the account's issuer id (App Store Connect \u2192 Users and Access \u2192 Integrations)");let i=ZT(s),r=e.flags["key-id"]??sE.exec(i)?.[1];if(r===void 0)throw m(`--key-id is needed: ${i} is not named AuthKey_<KEYID>.p8`);let o;try{let g=an(e.io.cwd,s);if((await Ul(g)).size>aE)throw new f("not_a_key",`${s} is larger than a .p8 key`);o=await HT(g,"utf8")}catch(g){throw g instanceof f?g:new f("unreadable_file",`${s} could not be read: ${g instanceof Error?g.message:String(g)}`)}if(!o.includes("-----BEGIN PRIVATE KEY-----"))throw new f("not_a_key",`${s} is not a .p8 key (no "BEGIN PRIVATE KEY")`);await v(e,t,`connect the Apple account of issuer ${a} with key ${r}`);let l=await h(e,t,"POST","/stores/apple/grants",void 0,j()),d=rn(e,t,l.connect_url,"the connect link"),p={grant:l.grant,issuer_id:a.trim(),key_id:r,private_key:o,file_name:i},u=await Da(e,`${d}/stores/connect`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(p)},"connecting the Apple key");e.out.result(u,()=>{e.out.line(`Connected key ${r} to ${N(t)}.`),zl(e,u)})}},gE={name:"stores:apple:check",summary:"ask Apple about the connected key again (after the account holder accepted its agreements, or its role changed), or with --apple-id about the Apple ID",flags:{"apple-id":{type:"boolean",description:"check the Apple ID's session instead: whether Apple still takes it, its team and roles"}},scope:"environment",async run(e){let t=await b(e);if(e.flags["apple-id"]===!0){let s=await h(e,t,"POST","/stores/apple/session/check",void 0,j());e.out.result(s,()=>Wl(e,s));return}let n=await h(e,t,"POST","/stores/apple/check",void 0,j());e.out.result(n,()=>zl(e,n))}},fE={name:"stores:apple:disconnect",summary:"take the environment's Apple key away (Apple keeps its apps and builds), or with --apple-id sign its Apple ID out",flags:{"apple-id":{type:"boolean",description:"sign the Apple ID out, at Apple too, and forget its session; the key stays"}},scope:"environment",async run(e){let t=await b(e);if(e.flags["apple-id"]===!0){let n=await h(e,t,"GET","/stores/apple/session"),s=n.shared_from?` (signed in for ${n.shared_from.name||n.shared_from.ref||n.shared_from.project_id}: every environment that uses it loses it)`:"";await v(e,t,`sign the Apple ID out${s}`),await h(e,t,"DELETE","/stores/apple/session",void 0,j()),e.out.result({disconnected:!0},()=>e.out.line(`Signed the Apple ID out of ${N(t)}, at Apple too.`));return}await v(e,t,"disconnect the Apple account (a key Palbase made is revoked at Apple)"),await h(e,t,"DELETE","/stores/apple",void 0,j()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected the Apple account from ${N(t)}.`))}},es={asc:"App Store Connect API key",apns:"APNs keys (one for production, one for the sandbox)",iap:"In-App Purchase key"},yE=2,bE=60;function Fl(e,t){let n=t.kind==="apns"?`APNs key (${t.environment??"?"})`:es[t.kind]??t.kind;e.out.line(` ${t.key_id} ${n}${t.module?` for ${t.module}`:""}: ${t.state}${t.bundles&&t.bundles.length>0?` \u2014 ${t.bundles.join(", ")}`:""}`),t.note&&e.out.line(` ${t.note}`)}async function $y(e,t,n){let s=o=>n.some(l=>l.kind===o&&l.state==="waiting"),a=await h(e,t,"GET","/stores/apple"),i=await h(e,t,"GET","/notify/providers"),r=await h(e,t,"GET","/purchases/apple");return{asc:!a.connected,apns:!i.providers.some(o=>o.channel==="push"&&o.provider==="apns")&&!s("apns"),iap:!r.connected&&!s("iap")}}var wE={name:"stores:apple:keys",summary:"the keys Palbase made at Apple for the environment with its Apple ID, where each stands, and which keys the environment lacks",details:["Palbase makes them with the Apple ID signed in for the environment (stores:apple:connect --apple-id): stores:apple:keys:make. No one downloads a .p8."],scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/stores/apple/keys"),s=await $y(e,t,n.keys);e.out.result({...n,lacking:Object.keys(s).filter(a=>s[a])},()=>{n.keys.length===0?e.out.line("Palbase made no key at Apple for this environment."):(e.out.line("Keys Palbase made at Apple:"),n.keys.forEach(i=>Fl(e,i)));let a=Object.keys(es).filter(i=>s[i]);if(a.length===0){e.out.line("The environment lacks no key.");return}e.out.line(`The environment lacks: ${a.map(i=>es[i]).join("; ")}.`),e.out.line("Make them at Apple: palbase stores:apple:keys:make")})}},vE={name:"stores:apple:keys:make",summary:"make at Apple, with the environment's Apple ID, the keys it lacks \u2014 App Store Connect API, APNs, In-App Purchase \u2014 and connect them: one confirmation",details:["With no flag, every key the environment lacks; a key it has is kept. The Apple ID is an Admin or the Account Holder of the team.","APNs: one key for production and one for the sandbox, scoped to the environment's iOS apps; notify takes them. In-App Purchase: for one iOS app (--bundle with more than one); purchases connects it."],flags:{asc:{type:"boolean",description:"the App Store Connect API key"},apns:{type:"boolean",description:"the APNs keys"},iap:{type:"boolean",description:"the In-App Purchase key"},bundle:{type:"string",description:"the iOS app the In-App Purchase key is for, when the environment has more than one"}},scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/stores/apple/keys"),s=await $y(e,t,n.keys),a=Object.keys(es).filter(p=>e.flags[p]===!0),i=a.length>0?a:Object.keys(es);for(let p of i.filter(u=>!s[u]))e.out.note(`The environment has its ${es[p]}: it is kept.`);let r=i.filter(p=>s[p]);if(r.length===0){e.out.result({keys:[]},()=>e.out.line("The environment lacks none of these keys: nothing to make."));return}await v(e,t,`make at Apple and connect: ${r.map(p=>es[p]).join("; ")}`);let o=[];for(let p of r){let u={kind:p};p==="iap"&&typeof e.flags.bundle=="string"&&(u.bundle=e.flags.bundle);let g=await h(e,t,"POST","/stores/apple/keys",u,j());o.push(...g.keys)}let l=e.io.now()+bE*1e3,d=o;for(;d.some(p=>p.state==="waiting")&&e.io.now()<l;){await e.io.sleep(yE*1e3);let p=await h(e,t,"GET","/stores/apple/keys");d=o.map(u=>p.keys.find(g=>g.key_id===u.key_id)??u)}e.out.result({keys:d},()=>{e.out.line(`Made at Apple for ${N(t)}:`),d.forEach(p=>Fl(e,p)),d.some(p=>p.state==="waiting")&&e.out.note("A module has not taken its key yet: palbase stores:apple:keys says when it has.")})}},_E={name:"stores:apple:keys:revoke",summary:"revoke at Apple an APNs or In-App Purchase key Palbase made for the environment (the App Store Connect key is revoked as stores:apple:disconnect takes it away)",usage:"<key-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=X(e,0,"the key id"),n=await b(e);await v(e,n,`revoke the key ${t} at Apple`);let s=await h(e,n,"DELETE",`/stores/apple/keys/${k(t)}`,void 0,j());e.out.result(s,()=>{e.out.line(`Revoked ${t} at Apple.`),Fl(e,s)})}};async function Py(e,t,n){let s=(await Pe(e.studio)).filter(i=>i.project_id===t.project_id),a=s.find(i=>i.slug===n||i.ref===n);if(!a)throw new f("no_such_environment",`${t.project_name} has no environment ${JSON.stringify(n)}`,{hint:`its environments: ${s.map(i=>i.slug).join(", ")}`});if(a.ref===t.env_ref)throw m("the environment uses its own session: name another environment of the project");return a}var kE={name:"stores:apple:share",summary:"share the environment's Apple ID session with another environment of the project, which uses it while it has none of its own",usage:"<environment>",details:["An environment of the same project alone: Palbase refuses another project's, of your organization or not (other_project).","You are an owner or an admin of both environments; a key or an environment token does not share.","Signed out, or signed in again, the session serves none it was shared with: share it again. stores:apple:unshare takes it back."],args:{min:1,max:1},scope:"environment",async run(e){let t=X(e,0,"the environment to share with"),n=await b(e),s=await Py(e,n,t);await v(e,n,`share its Apple ID session with ${s.name} (${s.slug})`);let a=await h(e,n,"PUT",`/stores/apple/session/shares/${k(s.ref)}`,void 0,j());e.out.result(a,()=>{e.out.line(`Shared with ${s.name} (${s.ref}): it uses this environment's Apple ID while it has none of its own.`)})}},SE={name:"stores:apple:unshare",summary:"take the environment's Apple ID session back from another environment of the project",usage:"<environment>",args:{min:1,max:1},scope:"environment",async run(e){let t=X(e,0,"the environment to take it back from"),n=await b(e),s=await Py(e,n,t);await v(e,n,`take its Apple ID session back from ${s.name} (${s.slug})`),await h(e,n,"DELETE",`/stores/apple/session/shares/${k(s.ref)}`,void 0,j()),e.out.result({unshared:s.ref},()=>{e.out.line(`Taken back from ${s.name} (${s.ref}): it uses this environment's Apple ID no more.`)})}};function Jl(e,t){if(!t.connected){e.out.line("Google Play is not connected."),e.out.line("Connect it: palbase stores:google:connect");return}e.out.line(`Play connection: ${t.service_account??"?"}`),e.out.line(`status: ${t.status??"not checked"}${t.checked_at?` (checked ${L(t.checked_at)})`:""}`),t.capabilities&&e.out.line(`reaches: ${t.capabilities.length>0?t.capabilities.join(", "):"nothing yet"}`);for(let n of t.apps??[])e.out.line(` ${n.package_name}: ${n.reached?`reached (${n.capabilities.join(", ")})`:`not reached \u2014 ${n.problem??"Play did not say why"}`}`);t.connected_at&&e.out.line(`connected ${L(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.action&&e.out.line(`To do: ${t.action}`)}var $E={name:"stores:google",summary:"the environment's Play connection: the service account Play Console invites, what Play let it reach",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/stores/google");e.out.result(n,()=>Jl(e,n))}},PE={name:"stores:google:connect",summary:"connect Google Play: Palbase makes a service account for the environment, which your Play Console invites",details:["No key changes hands: Palbase acts as the service account it made in its own Google Cloud project.","Then, in Play Console \u2192 Users and permissions, invite the service account with the app (Release to testing tracks; for purchases also View financial data and Manage orders and subscriptions), link the Android app (stores:apps:link) and check: stores:google:check."],scope:"environment",async run(e){let t=await b(e);await v(e,t,"connect Google Play (Palbase makes a service account for it)");let n=await h(e,t,"POST","/stores/google",void 0,j());e.out.result(n,()=>Jl(e,n))}},AE={name:"stores:google:check",summary:"ask Play what the environment's service account reaches of each Android app: after Play Console invited it",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"POST","/stores/google/check",void 0,j());e.out.result(n,()=>Jl(e,n))}},RE={name:"stores:google:disconnect",summary:"delete the environment's service account at Google: Play Console's invite of it reaches nothing any more",scope:"environment",async run(e){let t=await b(e);await v(e,t,"disconnect Google Play (its service account is deleted)"),await h(e,t,"DELETE","/stores/google",void 0,j()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected Google Play from ${N(t)}.`))}};function TE(e,t){t.asc_app_id===null&&e.out.line(`Apple has no App Store Connect record for ${t.bundle_id} yet: make it with palbase stores:apps:record ${t.app_id} --name <App Store name> (needs an Apple ID signed in), or on the website (App Store Connect \u2192 Apps \u2192 +), then link again.`)}var EE={name:"stores:apps",summary:"the environment's apps linked to their store",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/stores/apps");e.out.result(n,()=>{n.apps.length===0?e.out.line("No app is linked yet: palbase stores:apps:link <app id>"):e.out.table(n.apps,[{header:"app",value:s=>s.app_id},{header:"platform",value:s=>s.platform},{header:"name",value:s=>s.name},{header:"bundle id / package",value:s=>s.bundle_id},{header:"team",value:s=>s.team_id??""},{header:"app store connect",value:s=>s.platform==="ios"?s.asc_app_id??"no record yet":""}])})}},CE={name:"stores:apps:link",summary:"link an app of the project to its store: an iOS app to the App Store, an Android app to Google Play (with an upload key Palbase makes)",usage:"<app id> [--name <name in the store>]",args:{min:1,max:1},flags:{name:{type:"string",value:"name",description:"its name in the store (default: the bundle id or package)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=e.flags.name!==void 0?{name:e.flags.name}:{};await v(e,t,`link the app ${n} to its store`);let a=await h(e,t,"POST",`/stores/apps/${k(n)}/link`,s,j());e.out.result(a,()=>{if(a.platform==="android"){e.out.line(`Linked ${a.name} (${a.bundle_id}) to Google Play.`),a.upload_key&&e.out.line(`upload key: ${a.upload_key.fingerprint} (Palbase signs its builds with it)`),a.play?e.out.line(`Play: ${a.play.reached?`reached (${a.play.capabilities.join(", ")})`:`not reached \u2014 ${a.play.problem??"?"}`}`):e.out.line("Play was not asked \u2014 the project has no Play connection (stores:google:connect), or Google did not answer (a service account made just now answers after a minute): palbase stores:google:check asks it.");return}e.out.line(`Linked ${a.name} (${a.bundle_id}, team ${a.team_id}).`),TE(e,a)})}},jE={name:"stores:feedback",summary:"an app's TestFlight feedback: testers' screenshots and crashes",usage:"<app id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await h(e,t,"GET",`/stores/apps/${k(n)}/feedback`);e.out.result(s,()=>{s.feedback.length===0?e.out.line("No feedback yet."):e.out.table(s.feedback,[{header:"when",value:a=>L(a.created_at)},{header:"kind",value:a=>a.kind},{header:"tester",value:a=>a.email??""},{header:"comment",value:a=>a.comment??""},{header:"id",value:a=>a.id}]),s.feedback.length>0&&e.out.note(`Read one, with a crash's log: palbase stores:feedback:get ${n} <crash|screenshot> <id>`)})}},OE={name:"stores:feedback:get",summary:"one of an app's TestFlight feedback: the device, the build, and a crash's log",usage:"<app id> <crash|screenshot> <feedback id>",details:["A crash's log is cut at 32 KiB: the exception and the crashed thread come first. A screenshot's images are Apple's links, which expire."],args:{min:3,max:3},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=e.args[1];if(s!=="crash"&&s!=="screenshot")throw m("the kind is crash or screenshot");let a=X(e,2,"the feedback's id"),i=await h(e,t,"GET",`/stores/apps/${k(n)}/feedback/${s}/${k(a)}`);e.out.result(i,()=>{e.out.line(`${Bl(i.kind)} ${A(i.id)}, sent ${L(i.created_at)}${i.email?` by ${A(i.email)}`:""}`);let r=[i.device_model,i.os_version?`iOS ${i.os_version}`:void 0,i.locale].filter(Boolean).join(", ");r&&e.out.line(`from: ${A(r)}`),i.asc_build_id&&e.out.line(`build: ${A(i.asc_build_id)} (App Store Connect's id)`),i.comment&&e.out.line(`comment: ${A(i.comment)}`);for(let o of i.screenshots??[])e.out.line(`screenshot ${o.width}x${o.height}, until ${L(o.expires_at)}: ${A(o.url)}`);i.kind==="crash"&&(i.crash_log?(e.out.line(i.crash_log_cut?"crash log (cut at 32 KiB):":"crash log:"),e.out.line(i.crash_log)):e.out.line("Apple has no log of this crash."))})}};function gy(e,t,n){let s={on:"on: App Store Connect tells Palbase each change the moment it happens",refused:"refused: the connected key's role may not make it",failed:"failed: Apple refused it",none:"not made yet"};e.out.line(`App Store Connect webhook: ${s[n.state]??n.state}`),n.error&&e.out.line(`why: ${A(n.error)}`),n.url&&e.out.line(`reports to: ${A(n.url)}`),n.event_types.length>0&&e.out.line(`tells: ${n.event_types.join(", ")}`),n.installed_at&&e.out.line(`made ${L(n.installed_at)}${n.asc_webhook_id?` (App Store Connect's ${A(n.asc_webhook_id)})`:""}`),e.out.line(n.last_delivery_at?`last delivery: ${A(n.last_delivery_type??"?")}, ${L(n.last_delivery_at)}`:"last delivery: none yet"),n.pinged_at&&e.out.line(`last ping: ${L(n.pinged_at)}`),n.state!=="on"&&e.out.note(`Until it is on, Palbase reads Apple every few minutes. Make it again: palbase stores:webhook ${t} --make`)}var fy=30,yy=2,ME={name:"stores:webhook",summary:"an iOS app's App Store Connect webhook: whether Apple tells Palbase each change at once, and its last delivery",usage:"<app id> [--make] [--ping]",details:["Palbase makes the webhook when the app is linked (the key's role must be Admin or App Manager), and tries again every day while it is not on; meanwhile it reads Apple every few minutes.","--make points it at the environment again with a new secret; --ping asks Apple to send it a ping and waits for it to arrive."],args:{min:1,max:1},flags:{make:{type:"boolean",description:"make it again: a new secret, pointed at the environment"},ping:{type:"boolean",description:"ask Apple to send it a ping, and wait for it to arrive"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=`/stores/apps/${k(n)}/webhook`,a;if(e.flags.make?(await v(e,t,`make the App Store Connect webhook of ${n} again`),a=await h(e,t,"POST",s,{})):a=await h(e,t,"GET",s),e.flags.ping){let i=a.last_delivery_at;await h(e,t,"POST",`${s}/ping`,{});for(let o=0;o<fy&&(await e.io.sleep(yy*1e3),a=await h(e,t,"GET",s),!(a.pinged_at&&a.last_delivery_at&&a.last_delivery_at!==i));o+=yy);let r=!!(a.last_delivery_at&&a.last_delivery_at!==i);e.out.result({...a,ping_arrived:r},()=>{gy(e,n,a),e.out.line(r?"The ping arrived.":`Apple did not deliver the ping within ${fy} s: look again with palbase stores:webhook ${n}`)});return}e.out.result(a,()=>gy(e,n,a))}},La=e=>e==null?"\u2014":`${(e*100).toFixed(2)}%`,IE={ok:"App Store crash counts: the App Crashes report, last 30 days",none_yet:"App Store crash counts: Apple's report has no day yet",requested:"App Store crash counts: asked of Apple now; its first days come in a day or two",not_requested:"App Store crash counts: Palbase asks Apple for the report with its next round",admin_key_needed:"App Store crash counts: only an Admin key may read the App Crashes report \u2014 the connected key is not one"},LE={name:"stores:vitals",summary:"an app's health as its store has it: crashes, terminations and hangs, crash and ANR rates by version",usage:"<app id>",details:["An iOS app: the crashes testers sent from TestFlight, what TestFlight counted of its newest builds (installs, sessions, crashes, feedback), its App Store versions' terminations, hangs and launches, and App Store crashes by day (the App Crashes report, an Admin key's).","An Android app: Play's Android vitals \u2014 each version code's crash and ANR rates over seven days, its errors, and what Play flagged.","A new day of it is the environment's stores.vitals.changed event."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await h(e,t,"GET",`/stores/apps/${k(n)}/vitals`);e.out.result(s,()=>{if(e.out.line(`${s.platform==="android"?"Google Play":"App Store"} health of ${n}, read ${L(s.read_at)}`),e.out.line(s.through?`crash data through ${s.through}`:"no crash data yet"),s.apple){let a=s.apple;a.testflight_crashes.length===0?e.out.line("TestFlight crashes: none"):(e.out.line(`TestFlight crashes (palbase stores:feedback:get ${n} crash <id> reads one with its log):`),e.out.table(a.testflight_crashes,[{header:"when",value:i=>L(i.created_at)},{header:"id",value:i=>i.id},{header:"comment",value:i=>i.comment??""}])),a.testflight_builds.length>0&&(e.out.line("TestFlight builds, as Apple counts them:"),e.out.table(a.testflight_builds,[{header:"build",value:i=>`${i.version} (${i.build_number})${i.expired?", expired":""}`},{header:"days",value:i=>i.from?`${i.from} \u2013 ${i.to??i.from}`:"\u2014"},{header:"installs",value:i=>String(i.installs)},{header:"sessions",value:i=>String(i.sessions)},{header:"crashes",value:i=>String(i.crashes)},{header:"feedback",value:i=>String(i.feedback)},{header:"invites",value:i=>String(i.invites)}])),e.out.line(IE[a.crash_counts]??a.crash_counts),a.crash_days.length>0&&e.out.table(a.crash_days,[{header:"day",value:i=>i.date},{header:"version",value:i=>i.version},{header:"crashes",value:i=>String(i.crashes)},{header:"devices",value:i=>String(i.devices)}]),a.metrics.length===0?e.out.line("terminations, hangs, launches: Apple publishes none yet (enough people who share their data must run an App Store version)"):e.out.table(a.metrics,[{header:"what",value:i=>i.category},{header:"metric",value:i=>i.identifier},{header:"version",value:i=>i.version},{header:"value",value:i=>`${i.value}${i.unit?` ${i.unit}`:""}`},{header:"devices",value:i=>i.device??""}])}if(s.play){let a=s.play;a.versions.length===0?e.out.line("crash and ANR rates: Play has none yet (too few users)"):e.out.table(a.versions,[{header:"version code",value:i=>String(i.version_code)},{header:"crashes",value:i=>La(i.crash_rate)},{header:"crashes in use",value:i=>La(i.user_perceived_crash_rate)},{header:"ANRs",value:i=>La(i.anr_rate)},{header:"ANRs in use",value:i=>La(i.user_perceived_anr_rate)},{header:"users",value:i=>String(i.users)}]),a.issues.length>0&&e.out.table(a.issues,[{header:"error",value:i=>i.type},{header:"cause",value:i=>i.cause},{header:"where",value:i=>i.location},{header:"reports",value:i=>String(i.reports)},{header:"users",value:i=>String(i.users)}]);for(let i of a.anomalies)e.out.line(`Play flagged ${A(i.metric)}${i.version_code?` of version code ${i.version_code}`:""}${i.value!==null?`: ${La(i.value)}`:""}${i.from?` (${i.from}${i.to?` \u2013 ${i.to}`:""})`:""}`)}})}};function DE(e,t){e.out.line(`Package ${t.id} of ${t.app_id}: build ${t.build_number}${t.version?`, version ${t.version}`:""} \u2014 ${t.status==="uploaded"?`uploaded ${L(t.uploaded_at)}`:"waiting for its build"}`),t.size!==null&&e.out.line(`.ipa: ${t.size} bytes, sha256 ${t.sha256??"?"}`),t.bundles.length>0&&e.out.line(`bundles: ${t.bundles.map(n=>n.bundle_id+(n.path?` (${n.path})`:"")).join(", ")}`),t.notes&&e.out.line(`notes: ${t.notes}`),e.out.line(`made ${L(t.created_at)} by ${t.created_by} (command ${t.command_id})`);for(let n of t.deliveries)e.out.line(`${n.channel}: ${Ay(n)}`)}function Ay(e){let t=[e.status];return e.processing_state&&t.push(`Apple: ${e.processing_state}`),e.play_version_code!==void 0&&t.push(`Play: version code ${e.play_version_code}${e.play_release_status?`, ${e.play_release_status}`:""}`),e.groups.length>0&&t.push(`${e.groups.length} group${e.groups.length===1?"":"s"}`),e.error_code&&t.push(`${e.error_code}${e.error?` \u2014 ${e.error}`:""}`),t.join(", ")}var xE={name:"stores:packages",summary:"the packages handed to the stores, newest first",usage:"[--app <app id>] [--limit <n>]",flags:{app:{type:"string",value:"app id",description:"only this app's"},limit:{type:"string",value:"n",description:"how many (1\u2013200, default 20)"}},scope:"environment",async run(e){let t=await b(e),n=se(e.flags.limit,"limit")??20;if(n<1||n>200)throw m("--limit is a whole number from 1 to 200");let s=new URLSearchParams({limit:String(n),...e.flags.app?{app_id:e.flags.app}:{}}),a=await h(e,t,"GET",`/stores/packages?${s}`);e.out.result(a,()=>{a.packages.length===0?e.out.line("No package yet."):e.out.table(a.packages,[{header:"package",value:i=>i.id},{header:"app",value:i=>i.app_id},{header:"build",value:i=>String(i.build_number)},{header:"version",value:i=>i.version??""},{header:"status",value:i=>i.status},{header:"testflight",value:i=>i.deliveries.find(r=>r.channel==="testflight")?.status??""},{header:"made",value:i=>L(i.created_at)}]),a.next_cursor&&e.out.note(`More than ${n}: raise --limit to see older ones.`)})}},NE={name:"stores:packages:get",summary:"one package: its build, its bundles and its deliveries",usage:"<package id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET",`/stores/packages/${k(X(e,0,"the package's id"))}`);e.out.result(n,()=>DE(e,n))}},qE={name:"stores:packages:create",summary:"make a package of an app: its build number, and the URL and token its .ipa is uploaded with",usage:"<app id> --command-id <id> [--notes <text>] [--entitlements-file <json>]",details:["The build is made with the build number it answers (CFBundleVersion), then uploaded: palbase stores:packages:upload.","The same --command-id again answers the same package, with a new upload token while it waits for its build: a build machine sends its run's id."],args:{min:1,max:1},flags:{"command-id":{type:"string",value:"id",description:"names the request (a CI run id): sent again, the same package"},notes:{type:"string",value:"text",description:"notes kept with it (a commit, a branch)"},"entitlements-file":{type:"string",value:"json",description:'what each bundle asks for, by bundle id ({"com.acme.app": {"aps-environment": "production"}})'}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=e.flags["command-id"];if(s===void 0||s.trim()==="")throw m("--command-id names the request: sent again, it answers the same package");let a={command_id:s};if(e.flags.notes!==void 0&&(a.notes=e.flags.notes),e.flags["entitlements-file"]!==void 0){let o=me(await ke(e,e.flags["entitlements-file"],"the entitlements"),"the entitlements"),l=d=>typeof d=="object"&&d!==null&&!Array.isArray(d);if(!l(o)||!Object.values(o).every(l))throw m("the entitlements are an object of bundle id \u2192 its entitlements object");a.entitlements=o}await v(e,t,`make a package of ${n}`);let i=await qe(e,t,"POST",`/stores/apps/${k(n)}/packages`,a,j()),r=i.body;e.out.result(r,()=>{if(e.out.line(`Package ${r.id} of ${r.app_id}: build number ${r.build_number}${i.status===200?" (made before by this command id)":""}.`),r.status==="uploaded"){e.out.line("Its build has arrived already.");return}e.out.line(`Build it with CFBundleVersion ${r.build_number}, then upload its .ipa:`),r.upload&&(e.out.line(` palbase stores:packages:upload ${r.id} --file <app.ipa> --token ${r.upload.token}`),e.out.line(`url: ${r.upload.url}`),e.out.line(`token: ${r.upload.token} (shown this once; it works until ${L(r.upload.expires_at)})`))})}},KE={name:"stores:packages:upload",summary:"hand a package its build: the .ipa or .aab goes straight to the environment's address with the upload token",usage:"<package id> --file <app.ipa|app.aab> --token <upload token>",details:["The token is the one stores:packages:create printed; PALBASE_UPLOAD_TOKEN stands in for --token, out of the process list.","The file goes with its Content-Length. While the module is busy with another upload it is sent again, after the wait the module names, five times at most; a package that has its build already (this token's upload arrived before) counts as uploaded."],args:{min:1,max:1},flags:{file:{type:"string",value:"app.ipa|app.aab",description:"the unsigned .ipa, or the Android App Bundle (unsigned, or signed with the app's upload key), the build machine made"},token:{type:"string",value:"upload token",description:"the package's upload token"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the package's id"),s=e.flags.file;if(s===void 0)throw m("--file names the .ipa or .aab");let a=e.flags.token??e.io.env.PALBASE_UPLOAD_TOKEN;if(a===void 0||a.trim()==="")throw m("--token is the package's upload token (stores:packages:create printed it)","or PALBASE_UPLOAD_TOKEN");let i=an(e.io.cwd,s),r;try{let p=await Ul(i);if(!p.isFile())throw new Error("not a file");r=p.size}catch(p){throw new f("unreadable_file",`${s} could not be read: ${p instanceof Error?p.message:String(p)}`)}await v(e,t,`upload ${s} (${r} bytes) as the build of package ${n}`);let o=`${st(e.cloud,t.env_ref)}/stores/packages/${k(n)}/artifact`,l;try{l=await vy(i)}catch(p){throw new f("unreadable_file",`${s} could not be read: ${p instanceof Error?p.message:String(p)}`)}let d=`${s} \u2192 package ${n}`;for(let p=1;;p++)try{let u=await Da(e,o,{method:"PUT",headers:{"palbase-upload-token":a,"content-type":"application/octet-stream","content-length":String(l.size),accept:"application/json"},body:l},d);e.out.result(u,()=>{e.out.line(`Package ${u.id}: build ${u.build_number}${u.version?`, version ${u.version}`:""} arrived (${u.size??l.size} bytes, sha256 ${u.sha256??"?"}).`),e.out.line(`Send it to testers: palbase stores:deliver ${u.id}`)});return}catch(u){if(!(u instanceof E))throw u;if(u.status===409&&u.code==="package_uploaded"){e.out.result({id:n,uploaded:!0,already:!0},()=>{e.out.line(`Package ${n} has its build already: an upload with this token arrived before, and this one was not taken.`),e.out.line(`Send it to testers: palbase stores:deliver ${n}`)});return}let g=u.status===409&&u.code==="upload_in_progress"||u.status===503&&u.code==="stores_busy",y=Math.max(u.retryAfter??iE,1);if(!g||p>=cy||y>Sy)throw u;e.out.note(`${d}: ${u.message}; trying again in ${y} s (${p+1} of ${cy})`),await e.io.sleep(y*1e3)}}},GE={name:"stores:apps:upload-key",summary:"an Android app's upload key: the certificate Palbase signs its builds with (never its private key)",usage:"<app id> [--out <file.pem>]",details:["Play Console shows an app's upload key by this fingerprint; asked to change an app's upload key to Palbase's, it takes this certificate (--out)."],args:{min:1,max:1},flags:{out:{type:"string",value:"file.pem",description:"write the certificate (PEM) to this file"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await h(e,t,"GET",`/stores/apps/${k(n)}/upload-key`),a=e.flags.out;if(a!==void 0){let i=await _y(an(e.io.cwd,a),An.O_WRONLY|An.O_CREAT|An.O_TRUNC|An.O_NOFOLLOW);try{await i.writeFile(s.certificate)}finally{await i.close()}}e.out.result(s,()=>{e.out.line(`upload key of ${n}: SHA-256 ${s.fingerprint} (made ${L(s.created_at)})`),a!==void 0&&e.out.line(`certificate written to ${a}`)})}},UE={name:"stores:packages:bundle",summary:"download a package's bundle as Palbase signed it for Play: to upload it in Play Console by hand",usage:"<package id> --out <file.aab> [--channel play_internal]",details:["stores:deliver sends every build to Play, an app's first too; when Play wants a release made in Play Console instead (Testing \u2192 Internal testing \u2192 Create new release), upload this file there: it is signed with the app's upload key.","The bytes come from the environment's address on a link the module sealed for this bundle, valid 15 minutes; Studio is asked for the link alone."],args:{min:1,max:1},flags:{out:{type:"string",value:"file.aab",description:"where to write it"},channel:{type:"string",value:"channel",description:"the Play delivery (play_internal)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the package's id"),s=e.flags.out;if(s===void 0)throw m("--out names the file to write");let a=e.flags.channel??"play_internal";if(a!=="play_internal")throw m("--channel is play_internal");let i=await h(e,t,"POST",`/stores/packages/${k(n)}/deliveries/${k(a)}/bundle-link`,void 0,j());rn(e,t,i.url,"the download link");let r;try{r=await e.io.fetch(i.url,{method:"GET",redirect:"manual"})}catch(g){throw new f("network_error",`the signed bundle could not be downloaded: ${g instanceof Error?g.message:String(g)}`)}if(r.status!==200||!r.body){let g=await r.text(),y=g;try{y=JSON.parse(g)}catch{}throw new f("download_failed",`the signed bundle: ${ci(y,r.status)}`)}let o=an(e.io.cwd,s),l=await _y(o,An.O_WRONLY|An.O_CREAT|An.O_TRUNC|An.O_NOFOLLOW),d=0,p=tE.fromWeb(r.body).on("data",g=>{d+=g.length}),u=Number(r.headers.get("content-length")??NaN);try{if(await nE(p,l.createWriteStream()),Number.isFinite(u)&&d!==u)throw new Error(`${d} of its ${u} bytes arrived`)}catch(g){throw await YT(o,{force:!0}),new f("download_failed",`the signed bundle did not arrive whole: ${g instanceof Error?g.message:String(g)}; ask again`)}e.out.result({file:s,bytes:d},()=>{e.out.line(`Wrote ${s} (${d} bytes): package ${n}, signed with the app's upload key.`),e.out.line("Upload it in Play Console \u2192 Testing \u2192 Internal testing \u2192 Create new release, once; then send the next package with stores:deliver.")})}};async function BE(e,t,n,s){if(s.every(r=>py.test(r)))return s;let a=await h(e,t,"GET",`/stores/packages/${k(n)}`),i=(await h(e,t,"GET",`/stores/apps/${k(a.app_id)}/groups`)).groups;return s.map(r=>{if(py.test(r))return r;let o=i.filter(d=>d.name===r),l=o.length>0?o:i.filter(d=>d.name.toLowerCase()===r.toLowerCase());if(l.length!==1)throw new f(l.length===0?"no_such_group":"ambiguous_group",`${a.app_id} has ${l.length===0?"no group":"more than one group"} named ${JSON.stringify(r)}`,{hint:`palbase stores:groups ${a.app_id} lists them`});return l[0].id})}async function zE(e,t,n){let s=await h(e,t,"GET",`/stores/packages/${k(n)}`);return(await h(e,t,"GET","/stores/apps")).apps.find(i=>i.app_id===s.app_id)?.platform==="android"?"play_internal":"testflight"}var WE={name:"stores:deliver",summary:"send a package to a channel's testers: signed, handed to Apple or Play, and given to the testers",usage:"<package id> [--channel testflight|play_internal] [--groups <group,\u2026>] [--what-to-test <text>] [--locale <locale>]",details:["An iOS app goes to TestFlight: processed, then given to the groups; an export compliance question is answered with stores:export-compliance.","An Android app goes to Play's internal testing track, to the testers it lists in Play Console. An invite given in Play Console just now takes a while to reach Play's API: a delivery Play refuses then (google_not_allowed) is sent again later.","palbase stores:deliveries <package id> follows it."],args:{min:1,max:1},flags:{channel:{type:"string",value:"channel",description:"where it goes: testflight, or play_internal (default: the app's platform's)"},groups:{type:"string",multiple:!0,value:"group,\u2026",description:"the groups it goes to once ready, by id or name"},"what-to-test":{type:"string",value:"text",description:"the note testers read"},locale:{type:"string",value:"locale",description:"the note's locale (default: the app's primary one)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the package's id"),s=e.flags.channel??await zE(e,t,n);if(!uy.includes(s))throw m(`--channel is one of ${uy.join(", ")}`);let a=e.flags["what-to-test"];if(e.flags.locale!==void 0&&a===void 0)throw m("--locale is the --what-to-test note's");let i={channel:s},r=oe(e.flags.groups);r&&r.length>0&&(i.groups=await BE(e,t,n,r)),a!==void 0&&(i.what_to_test={text:a,...e.flags.locale!==void 0?{locale:e.flags.locale}:{}}),await v(e,t,`send package ${n} to ${s}${i.groups?` (${i.groups.length} group${i.groups.length===1?"":"s"})`:""}`);let o=await h(e,t,"POST",`/stores/packages/${k(n)}/deliveries`,i,j());e.out.result(o,()=>{e.out.line(`Package ${n} \u2192 ${o.channel}: ${Ay(o)}.`),o.status!=="ready"&&o.status!=="failed"&&e.out.line(`Follow it: palbase stores:deliveries ${n}`)})}},FE={name:"stores:deliveries",summary:"a package's deliveries: where each is now, and what to do when one failed",usage:"<package id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the package's id"),s=await h(e,t,"GET",`/stores/packages/${k(n)}/deliveries`);e.out.result(s,()=>{s.deliveries.length===0?e.out.line(`Package ${n} has not been sent anywhere: palbase stores:deliver ${n}`):e.out.table(s.deliveries,[{header:"channel",value:a=>a.channel},{header:"status",value:a=>a.status},{header:"store",value:a=>a.processing_state??(a.play_version_code!==void 0?`version code ${a.play_version_code}${a.play_release_status?` ${a.play_release_status}`:""}`:"")},{header:"groups",value:a=>String(a.groups.length)},{header:"updated",value:a=>L(a.updated_at)},{header:"error",value:a=>a.error_code?`${a.error_code}${a.error?`: ${a.error}`:""}`:""}])})}},JE={name:"stores:what-to-test:set",summary:"change what testers read with a package's TestFlight build, once Apple holds the build",usage:"<package id> --text <text> [--locale <locale>]",details:["Apple's note on the build, and the delivery's own; before Apple holds the build the module says so (build_not_at_apple) \u2014 stores:deliver --what-to-test sets it with the delivery."],args:{min:1,max:1},flags:{text:{type:"string",value:"text",description:"the note testers read (4000 characters at most)"},locale:{type:"string",value:"locale",description:"its locale (default: the app's primary one)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the package's id"),s=e.flags.text;if(s===void 0||s.trim()==="")throw m("--text is the note testers read");if(s.length>4e3)throw m(`the note is 4000 characters at most (${s.length} were given)`);let a={text:s,...e.flags.locale!==void 0?{locale:e.flags.locale}:{}};await v(e,t,`change what testers read with package ${n}${a.locale?` (${a.locale})`:""}`);let i=await h(e,t,"PUT",`/stores/packages/${k(n)}/what-to-test`,a,j());e.out.result(i,()=>e.out.line(`Testers of package ${n} read${a.locale?` (${a.locale})`:""}: ${i.what_to_test??s}`))}};function Ry(e,t){let n=(e.args[t]??"").trim();if(n===""||n.length>40||/[\r\n]/.test(n))throw m("a group's name is 1 to 40 characters on one line");return n}var VE={name:"stores:groups",summary:"an app's groups of testers",usage:"<app id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await h(e,t,"GET",`/stores/apps/${k(n)}/groups`);e.out.result(s,()=>{s.groups.length===0?e.out.line(`${n} has no group: palbase stores:groups:create ${n} <name>`):e.out.table(s.groups,[{header:"group",value:a=>a.id},{header:"name",value:a=>a.name},{header:"testers",value:a=>String(a.testers)},{header:"updated",value:a=>L(a.updated_at)}])})}},HE={name:"stores:groups:create",summary:"make a group of testers for an app (in TestFlight an internal and an external group)",usage:"<app id> <name>",args:{min:2,max:2},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=Ry(e,1);await v(e,t,`make the group ${JSON.stringify(s)} of ${n}`);let a=await h(e,t,"POST",`/stores/apps/${k(n)}/groups`,{name:s},j());e.out.result(a,()=>e.out.line(`Made ${a.name} (${a.id}).`))}},YE={name:"stores:groups:rename",summary:"rename a group",usage:"<group id> <name>",args:{min:2,max:2},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the group's id"),s=Ry(e,1);await v(e,t,`rename the group ${n} to ${JSON.stringify(s)}`);let a=await h(e,t,"PATCH",`/stores/groups/${k(n)}`,{name:s},j());e.out.result(a,()=>e.out.line(`${a.id} is ${a.name}.`))}},XE={name:"stores:groups:delete",summary:"delete a group: its testers lose the builds it gave them",usage:"<group id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the group's id");await v(e,t,`delete the group ${n}`),await h(e,t,"DELETE",`/stores/groups/${k(n)}`,void 0,j()),e.out.result({id:n,deleted:!0},()=>e.out.line(`Deleted the group ${n}.`))}},ZE={name:"stores:groups:testers",summary:"a group's testers",usage:"<group id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the group's id"),s=await h(e,t,"GET",`/stores/groups/${k(n)}/testers`);e.out.result(s,()=>{s.testers.length===0?e.out.line("No tester in the group."):e.out.table(s.testers,[{header:"email",value:a=>a.email},{header:"name",value:a=>[a.first_name,a.last_name].filter(Boolean).join(" ")},{header:"side",value:a=>a.side},{header:"added",value:a=>L(a.added_at)}])})}};function QE(e){let t=e.trim();if(t.startsWith("[")){let n=me(t,"the testers");if(!Array.isArray(n)||!n.every(s=>typeof s=="object"&&s!==null&&typeof s.email=="string"))throw m('the testers are a JSON array of { "email": \u2026, "first_name": \u2026, "last_name": \u2026 }');return n}return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>n!==""&&!n.startsWith("#")).map(n=>{let[s,a,i]=n.split(",").map(r=>r.trim());return{email:s,...a?{first_name:a}:{},...i?{last_name:i}:{}}})}var eC={name:"stores:groups:testers:set",summary:"set who a group holds, whole: those not named leave it",usage:"<group id> (--emails <a@x,\u2026> | --file <testers.txt>)",details:[`A file names one tester a line \u2014 email, or email,First,Last \u2014 or is a JSON array; - reads it from stdin. ${Kl} at most.`],args:{min:1,max:1},flags:{emails:{type:"string",multiple:!0,value:"a@x,\u2026",description:"the testers' addresses"},file:{type:"string",value:"path",description:"the testers, one a line (- for stdin)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the group's id"),s=oe(e.flags.emails);if(s===void 0==(e.flags.file===void 0))throw m("the testers are named by --emails or --file, one of the two");let a=s?s.map(d=>({email:d})):QE(await ke(e,e.flags.file,"the testers"));for(let d of a)if(!/^[^@\s]+@[^@\s]+$/.test(d.email))throw m(`${JSON.stringify(d.email)} is not an email address`);if(a.length>Kl)throw m(`a group holds ${Kl} testers at most (${a.length} were named)`);let i=(await h(e,t,"GET",`/stores/groups/${k(n)}/testers`)).testers,r=new Set(a.map(d=>d.email.toLowerCase())),o=i.filter(d=>!r.has(d.email.toLowerCase())).map(d=>d.email);await v(e,t,`set the testers of ${n} to ${a.length}${o.length>0?`; ${o.length} leave: ${o.join(", ")}`:""}`);let l=await h(e,t,"PUT",`/stores/groups/${k(n)}/testers`,{testers:a},j());e.out.result({...l,left:o},()=>{e.out.line(`${n} holds ${l.testers.length} tester${l.testers.length===1?"":"s"}${o.length>0?`; ${o.join(", ")} left it`:""}.`)})}},tC={name:"stores:groups:add-build",summary:"give a group a package that TestFlight has (external testers get it after Beta App Review)",usage:"<group id> <package id>",args:{min:2,max:2},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the group's id"),s=X(e,1,"the package's id");await v(e,t,`give package ${s} to the group ${n}`),await h(e,t,"POST",`/stores/groups/${k(n)}/builds`,{package_id:s},j()),e.out.result({group_id:n,package_id:s},()=>e.out.line(`Gave package ${s} to ${n}.`))}},nC={description:"description","feedback-email":"feedback_email","contact-first-name":"contact_first_name","contact-last-name":"contact_last_name","contact-phone":"contact_phone","contact-email":"contact_email","demo-account-name":"demo_account_name",notes:"notes",locale:"locale"};function Et(e){return e===""?"(not set)":e}var sC={name:"stores:review-info",summary:"an app's TestFlight test information as Apple holds it, in one locale, and what Beta App Review still lacks \u2014 the demo password only as set or not",usage:"<app id> [--locale <locale>]",args:{min:1,max:1},flags:{locale:{type:"string",value:"locale",description:"the locale to read (default: the app's primary one)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=e.flags.locale!==void 0?`?${new URLSearchParams({locale:e.flags.locale})}`:"",a=await h(e,t,"GET",`/stores/apps/${k(n)}/testflight/review-info${s}`);e.out.result(a,()=>{let i=a.locales.filter(p=>p!==a.locale);e.out.line(`Test information of ${n} in ${a.locale}${i.length>0?` (also in ${i.join(", ")})`:""}:`);let r=[`${a.contact_first_name} ${a.contact_last_name}`.trim(),a.contact_phone,a.contact_email].filter(p=>p!=="").join(", "),o=a.demo_account_required?`required: ${Et(a.demo_account_name)}, password ${a.demo_account_password_set?"set":"not set"}`:"not required",l=[["what to test",Et(a.description)],["feedback email",Et(a.feedback_email)],["review contact",Et(r)],["demo account",o],["notes",Et(a.notes)]],d=Math.max(...l.map(([p])=>p.length));for(let[p,u]of l)e.out.line(` ${p.padEnd(d)} ${u}`);e.out.line(a.missing.length===0?"Beta App Review has what it needs.":`Beta App Review still lacks: ${a.missing.join(", ")} (palbase stores:review-info:set ${n} \u2026).`)})}},aC={name:"stores:review-info:set",summary:"what Beta App Review needs to know of an app: only the fields given are written; it answers what is still missing",usage:"<app id> [--description <text>] [--feedback-email <a@x>] [--contact-\u2026 <\u2026>] [--demo-account-name <name> --demo-password-stdin] [--notes <text>] [--locale <locale>]",args:{min:1,max:1},flags:{description:{type:"string",value:"text",description:"what testers should test"},"feedback-email":{type:"string",value:"a@x",description:"where testers send feedback"},"contact-first-name":{type:"string",value:"name",description:"whom Apple calls: first name"},"contact-last-name":{type:"string",value:"name",description:"last name"},"contact-phone":{type:"string",value:"phone",description:"phone"},"contact-email":{type:"string",value:"a@x",description:"email"},"demo-account-name":{type:"string",value:"name",description:"a sign-in for the reviewer, when the app needs one"},"demo-password-stdin":{type:"boolean",description:"read the demo account's password from stdin (never the command line)"},notes:{type:"string",value:"text",description:"notes to the reviewer"},locale:{type:"string",value:"locale",description:"the description's and feedback address's locale (default: the app's primary one)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s={};for(let[i,r]of Object.entries(nC))e.flags[i]!==void 0&&(s[r]=e.flags[i]);if(e.flags["demo-password-stdin"]===!0&&(s.demo_account_password=await Me(e,"the demo account's password")),Object.keys(s).length===0)throw m("nothing to write: name at least one field","palbase help stores:review-info:set");await v(e,t,`write ${Object.keys(s).join(", ")} of ${n}'s Beta App Review information`);let a=await h(e,t,"PUT",`/stores/apps/${k(n)}/testflight/review-info`,s,j());e.out.result(a,()=>{e.out.line(a.missing.length===0?"Beta App Review has what it needs.":`Beta App Review still lacks: ${a.missing.join(", ")}.`)})}};async function Vl(e,t){let n=dE[QT(t).toLowerCase()];if(n===void 0)throw m(`${e}: a screenshot is a .png or .jpg file`);let s;try{let a=await Ul(t);if(!a.isFile())throw new Error("not a file");s=a.size}catch(a){throw new f("unreadable_file",`${e} could not be read: ${a instanceof Error?a.message:String(a)}`)}if(s===0||s>lE)throw m(`${e}: a screenshot is 1 byte to 10 MB, and it is ${s} bytes`);return{file:e,path:t,contentType:n}}async function iC(e,t,n){let s=an(e.io.cwd,z),a=an(t,n),i=ly(s,a);if(i===""||i===".."||i.startsWith(`..${dy}`)||eE(i))throw m(`${n}: a screenshot the page names by its file is under ${z}/, and ${ly(e.io.cwd,a)||a} is not`,`move it under ${z}/, or name it by the SHA-256 palbase stores:screenshots:upload printed`);let r,o;try{[o,r]=await Promise.all([oy(s),oy(a)])}catch(l){throw new f("unreadable_file",`${n} could not be read: ${l instanceof Error?l.message:String(l)}`)}if(!r.startsWith(o+dy))throw new f("outside_palbase",`${n} is a link out of ${z}/: palbase reads only what is under it`);return Vl(n,r)}async function Hl(e,t,n,s,a="page"){let i;try{i=await vy(s.path,{type:s.contentType})}catch(r){throw new f("unreadable_file",`${s.file} could not be read: ${r instanceof Error?r.message:String(r)}`)}for(let r=1;;r++)try{let o=`/stores/apps/${k(n)}/screenshots${a==="review"?"?for=review":""}`;return await h(e,t,"PUT",o,new Wt(i,s.contentType))}catch(o){if(!(o instanceof E)||o.status!==503||o.code!=="stores_busy")throw o;let l=Math.max(o.retryAfter??60,1);if(r>=my||l>Sy)throw o;e.out.note(`${s.file}: ${o.message}; trying again in ${l} s (${r+1} of ${my})`),await e.io.sleep(l*1e3)}}var Pn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function rC(e){let t=Pn(e)&&"draft"in e&&"revision"in e?e.draft:e;if(!Pn(t)||!Pn(t.locales))throw m('a page is a JSON object that names its languages: { "primary_category": \u2026, "locales": { "en-US": { "name": \u2026, "screenshots": { "iphone_6_9": [ \u2026 ] } } } }',`as palbase stores:listing:get <app id> --out ${sn} writes it`);for(let[n,s]of Object.entries(t.locales)){if(!Pn(s))throw m(`locales.${n} is an object: { "name": \u2026, \u2026 }`);if(s.screenshots!==void 0){if(!Pn(s.screenshots))throw m(`locales.${n}.screenshots is an object of display \u2192 its screenshots (${oE.join(", ")})`);for(let[a,i]of Object.entries(s.screenshots))if(!Array.isArray(i)||!i.every(r=>typeof r=="string"&&r.trim()!==""))throw m(`locales.${n}.screenshots.${a} is a list of screenshots, each a SHA-256 or a file under ${z}/`)}}return t}function oC(e,t){let n=structuredClone(e);for(let s of Object.values(n.locales))for(let[a,i]of Object.entries(s.screenshots??{}))s.screenshots[a]=i.map(t);return n}var Kt=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`;function Ty(e,t,n,s,a){if(t instanceof E){if(t.code==="listing_moved")throw new f("listing_moved",`${n}'s draft page is no longer at revision ${a??"?"}: someone saved a newer one since it was read \u2014 ${s}`,{hint:`read it again (palbase stores:listing:get ${n} --out <file>), make the edit on it, and save with that revision`});if(t.code==="listing_invalid"){let i=t.message.split("; ").filter(r=>r!=="");e.out.note(`The page has ${Kt(i.length,"problem")}:`);for(let r of i)e.out.note(` ${r}`);throw new f("listing_invalid",`${s}: the page breaks ${Kt(i.length,"rule")} of the App Store's`,{hint:"fix each in the file, and save it again"})}if(t.code==="listing_empty")throw new f("listing_empty",`${n} has no draft App Store page yet: ${s}`,{hint:`write one: palbase stores:listing:get ${n} --out ${sn}, edit it, then palbase stores:listing:put ${n} --file ${sn} --revision 0`});if(t.code==="no_editable_version")throw new f("no_editable_version",`${n} has no App Store version whose page can change: ${s}`,{hint:`prepare the next one: palbase stores:version:prepare ${n} --version <x.y.z>`})}throw t}var lC={name:"stores:listing:get",summary:"an iOS app's draft App Store page \u2014 categories, age rating, each language's text and screenshots \u2014 and its revision",usage:`<app id> [--out <${sn}>]`,details:["--out writes the draft to a file to edit, under palbase/; stores:listing:put saves the edit on the revision printed. A screenshot can be named there by its file under palbase/ (relative to the draft's file) instead of its SHA-256: listing:put uploads it first.","Nothing of the draft is at Apple: stores:listing:plan compares it with App Store Connect, and the plan, once confirmed, writes it."],args:{min:1,max:1},flags:{out:{type:"string",value:"file",description:"write the draft to this file, under palbase/"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=e.flags.out,a=s!==void 0?He(e,"out",s,".json",sn):void 0,i=await h(e,t,"GET",`/stores/apps/${k(n)}/listing`);if(a!==void 0){let r=await ge(e.io.cwd,a);await VT(ky(r),{recursive:!0}),await ge(e.io.cwd,a),await XT(r,`${JSON.stringify(i.draft,null,2)}
|
|
675
675
|
`),e.out.result({file:a,app_id:i.app_id,revision:i.revision},()=>{e.out.line(`Wrote revision ${i.revision} of ${n}'s draft App Store page to ${a}.`),e.out.line(`Save an edit of it: palbase stores:listing:put ${n} --file ${a} --revision ${i.revision}`)});return}e.out.result(i,()=>{if(i.revision===0){e.out.line(`${n} has no draft App Store page yet (revision 0).`),e.out.line(`Start one: palbase stores:listing:get ${n} --out ${sn}, then palbase stores:listing:put ${n} --file ${sn} --revision 0`);return}e.out.line(`${n}'s draft App Store page, revision ${i.revision}${i.updated_at?` (saved ${L(i.updated_at)}${i.updated_by?` by ${i.updated_by}`:""})`:""}:`);for(let r of JSON.stringify(i.draft,null,2).split(`
|
|
676
|
-
`))e.out.line(r);e.out.line(`Edit it in a file: palbase stores:listing:get ${n} --out ${sn}`)})}},dC={name:"stores:listing:put",summary:"save an iOS app's draft App Store page, whole, on the revision it was edited from \u2014 its screenshot files uploaded first",usage:`<app id> --file <${sn}> --revision <n>`,details:["A screenshot is named by its SHA-256, or by a file \u2014 a path from the draft's own file, under palbase/ (nothing else is read): each file is uploaded first, and the draft is saved with its SHA-256 in its place. The file itself is left as it is.","Of two people editing at once, the second is told \u2014 the draft moved past the revision they edited \u2014 never saved over. Nothing goes to Apple: stores:listing:plan says what the draft changes there."],args:{min:1,max:1},flags:{file:{type:"string",value:"listing.json",description:"the draft, as stores:listing:get --out wrote it ('-' or none: stdin)"},revision:{type:"string",value:"n",description:"the revision it was edited from, as stores:listing:get printed it (0: the first)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=se(e.flags.revision,"revision");if(s===void 0)throw m("--revision is the revision the draft was edited from, as stores:listing:get printed it (0 for the first): of two edits at once, the second is told, not saved over the first");let a=e.flags.file,i=rC(me(await ke(e,a,"the page"),"the page")),r=a!==void 0&&a!=="-"?ky(an(e.io.cwd,a)):e.io.cwd,o=new Map,l=new Map;for(let y of Object.values(i.locales))for(let w of Object.values(y.screenshots??{}).flat()){if(hy.test(w)||l.has(w))continue;let _=await iC(e,r,w);l.set(w,_.path),o.has(_.path)||o.set(_.path,_)}await v(e,t,`save ${n}'s draft App Store page over revision ${s}${o.size>0?`, uploading ${Kt(o.size,"screenshot")} first`:""}`);let d=new Map,p=[];for(let y of o.values()){let w=await Hl(e,t,n,y);d.set(y.path,w.sha256),p.push({file:y.file,sha256:w.sha256,displays:w.displays}),e.out.note(`uploaded ${y.file}: ${w.sha256} (${w.width}x${w.height}, fits ${w.displays.join(", ")||"no display"})`)}let u=oC(i,y=>hy.test(y)?y.toLowerCase():d.get(l.get(y))),g;try{g=await h(e,t,"PUT",`/stores/apps/${k(n)}/listing`,{revision:s,draft:u},j())}catch(y){Ty(e,y,n,"nothing was saved",s)}e.out.result({...g,uploaded:p},()=>{let y=Object.keys(g.draft.locales),w=Object.values(g.draft.locales).flatMap(_=>Object.values(_.screenshots??{}).flat()).length;e.out.line(`Saved revision ${g.revision} of ${n}'s draft App Store page: ${Kt(y.length,"language")}${y.length>0?` (${y.join(", ")})`:""}, ${Kt(w,"screenshot")}.`),e.out.line(`Nothing is at Apple yet: palbase stores:listing:plan ${n} says what it changes there.`)})}},pC={name:"stores:screenshots:upload",summary:"upload screenshots for an iOS app's App Store page: each is kept by its SHA-256, which the draft names it by",usage:"<app id> <file.png|file.jpg>\u2026",details:['Each is a PNG or JPEG of 10 MB at most, of a size the App Store takes: iPhone 6.9" (1320x2868, 1290x2796, 1260x2736), iPhone 6.5" (1242x2688, 1284x2778) or iPad 13" (2064x2752, 2048x2732), or turned. The same image again is the one kept.',"stores:listing:put uploads the files a draft names itself; this is for the SHA-256 alone."],args:{min:2,max:101},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=[];for(let i of e.args.slice(1))s.push(await Vl(i,an(e.io.cwd,i)));await v(e,t,`upload ${Kt(s.length,"screenshot")} for ${n}'s App Store page`);let a=[];for(let i of s)a.push({file:i.file,...await Hl(e,t,n,i)});e.out.result({screenshots:a},()=>{e.out.table(a,[{header:"file",value:i=>i.file},{header:"sha256",value:i=>i.sha256},{header:"size",value:i=>`${i.width}x${i.height}`},{header:"fits",value:i=>i.displays.length>0?i.displays.join(", "):"no display"}]),e.out.note(`Name them in the draft page by their SHA-256 (locales.<code>.screenshots.<display>), then: palbase stores:listing:put ${n} --file <file> --revision <n>`)})}},uC={name:"stores:review-screenshot",summary:"upload the screenshot App Review is shown of an in-app purchase: kept by its SHA-256, which the catalog names it by",usage:"<app id> <file.png|file.jpg>",details:[`A PNG or JPEG of 10 MB at most, at an App Store screenshot size \u2014 iPhone 6.9" 1320x2868, 1290x2796 or 1260x2736; iPhone 6.5" 1242x2688 or 1284x2778; iPad 13" 2064x2752 or 2048x2732 (or turned): App Review takes an in-app purchase's screenshot at no other.`,'Name it in the catalog, channels.ios.review.screenshot = "sha256:<hex>"; the next plan (palbase purchases:catalog:plan) gives it to App Store Connect, and Apple then has what it needs of the product to review it.'],args:{min:2,max:2},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await Vl(e.args[1],an(e.io.cwd,e.args[1]));await v(e,t,`upload ${s.file} as a review screenshot for ${n}`);let a=await Hl(e,t,n,s,"review");e.out.result(a,()=>{e.out.line(`Kept ${s.file} for App Review: sha256 ${a.sha256} (${a.width}x${a.height}).`),e.out.note(`Name it in the catalog: channels.ios.review.screenshot = "sha256:${a.sha256}", then palbase purchases:catalog:plan`)})}},cC={name:"stores:listing:plan",summary:"plan writing an iOS app's draft page to App Store Connect: what changes, language by language; it runs when confirmed",usage:"<app id>",details:["The draft is compared with the page of the app's version that can change; a field the draft leaves empty, and a language it has not, are left as they are."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id");await v(e,t,`plan writing ${n}'s App Store page`);let s;try{s=await h(e,t,"POST",`/stores/apps/${k(n)}/listing/plan`,void 0,j())}catch(a){Ty(e,a,n,"nothing was planned")}e.out.result(s,()=>{if(!s.action){e.out.line(`Nothing to change: App Store Connect holds ${n}'s page of version ${s.version} as revision ${s.revision} of the draft has it.`);return}e.out.line(`Revision ${s.revision} of the draft, written to version ${s.version}'s page, changes:`),s.steps.forEach((a,i)=>e.out.line(` ${i+1}. ${a.says}`)),Yl(e,s.action,{summary:!1})})}},hC={USES_THIRD_PARTY_CONTENT:"it shows, contains or reaches third-party content",DOES_NOT_USE_THIRD_PARTY_CONTENT:"no third-party content"},mC={manual:"manual: a person releases it once approved",after_approval:"as soon as it is approved"},gC=["paused","active","complete"];function Ey(e,t,n){let s=n.version;e.out.line(s?`${t}: version ${s.version_string} \u2014 ${s.state}${s.first_version?" (the app's first: it has no What's New)":""}`:`${t} has no App Store version that can change.`);let a=[];s&&(a.push(["build",s.build_number!==""?s.build_number:"(none yet)"]),a.push(["copyright",Tt(s.copyright)]),a.push(["release",s.release==="scheduled"?`scheduled: not before ${L(s.release_at)}`:mC[s.release]??Tt(s.release)]));let i=n.phased;a.push(["phased",i?`over seven days \u2014 ${i.state}${i.state!=="INACTIVE"?`, day ${i.day} of 7`:""}${i.paused_days>0?`, paused ${Kt(i.paused_days,"day")}`:""}`:"no: everyone gets it at once"]),a.push(["price",n.priced?"set":"none yet (stores:version:prepare --free makes it free)"]),a.push(["content rights",hC[n.content_rights]??Tt(n.content_rights)]);let r=n.review,o=[`${r.contact_first_name} ${r.contact_last_name}`.trim(),r.contact_phone,r.contact_email].filter(d=>d!=="").join(", ");a.push(["review contact",Tt(o)]),a.push(["demo account",r.demo_account_required?`required: ${Tt(r.demo_account_name)}, password ${r.has_demo_password?"set":"not set"}`:"not required"]),a.push(["review notes",Tt(r.notes)]),n.watched&&a.push(["watched",`${n.watched.version_string} ${n.watched.state} since ${L(n.watched.state_at)} (read ${L(n.watched.checked_at)})`]);let l=Math.max(...a.map(([d])=>d.length));for(let[d,p]of a)e.out.line(` ${d.padEnd(l)} ${p}`);if(n.missing.length>0){e.out.line("App Review would refuse it for:");for(let d of n.missing)e.out.line(` - ${d}`)}else s&&e.out.line(`App Review has what it needs: palbase stores:version:submit ${t}`);s||e.out.line(`Prepare the next one: palbase stores:version:prepare ${t} --version <x.y.z>`)}var fC={name:"stores:version",summary:"an iOS app's App Store version as App Review will see it \u2014 its build, release, phased release, price, content rights, review contact \u2014 and what App Review would refuse it for",usage:"<app id>",details:["The demo account's password is never read out: only whether Apple holds one. watched is what the module last saw of the version sent to App Review (it reads it every few minutes)."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await h(e,t,"GET",`/stores/apps/${k(n)}/version`);e.out.result(s,()=>Ey(e,n,s))}},by={contact_first_name:"string",contact_last_name:"string",contact_email:"string",contact_phone:"string",demo_account_required:"boolean",demo_account_name:"string",notes:"string"};function yC(e){let t=Pn(e)&&Pn(e.review)&&"app_id"in e?e.review:e;if(!Pn(t))throw m('the review file is a JSON object: { "contact_first_name": \u2026, "contact_email": \u2026, "demo_account_required": \u2026, "notes": \u2026 }');let{has_demo_password:n,...s}=t;for(let[a,i]of Object.entries(s)){if(a==="demo_account_password")throw m("the review file holds no password: the demo account's is read from stdin, never from a file","take it out of the file, and pipe it in: \u2026 --demo-password-stdin < password.txt");let r=by[a];if(r===void 0)throw m(`the review file's ${a} is not one of App Review's details: ${Object.keys(by).join(", ")}`);if(typeof i!==r)throw m(`the review file's ${a} is ${r==="string"?"text":"true or false"}`)}return s}function wy(e,t){if(e.flags[t]===!0&&e.flags[`no-${t}`]===!0)throw m(`--${t} and --no-${t} are one or the other`);if(e.flags[t]===!0)return!0;if(e.flags[`no-${t}`]===!0)return!1}var bC={name:"stores:version:prepare",summary:"prepare an iOS app's App Store version: its number, build, copyright, release, phased release, content rights, a free price, App Review's details",usage:"<app id> [--version <x.y.z>] [--build <n>] [--copyright <text>] [--release manual|after_approval|scheduled] [--release-at <RFC 3339>] [--phased | --no-phased] [--third-party-content | --no-third-party-content] [--free] [--territories all] [--app-privacy published|unpublished] [--review-file <review.json>] [--demo-password-stdin]",details:["Only what is given is written; --version makes the next version when the app has none that can change. The build is a TestFlight build of that version, by its number.","--review-file holds App Review's details as stores:version --json shows them (its review): a field the file leaves out stays as it is. The demo account's password is read from stdin alone (--demo-password-stdin), never from the file or the command line; it goes to Apple, and is never printed or kept."],args:{min:1,max:1},flags:{version:{type:"string",value:"x.y.z",description:"the version's number: makes it when the app has none that can change"},build:{type:"string",value:"n",description:"the TestFlight build App Review gets, by its build number"},copyright:{type:"string",value:"text",description:"the copyright line (2026 Your Company)"},release:{type:"string",value:"how",description:"how it goes out once approved: manual, after_approval or scheduled"},"release-at":{type:"string",value:"RFC 3339",description:"a scheduled release, not before then (alone, it is scheduled)"},phased:{type:"boolean",description:"release it in phases over seven days"},"no-phased":{type:"boolean",description:"release it to everyone at once"},"third-party-content":{type:"boolean",description:"the content rights statement: the app shows, contains or reaches third-party content"},"no-third-party-content":{type:"boolean",description:"the content rights statement: it does not"},free:{type:"boolean",description:"make an app with no price free everywhere (a paid price is set in App Store Connect)"},territories:{type:"string",value:"all",description:"all: sell an app sold nowhere in every country and region (chosen ones are set in App Store Connect)"},"app-privacy":{type:"string",value:"published|unpublished",description:"say the app's privacy details were published in App Store Connect (Apple has no API for them): the missing list stops asking for them"},"review-file":{type:"string",value:"review.json",description:"App Review's details: contact, demo account, notes ('-': stdin)"},"demo-password-stdin":{type:"boolean",description:"read the demo account's password from stdin (never a file or the command line)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s={},a=[],i=e.flags.version;if(i!==void 0){if(!/^\d+(\.\d+){0,2}$/.test(i)||i.length>18)throw m(`--version ${i}: one to three numbers with dots (1.2.3)`);s.version_string=i,a.push(`version ${i}`)}let r=se(e.flags.build,"build");if(r!==void 0){if(r<1)throw m("--build is a TestFlight build's number");s.build_number=r,a.push(`build ${r}`)}let o=e.flags.copyright;if(o!==void 0){if(o.trim()===""||o.length>200)throw m("--copyright is 1 to 200 characters (2026 Your Company)");s.copyright=o,a.push("copyright")}let l=e.flags.release,d=e.flags["release-at"];if(l!==void 0&&!["manual","after_approval","scheduled"].includes(l))throw m("--release is manual, after_approval or scheduled");if(d!==void 0){if(l!==void 0&&l!=="scheduled")throw m(`--release-at is a scheduled release's: not ${l}`);let S=Date.parse(d);if(!Number.isFinite(S))throw m(`--release-at ${d}: a time, RFC 3339 (2026-11-02T09:00:00Z)`);if(S<=e.io.now())throw m(`--release-at ${d}: a scheduled release's time is in the future`);s.release="scheduled",s.release_at=new Date(S).toISOString()}else{if(l==="scheduled")throw m("--release scheduled needs --release-at: when it may go out");l!==void 0&&(s.release=l)}s.release&&a.push(`release ${s.release}${s.release_at?` at ${s.release_at}`:""}`);let p=wy(e,"phased");p!==void 0&&(s.phased=p,a.push(p?"phased release":"release to everyone at once"));let u=wy(e,"third-party-content");u!==void 0&&(s.uses_third_party_content=u,a.push(u?"uses third-party content":"no third-party content")),e.flags.free===!0&&(s.price="free",a.push("free"));let g=e.flags.territories;if(g!==void 0){if(g!=="all")throw m("--territories is all (chosen countries are set in App Store Connect)");s.territories="all",a.push("sold in every country and region")}let y=e.flags["app-privacy"];if(y!==void 0){if(y!=="published"&&y!=="unpublished")throw m("--app-privacy is published or unpublished");s.app_privacy=y,a.push(`App Privacy ${y}`)}let w=e.flags["review-file"],_=e.flags["demo-password-stdin"]===!0;if(_&&w==="-")throw m("stdin carries the demo password or the review file, not both","--review-file <review.json> --demo-password-stdin < password.txt");if(w!==void 0||_){let S=w!==void 0?yC(me(await ke(e,w,"the review details"),"the review details")):{},$=_?await Me(e,"the demo account's password"):void 0;if($!==void 0&&$.length>256)throw m("the demo account's password is 256 characters at most");let{has_demo_password:R,...T}=(await h(e,t,"GET",`/stores/apps/${k(n)}/version`)).review;s.review={...T,...S,...$!==void 0?{demo_account_password:$}:{}},w!==void 0&&a.push("App Review's details"),$!==void 0&&a.push("the demo account's password")}if(a.length===0)throw m("nothing to prepare: name at least one of the version, its build, copyright, release, phased release, content rights, price, countries, App Privacy or review details","palbase help stores:version:prepare");await v(e,t,`prepare ${n}'s App Store version: ${a.join(", ")}`);let P;try{P=await h(e,t,"PUT",`/stores/apps/${k(n)}/version`,s)}catch(S){throw S instanceof E&&S.code==="no_editable_version"?new f("no_editable_version",`${n} has no App Store version that can change`,{hint:`make the next one: palbase stores:version:prepare ${n} --version <x.y.z> \u2026`}):S}e.out.result(P,()=>{e.out.line(`Prepared ${n}'s App Store version.`),Ey(e,n,P)})}};function Or(e,t,n,s,a={},i){return{name:e,summary:s,usage:"<app id>",args:{min:1,max:1},scope:"environment",...a,async run(r){let o=await b(r),l=X(r,0,"the app's id"),d=i?.(r);await v(r,o,`plan ${Rn[t]} of app ${l}`);let p;try{p=await h(r,o,"POST",`/stores/apps/${k(l)}/version/${n}`,d,j())}catch(u){if(u instanceof E&&u.code==="version_incomplete"){let g=u.message.slice(u.message.indexOf(": ")+2).split("; ").filter(y=>y!=="");r.out.note("App Review would refuse the version for:");for(let y of g)r.out.note(` - ${y}`);throw new f("version_incomplete",`nothing was planned: the version lacks ${Kt(g.length,"thing")} App Review needs`,{hint:`palbase stores:version ${l} says what is missing; palbase stores:version:prepare ${l} \u2026 writes what can be written from here`})}throw u instanceof E&&u.code==="no_editable_version"?new f("no_editable_version",`${l} has no App Store version to send`,{hint:`prepare one: palbase stores:version:prepare ${l} --version <x.y.z> --build <n> \u2026`}):u}r.out.result(p,()=>Yl(r,p))}}}var wC=Or("stores:version:submit","submit_review","submit","plan sending an iOS app's prepared version to App Review \u2014 refused, with what is missing, until it has what App Review needs; it runs when confirmed",{usage:"<app id> [--with <product id>,\u2026]",details:["--with sends the app's in-app purchases and subscriptions with the version, by product id: a product's first review goes with an app version, as Apple requires, and each is READY_TO_SUBMIT at Apple (its text, price, availability and review screenshot complete) or nothing is planned."],flags:{with:{type:"string",value:"product id,\u2026",description:"in-app purchases sent to App Review with the version, by product id"}}},e=>{let t=e.flags.with;if(t===void 0)return;let n=t.split(",").map(s=>s.trim()).filter(s=>s!=="");if(n.length===0||n.length>50)throw m("--with names 1 to 50 product ids, comma-separated");return{in_app_purchases:n}}),vC=Or("stores:version:withdraw","withdraw_review","withdraw","plan taking the version out of App Review: it is edited again, and sent again from the start; it runs when confirmed"),_C=Or("stores:version:release","release_version","release","plan releasing an approved version that waits for its developer (a manual release) on the App Store, for good; it runs when confirmed"),kC=Or("stores:version:phased","phased_release","phased-release","plan pausing, resuming or completing the version's phased release (complete: everyone gets it now); it runs when confirmed",{usage:"<app id> <paused|active|complete>",args:{min:2,max:2}},e=>{let t=e.args[1];if(!gC.includes(t))throw m(`a phased release is paused, active (resumed) or complete (everyone gets it now), not ${JSON.stringify(t)}`);return{state:t}});function Yl(e,t,n={}){e.out.line(`Planned ${Rn[t.kind]??t.kind} of ${Bs(t)} (action ${t.id}):`),n.summary!==!1&&e.out.line(` ${t.summary}`),e.out.line(` hash: ${t.hash}`),e.out.line(`It runs only when confirmed, before ${L(t.expires_at)}:`),e.out.line(` palbase stores:actions:confirm ${t.id} --hash ${t.hash}`)}function Xl(e,t,n,s,a={},i){return{name:e,summary:s,usage:"<package id>",args:{min:1,max:1},scope:"environment",...a,async run(r){let o=await b(r),l=X(r,0,"the package's id"),d=i?.(r);await v(r,o,`plan ${Rn[t]} of package ${l}`);let p=await h(r,o,"POST",`/stores/packages/${k(l)}/${n}`,d,j());r.out.result(p,()=>Yl(r,p))}}}var SC=Xl("stores:beta-review","beta_review","beta-review","plan sending a package to Beta App Review (external testers get it after Apple's review); it runs when confirmed"),$C=Xl("stores:export-compliance","export_compliance","export-compliance","plan the export compliance answer of a package's build (the question TestFlight waits on); it runs when confirmed",{usage:"<package id> --uses-non-exempt-encryption yes|no",flags:{"uses-non-exempt-encryption":{type:"string",value:"yes|no",description:"whether the app uses encryption beyond HTTPS and what iOS provides"}}},e=>{let t=mn(e.flags["uses-non-exempt-encryption"],"uses-non-exempt-encryption");if(t===void 0)throw m("--uses-non-exempt-encryption is yes or no: whether the app uses encryption beyond HTTPS and what iOS provides");return{uses_non_exempt_encryption:t}}),PC=Xl("stores:expire","expire_build","expire","plan expiring a package's build in TestFlight (testers can no longer install it); it runs when confirmed"),AC={name:"stores:actions",summary:"the actions planned at Apple, newest first: what each does, and whether it ran (running: a page still being written)",usage:"[--status planned|done|declined|failed] [--limit <n>]",flags:{status:{type:"string",value:"status",description:"only those planned, done, declined or failed"},limit:{type:"string",value:"n",description:"how many (1\u2013200, default 30)"}},scope:"environment",async run(e){let t=await b(e),n=e.flags.status;if(n!==void 0&&!["planned","done","declined","failed"].includes(n))throw m("--status is planned, done, declined or failed");let s=se(e.flags.limit,"limit")??30;if(s<1||s>200)throw m("--limit is a whole number from 1 to 200");let a=new URLSearchParams({limit:String(s),...n?{status:n}:{}}),i=await h(e,t,"GET",`/stores/actions?${a}`);e.out.result(i,()=>{i.actions.length===0?e.out.line(n?`No ${n} action.`:"No action yet."):e.out.table(i.actions,[{header:"action",value:r=>r.id},{header:"kind",value:r=>r.kind},{header:"package / app",value:r=>r.package_id??r.app_id??""},{header:"status",value:r=>r.status},{header:"planned",value:r=>L(r.created_at)},{header:"what",value:r=>r.summary}]),i.next_cursor&&e.out.note(`More than ${s}: raise --limit to see older ones.`)})}},RC={name:"stores:actions:confirm",summary:"run a planned action at Apple: it names the hash of the plan that was shown, and is asked about first",usage:"<action id> --hash <hash>",details:["What it does is shown, then asked about \u2014 in every environment, as it cannot be undone at Apple. -y confirms without asking.",`An App Store page's plan is written after the answer (its screenshots take minutes): the command waits for it to be done or failed, ${jr/60} minutes at most; stopping the wait does not stop the writing.`],args:{min:1,max:1},flags:{hash:{type:"string",value:"hash",description:"the plan's hash, as it was shown when it was planned"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the action's id"),s=e.flags.hash;if(s===void 0||s.trim()==="")throw m("--hash is the plan's hash, as stores:actions or the plan printed it: a confirmation names the plan it saw");let a=await h(e,t,"GET",`/stores/actions/${k(n)}`);if(a.status!=="planned")throw new f("action_not_planned",`the action ${n} is ${a.status}: only a planned one is confirmed`);await v(e,t,`run ${Rn[a.kind]??a.kind} of ${Bs(a)}: ${a.summary}`,"It is done at Apple and cannot be undone");let i=await h(e,t,"POST",`/stores/actions/${k(n)}/confirm`,{hash:s},j());return i.status==="running"&&(i=await EC(e,t,i)),e.out.result(i,()=>TC(e,i)),i.status==="failed"?1:0}};function TC(e,t){e.out.line(`${Bl(Rn[t.kind]??t.kind)} of ${Bs(t)}: ${t.status}.`);let n=t.result??{};if(typeof n.error=="string"&&n.error!==""&&e.out.line(` ${n.error}`),Array.isArray(n.missing))for(let s of n.missing)typeof s=="string"&&e.out.line(` - ${s}`);if(typeof n.steps_done=="number"&&(t.status==="done"?e.out.line(`${Kt(n.steps_done,"step")} written at App Store Connect.`):e.out.line(`${Kt(n.steps_done,"step")} written before it stopped${typeof n.failed_step=="string"?` at: ${n.failed_step}`:""}; planned again, what is left is written.`)),t.kind==="phased_release"&&t.status==="done"&&typeof n.state=="string"&&e.out.line(`The phased release is ${n.state}.`),n.in_app_purchases&&typeof n.in_app_purchases=="object")for(let[s,a]of Object.entries(n.in_app_purchases))typeof a=="string"&&e.out.line(`App Store Connect says of ${s}: ${a}.`);typeof n.version_state=="string"&&e.out.line(`App Store Connect says of the version: ${n.version_state}.`),n.withdrawing===!0&&e.out.line(`App Store Connect is taking the version out of App Review, which takes it a few seconds: palbase stores:version ${t.app_id??"<app id>"} shows it once it has.`)}async function EC(e,t,n){e.out.note(`${Bl(Rn[n.kind]??n.kind)} of ${Bs(n)} is under way at App Store Connect; waiting for it to end (${jr/60} minutes at most \u2014 stopping the wait does not stop it).`);let s=e.io.now()+jr*1e3,a=n;for(;a.status==="running";){if(e.io.now()>=s)throw new f("action_running",`${Rn[n.kind]??n.kind} of ${Bs(n)} is still running after ${jr/60} minutes (action ${n.id})`,{hint:"it goes on without this command: palbase stores:actions says when it is done or failed"});await e.io.sleep(rE*1e3),a=await h(e,t,"GET",`/stores/actions/${k(n.id)}`)}return a}var CC={name:"stores:actions:decline",summary:"decline a planned action: it never runs",usage:"<action id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the action's id");await v(e,t,`decline the action ${n}`);let s=await h(e,t,"POST",`/stores/actions/${k(n)}/decline`,void 0,j());e.out.result(s,()=>e.out.line(`Declined ${Rn[s.kind]??s.kind} of ${Bs(s)}.`))}},Gl={"3m":"MONTHLY_RENEWAL_EVERY_THREE_MINUTES","5m":"MONTHLY_RENEWAL_EVERY_FIVE_MINUTES","15m":"MONTHLY_RENEWAL_EVERY_FIFTEEN_MINUTES","30m":"MONTHLY_RENEWAL_EVERY_THIRTY_MINUTES","1h":"MONTHLY_RENEWAL_EVERY_ONE_HOUR"},Cy=e=>Object.entries(Gl).find(([,t])=>t===e)?.[0]??e,jC=100;function OC(e,t){t.testers.length===0&&e.out.line("The team has no sandbox tester yet."),e.out.table(t.testers,[{header:"email",value:n=>n.email},{header:"name",value:n=>`${n.first_name} ${n.last_name}`.trim()},{header:"storefront",value:n=>n.territory},{header:"monthly renews every",value:n=>Cy(n.subscription_renewal_rate)},{header:"interrupted",value:n=>n.interrupt_purchases?"yes":"no"},{header:"id",value:n=>n.id}]),t.create_in&&e.out.note(`A person makes another, Apple's API makes none: ${t.create_in}`)}async function jy(e,t,n){let s=(await h(e,t,"GET","/stores/apple/sandbox-testers")).testers,a=[];for(let i of n){let r=s.find(o=>o.id===i||o.email.toLowerCase()===i.toLowerCase());if(!r)throw new f("no_such_tester",`the team has no sandbox tester ${i}`,{hint:`its testers: ${s.map(o=>o.email).join(", ")||"none \u2014 App Store Connect \u203A Users and Access \u203A Sandbox makes one"}`});a.some(o=>o.id===r.id)||a.push(r)}return a}var MC={name:"stores:apple:sandbox-testers",summary:"the Apple team's sandbox testers: the accounts that buy in the App Store's sandbox, how fast their subscriptions renew",details:["They are the team's, every environment's alike. Only a person makes one: App Store Connect \u203A Users and Access \u203A Sandbox."],scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/stores/apple/sandbox-testers");e.out.result(n,()=>OC(e,n))}},IC={name:"stores:apple:sandbox-testers:set",summary:"change how a sandbox tester buys: how fast its monthly subscriptions renew, whether its purchases are interrupted, its storefront",usage:"<email|id> [--renewal 3m|5m|15m|30m|1h] [--interrupt on|off] [--storefront <code>]",details:["A monthly subscription renews at the rate given; a yearly one in proportion. Apple renews one 12 times at most, then lets it end.","An interrupted purchase stops for an action of the buyer's, as when a bank asks for one: what the app does then is tested."],args:{min:1,max:1},flags:{renewal:{type:"string",value:"rate",description:"every 3m, 5m, 15m, 30m or 1h"},interrupt:{type:"string",value:"on|off",description:"interrupt its purchases"},storefront:{type:"string",value:"code",description:"the storefront it buys in, three letters (USA, DEU, TUR \u2026)"}},scope:"environment",async run(e){let t=await b(e),n={},s=e.flags.renewal;if(s!==void 0){let l=Gl[s.trim().toLowerCase()];if(l===void 0)throw m(`--renewal ${s}: a monthly subscription renews every ${Object.keys(Gl).join(", ")}`);n.subscription_renewal_rate=l}let a=e.flags.interrupt;if(a!==void 0){if(a!=="on"&&a!=="off")throw m("--interrupt is on or off");n.interrupt_purchases=a==="on"}let i=e.flags.storefront?.trim().toUpperCase();if(i!==void 0){if(!xs.has(i))throw m(`--storefront ${e.flags.storefront}: not an App Store storefront`,"three letters, its country's ISO 3166-1 code: USA, DEU, TUR \u2026");n.territory=i}if(Object.keys(n).length===0)throw m("nothing to change: --renewal, --interrupt or --storefront");let[r]=await jy(e,t,[e.args[0]]);await v(e,t,`change the sandbox tester ${r.email}`);let o=await h(e,t,"PATCH",`/stores/apple/sandbox-testers/${k(r.id)}`,n,j());e.out.result(o,()=>{e.out.line(`${o.email}: monthly subscriptions renew every ${Cy(o.subscription_renewal_rate)}, purchases ${o.interrupt_purchases?"interrupted":"not interrupted"}, storefront ${o.territory}.`),n.territory!==void 0&&e.out.line("Sign out of the sandbox account on the device and in again for the storefront to change there.")})}},LC={name:"stores:apple:sandbox-testers:clear",summary:"clear sandbox testers' purchase history: each buys again as for the first time, introductory offers included",usage:"<email|id>\u2026",details:["Apple clears them after it answers, which can take minutes. Then sign out of the sandbox account on the device and in again."],args:{min:1,max:jC},scope:"environment",async run(e){let t=await b(e),n=await jy(e,t,e.args);await v(e,t,`clear what ${n.map(s=>s.email).join(", ")} bought in the sandbox`),await h(e,t,"POST","/stores/apple/sandbox-testers/clear-purchase-history",{tester_ids:n.map(s=>s.id)},j()),e.out.result({cleared:n.map(s=>s.email)},()=>{e.out.line(`Apple is clearing what ${n.map(s=>s.email).join(", ")} bought in the sandbox.`),e.out.line("Once it has (minutes), sign out of the sandbox account on the device and in again.")})}};function DC(e,t,n){if(n.threads.length===0){e.out.line("App Review has written nothing in this app's Resolution Center.");return}for(let s of n.threads){e.out.line(`thread ${s.id} \u2014 ${s.type??"?"}${s.state?`, ${s.state}`:""}${s.last_message_at?`, last ${L(s.last_message_at)}`:""}${s.can_reply?"":" (takes no answer)"}`);for(let a of s.rejections)for(let i of a.reasons)e.out.line(` guideline ${i.section??"?"}: ${i.description??""}`);for(let a of s.messages){e.out.line(` ${a.from??"message"}${a.created_at?` ${L(a.created_at)}`:""}:`);for(let i of a.body.split(`
|
|
676
|
+
`))e.out.line(r);e.out.line(`Edit it in a file: palbase stores:listing:get ${n} --out ${sn}`)})}},dC={name:"stores:listing:put",summary:"save an iOS app's draft App Store page, whole, on the revision it was edited from \u2014 its screenshot files uploaded first",usage:`<app id> --file <${sn}> --revision <n>`,details:["A screenshot is named by its SHA-256, or by a file \u2014 a path from the draft's own file, under palbase/ (nothing else is read): each file is uploaded first, and the draft is saved with its SHA-256 in its place. The file itself is left as it is.","Of two people editing at once, the second is told \u2014 the draft moved past the revision they edited \u2014 never saved over. Nothing goes to Apple: stores:listing:plan says what the draft changes there."],args:{min:1,max:1},flags:{file:{type:"string",value:"listing.json",description:"the draft, as stores:listing:get --out wrote it ('-' or none: stdin)"},revision:{type:"string",value:"n",description:"the revision it was edited from, as stores:listing:get printed it (0: the first)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=se(e.flags.revision,"revision");if(s===void 0)throw m("--revision is the revision the draft was edited from, as stores:listing:get printed it (0 for the first): of two edits at once, the second is told, not saved over the first");let a=e.flags.file,i=rC(me(await ke(e,a,"the page"),"the page")),r=a!==void 0&&a!=="-"?ky(an(e.io.cwd,a)):e.io.cwd,o=new Map,l=new Map;for(let y of Object.values(i.locales))for(let w of Object.values(y.screenshots??{}).flat()){if(hy.test(w)||l.has(w))continue;let _=await iC(e,r,w);l.set(w,_.path),o.has(_.path)||o.set(_.path,_)}await v(e,t,`save ${n}'s draft App Store page over revision ${s}${o.size>0?`, uploading ${Kt(o.size,"screenshot")} first`:""}`);let d=new Map,p=[];for(let y of o.values()){let w=await Hl(e,t,n,y);d.set(y.path,w.sha256),p.push({file:y.file,sha256:w.sha256,displays:w.displays}),e.out.note(`uploaded ${y.file}: ${w.sha256} (${w.width}x${w.height}, fits ${w.displays.join(", ")||"no display"})`)}let u=oC(i,y=>hy.test(y)?y.toLowerCase():d.get(l.get(y))),g;try{g=await h(e,t,"PUT",`/stores/apps/${k(n)}/listing`,{revision:s,draft:u},j())}catch(y){Ty(e,y,n,"nothing was saved",s)}e.out.result({...g,uploaded:p},()=>{let y=Object.keys(g.draft.locales),w=Object.values(g.draft.locales).flatMap(_=>Object.values(_.screenshots??{}).flat()).length;e.out.line(`Saved revision ${g.revision} of ${n}'s draft App Store page: ${Kt(y.length,"language")}${y.length>0?` (${y.join(", ")})`:""}, ${Kt(w,"screenshot")}.`),e.out.line(`Nothing is at Apple yet: palbase stores:listing:plan ${n} says what it changes there.`)})}},pC={name:"stores:screenshots:upload",summary:"upload screenshots for an iOS app's App Store page: each is kept by its SHA-256, which the draft names it by",usage:"<app id> <file.png|file.jpg>\u2026",details:['Each is a PNG or JPEG of 10 MB at most, of a size the App Store takes: iPhone 6.9" (1320x2868, 1290x2796, 1260x2736), iPhone 6.5" (1242x2688, 1284x2778) or iPad 13" (2064x2752, 2048x2732), or turned. The same image again is the one kept.',"stores:listing:put uploads the files a draft names itself; this is for the SHA-256 alone."],args:{min:2,max:101},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=[];for(let i of e.args.slice(1))s.push(await Vl(i,an(e.io.cwd,i)));await v(e,t,`upload ${Kt(s.length,"screenshot")} for ${n}'s App Store page`);let a=[];for(let i of s)a.push({file:i.file,...await Hl(e,t,n,i)});e.out.result({screenshots:a},()=>{e.out.table(a,[{header:"file",value:i=>i.file},{header:"sha256",value:i=>i.sha256},{header:"size",value:i=>`${i.width}x${i.height}`},{header:"fits",value:i=>i.displays.length>0?i.displays.join(", "):"no display"}]),e.out.note(`Name them in the draft page by their SHA-256 (locales.<code>.screenshots.<display>), then: palbase stores:listing:put ${n} --file <file> --revision <n>`)})}},uC={name:"stores:review-screenshot",summary:"upload the screenshot App Review is shown of an in-app purchase: kept by its SHA-256, which the catalog names it by",usage:"<app id> <file.png|file.jpg>",details:[`A PNG or JPEG of 10 MB at most, at an App Store screenshot size \u2014 iPhone 6.9" 1320x2868, 1290x2796 or 1260x2736; iPhone 6.5" 1242x2688 or 1284x2778; iPad 13" 2064x2752 or 2048x2732 (or turned): App Review takes an in-app purchase's screenshot at no other.`,'Name it in the catalog, channels.ios.review.screenshot = "sha256:<hex>"; the next plan (palbase purchases:catalog:plan) gives it to App Store Connect, and Apple then has what it needs of the product to review it.'],args:{min:2,max:2},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await Vl(e.args[1],an(e.io.cwd,e.args[1]));await v(e,t,`upload ${s.file} as a review screenshot for ${n}`);let a=await Hl(e,t,n,s,"review");e.out.result(a,()=>{e.out.line(`Kept ${s.file} for App Review: sha256 ${a.sha256} (${a.width}x${a.height}).`),e.out.note(`Name it in the catalog: channels.ios.review.screenshot = "sha256:${a.sha256}", then palbase purchases:catalog:plan`)})}},cC={name:"stores:listing:plan",summary:"plan writing an iOS app's draft page to App Store Connect: what changes, language by language; it runs when confirmed",usage:"<app id>",details:["The draft is compared with the page of the app's version that can change; a field the draft leaves empty, and a language it has not, are left as they are."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id");await v(e,t,`plan writing ${n}'s App Store page`);let s;try{s=await h(e,t,"POST",`/stores/apps/${k(n)}/listing/plan`,void 0,j())}catch(a){Ty(e,a,n,"nothing was planned")}e.out.result(s,()=>{if(!s.action){e.out.line(`Nothing to change: App Store Connect holds ${n}'s page of version ${s.version} as revision ${s.revision} of the draft has it.`);return}e.out.line(`Revision ${s.revision} of the draft, written to version ${s.version}'s page, changes:`),s.steps.forEach((a,i)=>e.out.line(` ${i+1}. ${a.says}`)),Yl(e,s.action,{summary:!1})})}},hC={USES_THIRD_PARTY_CONTENT:"it shows, contains or reaches third-party content",DOES_NOT_USE_THIRD_PARTY_CONTENT:"no third-party content"},mC={manual:"manual: a person releases it once approved",after_approval:"as soon as it is approved"},gC=["paused","active","complete"];function Ey(e,t,n){let s=n.version;e.out.line(s?`${t}: version ${s.version_string} \u2014 ${s.state}${s.first_version?" (the app's first: it has no What's New)":""}`:`${t} has no App Store version that can change.`);let a=[];s&&(a.push(["build",s.build_number!==""?s.build_number:"(none yet)"]),a.push(["copyright",Et(s.copyright)]),a.push(["release",s.release==="scheduled"?`scheduled: not before ${L(s.release_at)}`:mC[s.release]??Et(s.release)]));let i=n.phased;a.push(["phased",i?`over seven days \u2014 ${i.state}${i.state!=="INACTIVE"?`, day ${i.day} of 7`:""}${i.paused_days>0?`, paused ${Kt(i.paused_days,"day")}`:""}`:"no: everyone gets it at once"]),a.push(["price",n.priced?"set":"none yet (stores:version:prepare --free makes it free)"]),a.push(["content rights",hC[n.content_rights]??Et(n.content_rights)]);let r=n.review,o=[`${r.contact_first_name} ${r.contact_last_name}`.trim(),r.contact_phone,r.contact_email].filter(d=>d!=="").join(", ");a.push(["review contact",Et(o)]),a.push(["demo account",r.demo_account_required?`required: ${Et(r.demo_account_name)}, password ${r.has_demo_password?"set":"not set"}`:"not required"]),a.push(["review notes",Et(r.notes)]),n.watched&&a.push(["watched",`${n.watched.version_string} ${n.watched.state} since ${L(n.watched.state_at)} (read ${L(n.watched.checked_at)})`]);let l=Math.max(...a.map(([d])=>d.length));for(let[d,p]of a)e.out.line(` ${d.padEnd(l)} ${p}`);if(n.missing.length>0){e.out.line("App Review would refuse it for:");for(let d of n.missing)e.out.line(` - ${d}`)}else s&&e.out.line(`App Review has what it needs: palbase stores:version:submit ${t}`);s||e.out.line(`Prepare the next one: palbase stores:version:prepare ${t} --version <x.y.z>`)}var fC={name:"stores:version",summary:"an iOS app's App Store version as App Review will see it \u2014 its build, release, phased release, price, content rights, review contact \u2014 and what App Review would refuse it for",usage:"<app id>",details:["The demo account's password is never read out: only whether Apple holds one. watched is what the module last saw of the version sent to App Review (it reads it every few minutes)."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await h(e,t,"GET",`/stores/apps/${k(n)}/version`);e.out.result(s,()=>Ey(e,n,s))}},by={contact_first_name:"string",contact_last_name:"string",contact_email:"string",contact_phone:"string",demo_account_required:"boolean",demo_account_name:"string",notes:"string"};function yC(e){let t=Pn(e)&&Pn(e.review)&&"app_id"in e?e.review:e;if(!Pn(t))throw m('the review file is a JSON object: { "contact_first_name": \u2026, "contact_email": \u2026, "demo_account_required": \u2026, "notes": \u2026 }');let{has_demo_password:n,...s}=t;for(let[a,i]of Object.entries(s)){if(a==="demo_account_password")throw m("the review file holds no password: the demo account's is read from stdin, never from a file","take it out of the file, and pipe it in: \u2026 --demo-password-stdin < password.txt");let r=by[a];if(r===void 0)throw m(`the review file's ${a} is not one of App Review's details: ${Object.keys(by).join(", ")}`);if(typeof i!==r)throw m(`the review file's ${a} is ${r==="string"?"text":"true or false"}`)}return s}function wy(e,t){if(e.flags[t]===!0&&e.flags[`no-${t}`]===!0)throw m(`--${t} and --no-${t} are one or the other`);if(e.flags[t]===!0)return!0;if(e.flags[`no-${t}`]===!0)return!1}var bC={name:"stores:version:prepare",summary:"prepare an iOS app's App Store version: its number, build, copyright, release, phased release, content rights, a free price, App Review's details",usage:"<app id> [--version <x.y.z>] [--build <n>] [--copyright <text>] [--release manual|after_approval|scheduled] [--release-at <RFC 3339>] [--phased | --no-phased] [--third-party-content | --no-third-party-content] [--free] [--territories all] [--app-privacy published|unpublished] [--review-file <review.json>] [--demo-password-stdin]",details:["Only what is given is written; --version makes the next version when the app has none that can change. The build is a TestFlight build of that version, by its number.","--review-file holds App Review's details as stores:version --json shows them (its review): a field the file leaves out stays as it is. The demo account's password is read from stdin alone (--demo-password-stdin), never from the file or the command line; it goes to Apple, and is never printed or kept."],args:{min:1,max:1},flags:{version:{type:"string",value:"x.y.z",description:"the version's number: makes it when the app has none that can change"},build:{type:"string",value:"n",description:"the TestFlight build App Review gets, by its build number"},copyright:{type:"string",value:"text",description:"the copyright line (2026 Your Company)"},release:{type:"string",value:"how",description:"how it goes out once approved: manual, after_approval or scheduled"},"release-at":{type:"string",value:"RFC 3339",description:"a scheduled release, not before then (alone, it is scheduled)"},phased:{type:"boolean",description:"release it in phases over seven days"},"no-phased":{type:"boolean",description:"release it to everyone at once"},"third-party-content":{type:"boolean",description:"the content rights statement: the app shows, contains or reaches third-party content"},"no-third-party-content":{type:"boolean",description:"the content rights statement: it does not"},free:{type:"boolean",description:"make an app with no price free everywhere (a paid price is set in App Store Connect)"},territories:{type:"string",value:"all",description:"all: sell an app sold nowhere in every country and region (chosen ones are set in App Store Connect)"},"app-privacy":{type:"string",value:"published|unpublished",description:"say the app's privacy details were published in App Store Connect (Apple has no API for them): the missing list stops asking for them"},"review-file":{type:"string",value:"review.json",description:"App Review's details: contact, demo account, notes ('-': stdin)"},"demo-password-stdin":{type:"boolean",description:"read the demo account's password from stdin (never a file or the command line)"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s={},a=[],i=e.flags.version;if(i!==void 0){if(!/^\d+(\.\d+){0,2}$/.test(i)||i.length>18)throw m(`--version ${i}: one to three numbers with dots (1.2.3)`);s.version_string=i,a.push(`version ${i}`)}let r=se(e.flags.build,"build");if(r!==void 0){if(r<1)throw m("--build is a TestFlight build's number");s.build_number=r,a.push(`build ${r}`)}let o=e.flags.copyright;if(o!==void 0){if(o.trim()===""||o.length>200)throw m("--copyright is 1 to 200 characters (2026 Your Company)");s.copyright=o,a.push("copyright")}let l=e.flags.release,d=e.flags["release-at"];if(l!==void 0&&!["manual","after_approval","scheduled"].includes(l))throw m("--release is manual, after_approval or scheduled");if(d!==void 0){if(l!==void 0&&l!=="scheduled")throw m(`--release-at is a scheduled release's: not ${l}`);let S=Date.parse(d);if(!Number.isFinite(S))throw m(`--release-at ${d}: a time, RFC 3339 (2026-11-02T09:00:00Z)`);if(S<=e.io.now())throw m(`--release-at ${d}: a scheduled release's time is in the future`);s.release="scheduled",s.release_at=new Date(S).toISOString()}else{if(l==="scheduled")throw m("--release scheduled needs --release-at: when it may go out");l!==void 0&&(s.release=l)}s.release&&a.push(`release ${s.release}${s.release_at?` at ${s.release_at}`:""}`);let p=wy(e,"phased");p!==void 0&&(s.phased=p,a.push(p?"phased release":"release to everyone at once"));let u=wy(e,"third-party-content");u!==void 0&&(s.uses_third_party_content=u,a.push(u?"uses third-party content":"no third-party content")),e.flags.free===!0&&(s.price="free",a.push("free"));let g=e.flags.territories;if(g!==void 0){if(g!=="all")throw m("--territories is all (chosen countries are set in App Store Connect)");s.territories="all",a.push("sold in every country and region")}let y=e.flags["app-privacy"];if(y!==void 0){if(y!=="published"&&y!=="unpublished")throw m("--app-privacy is published or unpublished");s.app_privacy=y,a.push(`App Privacy ${y}`)}let w=e.flags["review-file"],_=e.flags["demo-password-stdin"]===!0;if(_&&w==="-")throw m("stdin carries the demo password or the review file, not both","--review-file <review.json> --demo-password-stdin < password.txt");if(w!==void 0||_){let S=w!==void 0?yC(me(await ke(e,w,"the review details"),"the review details")):{},$=_?await Me(e,"the demo account's password"):void 0;if($!==void 0&&$.length>256)throw m("the demo account's password is 256 characters at most");let{has_demo_password:R,...T}=(await h(e,t,"GET",`/stores/apps/${k(n)}/version`)).review;s.review={...T,...S,...$!==void 0?{demo_account_password:$}:{}},w!==void 0&&a.push("App Review's details"),$!==void 0&&a.push("the demo account's password")}if(a.length===0)throw m("nothing to prepare: name at least one of the version, its build, copyright, release, phased release, content rights, price, countries, App Privacy or review details","palbase help stores:version:prepare");await v(e,t,`prepare ${n}'s App Store version: ${a.join(", ")}`);let P;try{P=await h(e,t,"PUT",`/stores/apps/${k(n)}/version`,s)}catch(S){throw S instanceof E&&S.code==="no_editable_version"?new f("no_editable_version",`${n} has no App Store version that can change`,{hint:`make the next one: palbase stores:version:prepare ${n} --version <x.y.z> \u2026`}):S}e.out.result(P,()=>{e.out.line(`Prepared ${n}'s App Store version.`),Ey(e,n,P)})}};function Or(e,t,n,s,a={},i){return{name:e,summary:s,usage:"<app id>",args:{min:1,max:1},scope:"environment",...a,async run(r){let o=await b(r),l=X(r,0,"the app's id"),d=i?.(r);await v(r,o,`plan ${Rn[t]} of app ${l}`);let p;try{p=await h(r,o,"POST",`/stores/apps/${k(l)}/version/${n}`,d,j())}catch(u){if(u instanceof E&&u.code==="version_incomplete"){let g=u.message.slice(u.message.indexOf(": ")+2).split("; ").filter(y=>y!=="");r.out.note("App Review would refuse the version for:");for(let y of g)r.out.note(` - ${y}`);throw new f("version_incomplete",`nothing was planned: the version lacks ${Kt(g.length,"thing")} App Review needs`,{hint:`palbase stores:version ${l} says what is missing; palbase stores:version:prepare ${l} \u2026 writes what can be written from here`})}throw u instanceof E&&u.code==="no_editable_version"?new f("no_editable_version",`${l} has no App Store version to send`,{hint:`prepare one: palbase stores:version:prepare ${l} --version <x.y.z> --build <n> \u2026`}):u}r.out.result(p,()=>Yl(r,p))}}}var wC=Or("stores:version:submit","submit_review","submit","plan sending an iOS app's prepared version to App Review \u2014 refused, with what is missing, until it has what App Review needs; it runs when confirmed",{usage:"<app id> [--with <product id>,\u2026]",details:["--with sends the app's in-app purchases and subscriptions with the version, by product id: a product's first review goes with an app version, as Apple requires, and each is READY_TO_SUBMIT at Apple (its text, price, availability and review screenshot complete) or nothing is planned."],flags:{with:{type:"string",value:"product id,\u2026",description:"in-app purchases sent to App Review with the version, by product id"}}},e=>{let t=e.flags.with;if(t===void 0)return;let n=t.split(",").map(s=>s.trim()).filter(s=>s!=="");if(n.length===0||n.length>50)throw m("--with names 1 to 50 product ids, comma-separated");return{in_app_purchases:n}}),vC=Or("stores:version:withdraw","withdraw_review","withdraw","plan taking the version out of App Review: it is edited again, and sent again from the start; it runs when confirmed"),_C=Or("stores:version:release","release_version","release","plan releasing an approved version that waits for its developer (a manual release) on the App Store, for good; it runs when confirmed"),kC=Or("stores:version:phased","phased_release","phased-release","plan pausing, resuming or completing the version's phased release (complete: everyone gets it now); it runs when confirmed",{usage:"<app id> <paused|active|complete>",args:{min:2,max:2}},e=>{let t=e.args[1];if(!gC.includes(t))throw m(`a phased release is paused, active (resumed) or complete (everyone gets it now), not ${JSON.stringify(t)}`);return{state:t}});function Yl(e,t,n={}){e.out.line(`Planned ${Rn[t.kind]??t.kind} of ${Bs(t)} (action ${t.id}):`),n.summary!==!1&&e.out.line(` ${t.summary}`),e.out.line(` hash: ${t.hash}`),e.out.line(`It runs only when confirmed, before ${L(t.expires_at)}:`),e.out.line(` palbase stores:actions:confirm ${t.id} --hash ${t.hash}`)}function Xl(e,t,n,s,a={},i){return{name:e,summary:s,usage:"<package id>",args:{min:1,max:1},scope:"environment",...a,async run(r){let o=await b(r),l=X(r,0,"the package's id"),d=i?.(r);await v(r,o,`plan ${Rn[t]} of package ${l}`);let p=await h(r,o,"POST",`/stores/packages/${k(l)}/${n}`,d,j());r.out.result(p,()=>Yl(r,p))}}}var SC=Xl("stores:beta-review","beta_review","beta-review","plan sending a package to Beta App Review (external testers get it after Apple's review); it runs when confirmed"),$C=Xl("stores:export-compliance","export_compliance","export-compliance","plan the export compliance answer of a package's build (the question TestFlight waits on); it runs when confirmed",{usage:"<package id> --uses-non-exempt-encryption yes|no",flags:{"uses-non-exempt-encryption":{type:"string",value:"yes|no",description:"whether the app uses encryption beyond HTTPS and what iOS provides"}}},e=>{let t=mn(e.flags["uses-non-exempt-encryption"],"uses-non-exempt-encryption");if(t===void 0)throw m("--uses-non-exempt-encryption is yes or no: whether the app uses encryption beyond HTTPS and what iOS provides");return{uses_non_exempt_encryption:t}}),PC=Xl("stores:expire","expire_build","expire","plan expiring a package's build in TestFlight (testers can no longer install it); it runs when confirmed"),AC={name:"stores:actions",summary:"the actions planned at Apple, newest first: what each does, and whether it ran (running: a page still being written)",usage:"[--status planned|done|declined|failed] [--limit <n>]",flags:{status:{type:"string",value:"status",description:"only those planned, done, declined or failed"},limit:{type:"string",value:"n",description:"how many (1\u2013200, default 30)"}},scope:"environment",async run(e){let t=await b(e),n=e.flags.status;if(n!==void 0&&!["planned","done","declined","failed"].includes(n))throw m("--status is planned, done, declined or failed");let s=se(e.flags.limit,"limit")??30;if(s<1||s>200)throw m("--limit is a whole number from 1 to 200");let a=new URLSearchParams({limit:String(s),...n?{status:n}:{}}),i=await h(e,t,"GET",`/stores/actions?${a}`);e.out.result(i,()=>{i.actions.length===0?e.out.line(n?`No ${n} action.`:"No action yet."):e.out.table(i.actions,[{header:"action",value:r=>r.id},{header:"kind",value:r=>r.kind},{header:"package / app",value:r=>r.package_id??r.app_id??""},{header:"status",value:r=>r.status},{header:"planned",value:r=>L(r.created_at)},{header:"what",value:r=>r.summary}]),i.next_cursor&&e.out.note(`More than ${s}: raise --limit to see older ones.`)})}},RC={name:"stores:actions:confirm",summary:"run a planned action at Apple: it names the hash of the plan that was shown, and is asked about first",usage:"<action id> --hash <hash>",details:["What it does is shown, then asked about \u2014 in every environment, as it cannot be undone at Apple. -y confirms without asking.",`An App Store page's plan is written after the answer (its screenshots take minutes): the command waits for it to be done or failed, ${jr/60} minutes at most; stopping the wait does not stop the writing.`],args:{min:1,max:1},flags:{hash:{type:"string",value:"hash",description:"the plan's hash, as it was shown when it was planned"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the action's id"),s=e.flags.hash;if(s===void 0||s.trim()==="")throw m("--hash is the plan's hash, as stores:actions or the plan printed it: a confirmation names the plan it saw");let a=await h(e,t,"GET",`/stores/actions/${k(n)}`);if(a.status!=="planned")throw new f("action_not_planned",`the action ${n} is ${a.status}: only a planned one is confirmed`);await v(e,t,`run ${Rn[a.kind]??a.kind} of ${Bs(a)}: ${a.summary}`,"It is done at Apple and cannot be undone");let i=await h(e,t,"POST",`/stores/actions/${k(n)}/confirm`,{hash:s},j());return i.status==="running"&&(i=await EC(e,t,i)),e.out.result(i,()=>TC(e,i)),i.status==="failed"?1:0}};function TC(e,t){e.out.line(`${Bl(Rn[t.kind]??t.kind)} of ${Bs(t)}: ${t.status}.`);let n=t.result??{};if(typeof n.error=="string"&&n.error!==""&&e.out.line(` ${n.error}`),Array.isArray(n.missing))for(let s of n.missing)typeof s=="string"&&e.out.line(` - ${s}`);if(typeof n.steps_done=="number"&&(t.status==="done"?e.out.line(`${Kt(n.steps_done,"step")} written at App Store Connect.`):e.out.line(`${Kt(n.steps_done,"step")} written before it stopped${typeof n.failed_step=="string"?` at: ${n.failed_step}`:""}; planned again, what is left is written.`)),t.kind==="phased_release"&&t.status==="done"&&typeof n.state=="string"&&e.out.line(`The phased release is ${n.state}.`),n.in_app_purchases&&typeof n.in_app_purchases=="object")for(let[s,a]of Object.entries(n.in_app_purchases))typeof a=="string"&&e.out.line(`App Store Connect says of ${s}: ${a}.`);typeof n.version_state=="string"&&e.out.line(`App Store Connect says of the version: ${n.version_state}.`),n.withdrawing===!0&&e.out.line(`App Store Connect is taking the version out of App Review, which takes it a few seconds: palbase stores:version ${t.app_id??"<app id>"} shows it once it has.`)}async function EC(e,t,n){e.out.note(`${Bl(Rn[n.kind]??n.kind)} of ${Bs(n)} is under way at App Store Connect; waiting for it to end (${jr/60} minutes at most \u2014 stopping the wait does not stop it).`);let s=e.io.now()+jr*1e3,a=n;for(;a.status==="running";){if(e.io.now()>=s)throw new f("action_running",`${Rn[n.kind]??n.kind} of ${Bs(n)} is still running after ${jr/60} minutes (action ${n.id})`,{hint:"it goes on without this command: palbase stores:actions says when it is done or failed"});await e.io.sleep(rE*1e3),a=await h(e,t,"GET",`/stores/actions/${k(n.id)}`)}return a}var CC={name:"stores:actions:decline",summary:"decline a planned action: it never runs",usage:"<action id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the action's id");await v(e,t,`decline the action ${n}`);let s=await h(e,t,"POST",`/stores/actions/${k(n)}/decline`,void 0,j());e.out.result(s,()=>e.out.line(`Declined ${Rn[s.kind]??s.kind} of ${Bs(s)}.`))}},Gl={"3m":"MONTHLY_RENEWAL_EVERY_THREE_MINUTES","5m":"MONTHLY_RENEWAL_EVERY_FIVE_MINUTES","15m":"MONTHLY_RENEWAL_EVERY_FIFTEEN_MINUTES","30m":"MONTHLY_RENEWAL_EVERY_THIRTY_MINUTES","1h":"MONTHLY_RENEWAL_EVERY_ONE_HOUR"},Cy=e=>Object.entries(Gl).find(([,t])=>t===e)?.[0]??e,jC=100;function OC(e,t){t.testers.length===0&&e.out.line("The team has no sandbox tester yet."),e.out.table(t.testers,[{header:"email",value:n=>n.email},{header:"name",value:n=>`${n.first_name} ${n.last_name}`.trim()},{header:"storefront",value:n=>n.territory},{header:"monthly renews every",value:n=>Cy(n.subscription_renewal_rate)},{header:"interrupted",value:n=>n.interrupt_purchases?"yes":"no"},{header:"id",value:n=>n.id}]),t.create_in&&e.out.note(`A person makes another, Apple's API makes none: ${t.create_in}`)}async function jy(e,t,n){let s=(await h(e,t,"GET","/stores/apple/sandbox-testers")).testers,a=[];for(let i of n){let r=s.find(o=>o.id===i||o.email.toLowerCase()===i.toLowerCase());if(!r)throw new f("no_such_tester",`the team has no sandbox tester ${i}`,{hint:`its testers: ${s.map(o=>o.email).join(", ")||"none \u2014 App Store Connect \u203A Users and Access \u203A Sandbox makes one"}`});a.some(o=>o.id===r.id)||a.push(r)}return a}var MC={name:"stores:apple:sandbox-testers",summary:"the Apple team's sandbox testers: the accounts that buy in the App Store's sandbox, how fast their subscriptions renew",details:["They are the team's, every environment's alike. Only a person makes one: App Store Connect \u203A Users and Access \u203A Sandbox."],scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/stores/apple/sandbox-testers");e.out.result(n,()=>OC(e,n))}},IC={name:"stores:apple:sandbox-testers:set",summary:"change how a sandbox tester buys: how fast its monthly subscriptions renew, whether its purchases are interrupted, its storefront",usage:"<email|id> [--renewal 3m|5m|15m|30m|1h] [--interrupt on|off] [--storefront <code>]",details:["A monthly subscription renews at the rate given; a yearly one in proportion. Apple renews one 12 times at most, then lets it end.","An interrupted purchase stops for an action of the buyer's, as when a bank asks for one: what the app does then is tested."],args:{min:1,max:1},flags:{renewal:{type:"string",value:"rate",description:"every 3m, 5m, 15m, 30m or 1h"},interrupt:{type:"string",value:"on|off",description:"interrupt its purchases"},storefront:{type:"string",value:"code",description:"the storefront it buys in, three letters (USA, DEU, TUR \u2026)"}},scope:"environment",async run(e){let t=await b(e),n={},s=e.flags.renewal;if(s!==void 0){let l=Gl[s.trim().toLowerCase()];if(l===void 0)throw m(`--renewal ${s}: a monthly subscription renews every ${Object.keys(Gl).join(", ")}`);n.subscription_renewal_rate=l}let a=e.flags.interrupt;if(a!==void 0){if(a!=="on"&&a!=="off")throw m("--interrupt is on or off");n.interrupt_purchases=a==="on"}let i=e.flags.storefront?.trim().toUpperCase();if(i!==void 0){if(!xs.has(i))throw m(`--storefront ${e.flags.storefront}: not an App Store storefront`,"three letters, its country's ISO 3166-1 code: USA, DEU, TUR \u2026");n.territory=i}if(Object.keys(n).length===0)throw m("nothing to change: --renewal, --interrupt or --storefront");let[r]=await jy(e,t,[e.args[0]]);await v(e,t,`change the sandbox tester ${r.email}`);let o=await h(e,t,"PATCH",`/stores/apple/sandbox-testers/${k(r.id)}`,n,j());e.out.result(o,()=>{e.out.line(`${o.email}: monthly subscriptions renew every ${Cy(o.subscription_renewal_rate)}, purchases ${o.interrupt_purchases?"interrupted":"not interrupted"}, storefront ${o.territory}.`),n.territory!==void 0&&e.out.line("Sign out of the sandbox account on the device and in again for the storefront to change there.")})}},LC={name:"stores:apple:sandbox-testers:clear",summary:"clear sandbox testers' purchase history: each buys again as for the first time, introductory offers included",usage:"<email|id>\u2026",details:["Apple clears them after it answers, which can take minutes. Then sign out of the sandbox account on the device and in again."],args:{min:1,max:jC},scope:"environment",async run(e){let t=await b(e),n=await jy(e,t,e.args);await v(e,t,`clear what ${n.map(s=>s.email).join(", ")} bought in the sandbox`),await h(e,t,"POST","/stores/apple/sandbox-testers/clear-purchase-history",{tester_ids:n.map(s=>s.id)},j()),e.out.result({cleared:n.map(s=>s.email)},()=>{e.out.line(`Apple is clearing what ${n.map(s=>s.email).join(", ")} bought in the sandbox.`),e.out.line("Once it has (minutes), sign out of the sandbox account on the device and in again.")})}};function DC(e,t,n){if(n.threads.length===0){e.out.line("App Review has written nothing in this app's Resolution Center.");return}for(let s of n.threads){e.out.line(`thread ${s.id} \u2014 ${s.type??"?"}${s.state?`, ${s.state}`:""}${s.last_message_at?`, last ${L(s.last_message_at)}`:""}${s.can_reply?"":" (takes no answer)"}`);for(let a of s.rejections)for(let i of a.reasons)e.out.line(` guideline ${i.section??"?"}: ${i.description??""}`);for(let a of s.messages){e.out.line(` ${a.from??"message"}${a.created_at?` ${L(a.created_at)}`:""}:`);for(let i of a.body.split(`
|
|
677
677
|
`))e.out.line(` ${i}`)}for(let a of s.attachments)e.out.line(` attachment ${a.id}: ${a.file_name??"?"}${a.file_size?` (${a.file_size} bytes)`:""} \u2014 GET /stores/apps/${t}/review/threads/${s.id}/attachments/${a.id}`);s.draft&&e.out.line(` answer not sent yet: ${s.draft.body}`)}}var xC={name:"stores:app-review",summary:"an iOS app's Resolution Center, read with the Apple ID: App Review's messages, the guidelines a rejection names, its attachments, the answer not sent yet",usage:"<app id>",details:["Apple's API gives no reason for a rejection: the Apple ID signed in for the environment reads it (stores:apple:connect --apple-id). The five threads written to last."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await h(e,t,"GET",`/stores/apps/${k(n)}/review`);e.out.result(s,()=>DC(e,n,s))}},NC={name:"stores:app-review:answer",summary:"write the answer to an App Review thread, as App Store Connect's draft; --send sends it",usage:"<app id> <thread id> [--file <answer.txt>] [--send]",details:["The answer is read from --file, or piped in. Without --send it stays a draft, which App Store Connect's website shows too; with --send it goes to App Review."],args:{min:2,max:2},flags:{file:{type:"string",value:"answer.txt",description:"the answer (default: stdin)"},send:{type:"boolean",description:"send it to App Review once written"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=X(e,1,"the thread's id"),a=(await ke(e,e.flags.file,"the answer")).trim(),i=e.flags.send===!0;await v(e,t,i?`send an answer to App Review on thread ${s}`:`write an answer to App Review on thread ${s}`);let r=await h(e,t,"PUT",`/stores/apps/${k(n)}/review/threads/${k(s)}/draft`,{body:a},j());if(!i){e.out.result(r,()=>e.out.line(`Wrote the answer as a draft (${r.id}); send it with --send, or from App Store Connect.`));return}let o=await h(e,t,"POST",`/stores/apps/${k(n)}/review/threads/${k(s)}/draft/send`,void 0,j());e.out.result(o,()=>e.out.line(`Sent the answer to App Review (message ${o.id}).`))}};function Oy(e,t){e.out.line(`App Privacy: ${t.published?"published":"not published"}`),t.usages.length===0?e.out.line("No line is written."):e.out.table(t.usages,[{header:"category",value:n=>n.category??""},{header:"purpose",value:n=>n.purpose??""},{header:"data protection",value:n=>n.data_protection}])}var qC={name:"stores:privacy",summary:"an iOS app's App Privacy details as App Store Connect has them, read with the Apple ID",usage:"<app id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=await h(e,t,"GET",`/stores/apps/${k(n)}/privacy`);e.out.result(s,()=>Oy(e,s))}},KC={name:"stores:privacy:set",summary:"write an iOS app's App Privacy details at Apple with the Apple ID, and publish them with --publish",usage:"<app id> --file <usages.json> [--publish]",details:[`The file is the details' lines in Apple's words: [{"category":"USER_ID","purpose":"APP_FUNCTIONALITY","data_protection":"DATA_LINKED_TO_YOU"}], or [{"data_protection":"DATA_NOT_COLLECTED"}] alone. What Apple has and the file lacks is removed; what the file has and Apple lacks is made.`],args:{min:1,max:1},flags:{file:{type:"string",value:"usages.json",description:"the lines (default: stdin)"},publish:{type:"boolean",description:"publish them once written"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=me(await ke(e,e.flags.file,"the App Privacy lines"),"the App Privacy lines"),a=Array.isArray(s)?s:s?.usages;if(!Array.isArray(a))throw m('the file is a list of lines, or {"usages": [...]}');await v(e,t,`write the App Privacy details of ${n} at Apple${e.flags.publish===!0?" and publish them":""}`);let i={usages:a,publish:e.flags.publish===!0},r=await h(e,t,"PUT",`/stores/apps/${k(n)}/privacy`,i,j());e.out.result(r,()=>Oy(e,r))}},GC={name:"stores:apps:record",summary:"make a linked iOS app's App Store Connect record with the Apple ID \u2014 Apple's API leaves it to a person on the website \u2014 and link the app to it",usage:"<app id> --name <App Store name> [--sku <sku>] [--locale <en-US>] [--company <seller name>]",args:{min:1,max:1},flags:{name:{type:"string",value:"name",description:"its App Store name (30 characters at most)"},sku:{type:"string",value:"sku",description:"the record's own id in the team (default: the bundle id)"},locale:{type:"string",value:"locale",description:"its store page's first language (default: en-US)"},company:{type:"string",value:"name",description:"the seller's name, which a team's first app sets"}},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id"),s=e.flags.name;if(s===void 0||s.trim()==="")throw m("--name is the app's App Store name");let a={name:s.trim()};e.flags.sku!==void 0&&(a.sku=e.flags.sku),e.flags.locale!==void 0&&(a.primary_locale=e.flags.locale),e.flags.company!==void 0&&(a.company_name=e.flags.company),await v(e,t,`make the App Store Connect record "${a.name}" for ${n}`);let i=await h(e,t,"POST",`/stores/apps/${k(n)}/record`,a,j());e.out.result(i,()=>e.out.line(`Made the App Store Connect record ${i.asc_app_id??"?"} for ${i.bundle_id}, and linked ${i.name} to it.`))}},UC={name:"stores:apps:record:remove",summary:"remove a linked iOS app's App Store Connect record with the Apple ID, as App Store Connect's Remove App does (an app never approved)",usage:"<app id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=X(e,0,"the app's id");await v(e,t,`remove the App Store Connect record of ${n}`),await h(e,t,"DELETE",`/stores/apps/${k(n)}/record`,void 0,j()),e.out.result({removed:!0},()=>e.out.line(`Removed the App Store Connect record of ${n}; the app stays linked, with no record.`))}},My=[uE,mE,gE,fE,wE,vE,_E,kE,SE,$E,PE,AE,RE,MC,IC,LC,EE,CE,GC,UC,GE,jE,OE,ME,LE,xE,NE,qE,KE,UE,WE,FE,JE,VE,HE,YE,XE,ZE,eC,tC,sC,aC,SC,$C,PC,lC,dC,pC,uC,cC,fC,bC,wC,vC,_C,kC,xC,NC,qC,KC,AC,RC,CC];import{createHash as o2}from"node:crypto";import{mkdir as l2,writeFile as d2}from"node:fs/promises";import{dirname as p2}from"node:path";import{spawn as BC}from"node:child_process";import{accessSync as zC,constants as WC,mkdtempSync as FC,readFileSync as JC,rmSync as VC}from"node:fs";import{tmpdir as HC}from"node:os";import{delimiter as YC,join as ts}from"node:path";import{pathToFileURL as XC}from"node:url";function Iy(e,t=process.platform){let n=r=>{try{return zC(r,WC.X_OK),!0}catch{return!1}},s=e.PALBASE_BROWSER?.trim();if(s)return n(s)?{path:s}:{named:s};let a=[];if(t==="darwin")for(let r of["/Applications",ts(e.HOME??"","Applications")])a.push(`${r}/Google Chrome.app/Contents/MacOS/Google Chrome`,`${r}/Chromium.app/Contents/MacOS/Chromium`,`${r}/Microsoft Edge.app/Contents/MacOS/Microsoft Edge`,`${r}/Brave Browser.app/Contents/MacOS/Brave Browser`);else if(t==="win32")for(let r of[e.PROGRAMFILES,e["PROGRAMFILES(X86)"],e.LOCALAPPDATA])r&&a.push(ts(r,"Google","Chrome","Application","chrome.exe"),ts(r,"Microsoft","Edge","Application","msedge.exe"),ts(r,"Chromium","Application","chrome.exe"));else for(let r of(e.PATH??"").split(YC).filter(Boolean))for(let o of["google-chrome","google-chrome-stable","chromium","chromium-browser","microsoft-edge","microsoft-edge-stable","brave-browser"])a.push(ts(r,o));let i=a.find(n);return i?{path:i}:{}}function Ly(e){return(e.PALBASE_BROWSER_ARGS??"").split(/\s+/).filter(Boolean)}var xa=class extends Error{noSandbox;constructor(t){let n=t.split(`
|
|
678
678
|
`).map(i=>i.replace(/^\[[^\]]*\]\s*/,"").trim()).filter(Boolean),s=n.some(i=>i.includes("No usable sandbox")),a=s?"it has no sandbox to run in here":[...n].reverse().find(i=>/FATAL|ERROR|error/.test(i))??n.at(-1);super(`the browser closed as it started${a?`: ${a.slice(0,200)}`:""}`),this.noSandbox=s}},Mr=e=>new Promise(t=>setTimeout(t,e));async function Dy(e,t,n,s={}){let a=s.timeoutMs??3e4,i=FC(ts(HC(),"palbase-preview-")),r=BC(e,["--headless=new","--disable-gpu","--hide-scrollbars","--no-first-run","--no-default-browser-check","--disable-extensions","--disable-background-networking","--disable-sync","--mute-audio","--autoplay-policy=no-user-gesture-required",`--user-data-dir=${i}`,"--remote-debugging-port=0",...s.args??[],"about:blank"],{stdio:["ignore","ignore","pipe"]}),o="";r.stderr?.on("data",p=>{o=(o+p.toString("utf8")).slice(-8192)});let l=!1;r.once("exit",()=>{l=!0});let d=new Promise((p,u)=>r.once("error",g=>u(new Error(`the browser did not start: ${g.message}`))));try{return await Promise.race([d,(async()=>{let p;for(let w=Date.now()+2e4;p===void 0&&Date.now()<w&&!l;await Mr(100))try{p=Number(JC(ts(i,"DevToolsActivePort"),"utf8").split(`
|
|
679
679
|
`)[0])}catch{}if(p===void 0||!Number.isInteger(p))throw l?new xa(o):new Error("the browser did not open its DevTools port in 20 s");let u;for(let w=Date.now()+1e4;u===void 0;await Mr(100))try{u=await(await fetch(`http://127.0.0.1:${p}/json/list`)).json()}catch(_){if(Date.now()>w||l)throw new Error(`the browser's DevTools did not answer: ${_ instanceof Error?_.message:String(_)}`)}let g=u.find(w=>w.type==="page");if(!g)throw new Error("the browser opened no page");let y=await ZC(g.webSocketDebuggerUrl);try{await y.send("Page.enable");let w=[];for(let _ of n){await y.send("Emulation.setDeviceMetricsOverride",{width:_.width,height:_.height,deviceScaleFactor:_.scale,mobile:!1}),await y.send("Page.navigate",{url:`${XC(t).href}?${_.query}`});let P=!1;for(let W=Date.now()+a;!P&&Date.now()<W;)await Mr(100),P=(await y.send("Runtime.evaluate",{expression:"document.readyState === 'complete' && document.body?.dataset.ready === '1'",returnByValue:!0})).result?.value===!0;if(!P)throw new Error(`the page did not finish drawing in ${Math.round(a/1e3)} s`);let S=await y.send("Runtime.evaluate",{expression:"JSON.stringify({ error: document.body.dataset.error, selected: document.body.dataset.selected, findings: document.body.dataset.findings })",returnByValue:!0}),{error:$,selected:R,findings:T}=JSON.parse(String(S.result.value)),D=_.height;if(_.full&&!$){let W=await y.send("Runtime.evaluate",{expression:"window.PALBASE_FULL()",awaitPromise:!0,returnByValue:!0}),I=Number(W.result?.value);Number.isFinite(I)&&I>D&&(D=Math.min(I,16e3),await y.send("Emulation.setDeviceMetricsOverride",{width:_.width,height:D,deviceScaleFactor:_.scale,mobile:!1}),await y.send("Runtime.evaluate",{expression:"new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(1))))",awaitPromise:!0}))}let U=_.measureOnly?void 0:await y.send("Page.captureScreenshot",{format:"png",captureBeyondViewport:!1});w.push({png:U?Buffer.from(String(U.data),"base64"):new Uint8Array,height:D,...$?{error:$}:{},...R?{selected:R}:{},...T?{findings:JSON.parse(T)}:{}})}return w}finally{y.close()}})()])}finally{r.kill();for(let p=0;p<20&&!l;p++)await Mr(50);l||r.kill("SIGKILL");try{VC(i,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}catch{}}}async function ZC(e){let t=new WebSocket(e);await new Promise((a,i)=>{t.addEventListener("open",()=>a(),{once:!0}),t.addEventListener("error",()=>i(new Error("the browser refused the DevTools connection")),{once:!0})});let n=0,s=new Map;return t.addEventListener("message",a=>{let i=JSON.parse(String(a.data));if(i.id===void 0)return;let r=s.get(i.id);s.delete(i.id),i.error?r?.reject(new Error(i.error.message)):r?.resolve(i.result??{})}),t.addEventListener("close",()=>{for(let a of s.values())a.reject(new Error("the browser closed the DevTools connection"));s.clear()}),{send(a,i={}){let r=++n;return new Promise((o,l)=>{s.set(r,{resolve:o,reject:l}),t.send(JSON.stringify({id:r,method:a,params:i}))})},close:()=>t.close()}}function xy(){return Promise.resolve('"use strict";(()=>{var Ue=o=>`pw-font-${o}`;function Se(o){return(typeof o=="string"?/^asset:([0-9a-f-]{36})$/.exec(o):null)?.[1]}async function dt(o){let t=new DataView(o.buffer,o.byteOffset,o.byteLength),n=-1;for(let b=o.length-22;b>=Math.max(0,o.length-22-65535);b--)if(t.getUint32(b,!0)===101010256){n=b;break}if(n<0)throw new Error("not a zip");let i=t.getUint16(n+10,!0),c=t.getUint32(n+16,!0),p=new Map,m=0;for(let b=0;b<i;b++){if(t.getUint32(c,!0)!==33639248)throw new Error("a broken zip");let y=t.getUint16(c+10,!0),w=t.getUint32(c+20,!0),v=t.getUint32(c+24,!0),x=t.getUint16(c+28,!0),_=t.getUint16(c+30,!0),O=t.getUint16(c+32,!0),L=t.getUint32(c+42,!0),R=new TextDecoder().decode(o.subarray(c+46,c+46+x));if(c+=46+x+_+O,R.endsWith("/"))continue;if(R.startsWith("/")||R.split("/").includes(".."))throw new Error("a path leaving the zip");if(m+=v,p.size>=200||m>20971520)throw new Error("a zip too large");let j=L+30+t.getUint16(L+26,!0)+t.getUint16(L+28,!0),N=o.subarray(j,j+w);if(y===0)p.set(R,N);else if(y===8)p.set(R,await Ut(N));else throw new Error("a zip entry compressed another way")}return p}async function Ut(o){let t=new Response(new Uint8Array(o)).body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}var Wt={html:"text/html",css:"text/css",js:"text/javascript",mjs:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};function ct(o,t){let n=Wt[o.split(".").pop()?.toLowerCase()??""]??"application/octet-stream",i="";for(let c=0;c<t.length;c+=32768)i+=String.fromCharCode(...t.subarray(c,c+32768));return`data:${n};base64,${btoa(i)}`}var Kt="default-src \'none\'; img-src data:; media-src data:; font-src data:; style-src \'unsafe-inline\' data:; script-src \'unsafe-inline\' data:";function pt(o){let t=o.get("index.html");if(!t)return;let n=new TextDecoder().decode(t),i=w=>new TextDecoder().decode(o.get(w)),c=w=>{let v=w.replace(/^\\.\\//,"").split(/[?#]/)[0];return o.has(v)?v:void 0},p=w=>w.replace(/url\\(\\s*([\'"]?)([^\'")]+)\\1\\s*\\)/g,(v,x,_)=>{let O=c(_);return O?`url("${ct(O,o.get(O))}")`:v}),m=globalThis.DOMParser;if(!m)return;let b=new m().parseFromString(n,"text/html");for(let w of[...b.querySelectorAll(\'link[rel~="stylesheet"][href]\')]){let v=c(w.getAttribute("href")),x=b.createElement("style");x.textContent=v?p(i(v)):"",w.replaceWith(x)}for(let w of[...b.querySelectorAll("style")])w.textContent=p(w.textContent??"");for(let w of[...b.querySelectorAll("[src], [href], [poster]")])for(let v of["src","href","poster"]){let x=w.getAttribute(v);if(x===null)continue;let _=c(x);_?w.setAttribute(v,ct(_,o.get(_))):/^(https?:)?\\/\\//i.test(x)&&w.removeAttribute(v)}for(let w of[...b.querySelectorAll("[style]")])w.setAttribute("style",p(w.getAttribute("style")??""));let y=b.createElement("meta");return y.setAttribute("http-equiv","Content-Security-Policy"),y.setAttribute("content",Kt),b.head.prepend(y),`<!doctype html>${b.documentElement.outerHTML}`}var Gt={ios:44,android:44,web:24},ut=.12;function se(o){let t=/^rgba?\\(([\\d.]+),\\s*([\\d.]+),\\s*([\\d.]+)(?:,\\s*([\\d.]+))?\\)$/.exec(o.trim());return t?[Number(t[1]),Number(t[2]),Number(t[3]),t[4]===void 0?1:Number(t[4])]:void 0}var Me;function Xt(o){if(o.trim()==="")return;let t=se(o);return t||(Me??=document.body.appendChild(document.createElement("i")),Me.style.color="",Me.style.color=o.trim(),Me.style.color===""?void 0:se(getComputedStyle(Me).color))}var Ge=(o,t)=>{let n=o[3]+t[3]*(1-o[3]);if(n===0)return[0,0,0,0];let i=c=>(o[c]*o[3]+t[c]*t[3]*(1-o[3]))/n;return[i(0),i(1),i(2),n]};function ft([o,t,n]){let i=c=>{let p=c/255;return p<=.04045?p/12.92:((p+.055)/1.055)**2.4};return .2126*i(o)+.7152*i(t)+.0722*i(n)}function gt(o,t){let[n,i]=[ft(o),ft(t)].sort((c,p)=>p-c);return(n+.05)/(i+.05)}var ht=([o,t,n])=>`#${[o,t,n].map(i=>Math.round(i).toString(16).padStart(2,"0")).join("").toUpperCase()}`,We=o=>`${(Math.floor(o*10)/10).toFixed(1)}:1`,Z=o=>Math.round(o);function He(o){return o.parentElement??o.getRootNode().host??null}function yt(o){let t=[],n=1;for(let c=o;c;c=He(c)){let p=getComputedStyle(c);if(p.backgroundImage!=="none")return;let m=se(p.backgroundColor);if(m&&m[3]>0&&t.push(m),t.length===0&&(n*=Number(p.opacity)),m&&m[3]>=1)break}let i=[255,255,255,1];for(let c of t.reverse())i=Ge(c,i);return{color:i,opacity:n}}function Yt(o){for(let t=o;t;t=He(t)){let n=getComputedStyle(t);if(n.backgroundImage!=="none")return t;let i=se(n.backgroundColor);if(i&&i[3]>=1)return}}function mt(o){let t=yt(o),n=se(getComputedStyle(o).color);if(!t||!n)return;let i=n[3];for(let c=o;c;c=He(c)){let p=getComputedStyle(c);i*=Number(p.opacity);let m=se(p.backgroundColor);if(m&&m[3]>0)break}return{text:Ge([n[0],n[1],n[2],i],t.color),bg:t.color}}function le(o){let t=o.getBoundingClientRect();if(t.width<1||t.height<1)return!1;for(let n=o;n;n=He(n)){let i=getComputedStyle(n);if(i.visibility==="hidden"||i.display==="none"||Number(i.opacity)===0)return!1}return!0}var Ce=o=>o.closest("[data-pw-path]")?.dataset.pwPath??"the page";function wt(o){let t=(o.innerText??o.textContent??"").replace(/\\s+/g," ").trim();return t.length>40?`${t.slice(0,39)}\\u2026`:t}var ue=o=>{let t=wt(o),n=o.dataset?.pwType??o.getAttribute("role")??o.closest("[data-pw-path]")?.dataset.pwType??o.tagName.toLowerCase();return`${Ce(o)}${t?` "${t}"`:` (${n}${o.getAttribute("aria-label")?` "${o.getAttribute("aria-label")}"`:""})`}`},bt="button, [role=radio], [role=tab], [role=switch], a[href]";function Zt(o,t){for(let n=o.parentElement;n&&t.contains(n);n=n.parentElement){if(n.classList.contains("pw2-body")||n.classList.contains("pw2"))return;let i=getComputedStyle(n);if(i.overflowX!=="visible"||i.overflowY!=="visible")return n}}function Ke(o,t){for(let n=o.parentElement;n&&t.contains(n);n=n.parentElement){if(n.classList.contains("pw-track")||n.classList.contains("pw-carousel"))return!0;let i=getComputedStyle(n).overflowX;if((i==="auto"||i==="scroll")&&!n.classList.contains("pw2-body"))return!0}return!1}function kt(o,t){let n=[],i=(u,h,M)=>n.push({code:u,where:typeof h=="string"?h:ue(h),message:M}),c=o.querySelector(".pw2"),p=o.querySelector(".pw2-body"),m=o.querySelector(".pw2-foot"),b=c.getBoundingClientRect(),y=m&&le(m)?m.getBoundingClientRect():void 0,w=()=>{let u=p.getBoundingClientRect(),h=c.getBoundingClientRect(),M=m&&le(m)?m.getBoundingClientRect():void 0;return{top:Math.max(u.top,h.top),bottom:Math.min(u.bottom,h.bottom,M&&M.height>0?M.top:1/0)}},v=w(),x=[...o.querySelectorAll("[data-pw-path]")].filter(le),_=u=>u.dataset.pwType??"",O=u=>p.contains(u),L=(u,h)=>{let M=u.getBoundingClientRect(),E=Math.max(M.top,h.top),P=Math.min(M.bottom,h.bottom);for(let $=u.parentElement;$&&o.contains($)&&!$.classList.contains("pw2-body")&&!$.classList.contains("pw2");$=$.parentElement){let k=getComputedStyle($);if(k.overflowX==="visible"&&k.overflowY==="visible")continue;let D=$.getBoundingClientRect();Math.min(M.right,D.right)-Math.max(M.left,D.left)<=0&&(P=E),E=Math.max(E,D.top),P=Math.min(P,D.bottom)}return{top:E,bottom:P,r:M,area:h}},R=u=>L(u,O(u)?v:b),j=Math.max(c.scrollWidth-c.clientWidth,p.scrollWidth-p.clientWidth);j>1&&i("overflow_x","the page",`the paywall is ${Z(j)}px wider than the screen: it moves sideways`);let N=new Set;for(let u of x){if(Ke(u,o)||[...N].some(E=>E.contains(u)))continue;let h=u.getBoundingClientRect(),M=Math.max(b.left-h.left,h.right-b.right);M>1&&(N.add(u),i("overflow_x",u,`it reaches ${Z(M)}px past the screen\'s ${h.right>b.right?"right":"left"} edge`))}let Q=x.filter(u=>_(u)==="text");for(let u of Q){if(u.classList.contains("pw-clamp")&&u.scrollHeight>u.clientHeight+1){i("text_cut",u,"its text is cut off: it needs more lines than its max_lines gives at this size");continue}if(u.scrollWidth>u.clientWidth+1){i("text_cut",u,`a word is ${Z(u.scrollWidth-u.clientWidth)}px wider than its place and is cut`);continue}let h=Ke(u,o)?void 0:Zt(u,o);if(h){let P=u.getBoundingClientRect(),$=h.getBoundingClientRect(),k=Math.max($.top-P.top,P.bottom-$.bottom,$.left-P.left,P.right-$.right);if(k>1){i("text_cut",u,`${Z(k)}px of its text is hidden by ${Ce(h)}, which clips what overflows it`);continue}}let M=document.createTreeWalker(u,NodeFilter.SHOW_TEXT),E;for(let P=M.nextNode();P&&!E;P=M.nextNode())for(let $ of(P.textContent??"").matchAll(/\\S+/g)){let k=document.createRange();if(k.setStart(P,$.index),k.setEnd(P,$.index+$[0].length),new Set([...k.getClientRects()].filter(q=>q.width>0).map(q=>Math.round(q.top))).size>1){E=$[0];break}}E&&i("word_broken",u,`"${E}" is broken across lines: a word, a price above all, is drawn whole`)}let te=x.filter(u=>_(u)==="purchase_button"&&!o.querySelector(".pw-layer")?.contains(u));if(te.length===0)i("purchase_hidden","the paywall","nothing on it buys: it has no purchase button where it is drawn");else if(!te.some(u=>{let h=R(u);return h.r.top>=h.area.top-1&&h.r.bottom<=h.area.bottom+1})){let u=R(te[0]),h=u.r.top>=u.area.bottom?`${Z(u.r.top-u.area.bottom)}px below what shows`:`${Z(u.r.height-Math.max(0,u.bottom-u.top))}px of it hidden`;i("purchase_hidden",te[0],`the purchase button is not on the screen as the paywall opens (${h}): a customer scrolls to find it \\u2014 keep it in the fixed footer`)}if(y&&y.height>0){let u=[p,c].filter(M=>/^(auto|scroll)$/.test(getComputedStyle(M).overflowY)&&M.scrollHeight>M.clientHeight+1),h=u.map(M=>M.scrollTop);for(let M of u)M.scrollTop=M.scrollHeight;try{let M=w(),E=new Set;for(let P of x.filter($=>O($)&&$.matches(bt))){if(Ke(P,o)||[...E].some(k=>k.contains(P)))continue;let $=L(P,{top:-1/0,bottom:1/0});if($.bottom>$.top&&$.bottom>M.bottom+1){E.add(P);let k=Math.min($.bottom-M.bottom,$.bottom-$.top);i("covered_by_footer",P,`${Z(k)}px of its ${Z($.r.height)}px ${k>=$.bottom-$.top-1?"(all of it) ":""}stay under the fixed footer with the paywall scrolled to its end: nothing brings it into view \\u2014 end the body with room as tall as the footer (padding or a spacer)`)}}}finally{u.forEach((M,E)=>{M.scrollTop=h[E]})}}let ve=new Set(["stack","tabs","switch","carousel","countdown"]),he=[...o.querySelectorAll(".pw-switchrow, .pw-tablist, .pw-dots")].filter(le);he.push(...x.filter(u=>{let h=_(u);if(h==="spacer")return!1;if(!ve.has(h))return!0;let M=u.parentElement;if(M&&(M.classList.contains("pw2-head")||M.classList.contains("pw2-body")||M.classList.contains("pw2-foot")))return!1;let E=getComputedStyle(u),P=se(E.backgroundColor);return E.backgroundImage!=="none"||P!==void 0&&P[3]>0||u.style.getPropertyValue("--pw-bw")!==""}));let me=he.filter(u=>{let h=R(u);return h.bottom>h.top}),Ae=me.map(R).map(u=>[u.top,u.bottom]).sort((u,h)=>u[0]-h[0]),K={size:0,from:b.top,to:b.top},X=b.top;for(let[u,h]of Ae)u-X>K.size&&(K={size:u-X,from:X,to:u}),X=Math.max(X,h);if(b.bottom-X>K.size&&(K={size:b.bottom-X,from:X,to:b.bottom}),K.size>t.height*ut){let u=me.filter(E=>Math.abs(R(E).bottom-K.from)<1).pop(),h=me.find(E=>Math.abs(R(E).top-K.to)<1),M=u&&h?`between ${ue(u)} and ${ue(h)}`:u?`below ${ue(u)}`:h?`above ${ue(h)}`:"on the screen";i("large_gap",u?Ce(u):h?Ce(h):"the paywall",`a ${Z(K.size)}px empty band (${Math.round(K.size/t.height*100)}% of the screen) ${M}: no single empty space is over ${Math.round(ut*100)}%`)}let xe=new Set,be=document.createTreeWalker(c,NodeFilter.SHOW_TEXT);for(let u=be.nextNode();u;u=be.nextNode())(u.textContent??"").trim()!==""&&u.parentElement&&xe.add(u.parentElement);let ne=new Map;for(let u of xe){if(!le(u)||u.closest(".pw-grad")||u.closest("button:disabled, [aria-disabled=true]"))continue;let h=mt(u);if(!h){let D=Yt(u);D&&ne.set(D,[...ne.get(D)??[],wt(u)]);continue}let M=getComputedStyle(u),E=parseFloat(M.fontSize),P=E>=24||E>=18.66&&Number(M.fontWeight)>=700,$=P?3:4.5,k=gt(h.text,h.bg);k<$&&i("contrast",u,`its text is ${We(k)} against what is behind it (${ht(h.text)} on ${ht(h.bg)}): ${P?"large ":""}text needs ${We($)}`)}for(let[u,h]of ne){let M=h.slice(0,3).map(P=>`"${P}"`).join(", "),E=u.dataset?.pwPath!==void 0||u.closest("[data-pw-path]")?ue(u).replace(/ ".*"$/,""):"the page";n.push({code:"unmeasured_contrast",where:E,message:`not measured: ${h.length} text(s) over its picture or gradient \\u2014 ${M}${h.length>3?" \\u2026":""} \\u2014 whose colors the check does not read; look at them (purchases:paywalls:preview)`,note:!0})}let B=u=>{let h=getComputedStyle(u),M=se(h.backgroundColor);return h.backgroundImage!=="none"||M!==void 0&&M[3]>0||(u.style?.getPropertyValue("--pw-bw")??"")!==""||parseFloat(h.borderTopWidth)>0},ye=u=>{for(let h=u,M=0;h&&M<4;h=h.firstElementChild,M++)if(B(h))return h;return u},de=new Map;for(let u of[...o.querySelectorAll("[role=radio], [role=tab]")].filter(le)){let h=u.parentElement;de.set(h,[...de.get(h)??[],u])}for(let[,u]of de){let h=u.find(k=>k.getAttribute("aria-checked")==="true"||k.getAttribute("aria-selected")==="true");if(!h||u.length<2)continue;let M=k=>{let D=ye(k),q=yt(D),oe=getComputedStyle(D),U=Xt(oe.getPropertyValue("--pw-bc"))??se(oe.borderTopColor),pe=parseFloat(oe.getPropertyValue("--pw-bw"))||parseFloat(oe.borderTopWidth)||0,Le=[...k.querySelectorAll("*")].find(Ie=>[...Ie.childNodes].some(_e=>_e.nodeType===3&&(_e.textContent??"").trim()!==""));return{bg:q?.color,border:pe>0&&U&&q?Ge(U,q.color):q?.color,text:Le?mt(Le)?.text:void 0}},E=M(h),P=1/0,$;for(let k of u.filter(D=>D!==h)){let D=M(k),q=[[E.bg,D.bg],[E.border,D.border],[E.text,D.text]].filter(([U,pe])=>U&&pe);if(q.length===0)continue;let oe=Math.max(...q.map(([U,pe])=>gt(U,pe)));oe<P&&(P=oe,$=k)}if($&&P<3){let k=h.getAttribute("role")==="tab"?"tab":"package";i("selection_contrast",h,`the selected ${k} differs from ${ue($)} by ${We(P)} at most \\u2014 in its fill, its border and its text: what shows it is selected needs 3:1`)}}let Y=Gt[t.platform];for(let u of[...o.querySelectorAll(bt)].filter(le)){if(u.closest(".pw-text")||u.closest(".pw-dots")||u.getAttribute("role")==="switch"||u.disabled)continue;let h=u.getBoundingClientRect();(h.width<Y||h.height<Y)&&i("small_target",u,`it is ${Z(h.width)}\\xD7${Z(h.height)}: ${t.platform==="web"?"a pointer needs":"a finger needs"} ${Y}\\xD7${Y} \\u2014 give it padding or a height`)}for(let u of x.filter(h=>_(h)==="image"||_(h)==="video")){let h=u.querySelector("img, video");if(!h||(h instanceof HTMLImageElement?h.complete&&h.naturalWidth===0:h.readyState<2)){let E=t.nodeAt(u.dataset.pwPath??"")?.src;i("image_missing",u.dataset.pwPath??"an image",`the ${_(u)} did not load${typeof E=="string"?` (${E})`:""}: it is drawn as an empty frame`)}}for(let u of x.filter(h=>_(h)==="package")){let h=[...u.querySelectorAll("[data-pw-type=text]")].filter(le).map(E=>(E.textContent??"").replace(/\\s+/g," ").trim()).filter(E=>E!==""),M=(E,P)=>{let $=D=>` ${D.replace(/[^\\p{L}\\p{N}]+/gu," ").trim()} `,k=$(E);return k.trim().length>=3&&$(P).includes(k)};e:for(let E=0;E<h.length;E++)for(let P=0;P<h.length;P++)if(!(E===P||h[E].length>h[P].length)&&M(h[E],h[P])){i("repeated_text",u,`"${h[E]}" is said twice in one package: in "${h[E]}" and in "${h[P]}"`);break e}}return n}var ce=(o,t,n)=>`M${o-n} ${t}a${n} ${n} 0 1 0 ${2*n} 0a${n} ${n} 0 1 0 ${-2*n} 0`,Oe={ad_free:["M3 7h18v10H3z","M4 4l16 16"],bell:["M6 16v-5a6 6 0 0 1 12 0v5l2 2H4z","M10 21a2 2 0 0 0 4 0"],bolt:["M13 2L4 14h7l-1 8 9-12h-7z"],book:["M5 4h11a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3z","M5 17a3 3 0 0 1 3-3h11"],chart:["M3 20h18","M6 20v-8","M11 20V5","M16 20v-6","M21 20V9"],chat:["M4 5h16v11H9l-5 4z"],check:["M5 12l5 5 9-10"],check_circle:[ce(12,12,9),"M8 12l3 3 5-6"],clock:[ce(12,12,9),"M12 7v5l3 2"],cloud:["M7 18a4 4 0 0 1-.5-7.97A6 6 0 0 1 18 9a4.5 4.5 0 0 1-.5 9z"],crown:["M3 8l4 4 5-7 5 7 4-4-2 11H5z"],download:["M12 4v11","M7 10l5 5 5-5","M4 20h16"],gift:["M3 9h18v4H3z","M5 13v8h14v-8","M12 9v12","M12 9C10 5 6 5 6 7.5S12 9 12 9zm0 0c2-4 6-4 6-1.5S12 9 12 9z"],globe:[ce(12,12,9),"M3 12h18","M12 3a14 14 0 0 1 0 18a14 14 0 0 1 0-18z"],heart:["M12 20s-7-4.5-9-9a4.5 4.5 0 0 1 9-3 4.5 4.5 0 0 1 9 3c-2 4.5-9 9-9 9z"],infinity:["M7 9a3 3 0 1 0 0 6c3 0 7-6 10-6a3 3 0 1 1 0 6c-3 0-7-6-10-6z"],lock_open:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 7.5-2"],music:["M9 18V5l11-2v13",ce(6,18,3),ce(17,16,3)],people:[ce(9,8,3.5),"M2 20a7 7 0 0 1 14 0","M16 4.5a3.5 3.5 0 0 1 0 7","M18 14a6 6 0 0 1 4 6"],person:[ce(12,8,4),"M4 21a8 8 0 0 1 16 0"],photo:["M3 5h18v14H3z",ce(8.5,9.5,1.5),"M3 17l5-5 4 4 3-3 6 6"],shield:["M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"],sparkles:["M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z","M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"],star:["M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3l-5.5 2.9 1-6.2L3 9.6l6.2-.9z"],video:["M3 6h12v12H3z","M15 10l6-3v10l-6-3z"],arrow_right:["M4 12h15","M13 6l6 6-6 6"],calendar:["M4 6h16v15H4z","M4 10h16","M8 3v5","M16 3v5"],close:["M6 6l12 12","M18 6L6 18"],lock:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 8 0v4"],play:["M7 4l13 8-13 8z"],quote:["M5 17c3 0 4-2 4-5V7H4v5h3","M15 17c3 0 4-2 4-5V7h-5v5h3"],trophy:["M7 4h10v5a5 5 0 0 1-10 0z","M7 6H4v2a3 3 0 0 0 3 3","M17 6h3v2a3 3 0 0 1-3 3","M12 14v4","M8 21h8","M9 18h6v3H9z"]};var vt="http://www.w3.org/2000/svg";function ze(o,t,n){let i=o.createElementNS(vt,"svg");i.setAttribute("viewBox","0 0 24 24"),i.setAttribute("width",String(n)),i.setAttribute("height",String(n)),i.setAttribute("fill","none"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","2"),i.setAttribute("stroke-linecap","round"),i.setAttribute("stroke-linejoin","round"),i.setAttribute("aria-hidden","true"),i.setAttribute("focusable","false");for(let c of t){let p=o.createElementNS(vt,"path");p.setAttribute("d",c),i.append(p)}return i}var g=(o,t=!1)=>({kind:"value",value:"plain",def:o,required:t}),J=o=>({kind:"value",value:"color",def:o}),xt=o=>({kind:"value",value:"spacing",def:o}),Qt=o=>({kind:"value",value:"radius",def:o}),ge=(o=!1)=>({kind:"text",required:o}),Xe=(o,t=!1)=>({kind:"list",item:o,required:t}),Ee=(o,t=!1)=>({kind:"object",item:o,required:t}),St=(o=!1)=>({kind:"component",required:o}),Ye={kind:"components"},Mt={stack:{axis:g("vertical"),spacing:xt(0),align:g("center"),distribution:g("start"),scroll:g(!1),children:Ye},text:{text:ge(),spans:Xe("span"),font:g(),size:g(),weight:g(),line_height:g(),letter_spacing:g(),color:{kind:"value",value:"textColor",def:"text"},align:g("center"),max_lines:g(),uppercase:g(!1)},image:{src:g(void 0,!0),fit:g("fit"),aspect:g(),mask:Ee("mask"),overlay:{kind:"value",value:"textColor"},alt:ge(),decorative:g(!1)},icon:{name:g(void 0,!0),color:J("accent"),size:g(24)},video:{src:g(void 0,!0),poster:g(),autoplay:g(!0),loop:g(!0),mute:g(!0),controls:g(!1),fit:g("fill"),aspect:g(),alt:ge()},button:{action:Ee("action",!0),content:St(!0)},purchase_button:{content:St(!0),package:g()},package:{product:g(void 0,!0),plan:g(void 0,!0),selected:g(!1),offer:g(),children:Ye},tabs:{},switch:{},carousel:{pages:Ye,peek:g(0),spacing:g(8),loop:g(!1),auto_advance_ms:g(),indicator:Ee("indicator"),height:g("")},countdown:{},timeline:{items:Xe("timeline_item",!0),line_color:J("accent"),line_width:g(2),icon_color:J("on_accent"),color:J("text"),spacing:g(16)},features:{items:Xe("feature",!0),icon_color:J("accent"),color:J("text"),spacing:g(12)},spacer:{size:xt()},divider:{color:J("muted"),thickness:g(1)},custom_html:{src:g(void 0,!0),height:g("",!0)}},en={style:{padding:{kind:"edges"},margin:{kind:"edges"},width:g(""),height:g(""),max_width:g(),background:{kind:"fill"},border:Ee("border"),corners:{kind:"corners"},shadow:Ee("shadow"),opacity:g(1)},border:{width:g(),color:J("")},shadow:{color:J(""),radius:g(0),x:g(0),y:g(0)},linear:{type:g(""),angle:g(180),stops:g()},radial:{type:g(""),center_x:g(.5),center_y:g(.5),radius:g(.5),stops:g()},image_fill:{type:g(""),src:g(),fit:g("fill")},video_fill:{type:g(""),src:g(),poster:g(),loop:g(!0)},animation:{type:g(""),duration_ms:g(300),delay_ms:g(0),easing:g("ease_out")},action:{type:g(""),url:g(),sheet:g(),package:g()},mask:{shape:g(""),radius:Qt(0),depth:g(16)},span:{text:ge(!0),bold:g(!1),italic:g(!1),underline:g(!1),strikethrough:g(!1),color:J(""),link:g()},timeline_item:{icon:g(void 0,!0),title:ge(!0),text:ge(),color:J("")},feature:{icon:g(void 0,!0),text:ge(!0)},indicator:{style:g("dots"),color:J("muted"),active_color:J("accent"),size:g(8),spacing:g(6)},typography:{font:g("system"),size:g(),weight:g(400),line_height:g(),letter_spacing:g(0),text_style:g("body")}},Et=new Set(["package","purchase_button"]),tn={action:{type:g(""),url:g(),link:g(),sheet:g(),placement:g(),name:g(),value:g(),offer:g(),dismiss:g(!0)},presentation:{type:g(""),position:g("bottom"),auto_dismiss_seconds:g(),dismissible:g(!0),backdrop:J("#00000080")}},nn={modal:["type","dismissible","backdrop"],fullscreen:["type"],banner:["type","position","auto_dismiss_seconds","dismissible"],card:["type"]},on={linear:"linear",radial:"radial",image:"image_fill",video:"video_fill"},sn=["top","bottom","leading","trailing"],rn=["top_leading","top_trailing","bottom_leading","bottom_trailing"],an=Object.keys(Mt),zn=an.filter(o=>!Et.has(o)),Rt=/\\{\\{\\s*([^{}]*?)\\s*\\}\\}/g,we=(o,t)=>typeof o=="object"&&o!==null&&Object.hasOwn(o,t),T=o=>typeof o=="object"&&o!==null&&!Array.isArray(o)?o:{},ie=o=>Array.isArray(o)?o:[],fe=(o,t)=>o??t;function ln(o){let t="";for(let n of new TextEncoder().encode(o)){let i=String.fromCharCode(n);t+=/^[A-Za-z0-9._~-]$/.test(i)?i:`%${n.toString(16).toUpperCase().padStart(2,"0")}`}return t}function cn(o){let t=Math.floor(o/86400),n=Math.floor(o%86400/3600),i=Math.floor(o%3600/60),c=o%60,p=b=>String(b).padStart(2,"0");return{countdown:t>0?`${t}d ${p(n)}:${p(i)}:${p(c)}`:n>0?`${n}:${p(i)}:${p(c)}`:`${p(i)}:${p(c)}`,days:String(t),hours:p(n),minutes:p(i),seconds:p(c)}}function dn(o){let t=new Map,n=c=>{if(Array.isArray(c))return c.forEach(n);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.offer=="string"){let m=`${p.product}.${p.plan}`;t.has(m)||t.set(m,p.offer)}for(let m of Object.keys(p).sort())n(p[m])},i=o;for(let c of["header","root","footer","sheets"])n(i[c]);return t}function Fe(o,t){return new je("paywall",o,t).resolve()}function At(o,t){let{variables:n,...i}=t;return new je("message",o,{...i,packages:{"":{...n}}}).resolve()}var je=class{kind;d;opts;lang;texts={};palette;typography={};radii;spacing;packages;offers;selected="";tab="";paths=new WeakMap;tabsShown={};switchesOn={};countdowns={};constructor(t,n,i){this.kind=t,this.d=n,this.opts=i,this.offers=dn(n);let c={};for(let[w,v]of Object.entries(i.packages??{})){let x={...v};this.open(w)||(v.price!==void 0?x.offer_price=v.price:delete x.offer_price),c[w]=x}this.packages=c;let p=T(this.d.locales),m=String(this.d.default_locale??""),b=i.locale;we(p,b)||(b=b.split("-")[0]??"",we(p,b)||(b=m)),this.lang=b;for(let w of[m,b])for(let[v,x]of Object.entries(T(p[w])))typeof x=="string"&&(this.texts[v]=x);let y=T(this.d.theme);this.palette=T(T(y.colors)[i.appearance]);for(let[w,v]of Object.entries(T(y.typography))){let x={};for(let[_,O]of Object.entries(this.objectFields("typography"))){let L=fe(T(v)[_],O.def);L!=null&&(x[_]=L)}this.typography[w]=x}this.radii=T(y.radii),this.spacing=T(y.spacing)}open(t){let n=this.offers.get(t);return n!==void 0&&(this.opts.offers??[]).includes(n)}fields(t){if(!(this.kind==="message"&&Et.has(t)))return Mt[t]}objectFields(t){return(this.kind==="message"?tn[t]:void 0)??en[t]??{}}resolve(){let[t,n]=this.initialState();this.tab=t,this.selected=this.kind==="paywall"?n:"";let i={theme:{colors:this.palette,typography:this.typography,radii:this.radii,spacing:this.spacing}};this.kind==="paywall"&&(i.selected=n);let c=this.d.presentation;if(typeof c=="object"&&c!==null){let m=this.item("presentation",T(c),void 0)??{},b=nn[String(T(c).type)]??[];for(let y of Object.keys(m))b.includes(y)||delete m[y];i.presentation=m}for(let m of["header","root","footer"]){let b=this.d[m];if(typeof b=="object"&&b!==null){let y=this.component(T(b),m,"",!1);y&&(i[m]=y)}}let p={};if(typeof this.d.sheets=="object"&&this.d.sheets!==null){let m={};for(let[b,y]of Object.entries(T(this.d.sheets))){let w=this.component(T(T(y).root),`sheets.${b}.root`,"",!1);w&&(m[b]=w);let v=this.text(T(y).title,this.packages[this.selected]);v!==null&&(p[b]=v)}i.sheets=m}return{tree:i,pathOf:m=>this.paths.get(m),tabs:this.tabsShown,switches:this.switchesOn,sheetTitles:p,countdowns:this.countdowns,language:this.lang}}switchOn(t,n){return this.opts.switches&&Object.hasOwn(this.opts.switches,n)?this.opts.switches[n]:this.opts.switch?this.opts.switch==="on":t.default===!0}tabShown(t,n){let c=ie(t.tabs).map(T).map(m=>String(m.id)),p=this.opts.tabs?.[n];return p!==void 0&&c.includes(p)?p:this.opts.tab?this.opts.tab:typeof t.default=="string"&&t.default!==""?t.default:c[0]??""}initialState(){let t="",n="",i="",c="",p=(b,y)=>{if(Array.isArray(b)){b.forEach((v,x)=>p(v,`${y}[${x}]`));return}if(typeof b!="object"||b===null)return;let w=b;switch(w.type){case"package":{let v=`${w.product}.${w.plan}`;i===""&&(i=v),w.selected===!0&&n===""&&(n=v);break}case"switch":{let v=this.switchOn(w,y),x=v?w.on_package:w.off_package;typeof x=="string"&&c===""&&(c=x),p(v?w.on:w.off,`${y}.${v?"on":"off"}`);return}case"tabs":{let v=this.tabShown(w,y);t===""&&(t=v),ie(w.tabs).forEach((x,_)=>{let O=T(x);O.id===v&&(typeof O.package=="string"&&c===""&&(c=O.package),p(O.content,`${y}.tabs[${_}].content`))});return}}for(let v of Object.keys(w).sort())v!=="sheets"&&p(w[v],y===""?v:`${y}.${v}`)};for(let b of["header","root","footer"])p(this.d[b],b);let m=this.opts.selected||c||n||i;return[t,m]}holds(t,n){let i=n||this.selected;for(let[c,p]of Object.entries(t))switch(c){case"selected_package":if(!ie(p).includes(this.selected))return!1;break;case"intro_eligible":if((this.opts.eligible??[]).includes(i)!==p)return!1;break;case"offer_open":if(this.open(i)!==p)return!1;break;case"platform":if(!ie(p).includes(this.opts.platform))return!1;break;case"locale":if(!ie(p).includes(this.opts.locale)&&!ie(p).includes(this.lang))return!1;break;case"appearance":if(p!==this.opts.appearance)return!1;break;case"tab":if(p!==this.tab)return!1;break}return!0}component(t,n,i,c){if(typeof t.visible=="object"&&t.visible!==null&&!this.holds(T(t.visible),i))return null;let p=String(t.type),m=i,b=c;p==="package"&&(m=`${t.product}.${t.plan}`,b=m===this.selected);let y={type:p};this.paths.set(y,n),we(t,"id")&&(y.id=t.id);let w={...T(t.style)};b&&Object.assign(w,T(T(t.states).selected)),Object.keys(w).length>0&&(y.style=this.style(w)),typeof t.animation=="object"&&t.animation!==null&&(y.animation=this.defaults(T(t.animation),this.objectFields("animation")));let v=this.packages[m||this.selected];switch(p){case"tabs":return this.tabs(t,y,n,m);case"switch":return this.switchOf(t,y,n,m,b);case"countdown":return this.countdown(t,y,n,m,b);case"purchase_button":{let x=typeof t.package=="string"?t.package:this.selected;y.package=x,this.open(x)&&(y.offer=this.offers.get(x));let _=this.component(T(t.content),`${n}.content`,x,b);return _?(y.content=_,y):null}case"package":y.product=t.product,y.plan=t.plan,y.selected=b,typeof t.offer=="string"&&(this.opts.offers??[]).includes(t.offer)&&(y.offer=t.offer)}for(let[x,_]of Object.entries(this.fields(p)??{})){if(p==="package"&&(x==="product"||x==="plan"||x==="selected"||x==="offer"))continue;let O=t[x],L=we(t,x);switch(_.kind){case"component":{if(!L)continue;let R=this.component(T(O),`${n}.${x}`,m,b);if(!R&&_.required)return null;R&&(y[x]=R);break}case"components":{let R=[];ie(O).forEach((j,N)=>{let Q=this.component(T(j),`${n}.${x}[${N}]`,m,b);Q&&R.push(Q)}),y[x]=R;break}case"text":{let R=this.text(O,v);if(R!==null)y[x]=R;else if(_.required||p==="text"&&x==="text"&&L)return null;break}case"list":{let R=[];for(let j of ie(O)){let N=this.item(_.item,T(j),v);N&&R.push(N)}if(p==="text"&&R.length===0&&L)return null;L&&(y[x]=R);break}case"object":{if(L){let R=this.object(T(O),_.item,v);if(R===null&&_.required)return null;y[x]=R}else x==="indicator"&&(y[x]=this.object({},_.item,v));break}case"value":{let R=this.value(fe(O,_.def),_);R!=null&&R!==""&&(y[x]=R);break}}}return p==="text"&&this.typeStyle(y),y}typeStyle(t){if(typeof t.size!="string"){t.size!==void 0&&t.size!==null&&(t.text_style="body");return}let n=this.typography[t.size];for(let i of["font","weight","line_height","letter_spacing","text_style"])!we(t,i)&&n?.[i]!==void 0&&n?.[i]!==null&&(t[i]=n[i]);t.size=n?.size??null}tabs(t,n,i,c){let p=this.tabShown(t,i);this.tabsShown[i]=p;let m=[];return ie(t.tabs).forEach((b,y)=>{let w=T(b),v=w.id===p,x=this.component(T(w.label),`${i}.tabs[${y}].label`,c,v);if(m.push({id:w.id,selected:v,label:x}),v){let _=this.component(T(w.content),`${i}.tabs[${y}].content`,c,!1);_&&(n.content=_)}}),n.tabs=m,typeof t.bar=="object"&&t.bar!==null&&(n.bar=this.style(T(t.bar))),n}switchOf(t,n,i,c,p){let m=this.switchOn(t,i);this.switchesOn[i]=m,n.on=m;let b=this.text(t.label,this.packages[c||this.selected]);b!==null&&(n.label=b),n.tint=this.color(String(fe(t.tint,"accent")));let y=m?"on":"off",w=this.component(T(t[y]),`${i}.${y}`,c,p);return w&&(n.content=w),n}countdown(t,n,i,c,p){let m=T(t.target),b=this.opts.now??Date.now(),y;if(typeof m.after_open_seconds=="number"?y=Math.trunc(m.after_open_seconds)-(this.opts.openedSecondsAgo??0):y=Math.trunc((Date.parse(String(m.at))-b)/1e3),y>0){n.state="counting",n.remaining_seconds=y,this.countdowns[i]=y;let w=this.packages,v={};for(let[_,O]of Object.entries(w))v[_]={...O,...cn(y)};this.packages=v;let x=this.component(T(t.counting),`${i}.counting`,c,p);return x&&(n.content=x),this.packages=w,n}if(n.state="ended",n.remaining_seconds=0,typeof t.ended=="object"&&t.ended!==null){let w=this.component(T(t.ended),`${i}.ended`,c,p);w&&(n.content=w)}return n}item(t,n,i){let c={};for(let[p,m]of Object.entries(this.objectFields(t))){let b=n[p];if(m.kind==="text"){let y=this.text(b,i);if(y!==null)c[p]=y;else if(m.required)return null}else{let y=m.def,w=this.value(fe(b,y),m);w!=null&&(we(n,p)||y!=null&&y!=="")&&(c[p]=w)}}return c}object(t,n,i){if(n==="style")return this.style(t);let c=this.item(n,t,i)??{};if(n==="action")for(let p of["url","link"]){if(typeof c[p]!="string")continue;let m=pn(c[p],i);if(m===null)return null;c[p]=m}return c}defaults(t,n){let i={};for(let[c,p]of Object.entries(n)){let m=fe(t[c],p.def);m!=null&&m!==""&&(i[c]=m)}return i}style(t){let n={};for(let[i,c]of Object.entries(t)){let p=this.objectFields("style")[i];if(!p){n[i]=c;continue}switch(p.kind){case"edges":n[i]=this.sides(c,sn,this.spacing);break;case"corners":n[i]=this.sides(c,rn,this.radii);break;case"fill":n[i]=this.fill(c);break;case"object":{let m=T(c),b={};for(let[y,w]of Object.entries(this.objectFields(p.item))){let v=fe(m[y],w.def);v!=null&&v!==""&&(b[y]=this.value(v,w))}n[i]=b;break}default:n[i]=c}}return n}sides(t,n,i){let c={};for(let p of n){let m=typeof t=="object"&&t!==null?fe(T(t)[p],0):t;c[p]=Ze(m,i)}return c}fill(t){if(typeof t=="string")return{type:"color",color:this.color(t)};let n=T(t),i=this.defaults(n,this.objectFields(on[String(n.type)]??""));return Array.isArray(n.stops)&&(i.stops=n.stops.map(c=>({color:this.color(String(T(c).color)),at:T(c).at}))),i}value(t,n){if(n.kind!=="value")return t;switch(n.value){case"color":return typeof t=="string"&&t!==""?this.color(t):t;case"textColor":return typeof t=="string"?this.color(t):t==null?t:this.fill(t);case"spacing":return Ze(t,this.spacing);case"radius":return Ze(t,this.radii);default:return t}}color(t){let n=Object.hasOwn(this.palette,t)?this.palette[t]:void 0;return typeof n=="string"?n:t}text(t,n){let i;if(typeof t=="string")i=t;else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let p=t.t;i=typeof p=="string"&&Object.hasOwn(this.texts,p)?this.texts[p]:""}else return null;let c=!1;return i=i.replace(Rt,(p,m)=>{let b=n&&Object.hasOwn(n,m)?n[m]:void 0;return typeof b!="string"||b===""?(c=!0,""):b}),c||i.trim()===""?null:i}};function pn(o,t){let n=!1,i=o.replace(Rt,(c,p)=>{let m=t&&Object.hasOwn(t,p)?t[p]:void 0;return typeof m!="string"||m===""?(n=!0,""):ln(m)});return n?null:i}function Ze(o,t){return typeof o=="string"?Object.hasOwn(t,o)?t[o]:null:o}var un={packages:"Choose a plan",close:"Close",restore:"Restore purchases",page:(o,t)=>`${o} of ${t}`},ke={system:\'-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif\',rounded:\'ui-rounded, "SF Pro Rounded", Nunito, "Varela Round", system-ui, -apple-system, sans-serif\',serif:\'ui-serif, "New York", "Iowan Old Style", Georgia, "Times New Roman", serif\',mono:\'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace\'},fn=1.35,Lt=20,gn=new Set(["button","purchase_button","package","text"]),hn=new Set(["ar","he","fa","ur","ps","yi","dv","ug","ku","sd"]),_t={ease_out:"cubic-bezier(0.16, 1, 0.3, 1)",ease_in_out:"cubic-bezier(0.65, 0, 0.35, 1)",spring:"cubic-bezier(0.34, 1.56, 0.64, 1)"},mn={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"},bn={start:"flex-start",center:"center",end:"flex-end",space_between:"space-between",space_around:"space-around",space_evenly:"space-evenly"},yn={stack:["children"],package:["children"],button:["content"],purchase_button:["content"],tabs:["tabs","content"],switch:["content"],carousel:["pages"],countdown:["content"]},wn={package:["selected"],purchase_button:["package"],switch:["on"],countdown:["state","remaining_seconds"]},kn=`\n:host{display:block;height:100%}\n.pw2{position:relative;box-sizing:border-box;display:flex;flex-direction:column;height:100%;overflow:hidden;font-family:${ke.system};font-size:1rem;line-height:1.3;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;text-rendering:optimizeLegibility}\n.pw2 *,.pw2 *::before,.pw2 *::after{box-sizing:border-box}\n.pw2-head,.pw2-foot{flex:none;display:flex;flex-direction:column;position:relative;z-index:1}\n.pw2-head[hidden],.pw2-foot[hidden]{display:none}\n.pw2-foot{max-height:30%;overflow-y:auto;scrollbar-width:none}\n.pw2-foot .pw-text{font-size:min(var(--pw-fs,1rem),var(--pw-fs-max,21.6px))}\n.pw2.pw2-large{overflow-y:auto;overscroll-behavior:contain;scrollbar-width:none}\n.pw2.pw2-large>.pw2-body{flex:1 0 auto;overflow:visible;min-height:auto}\n.pw2.pw2-large>.pw2-foot{position:sticky;bottom:0}\n.pw2:not(.pw2-fit){padding-left:env(safe-area-inset-left,0px);padding-right:env(safe-area-inset-right,0px)}\n.pw2:not(.pw2-fit)>.pw2-head,.pw2:not(.pw2-fit)>.pw2-body.pw2-top{padding-top:env(safe-area-inset-top,0px)}\n.pw2:not(.pw2-fit)>.pw2-foot,.pw2:not(.pw2-fit)>.pw2-body.pw2-bottom{padding-bottom:env(safe-area-inset-bottom,0px)}\n.pw2.pw2-fit{height:auto;flex:0 1 auto;min-height:0}\n.pw2-body{flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;display:flex;flex-direction:column;overscroll-behavior:contain;scrollbar-width:none}\n.pw2-body::-webkit-scrollbar{display:none}\n.pw2-body>.pw-c{flex:1 0 auto}\n/* A part as wide as its place \\u2014 narrower when it says how wide it is at most, then in the middle, as SwiftUI\'s stacks place it. */\n.pw2-head>.pw-c,.pw2-body>.pw-c,.pw2-foot>.pw-c{align-self:center;width:100%}\n.pw-c{position:relative;min-width:0}\n.pw-c[style*="--pw-bw"]{isolation:isolate}\n.pw-c[style*="--pw-bw"]::after{content:"";position:absolute;inset:0;border:var(--pw-bw) solid var(--pw-bc);border-radius:inherit;pointer-events:none;z-index:2}\n.pw-stack{display:flex;flex-direction:column}\n.pw-stack.h{flex-direction:row}\n.pw-stack.z{display:grid}\n.pw-stack.z>.pw-c{grid-area:1/1}\n.pw-stack.scroll{overflow-y:auto;scrollbar-width:none}\n.pw-stack.h.scroll{overflow-x:auto;overflow-y:hidden}\n.pw-stack.scroll>.pw-c{flex-shrink:0}\n.pw-text{margin:0;overflow-wrap:break-word;white-space:pre-line}\n/* A text beside others wraps between its words, never inside one: a price stays whole, what is beside it wraps. */\n.pw-stack.h>.pw-text{min-width:min-content}\n.pw-text a{color:inherit}\n.pw-clamp{display:-webkit-box;-webkit-box-orient:vertical;overflow:hidden}\n.pw-grad{-webkit-background-clip:text;background-clip:text;color:transparent!important;-webkit-text-fill-color:transparent}\n.pw-icon{display:inline-flex;flex:none}\n.pw-icon svg{display:block}\n.pw-img{overflow:hidden;flex:none}\n.pw-img img,.pw-img video{display:block;width:100%;height:100%}\n.pw-img.natural img{height:auto}\n.pw-overlay{position:absolute;inset:0;pointer-events:none}\n.pw-bgvideo{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;z-index:-1;pointer-events:none}\nbutton.pw-c{font:inherit;color:inherit;background:none;border:0;margin:0;padding:0;cursor:pointer;text-align:inherit;display:flex;flex-direction:column;align-items:stretch;justify-content:center;-webkit-tap-highlight-color:transparent;transition:opacity .15s ease,transform .15s ease}\nbutton.pw-c:active{transform:scale(.98)}\nbutton.pw-c:disabled{cursor:default;opacity:.5}\n.pw-pkg{cursor:pointer;display:flex;flex-direction:column;transition:background-color .2s ease,border-color .2s ease,box-shadow .2s ease}\n.pw-pkg[aria-disabled=true]{cursor:default;opacity:.55}\n:focus-visible{outline:2px solid currentColor;outline-offset:2px}\n.pw-features{list-style:none;margin:0;padding:0;display:flex;flex-direction:column}\n.pw-feature{display:flex;align-items:center;gap:12px;text-align:start}\n.pw-timeline{list-style:none;margin:0;padding:0;display:flex;flex-direction:column}\n.pw-step{display:grid;grid-template-columns:auto 1fr;column-gap:14px;position:relative;text-align:start}\n.pw-dot{width:32px;height:32px;border-radius:50%;display:grid;place-items:center;position:relative;z-index:1}\n.pw-line{position:absolute;left:calc(16px - var(--pw-line-w)/2);top:32px;width:var(--pw-line-w);bottom:calc(-1 * var(--pw-gap))}\n.pw-step:last-child .pw-line{display:none}\n.pw-step-title{font-weight:600}\n.pw-step-text{opacity:.72;font-size:.9375rem;margin-top:2px}\n.pw-tabs{display:flex;flex-direction:column;gap:12px}\n.pw-tablist{display:flex}\n.pw-tab{flex:1 1 0;min-width:0;font:inherit;color:inherit;background:none;border:0;margin:0;padding:0;cursor:pointer;display:flex}\n.pw-tab>.pw-c{flex:1 1 auto}\n.pw-switch{display:flex;flex-direction:column;gap:12px}\n.pw-switchcontent{display:flex;flex-direction:column}\n.pw-switchrow{display:flex;align-items:center;justify-content:space-between;gap:12px;text-align:start}\n.pw-toggle{flex:none;width:51px;height:31px;border-radius:999px;border:0;padding:2px;cursor:pointer;background:var(--pw-off);transition:background-color .2s ease}\n.pw-toggle[aria-checked=true]{background:var(--pw-tint)}\n.pw-toggle i{display:block;width:27px;height:27px;border-radius:50%;background:#fff;box-shadow:0 2px 4px #0003;transition:transform .2s ease}\n.pw-toggle[aria-checked=true] i{transform:translateX(20px)}\n.pw-carousel{display:flex;flex-direction:column;gap:12px;min-width:0}\n.pw-track{display:flex;overflow-x:auto;scroll-snap-type:x mandatory;scrollbar-width:none;scroll-behavior:smooth;padding-inline:var(--pw-peek);scroll-padding-inline:var(--pw-peek);gap:var(--pw-gap)}\n.pw-track::-webkit-scrollbar{display:none}\n.pw-track>.pw-c{flex:none;width:100%;scroll-snap-align:center}\n.pw-dots{display:flex;justify-content:center;gap:var(--pw-dot-gap)}\n.pw-dots button{border:0;padding:0;cursor:pointer;width:var(--pw-dot);height:var(--pw-dot);border-radius:999px;background:var(--pw-dot-c);transition:width .25s ease,background-color .25s ease}\n.pw-dots.bars button{width:calc(var(--pw-dot) * 3)}\n.pw-dots button[aria-current=true]{background:var(--pw-dot-on)}\n.pw-dots.dots button[aria-current=true]{width:calc(var(--pw-dot) * 2.5)}\n.pw-html{display:block;width:100%;border:0;pointer-events:none;background:transparent}\n.pw-spacer{flex:1 1 0}\n.pw-stack:not(.h):not(.z)>.greedy-h,.pw-pkg>.greedy-h,button.pw-c>.greedy-h{align-self:stretch}\n.pw-stack.h>.greedy-h{flex:1 1 0}\n.pw-stack.z>.greedy-h{justify-self:stretch}\n.pw-stack:not(.h):not(.z)>.greedy-v,.pw-pkg>.greedy-v{flex:1 1 auto}\n.pw-stack.h>.greedy-v,.pw-stack.z>.greedy-v{align-self:stretch}\n.pw-layer{position:absolute;inset:0;z-index:5;display:flex;flex-direction:column;justify-content:flex-end;background:#0007}\n.pw-sheet{max-height:92%;overflow-y:auto;border-radius:16px 16px 0 0;display:flex;flex-direction:column;outline:none;padding-bottom:env(safe-area-inset-bottom,0px)}\n.pw-sheet>.pw-c{flex:1 0 auto}\n.pw-grab{width:36px;height:5px;border-radius:3px;background:currentColor;opacity:.25;margin:8px auto 0;flex:none}\n[data-pw-highlight]{outline:2px solid #2E7CF6!important;outline-offset:-1px}\n[data-pw-hover]:not([data-pw-highlight]){outline:1px dashed #2E7CF6aa!important;outline-offset:-1px}\n.pw-editing button,.pw-editing .pw-pkg,.pw-editing a{cursor:default}\n@media (prefers-reduced-motion:reduce){.pw2 *{transition:none!important;scroll-behavior:auto!important}}\n`,Re=o=>{if(typeof o!="string"||o.length>2048)return!1;try{let t=new URL(o);return t.protocol==="https:"&&t.hostname!==""&&t.username===""&&t.password===""}catch{return!1}},vn=o=>{if(typeof o!="string"||o.length>2048||/[\\s\\u0000-\\u001f\\u007f]/.test(o))return!1;if(Re(o))return!0;let t=/^([a-z][a-z0-9+.-]{1,31}):(.+)$/.exec(o)?.[1];if(!t||xn.has(t))return!1;try{let n=new URL(o);return n.username===""&&n.password===""}catch{return!1}},xn=new Set(["https","http","javascript","data","file","vbscript","about","blob","content","intent"]),Sn=o=>`${String(o.product)}.${String(o.plan)}`,Ne=o=>{let[t,n]=o.split(".");return{product:t??"",plan:n??""}},C=o=>`${Number(o)||0}px`,Pt=o=>`${o/16}rem`,Mn=0;function $t(o,t,n){return En("paywall",o,t,n)}function En(o,t,n,i){let c=t.ownerDocument,p=c.defaultView,m=`pw${++Mn}`,b=c.createElement("div");b.setAttribute(o==="paywall"?"data-palbase-paywall":"data-palbase-message",""),b.style.display="block",b.style.height="100%";let y=b.attachShadow({mode:"open"});Rn(c,y,kn);let w=c.createElement("div");w.className="pw2";let v=c.createElement("div");v.className="pw2-head";let x=c.createElement("div");x.className="pw2-body";let _=c.createElement("div");_.className="pw2-foot";let O=c.createElement("div");w.append(v,x,_),y.append(w),t.replaceChildren(b);let L={...n},R={openedAt:Date.now(),...n.state},j,N=new Map,Q=new Map,te=!1,ve=null,he,me=!1,Ae=c.defaultView?.ResizeObserver,K=typeof Ae=="function"?new Ae(()=>{w.classList.toggle("pw2-large",u()>=Lt),h()}):null;K?.observe(w);let X=()=>h();c.fonts?.addEventListener?.("loadingdone",X);let xe=null,be=p?.matchMedia?.("(prefers-reduced-motion: reduce)"),ne=()=>L.reduceMotion??be?.matches??!1,B=()=>!!i.editor,ye={...un,...i.labels},de=()=>j.tree.selected??"";function Y(){let e=R.now??Date.now(),l={locale:L.locale,appearance:L.appearance,platform:L.platform??"web",tabs:R.tabs??{},switches:R.switches??{},openedSecondsAgo:Math.max(0,Math.floor((e-(R.openedAt??e))/1e3)),now:e};j=o==="paywall"?Fe(L.definition,{...l,packages:L.packages??{},eligible:L.eligible??[],offers:L.offers??[],...R.selected?{selected:R.selected}:{}}):At(L.definition,{...l,variables:L.variables??{}});let a=j.tree.theme.colors,s=j.tree.presentation?.type,r=o==="message"&&s!==void 0&&s!=="fullscreen";w.classList.toggle("pw2-fit",r),b.style.display=r?"flex":"block",b.style.flexDirection=r?"column":"",b.style.minHeight=r?"0":"",b.style.flex=r?"0 1 auto":"",b.style.height=r?"auto":"100%",w.style.background=r?"":a.background??"",w.style.color=a.text??"",w.classList.toggle("pw-editing",B()),w.classList.toggle("pw2-large",u()>=Lt),w.lang=j.language,w.dir=hn.has(j.language.split("-")[0]??"")?"rtl":"ltr",Q=new Map,M(v,j.tree.header,"vertical"),M(x,j.tree.root,"vertical"),M(_,j.tree.footer,"vertical"),v.hidden=!j.tree.header,_.hidden=!j.tree.footer,x.classList.toggle("pw2-top",!j.tree.header),x.classList.toggle("pw2-bottom",!j.tree.footer),Vt();for(let[d,f]of N)Q.has(d)||f.cleanup.forEach(S=>S());N=Q,ve&&rt(ve);for(let d of N.values())d.type==="custom_html"&&it(d.el);h(),clearTimeout(he),me||=b.isConnected,R.now===void 0&&Object.keys(j.countdowns).length>0&&(he=setTimeout(()=>{me&&!b.isConnected||Y()},1e3-Date.now()%1e3+5))}function u(){let e=c.documentElement,l=e&&p?parseFloat(p.getComputedStyle(e).fontSize):NaN;return Number.isFinite(l)?l:16}function h(){let e=[];for(let a of N.values()){if(a.type!=="text")continue;let s=a.el,r=s.dataset.pwFit??s.style.fontSize;if(!r||(s.style.fontSize=r,delete s.dataset.pwFit,!/^\\S+$/.test(s.textContent??"")))continue;let d=s.parentElement,f=d&&p?p.getComputedStyle(d):null,S=d&&f?d.clientWidth-parseFloat(f.paddingLeft||"0")-parseFloat(f.paddingRight||"0"):1/0,A=Math.min(s.clientWidth,S);e.push({e:s,base:r,k:A<=0||s.scrollWidth<=A+.5?1:Math.max(.6,A/s.scrollWidth)})}let l=a=>a.closest(".pw-stack.h");for(let a of e){let s=Math.min(a.k,...e.filter(r=>r!==a&&r.base===a.base&&l(r.e)&&l(r.e)===l(a.e)).map(r=>r.k));s>=1||(a.e.dataset.pwFit=a.base,a.e.style.fontSize=`calc(${a.base} * ${s.toFixed(3)})`)}}function M(e,l,a){let s=l?E(l,a,{inControl:!1,inSheet:!1,inFooter:e===_}):null;re(e,s?[s]:[])}function E(e,l,a){let s=j.pathOf(e)??"",r=P(e),d=N.get(s),f;if(d&&d.type===e.type&&d.key===r&&d.axis===l&&!Q.has(s))f=d;else{let A=D(e,s,l,a);if(!A)return null;f={el:A.el,type:e.type,key:r,styleKey:"",axis:l,slots:A.slots,cleanup:A.cleanup??[]},f.el.classList.add("pw-c"),f.el.dataset.pwPath=s,f.el.dataset.pwType=e.type,e.id&&(f.el.dataset.pwId=e.id),d&&d.cleanup.forEach(z=>z()),Ft(f.el,e)}let S=`${JSON.stringify(e.style??null)}|${l}`;return f.styleKey!==S&&(Qe(f.el,e,l),f.styleKey=S),Q.set(s,f),Ot(f,e),zt(f,e,a),f.el}function P(e){let l=new Set(["style",...yn[e.type]??[],...wn[e.type]??[]]),a={};for(let[s,r]of Object.entries(e))l.has(s)||(a[s]=r);return e.type==="tabs"&&(a.tabs=e.tabs.map(s=>s.id)),e.type==="carousel"&&(a.pages=e.pages.length),e.type==="stack"&&(a.greedy=e.children.some(s=>s.type==="spacer"&&typeof s.size!="number")),(e.type==="image"||e.type==="video"||e.type==="custom_html")&&(a.asset=$(e)),JSON.stringify(a)}function $(e){let l=Se(e.src);return l?(L.assets?.[l]?.url??L.assets?.[l]?.html?.length??"none").toString():""}function k(e,l){let a=c.createElement(e);return l&&(a.className=l),a}function D(e,l,a,s){let r=e;switch(e.type){case"stack":{let d=k("div",`pw-stack${r.axis==="horizontal"?" h":r.axis==="z"?" z":""}${r.scroll?" scroll":""}`);return r.axis!=="z"&&r.children.some(f=>f.type==="spacer"&&typeof f.size!="number")&&d.classList.add(r.axis==="horizontal"?"greedy-h":"greedy-v"),d.style.gap=C(r.spacing),r.axis==="z"?d.style.placeItems=r.align==="stretch"?"stretch":String(r.align??"center"):(d.style.alignItems=mn[String(r.align)]??"center",d.style.justifyContent=bn[String(r.distribution)]??"flex-start"),{el:d,slots:{children:d}}}case"text":return{el:q(r,s),slots:{}};case"icon":{let d=Oe[String(r.name)];if(!d)return null;let f=k("span","pw-icon");return f.style.color=String(r.color??""),f.append(ze(c,d,Number(r.size)||24)),f.setAttribute("aria-hidden","true"),{el:f,slots:{}}}case"image":return pe(r);case"video":return Le(r);case"features":{let d=k("ul","pw-features");d.style.gap=C(r.spacing);for(let f of r.items??[]){let S=k("li","pw-feature"),A=Oe[f.icon];if(A){let I=ze(c,A,22);I.style.color=String(r.icon_color),I.style.flex="none",S.append(I)}let z=k("span");z.textContent=f.text,z.style.color=String(r.color),S.append(z),d.append(S)}return{el:d,slots:{}}}case"timeline":{let d=k("ol","pw-timeline");d.style.gap=C(r.spacing),d.style.setProperty("--pw-gap",C(r.spacing)),d.style.setProperty("--pw-line-w",C(r.line_width));for(let f of r.items??[]){let S=k("li","pw-step"),A=k("span","pw-dot");A.style.background=f.color??String(r.line_color),A.style.color=String(r.icon_color);let z=Oe[f.icon];z&&A.append(ze(c,z,18)),A.setAttribute("aria-hidden","true");let I=k("span","pw-line");I.style.background=String(r.line_color),I.setAttribute("aria-hidden","true");let G=k("span");G.style.color=String(r.color);let ae=k("span","pw-step-title");if(ae.textContent=f.title,G.append(ae),f.text){let F=k("span","pw-step-text");F.style.display="block",F.textContent=f.text,G.append(F)}S.append(A,G,I),d.append(S)}return{el:d,slots:{}}}case"spacer":{let d=k("div","pw-spacer");return d.setAttribute("aria-hidden","true"),typeof r.size=="number"&&(d.style.flex="none",a==="horizontal"?d.style.width=C(r.size):d.style.height=C(r.size)),{el:d,slots:{}}}case"divider":{let d=k("div","pw-divider");return d.setAttribute("role","separator"),d.style.background=String(r.color),d.style.alignSelf="stretch",d.style.flex="none",a==="horizontal"?(d.setAttribute("aria-orientation","vertical"),d.style.width=C(r.thickness)):d.style.height=C(r.thickness),{el:d,slots:{}}}case"button":return Ie(r,s,l);case"purchase_button":{let d=k("button","pw-buy");return d.type="button",d.addEventListener("click",()=>{ot(d,()=>Bt(d.dataset.package??"",d.dataset.offer))}),{el:d,slots:{content:d}}}case"package":{let d=k("div","pw-pkg");return d.setAttribute("role","radio"),d.addEventListener("click",()=>qe(d)),d.addEventListener("keydown",f=>Nt(f,d)),{el:d,slots:{children:d}}}case"tabs":return Tt(r,l);case"switch":return Ct(r,l);case"carousel":return Ht(r);case"countdown":{let d=k("div","pw-countdown");return d.setAttribute("role","timer"),d.setAttribute("aria-live","off"),{el:d,slots:{content:d}}}case"custom_html":{let d=L.assets?.[Se(r.src)??""];if(!d?.html)return null;let f=k("iframe","pw-html");return f.setAttribute("sandbox","allow-scripts"),f.setAttribute("aria-hidden","true"),f.setAttribute("title",""),f.tabIndex=-1,f.srcdoc=d.html,typeof r.height=="number"?f.style.height=C(r.height):typeof r.height=="string"&&r.height.endsWith("%")?f.style.height=r.height:r.height==="fill"&&(f.style.flex="1 1 0"),f.addEventListener("load",()=>it(f)),{el:f,slots:{}}}default:return null}}function q(e,l){let a=String(e.text_style??"body"),s=l.inControl?"span":a==="large_title"?"h1":a==="title"||a==="title2"?"h2":a==="title3"?"h3":"p",r=k(s,"pw-text");l.inControl&&(r.style.display="block"),r.style.fontFamily=oe(e.font);let d=typeof e.size=="number"?e.size:16;if(l.inFooter?(r.style.setProperty("--pw-fs",Pt(d)),r.style.setProperty("--pw-fs-max",`${Number((d*fn).toFixed(2))}px`)):r.style.fontSize=Pt(d),typeof e.weight=="number"&&(r.style.fontWeight=String(e.weight)),typeof e.line_height=="number"&&(r.style.lineHeight=String(e.line_height)),typeof e.letter_spacing=="number"&&e.letter_spacing!==0&&(r.style.letterSpacing=C(e.letter_spacing)),r.style.textAlign=String(e.align??"center"),e.uppercase===!0&&(r.style.textTransform="uppercase"),typeof e.max_lines=="number"&&(r.classList.add("pw-clamp"),r.style.setProperty("-webkit-line-clamp",String(e.max_lines))),typeof e.color=="string"?r.style.color=e.color:e.color&&typeof e.color=="object"&&(r.classList.add("pw-grad"),r.style.backgroundImage=Ve(e.color)??""),Array.isArray(e.spans))for(let f of e.spans){let S=f.link==="terms"?L.links?.terms:f.link==="privacy"?L.links?.privacy:f.link,A=Re(S)&&!l.inControl,z=k(A?"a":"span");z.textContent=String(f.text),f.bold&&(z.style.fontWeight="700"),f.italic&&(z.style.fontStyle="italic");let I=[f.underline?"underline":"",f.strikethrough?"line-through":""].filter(Boolean).join(" ");I&&(z.style.textDecoration=I),typeof f.color=="string"&&f.color!==""&&(z.style.color=f.color),A&&Re(S)&&(z.href=S,z.target="_blank",z.rel="noopener noreferrer",z.addEventListener("click",G=>{B()||!i.onLink||(G.preventDefault(),i.onLink(S))})),r.append(z)}else r.textContent=String(e.text??"");return r}function oe(e){if(typeof e!="string")return ke.system;let l=Se(e);if(l){let a=L.assets?.[l]?.family;return a?`"${a}", ${ke.system}`:ke.system}return ke[e]??ke.system}function U(e){let l=Se(e);return l?L.assets?.[l]?.url||void 0:Re(e)?e:void 0}function pe(e){let l=k("div","pw-img");typeof e.aspect=="number"&&(l.style.aspectRatio=String(e.aspect));let a=U(e.src),s=e.mask;if(s?.shape==="circle")l.style.borderRadius="50%";else if(s?.shape==="rect"&&s.radius)l.style.borderRadius=C(s.radius);else if(s?.shape==="convex")l.style.setProperty("border-end-start-radius",`50% ${C(s.depth)}`),l.style.setProperty("border-end-end-radius",`50% ${C(s.depth)}`);else if(s?.shape==="concave"){let r=`radial-gradient(ellipse 50% ${C(s.depth)} at 50% 100%, transparent 98%, #000 100%)`;l.style.setProperty("-webkit-mask-image",r),l.style.setProperty("mask-image",r)}if(a){let r=k("img");r.src=a,r.decoding="async",r.style.objectFit=e.fit==="fill"?"cover":"contain",e.decorative===!0?(r.alt="",l.setAttribute("aria-hidden","true")):r.alt=String(e.alt??""),r.addEventListener("error",()=>r.style.visibility="hidden"),l.append(r)}if(e.overlay&&typeof e.overlay=="object"){let r=k("div","pw-overlay");r.style.backgroundImage=Ve(e.overlay)??"",l.append(r)}return{el:l,slots:{}}}function Le(e){let l=k("div","pw-img");typeof e.aspect=="number"&&(l.style.aspectRatio=String(e.aspect));let a=U(e.src);if(a){let s=k("video");s.src=a;let r=U(e.poster);r&&(s.poster=r),s.muted=e.mute!==!1,s.loop=e.loop!==!1,s.playsInline=!0,s.controls=e.controls===!0,s.preload="auto",s.style.objectFit=e.fit==="fit"?"contain":"cover",s.autoplay=e.autoplay!==!1&&!ne()&&!B(),typeof e.alt=="string"?s.setAttribute("aria-label",e.alt):s.setAttribute("aria-hidden","true"),l.append(s)}return{el:l,slots:{}}}function Ie(e,l,a){let s=e.action??{},r,d=s.type==="restore"||s.type==="offer_code"||s.type==="request_push"||s.type==="show_paywall"||s.type==="offer",f=o==="message"&&s.type!=="close"&&s.type!=="sheet"&&s.dismiss!==!1;switch(s.type){case"close":l.inSheet?r=()=>Te(null):i.onClose&&(r=()=>i.onClose());break;case"restore":i.onRestore&&(r=()=>i.onRestore());break;case"offer_code":i.onOfferCode&&(L.platform??"web")!=="web"&&(r=()=>i.onOfferCode());break;case"open_url":case"terms":case"privacy":{let A=s.type==="open_url"?s.url:s.type==="terms"?L.links?.terms:L.links?.privacy;Re(A)&&(r=()=>i.onLink?i.onLink(A):void p?.open(A,"_blank","noopener,noreferrer"));break}case"sheet":s.sheet&&(r=()=>Te(s.sheet));break;case"select_package":s.package&&(r=()=>Je(s.package));break;case"deep_link":{let A=s.link;vn(A)&&(r=()=>i.onDeepLink?i.onDeepLink(A):p?.location.assign(A));break}case"request_push":i.onRequestPush&&(r=()=>i.onRequestPush());break;case"show_paywall":s.placement&&i.onShowPaywall&&(r=()=>i.onShowPaywall(s.placement));break;case"custom":s.name&&i.onCustom&&(r=()=>i.onCustom(s.name,s.value));break;case"offer":s.offer&&i.onOffer&&(r=()=>i.onOffer(s.offer));break}if(!r&&!B())return null;let S=k("button");return S.type="button",s.type==="close"&&S.setAttribute("aria-label",ye.close),S.addEventListener("click",()=>{if(!r||B())return;o==="message"&&i.onAction?.(_e(s,a,e.id));let A=f?()=>i.onClose?.():void 0;d?ot(S,async()=>{await r(),A?.()}):(r(),A?.())}),{el:S,slots:{content:S}}}function _e(e,l,a){let s={type:e.type,dismiss:e.type==="sheet"?!1:e.type==="close"||e.dismiss!==!1,path:l};for(let r of["url","link","placement","name","value","sheet","offer"])typeof e[r]=="string"&&(s[r]=e[r]);return typeof a=="string"&&(s.id=a),s}function Tt(e,l){let a=k("div","pw-tabs"),s=k("div","pw-tablist");s.setAttribute("role","tablist");let r=k("div","pw-tabpanel");r.setAttribute("role","tabpanel"),r.id=`${m}-${l}-panel`;let d={content:r},f=e.tabs.map(S=>S.id);return f.forEach((S,A)=>{let z=k("button","pw-tab");z.type="button",z.setAttribute("role","tab"),z.id=`${m}-${l}-tab-${A}`,z.setAttribute("aria-controls",r.id),z.dataset.tab=S,z.addEventListener("click",()=>tt(l,S)),z.addEventListener("keydown",I=>{let G=I.key==="ArrowRight"?A+1:I.key==="ArrowLeft"?A-1:I.key==="Home"?0:I.key==="End"?f.length-1:-2;if(G===-2)return;I.preventDefault();let ae=f[(G+f.length)%f.length];tt(l,ae),s.querySelector(`[data-tab="${ae}"]`)?.focus()}),s.append(z),d[`label:${S}`]=z}),a.append(s,r),d.bar=s,{el:a,slots:d}}function Ct(e,l){let a=k("div","pw-switch"),s=k("div","pw-switchrow"),r=k("span","pw-switchlabel");r.id=`${m}-${l}-label`;let d=k("button","pw-toggle");d.type="button",d.setAttribute("role","switch"),d.setAttribute("aria-labelledby",r.id),d.append(k("i")),d.addEventListener("click",()=>It(l,d.getAttribute("aria-checked")!=="true")),s.append(r,d);let f=k("div","pw-switchcontent");return a.append(s,f),{el:a,slots:{content:f,label:r,toggle:d}}}function Ht(e){let l=k("div","pw-carousel");l.setAttribute("role","region"),l.setAttribute("aria-roledescription","carousel");let a=k("div","pw-track");a.tabIndex=0,a.style.setProperty("--pw-peek",C(e.peek)),a.style.setProperty("--pw-gap",C(e.spacing)),typeof e.height=="number"&&(a.style.minHeight=C(e.height));let s=e.indicator??{},r=k("div",`pw-dots ${s.style??"dots"}`);r.style.setProperty("--pw-dot",C(s.size??8)),r.style.setProperty("--pw-dot-gap",C(s.spacing??6)),r.style.setProperty("--pw-dot-c",s.color??"#8888"),r.style.setProperty("--pw-dot-on",s.active_color??"currentColor"),s.style==="none"&&(r.hidden=!0),l.append(a,r);let d=()=>[...a.children].filter(F=>F instanceof(p?.HTMLElement??HTMLElement)),f=()=>{let F=d(),W=a.scrollLeft+a.clientWidth/2,V=0;return F.forEach((ee,qt)=>{Math.abs(ee.offsetLeft+ee.offsetWidth/2-W)<Math.abs((F[V]?.offsetLeft??0)+(F[V]?.offsetWidth??0)/2-W)&&(V=qt)}),V},S=F=>{let W=d();if(W.length===0)return;let V=e.loop?(F+W.length)%W.length:Math.max(0,Math.min(W.length-1,F)),ee=W[V];a.scrollTo?.({left:ee.offsetLeft-(a.clientWidth-ee.offsetWidth)/2,behavior:ne()?"auto":"smooth"}),A(V)},A=F=>{[...r.children].forEach((W,V)=>W.setAttribute("aria-current",String(V===F)))};a.addEventListener("scroll",()=>A(f()),{passive:!0}),a.addEventListener("keydown",F=>{F.key!=="ArrowRight"&&F.key!=="ArrowLeft"||(F.preventDefault(),S(f()+(F.key==="ArrowRight"?1:-1)))});let z=!1,I=()=>z=!0,G=()=>z=!1;l.addEventListener("pointerenter",I),l.addEventListener("pointerleave",G),l.addEventListener("focusin",I),l.addEventListener("focusout",G);let ae=[];if(typeof e.auto_advance_ms=="number"){let F=setInterval(()=>{if(z||ne()||B())return;let W=d(),V=f();!e.loop&&V>=W.length-1||S(V+1)},e.auto_advance_ms);ae.push(()=>clearInterval(F))}return l.pwDots=F=>{r.children.length!==F&&(r.replaceChildren(...Array.from({length:F},(W,V)=>{let ee=k("button");return ee.type="button",ee.setAttribute("aria-label",ye.page(V+1,F)),ee.addEventListener("click",()=>S(V)),ee})),A(f()))},{el:l,slots:{pages:a},cleanup:ae}}function Ot(e,l){let a=l;switch(l.type){case"package":{let s=Sn(a),d=!!L.packages?.[s]?.price;e.el.dataset.package=s,e.el.setAttribute("aria-checked",String(a.selected===!0)),e.el.setAttribute("aria-disabled",String(!d));break}case"purchase_button":{let s=String(a.package);e.el.dataset.package=s,typeof a.offer=="string"?e.el.dataset.offer=a.offer:delete e.el.dataset.offer,e.el.disabled=te||!L.packages?.[s]?.price;break}case"switch":{let s=e.slots.toggle;s.setAttribute("aria-checked",String(a.on===!0)),s.style.setProperty("--pw-tint",String(a.tint??"")),s.style.setProperty("--pw-off",`color-mix(in srgb, ${j.tree.theme.colors.muted??"#888888"} 45%, transparent)`),e.slots.label.textContent=String(a.label??""),e.slots.label.hidden=a.label===void 0;break}case"tabs":{for(let s of a.tabs){let r=e.slots[`label:${s.id}`];r.setAttribute("aria-selected",String(s.selected)),r.tabIndex=s.selected?0:-1,s.selected&&e.slots.content.setAttribute("aria-labelledby",r.id)}a.bar&&Qe(e.slots.bar,{type:"stack",style:a.bar},"vertical");break}}}function zt(e,l,a){let s=l,r={...a,inControl:a.inControl||l.type==="button"||l.type==="purchase_button"||l.type==="package"};switch(l.type){case"stack":case"package":{let d=l.type==="stack"?String(s.axis??"vertical"):"vertical",f=s.children.map(A=>[A,E(A,d,r)]).filter(A=>A[1]!==null),S=f.map(A=>A[1]);re(e.slots.children,S),jt(d,f),l.type==="stack"&&Pe(e.el,S);break}case"button":case"purchase_button":{let d=s.content?E(s.content,"vertical",r):null;re(e.slots.content,d?[d]:[]);break}case"countdown":case"switch":{let d=s.content?E(s.content,"vertical",r):null;re(e.slots.content,d?[d]:[]),Pe(e.slots.content,d?[d]:[]);break}case"tabs":{for(let f of s.tabs){let S=f.label?E(f.label,"vertical",{...r,inControl:!0}):null;re(e.slots[`label:${f.id}`],S?[S]:[])}let d=s.content?E(s.content,"vertical",r):null;re(e.slots.content,d?[d]:[]),Pe(e.slots.content,d?[d]:[]);break}case"carousel":{let d=s.pages.map(f=>E(f,"page",r)).filter(Boolean);d.forEach((f,S)=>{f.setAttribute("role","group"),f.setAttribute("aria-roledescription","slide"),f.setAttribute("aria-label",ye.page(S+1,d.length))}),re(e.slots.pages,d),Pe(e.slots.pages,d),e.el.pwDots?.(d.length);break}}}function jt(e,l){let a=e==="horizontal"?"width":e==="vertical"?"height":null;if(!a)return;let s=f=>f?a==="width"?f.leading+f.trailing:f.top+f.bottom:0,r=l.filter(([f])=>f.style?.[a]==="fill"),d=Math.max(0,...r.map(([f])=>s(f.style?.padding)+s(f.style?.margin)));for(let[f,S]of r)S.style.flexBasis=C(d-s(f.style?.margin))}function Pe(e,l){let a=l.filter(r=>r.dataset.pwType==="package");if(a.length===0){e.getAttribute("role")==="radiogroup"&&e.removeAttribute("role");return}e.setAttribute("role","radiogroup"),e.setAttribute("aria-label",ye.packages);let s=a.find(r=>r.getAttribute("aria-checked")==="true")??a[0];for(let r of a)r.tabIndex=r===s?0:-1}function re(e,l){let a=()=>[...e.children].filter(r=>r.dataset?.pwPath!==void 0),s=a();for(let r of s)l.includes(r)||r.remove();s=a(),l.forEach((r,d)=>{s[d]!==r&&(e.insertBefore(r,s[d]??null),s=a())})}let Be=new WeakMap;function H(e,l,a){e.style.setProperty(l,a),Be.get(e).push(l)}function Qe(e,l,a){for(let f of Be.get(e)??[])e.style.removeProperty(f);Be.set(e,[]);for(let f of[...e.children])f.classList.contains("pw-bgvideo")&&f.remove();let s=l.style;if(l.type==="image"&&e.classList.toggle("natural",typeof l.aspect!="number"&&(s?.height===void 0||s.height==="fit")),!s)return;let r=(f,S)=>{S&&(H(e,`${f}-block-start`,C(S.top)),H(e,`${f}-block-end`,C(S.bottom)),H(e,`${f}-inline-start`,C(S.leading)),H(e,`${f}-inline-end`,C(S.trailing)))};r("padding",s.padding),r("margin",s.margin),et(e,"width",s.width,a),typeof s.height=="number"&&gn.has(l.type)?(H(e,"min-height",C(s.height)),a==="vertical"&&H(e,"flex","none")):et(e,"height",s.height,a),typeof s.max_width=="number"&&H(e,"max-width",C(s.max_width));let d=s.background;if(d){if(d.type==="color")H(e,"background-color",d.color);else if(d.type==="linear"||d.type==="radial")H(e,"background-image",Ve(d)??"");else if(d.type==="image"){let f=U(d.src);f&&(H(e,"background-image",`url("${f.replace(/"/g,"%22")}")`),H(e,"background-size",d.fit==="fit"?"contain":"cover"),H(e,"background-position","center"),H(e,"background-repeat","no-repeat"))}else if(d.type==="video"){let f=U(d.src);if(f){let S=k("video","pw-bgvideo");S.src=f;let A=U(d.poster);A&&(S.poster=A),S.muted=!0,S.loop=d.loop!==!1,S.playsInline=!0,S.autoplay=!ne()&&!B(),S.setAttribute("aria-hidden","true"),H(e,"isolation","isolate"),e.prepend(S)}}}if(s.border&&l.type==="custom_html"?H(e,"border",`${C(s.border.width)} solid ${s.border.color??"transparent"}`):s.border&&(H(e,"--pw-bw",C(s.border.width)),H(e,"--pw-bc",s.border.color??"transparent")),s.corners){let f=s.corners;H(e,"border-start-start-radius",C(f.top_leading)),H(e,"border-start-end-radius",C(f.top_trailing)),H(e,"border-end-start-radius",C(f.bottom_leading)),H(e,"border-end-end-radius",C(f.bottom_trailing)),(l.type==="image"||l.type==="video"||d?.type==="image"||d?.type==="video")&&H(e,"overflow","hidden")}s.shadow&&H(e,"box-shadow",`${C(s.shadow.x)} ${C(s.shadow.y)} ${C(s.shadow.radius)} ${s.shadow.color}`),typeof s.opacity=="number"&&s.opacity!==1&&H(e,"opacity",String(s.opacity))}function et(e,l,a,s){if(a==null||a==="")return;if(s==="page"){l==="height"&&H(e,"height",a==="fill"?"100%":typeof a=="number"?C(a):a==="fit"?"fit-content":String(a));return}let r=s==="horizontal"?"width":s==="vertical"?"height":null;a==="fill"?l===r?(H(e,"flex","1 1 0"),H(e,`min-${l}`,"0")):s==="z"?H(e,l,"100%"):(H(e,"align-self","stretch"),H(e,l,"auto")):a==="fit"?(l===r&&H(e,"flex","0 0 auto"),H(e,l,"fit-content")):(H(e,l,typeof a=="number"?C(a):String(a)),l===r&&H(e,"flex","none"))}function Ve(e){let l=a=>a.map(s=>`${s.color} ${(s.at*100).toFixed(2)}%`).join(", ");if(e.type==="linear")return`linear-gradient(${e.angle}deg, ${l(e.stops)})`;if(e.type==="radial"){let a=`${(e.radius*100).toFixed(2)}%`;return`radial-gradient(ellipse ${a} ${a} at ${(e.center_x*100).toFixed(2)}% ${(e.center_y*100).toFixed(2)}%, ${l(e.stops)})`}}function Ft(e,l){let a=l.animation;if(!a||L.animate===!1||ne()||typeof e.animate!="function")return;let s=24,d={fade:{opacity:0},slide_up:{opacity:0,transform:`translateY(${s}px)`},slide_down:{opacity:0,transform:`translateY(-${s}px)`},slide_leading:{opacity:0,transform:`translateX(-${s}px)`},slide_trailing:{opacity:0,transform:`translateX(${s}px)`},scale:{opacity:0,transform:"scale(0.92)"}}[a.type];d&&e.animate([d,{opacity:1,transform:"none"}],{duration:a.duration_ms,delay:a.delay_ms,easing:_t[a.easing]??_t.ease_out,fill:"backwards"})}function $e(){i.onState?.({...R}),Y()}function Je(e){R.selected===e&&de()===e||(R.selected=e,$e(),i.onSelect?.(Ne(e)))}function qe(e){B()||e.getAttribute("aria-disabled")==="true"||Je(e.dataset.package??"")}function Nt(e,l){if(e.key===" "||e.key==="Enter"){e.preventDefault(),qe(l);return}let a=e.key==="ArrowDown"||e.key==="ArrowRight"?1:e.key==="ArrowUp"||e.key==="ArrowLeft"?-1:0;if(a===0)return;e.preventDefault();let s=l.closest("[role=radiogroup]"),d=(s?[...s.children].filter(A=>A.dataset.pwType==="package"):[l]).filter(A=>A.getAttribute("aria-disabled")!=="true"),f=d.indexOf(l),S=d[(f+a+d.length)%d.length];S&&(qe(S),(N.get(S.dataset.pwPath??"")?.el??S).focus())}function tt(e,l){if(B())return;R.tabs={...R.tabs,[e]:l};let a=Dt(e,l);a&&(R.selected=a),$e()}function Dt(e,l){return nt(e)?.tabs?.find(s=>s.id===l)?.package}function It(e,l){if(B())return;R.switches={...R.switches,[e]:l};let a=nt(e),s=l?a?.on_package:a?.off_package;s&&(R.selected=s),$e()}function nt(e){let l=L.definition;for(let a of e.match(/[^.[\\]]+/g)??[])l=l?.[/^\\d+$/.test(a)?Number(a):a];return l}async function ot(e,l){if(!(B()||te)){te=!0,e.disabled=!0,e.setAttribute("aria-busy","true");try{await l()}finally{te=!1,e.removeAttribute("aria-busy"),e.disabled=!1;for(let a of N.values())a.type==="purchase_button"&&(a.el.disabled=!L.packages?.[a.el.dataset.package??""]?.price)}}}async function Bt(e,l){!L.packages?.[e]?.price||!i.onPurchase||await i.onPurchase(l!==void 0?{...Ne(e),offer:l}:Ne(e))}function Te(e){B()&&e!==null&&R.sheet===e||(e&&!R.sheet&&(xe=y.activeElement??null),R.sheet=e,$e(),e||xe?.focus())}function Vt(){let e=R.sheet,l=e?j.tree.sheets?.[e]:void 0;if(!l){O.remove();return}O.className="pw-layer";let a=O.firstElementChild;if(!a){a=k("div","pw-sheet"),a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true"),a.tabIndex=-1;let r=k("div","pw-grab");r.setAttribute("aria-hidden","true"),a.append(r),O.append(a),O.addEventListener("click",d=>{d.target===O&&!B()&&Te(null)}),a.addEventListener("keydown",d=>Jt(d,a))}a.style.background=j.tree.theme.colors.background??"",a.setAttribute("aria-label",j.sheetTitles[e]??"");let s=E(l,"vertical",{inControl:!1,inSheet:!0});re(a,s?[s]:[]),O.isConnected||(w.append(O),queueMicrotask(()=>(st(a)[0]??a).focus()))}function st(e){return[...e.querySelectorAll(\'button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])\')].filter(l=>!l.hidden)}function Jt(e,l){if(e.key==="Escape"){e.preventDefault(),Te(null);return}if(e.key!=="Tab")return;let a=st(l);if(a.length===0){e.preventDefault();return}let s=a[0],r=a[a.length-1],d=y.activeElement;e.shiftKey&&d===s?(e.preventDefault(),r.focus()):!e.shiftKey&&d===r&&(e.preventDefault(),s.focus())}function it(e){try{let l=o==="paywall"?{type:"palbase.paywall",package:de()}:{type:"palbase.message"};e.contentWindow?.postMessage({...l,locale:j.language,appearance:L.appearance},"*")}catch{}}function rt(e){for(let l of y.querySelectorAll("[data-pw-highlight]"))l.removeAttribute("data-pw-highlight");ve=e,e&&N.get(e)?.el.setAttribute("data-pw-highlight","")}let at=e=>e.composedPath().find(l=>l instanceof(p?.HTMLElement??HTMLElement)&&l.dataset.pwPath!==void 0);w.addEventListener("click",e=>{if(!i.editor)return;let l=at(e);l&&(e.preventDefault(),e.stopPropagation(),i.editor.onPick(l.dataset.pwPath))},!0),w.addEventListener("pointerover",e=>{if(i.editor){for(let l of y.querySelectorAll("[data-pw-hover]"))l.removeAttribute("data-pw-hover");at(e)?.setAttribute("data-pw-hover","")}}),w.addEventListener("pointerleave",()=>{for(let e of y.querySelectorAll("[data-pw-hover]"))e.removeAttribute("data-pw-hover")});let lt=()=>Y();return be?.addEventListener?.("change",lt),Y(),{get selected(){let e=de();return e?Ne(e):null},get state(){return{...R}},select(e){Je(e)},update(e){L={...L,...e},e.state&&Object.assign(R,e.state),Y()},highlight(e){rt(e)},replay(){for(let e of N.values())e.cleanup.forEach(l=>l());N=new Map;for(let e of[v,x,_])e.replaceChildren();Y()},destroy(){clearTimeout(he),K?.disconnect(),c.fonts?.removeEventListener?.("loadingdone",X),be?.removeEventListener?.("change",lt);for(let e of N.values())e.cleanup.forEach(l=>l());b.remove()}}}function Rn(o,t,n){let i=o.defaultView;try{if(i&&"adoptedStyleSheets"in t&&typeof i.CSSStyleSheet=="function"){let p=new i.CSSStyleSheet;p.replaceSync(n),t.adoptedStyleSheets=[p];return}}catch{}let c=o.createElement("style");c.textContent=n,t.append(c)}function An(o,t){let n=o;for(let i of t.split(".")){let c=/^([^[\\]]+)((?:\\[\\d+\\])*)$/.exec(i);if(!c||typeof n!="object"||n===null)return;n=n[c[1]];for(let p of c[2].matchAll(/\\[(\\d+)\\]/g))n=Array.isArray(n)?n[Number(p[1])]:void 0}return typeof n=="object"&&n!==null?n:void 0}var Ln=o=>Uint8Array.from(atob(o),t=>t.charCodeAt(0));async function _n(o){let t={};for(let n of o.assets){let i=Ln(n.data);if((n.kind==="image"||n.kind==="video")&&(t[n.id]={kind:n.kind,url:URL.createObjectURL(new Blob([i],{type:n.type}))}),n.kind==="font"){let c=new FontFace(Ue(n.id),i,{display:"block"});await c.load(),document.fonts.add(c),t[n.id]={kind:"font",url:"",family:Ue(n.id)}}if(n.kind==="html"){let c=pt(await dt(i));c!==void 0&&(t[n.id]={kind:"html",url:"",html:c})}}return t}function Pn(o,t){let n=o.catalog[t.platform]??{packages:{},eligible:[]},i=Fe(o.definition,{locale:o.locale,appearance:t.appearance,platform:t.platform,packages:n.packages,eligible:n.eligible}),c=o.state;return{...c.selected?{selected:c.selected}:{},...c.tab?{tabs:Object.fromEntries(Object.keys(i.tabs).map(p=>[p,c.tab]))}:{},...c.switch?{switches:Object.fromEntries(Object.keys(i.switches).map(p=>[p,c.switch==="on"]))}:{},...c.sheet?{sheet:c.sheet}:{}}}async function $n(o){let t=[...o.querySelectorAll("img, video")];await Promise.race([Promise.all(t.map(n=>n instanceof HTMLImageElement?n.complete?Promise.resolve():n.decode().catch(()=>{}):n.readyState>=2?Promise.resolve():new Promise(i=>{n.addEventListener("loadeddata",()=>i(),{once:!0}),n.addEventListener("error",()=>i(),{once:!0})}))),new Promise(n=>setTimeout(n,5e3))])}var De=()=>new Promise(o=>requestAnimationFrame(()=>o(void 0)));async function Tn(){let o=window.PALBASE_PREVIEW,t=o.shots[Number(new URLSearchParams(location.search).get("shot")??"0")]??o.shots[0];document.documentElement.style.fontSize=`${t.fontSize}px`,document.documentElement.style.colorScheme=t.appearance;let n=document.getElementById("screen");Object.assign(n.style,{width:`${t.width}px`,height:`${t.height}px`,paddingTop:`${t.top}px`,paddingBottom:`${t.bottom}px`});let i=document.getElementById("paywall"),c=o.catalog[t.platform]??{packages:{},eligible:[]},p=$t(i,{definition:o.definition,locale:o.locale,appearance:t.appearance,platform:t.platform,packages:c.packages,eligible:c.eligible,links:o.links,assets:await _n(o),state:Pn(o,t),animate:!1,reduceMotion:!0},{onPurchase:()=>{},onRestore:()=>{},onClose:()=>{},onLink:()=>{},onOfferCode:()=>{}}),m=i.querySelector("[data-palbase-paywall]")?.shadowRoot;if(!m)throw new Error("the renderer drew nothing");let b=getComputedStyle(m.querySelector(".pw2")).backgroundColor;n.style.background=b==="rgba(0, 0, 0, 0)"||b==="transparent"?t.appearance==="dark"?"#000":"#fff":b,await document.fonts.ready,await $n(m),await De(),await De(),document.body.dataset.selected=p.selected?`${p.selected.product}.${p.selected.plan}`:"",o.check&&(document.body.dataset.findings=JSON.stringify(kt(m,{platform:t.platform,width:t.width,height:t.height,nodeAt:y=>An(o.definition,y)}))),window.PALBASE_FULL=async()=>{let y=Math.max(...[".pw2-body",".pw2"].map(v=>m.querySelector(v)).map(v=>v.scrollHeight-v.clientHeight)),w=Math.max(t.height,Math.ceil(n.offsetHeight+y));return n.style.height=`${w}px`,await De(),await De(),w}}Tn().then(()=>{document.body.dataset.ready="1"},o=>{document.body.dataset.error=o instanceof Error?o.message:String(o),document.body.dataset.ready="1"});})();\n')}function Zl(e){let t=/^P(\d+)([DWMY])$/.exec(e??"");if(!t)return null;let n=Number(t[1]);if(!Number.isSafeInteger(n)||n<1)return null;switch(t[2]){case"D":return{count:n,unit:"day",months:n*12/365};case"W":return{count:n,unit:"week",months:n*12/52};case"M":return{count:n,unit:"month",months:n};default:return{count:n,unit:"year",months:n*12}}}function Ny(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function Ql(e,t,n){let s=e/10**Ny(t);try{return new Intl.NumberFormat(n,{style:"currency",currency:t}).format(s)}catch{return`${s.toFixed(Ny(t))} ${t}`}}function QC(e,t){try{let n=new Intl.NumberFormat(t,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?n.format(e.count):n.formatToParts(1).filter(a=>a.type==="unit").map(a=>a.value).join("").trim()||n.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var e2={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function t2(e,t){let n;try{n=new Intl.NumberFormat(t,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{n=`${e.count} ${e.unit}${e.count>1?"s":""}`}let s=e2[t.split("-")[0].toLowerCase()];return s?s(n):n}function n2(e,t){try{return new Intl.NumberFormat(t,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function qy(e,t){let n=new Map,s=new Map;for(let i of e){let r=Zl(i.period);if(!r)continue;let o=i.price.amount/r.months;n.set(i.key,o),s.set(i.price.currency,Math.max(s.get(i.price.currency)??0,o))}let a={};for(let i of e){let r={product_name:i.productName,price:Ql(i.price.amount,i.price.currency,t)},o=Zl(i.period);if(o){r.period=QC(o,t),r.price_per_month=Ql(Math.round(n.get(i.key)),i.price.currency,t);let d=s.get(i.price.currency)??0,p=d>0?Math.floor((1-n.get(i.key)/d)*100)/100:0;p>=.01&&(r.savings=n2(p,t))}let l=i.intro?.mode==="free_trial"?Zl(i.intro.duration):null;l&&(r.trial=t2(l,t)),i.offer&&(r.offer_price=Ql(Math.floor((i.price.amount*(100-i.offer.percentOff)+50)/100),i.price.currency,t)),a[i.key]=r}return a}var M=(e,t=!1)=>({kind:"value",value:"plain",def:e,required:t}),tt=e=>({kind:"value",value:"color",def:e}),Ky=e=>({kind:"value",value:"spacing",def:e}),s2=e=>({kind:"value",value:"radius",def:e}),ns=(e=!1)=>({kind:"text",required:e}),ed=(e,t=!1)=>({kind:"list",item:e,required:t}),Na=(e,t=!1)=>({kind:"object",item:e,required:t}),Gy=(e=!1)=>({kind:"component",required:e}),td={kind:"components"},a2={stack:{axis:M("vertical"),spacing:Ky(0),align:M("center"),distribution:M("start"),scroll:M(!1),children:td},text:{text:ns(),spans:ed("span"),font:M(),size:M(),weight:M(),line_height:M(),letter_spacing:M(),color:{kind:"value",value:"textColor",def:"text"},align:M("center"),max_lines:M(),uppercase:M(!1)},image:{src:M(void 0,!0),fit:M("fit"),aspect:M(),mask:Na("mask"),overlay:{kind:"value",value:"textColor"},alt:ns(),decorative:M(!1)},icon:{name:M(void 0,!0),color:tt("accent"),size:M(24)},video:{src:M(void 0,!0),poster:M(),autoplay:M(!0),loop:M(!0),mute:M(!0),controls:M(!1),fit:M("fill"),aspect:M(),alt:ns()},button:{action:Na("action",!0),content:Gy(!0)},purchase_button:{content:Gy(!0),package:M()},package:{product:M(void 0,!0),plan:M(void 0,!0),selected:M(!1),offer:M(),children:td},tabs:{},switch:{},carousel:{pages:td,peek:M(0),spacing:M(8),loop:M(!1),auto_advance_ms:M(),indicator:Na("indicator"),height:M("")},countdown:{},timeline:{items:ed("timeline_item",!0),line_color:tt("accent"),line_width:M(2),icon_color:tt("on_accent"),color:tt("text"),spacing:M(16)},features:{items:ed("feature",!0),icon_color:tt("accent"),color:tt("text"),spacing:M(12)},spacer:{size:Ky()},divider:{color:tt("muted"),thickness:M(1)},custom_html:{src:M(void 0,!0),height:M("",!0)}},hU={style:{padding:{kind:"edges"},margin:{kind:"edges"},width:M(""),height:M(""),max_width:M(),background:{kind:"fill"},border:Na("border"),corners:{kind:"corners"},shadow:Na("shadow"),opacity:M(1)},border:{width:M(),color:tt("")},shadow:{color:tt(""),radius:M(0),x:M(0),y:M(0)},linear:{type:M(""),angle:M(180),stops:M()},radial:{type:M(""),center_x:M(.5),center_y:M(.5),radius:M(.5),stops:M()},image_fill:{type:M(""),src:M(),fit:M("fill")},video_fill:{type:M(""),src:M(),poster:M(),loop:M(!0)},animation:{type:M(""),duration_ms:M(300),delay_ms:M(0),easing:M("ease_out")},action:{type:M(""),url:M(),sheet:M(),package:M()},mask:{shape:M(""),radius:s2(0),depth:M(16)},span:{text:ns(!0),bold:M(!1),italic:M(!1),underline:M(!1),strikethrough:M(!1),color:tt(""),link:M()},timeline_item:{icon:M(void 0,!0),title:ns(!0),text:ns(),color:tt("")},feature:{icon:M(void 0,!0),text:ns(!0)},indicator:{style:M("dots"),color:tt("muted"),active_color:tt("accent"),size:M(8),spacing:M(6)},typography:{font:M("system"),size:M(),weight:M(400),line_height:M(),letter_spacing:M(0),text_style:M("body")}},i2=new Set(["package","purchase_button"]),mU={action:{type:M(""),url:M(),link:M(),sheet:M(),placement:M(),name:M(),value:M(),offer:M(),dismiss:M(!0)},presentation:{type:M(""),position:M("bottom"),auto_dismiss_seconds:M(),dismissible:M(!0),backdrop:tt("#00000080")}};var r2=Object.keys(a2),gU=r2.filter(e=>!i2.has(e));var nd=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{};function qa(e){let t=[],n=a=>{if(Array.isArray(a))return a.forEach(n);if(typeof a!="object"||a===null)return;let i=a;if(i.type==="package"&&typeof i.product=="string"&&typeof i.plan=="string"){let r=`${i.product}.${i.plan}`;t.includes(r)||t.push(r)}for(let r of Object.keys(i).sort())n(i[r])},s=e;for(let a of["header","root","footer"])n(s[a]);for(let a of Object.keys(nd(s.sheets)).sort())n(nd(nd(s.sheets)[a]).root);return t}var Uy=["ios","android","web"],By=["light","dark"],u2={default:16,largest:24},c2={ios:{width:393,height:852,top:54,bottom:34},android:{width:412,height:915,top:40,bottom:24},web:{width:1024,height:720,top:0,bottom:0}},ad=2,h2={terms:"https://example.com/terms",privacy:"https://example.com/privacy"};function sd(e,t,n,s){let a=e.flags[t];if(a===void 0)return s;if(!n.includes(a))throw m(`--${t} is one of ${n.join(", ")}`);return a}function zy(e,t){let n=e.flags[t];if(n===void 0)return;let s=Number(n);if(!Number.isInteger(s)||s<200||s>4e3)throw m(`--${t} is a whole number of CSS pixels, 200 to 4000`);return s}function m2(e){let t={};for(let n of e??[]){let s=n.indexOf("="),[a,i]=s<0?[n,""]:[n.slice(0,s),n.slice(s+1)];if(a==="tab"&&i!=="")t.tab=i;else if(a==="sheet"&&i!=="")t.sheet=i;else if(a==="switch"&&(i==="on"||i==="off"))t.switch=i;else throw m(`--state ${n}: it names tab=<id>, switch=on|off or sheet=<id>`)}return t}function g2(e,t){if(e)return e[t]?.name??e[t.split("-")[0]]?.name??Object.values(e).find(n=>n.name)?.name}function f2(e){let t=e.split(".").slice(1).join(".").toLowerCase(),[n,s]=/year|annual|12m/.test(t)?["P1Y",5999]:/week/.test(t)?["P1W",499]:/life|forever|once|onetime|one_time/.test(t)?[void 0,14999]:["P1M",999];return{key:e,productName:e.split(".")[0],price:{amount:s,currency:"USD"},...n?{period:n}:{}}}function y2(e,t,n,s){let a=[],i=[];for(let o of n){let[l,d]=o.split("."),p=e?.products.find(y=>y.key===l),u=p?.channels[t],g=u?.plans.find(y=>y.key===d);if(!p||!u||!g){a.push(f2(o)),i.push(o);continue}a.push({key:o,productName:g2(u.locales,s)??p.key,price:{amount:g.price.amount,currency:g.price.currency},period:g.period,intro:g.intro})}let r=a.filter(o=>o.intro?.mode==="free_trial").map(o=>o.key);return{packages:qy(a,s),eligible:r,sampled:i}}function b2(e){return[...new Set([...JSON.stringify(e).matchAll(/asset:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/g)].map(t=>t[1]))]}async function w2(e,t,n){if(n.length===0)return{assets:[],left:[]};let s=await Us(e,t),a=st(e.cloud,t.env_ref),i=[],r=[];for(let o of n){let l=s.find(d=>d.id===o);if(!l){r.push(`asset:${o} is not one of the project's assets`);continue}try{let d;try{d=new URL(l.url)}catch{throw new Error("its address is not one")}if(d.origin!==a)throw new Error(`its address is not the environment's (${a}) \u2014 ${d.protocol==="https:"||d.protocol==="http:"?d.host:d.protocol}: the CLI does not ask another host`);let p=await e.io.fetch(d.href,{credentials:"omit",redirect:"manual"});if(!p.ok)throw new Error(`its address answered ${p.status}`);let u=Buffer.from(await p.arrayBuffer());if(o2("sha256").update(u).digest("hex")!==l.sha256.toLowerCase())throw new Error("its bytes are not the ones registered");i.push({id:o,kind:l.kind,type:l.content_type,data:u.toString("base64")})}catch(d){r.push(`${l.ref} could not be had: ${d instanceof Error?d.message:String(d)}`)}}return{assets:i,left:r}}function v2(e,t,n){let s=JSON.stringify(n).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");return`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${t.replace(/[&<>"]/g,i=>`&#${i.charCodeAt(0)};`)} \u2014 paywall preview</title>
|
|
@@ -691,13 +691,13 @@ ${t}}`}var tn=e=>["",e.toUpperCase(),"-".repeat(e.length)],AT=[{title:"One packa
|
|
|
691
691
|
`),e.out.result({file:s,revision:n.revision},()=>{e.out.line(`Wrote revision ${n.revision} of the catalog to ${s}.`),e.out.line(`Save an edit of it: palbase purchases:catalog:put --file ${s} --revision ${n.revision}`)});return}e.out.result(n,()=>Mb(e,n))}},mO={name:"purchases:catalog:put",summary:"save a new revision of the whole catalog, on the revision it was edited from; nothing is written to a store",usage:"--file <catalog.json> --revision <n>",details:["The module checks it first: a catalog that breaks a rule is refused with every problem, and nothing is saved.","Of two people editing at once, the second is told \u2014 the catalog moved past the revision they edited \u2014 never overwritten.","The stores are brought to it by a plan: palbase purchases:catalog:plan."],flags:{file:{type:"string",value:"catalog.json",description:"the catalog, as catalog:get --out wrote it ('-' or none: stdin)"},revision:{type:"string",value:"n",description:"the revision it was edited from (0 for the first), as catalog:get printed it"}},scope:"environment",async run(e){let t=await b(e),n=se(e.flags.revision,"revision");if(n===void 0)throw m("--revision is the revision the catalog was edited from (0 for the first): of two edits at once, the second is told, not saved over the first");let s=await jb(e);await v(e,t,`save the catalog (${s.products?.length??0} products) over revision ${n}`);let a;try{a=await h(e,t,"PUT","/purchases/catalog",s,{"if-match":Cb(n),...j()})}catch(i){if(i instanceof E&&i.status===412)throw new f("catalog_changed",`the catalog is no longer at revision ${n}: someone saved a newer one since it was read \u2014 nothing was saved`,{hint:"read it again (palbase purchases:catalog:get --out <file>), make the edit on it, and save it with that revision"});gd(e,i,"the catalog was not saved")}e.out.result(a,()=>{e.out.line(`Saved revision ${a.revision} of the catalog.`),e.out.line("Bring the stores to it: palbase purchases:catalog:plan")})}},gO={name:"purchases:catalog:validate",summary:"check a catalog without saving it: every problem, with its path and the store whose rule it breaks",usage:"--file <catalog.json>",flags:{file:{type:"string",value:"catalog.json",description:"the catalog ('-' or none: stdin)"}},scope:"environment",async run(e){let t=await b(e),n=await jb(e),s;try{s=await h(e,t,"POST","/purchases/catalog/validate",n,j())}catch(a){gd(e,a,"the catalog cannot be read")}if(e.out.result(s,()=>{s.problems.length>0&&Ob(e,s.problems),e.out.line(s.valid?`The catalog can be saved${s.problems.length>0?`, with ${s.problems.length} warning(s)`:""}.`:"The catalog cannot be saved as it is.")}),!s.valid)throw new f("invalid_catalog",`the catalog breaks ${s.problems.filter(a=>!a.warning).length} rule(s)`)}};function ud(e,t,n){e.out.line(`${t}${n.store_env?` (${n.store_env})`:""}: ${n.steps.length===0?"nothing to write":`${n.steps.length} step(s)`}`);for(let s of n.steps)e.out.line(` ${s.op} ${s.product}${s.plan?`/${s.plan}`:""}${s.store_id?` (${s.store_id})`:""}${s.irreversible?" \u2014 permanent":""}${s.note?`: ${s.note}`:""}`);n.note&&e.out.line(` ${n.note}`)}function fd(e){let t=ce(e,0,"the plan's id");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw m(`${t} is no plan's id: it is the id purchases:catalog:plan printed`);return t}function Ib(e){return e.apple_result!=null&&!e.apple_result.ok||e.google_result!=null&&!e.google_result.pending&&!e.google_result.ok}function fO(e,t){if(e.out.line(`Plan ${t.id} for revision ${t.revision}: ${t.status}`),t.stripe?ud(e,qr.stripe,t.stripe):e.out.line(`${qr.stripe}: no account connected (palbase purchases:stripe:grant connects one)`),ud(e,qr.apple,t.apple),ud(e,qr.google,t.google),t.problems.length>0){e.out.line("Warnings of the revision:");for(let i of t.problems)e.out.line(` ${i.path}: ${i.message}${i.channel?` (${i.channel})`:""}`)}t.status==="failed"&&t.error&&e.out.line(Ib(t)||!t.stripe?`It failed: ${t.error}`:`Stripe answered: ${t.error}`);let n=t.apple_result;if(!n&&t.apple.steps.length>0&&(t.status==="applying"||t.status==="applied")&&e.out.line("App Store Connect: waiting for the stores module"),n){e.out.line(`App Store Connect (${n.bundle_id}): ${n.ok?"written":`not all written${n.error?`: ${n.error}`:""}`}`);for(let i of n.steps){let r=i.price?`, ${i.price.customer_price} ${i.price.currency}`:"",o=i.next_price?`, ${i.next_price.customer_price} ${i.next_price.currency} from ${i.next_price.from}`:"";e.out.line(` ${i.op} ${i.store_id}${i.state?`: ${i.state}`:""}${r}${o}${i.error?` \u2014 ${i.error}`:""}`)}}let s=t.google_result;if(s){e.out.line(`Google Play (${s.package_name}): ${s.pending?"waiting for the stores module":s.ok?"written":`not all written${s.error?`: ${s.error}`:""}`}`);for(let i of s.steps)e.out.line(` ${i.op} ${i.store_id}${i.state?`: ${i.state}`:""}${i.error?` \u2014 ${i.error}`:""}`)}let a=t.stripe?t.stripe.hash:t.apple.hash||t.google.hash;t.status==="planned"&&a&&(e.out.line(` hash: ${a}`),e.out.line(t.stripe?`The Stripe part is written only when confirmed${t.apple.steps.length>0?" (the App Store part goes with it, to the stores module)":""}:`:t.apple.hash?"The App Store part is written only when confirmed (the stores module writes it to App Store Connect):":"The Google Play part is written only when confirmed (the stores module writes it to Google Play):"),e.out.line(` palbase purchases:catalog:confirm ${t.id} --hash ${a}`))}var yO={name:"purchases:catalog:plan",summary:"plan bringing the stores to the catalog's newest revision, store by store, before anything is written",usage:"[<plan id>]",details:["A plan is confirmed with its Stripe part's hash (purchases:catalog:confirm) \u2014 with no Stripe account connected, its App Store part's; the App Store and Google Play parts are written by the stores module once their accounts are connected.","With a plan's id it makes none: it shows that plan, and once confirmed what each store answered \u2014 the state of every product written, and a price that changes on a later day."],args:{min:0,max:1},scope:"environment",async run(e){let t=await b(e),n=e.args.length===0?await h(e,t,"POST","/purchases/catalog/plans",void 0,j()):await h(e,t,"GET",`/purchases/catalog/plans/${k(fd(e))}`);e.out.result(n,()=>fO(e,n))}},bO={name:"purchases:catalog:confirm",summary:"write a plan \u2014 its Stripe part now, its App Store part through the stores module: it names the hash of the plan that was shown, and is asked about first",usage:"<plan id> --hash <hash>",details:["What it writes is shown, then asked about \u2014 in every environment: a price written to Stripe is never changed or removed there, a product made in App Store Connect never goes away. -y confirms without asking."],args:{min:1,max:1},flags:{hash:{type:"string",value:"hash",description:"the hash the plan printed (its Stripe part's; with no Stripe account, its App Store part's)"}},scope:"environment",async run(e){let t=await b(e),n=fd(e),s=e.flags.hash;if(s===void 0||s.trim()==="")throw m("--hash is the hash purchases:catalog:plan printed: a confirmation names the plan it saw");let a=await h(e,t,"GET",`/purchases/catalog/plans/${k(n)}`);if(a.status!=="planned")throw new f("plan_not_open",`the plan ${n} is ${a.status}: only a planned one is confirmed`,{hint:"make a new one: palbase purchases:catalog:plan"});let i=a.apple.steps.length,r=a.google.steps.length,o=[i>0?`${i} to App Store Connect`:"",r>0?`${r} to Google Play`:""].filter(Boolean);if(a.stripe)await v(e,t,`write ${a.stripe.steps.length} step(s) of revision ${a.revision} to Stripe${o.length>0?`, and ${o.join(" and ")}`:""}`,"It writes the project's Stripe account, where a price is never changed or removed");else if(a.apple.hash&&i>0)await v(e,t,`write ${i} step(s) of revision ${a.revision} to App Store Connect${r>0?`, and ${r} to Google Play`:""}`,"It makes the products in App Store Connect, where a product id never goes away");else if(a.google.hash&&r>0)await v(e,t,`write ${r} step(s) of revision ${a.revision} to Google Play`,"It makes the products in Google Play, where a product id never goes away");else throw new f("no_stripe_part",`the plan ${n} has no Stripe part (no Stripe account was connected when it was made), and nothing for App Store Connect or Google Play to confirm`);let l=await h(e,t,"POST",`/purchases/catalog/plans/${k(n)}/confirm`,{hash:s},j());if(e.out.result(l,()=>{e.out.line(`Plan ${l.id}: ${l.status}${l.applied_at?` (${L(l.applied_at)})`:""}.`),l.status==="failed"&&l.error&&e.out.line(Ib(l)||!l.stripe?`It failed: ${l.error}`:`Stripe answered: ${l.error}`);let d=[i>0&&!l.apple_result?"App Store Connect":"",r>0&&(!l.google_result||l.google_result.pending)?"Google Play":""].filter(Boolean);d.length>0&&e.out.line(`The stores module is writing to ${d.join(" and ")}: palbase purchases:catalog:plan ${l.id} shows what it wrote.`)}),l.status==="failed")throw new f("plan_failed",`the plan ${l.id} failed: a new plan picks up where it stopped`)}},wO={name:"purchases:catalog:decline",summary:"decline a plan: its Stripe part is never written",usage:"<plan id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=fd(e);await v(e,t,`decline the plan ${n}`);let s=await h(e,t,"POST",`/purchases/catalog/plans/${k(n)}/decline`,void 0,j());e.out.result(s,()=>e.out.line(`Declined the plan ${s.id}.`))}};function Lb(e){let t=e.args[0],n=Number(t);if(t===void 0||!Number.isInteger(n)||n<1)throw m("the revision's number is required (purchases:catalog:revisions lists them)");return n}var vO={name:"purchases:catalog:revisions",summary:"every revision the catalog was saved as, the newest first: who saved it, when, and when a plan of it was written to the stores",usage:"[--limit <n>] [--cursor <next>]",details:["purchases:catalog:revision <n> reads one; purchases:catalog:restore <n> puts it back as the next revision."],flags:{limit:{type:"string",value:"n",description:"revisions a page (default 50, at most 200)"},cursor:{type:"string",value:"next",description:"the next page, as the last one printed it"}},scope:"environment",async run(e){let t=await b(e),n=new URLSearchParams,s=se(e.flags.limit,"limit");s!==void 0&&n.set("limit",String(s)),e.flags.cursor!==void 0&&n.set("cursor",String(e.flags.cursor));let a=await h(e,t,"GET",`/purchases/catalog/revisions${n.size?`?${n}`:""}`);e.out.result(a,()=>{if(a.revisions.length===0){e.out.line("No catalog yet: palbase purchases:catalog:put --file catalog.json --revision 0");return}e.out.table(a.revisions,[{header:"revision",value:i=>`${i.revision}${i.current?" (now)":""}`},{header:"saved",value:i=>L(i.created_at)},{header:"by",value:i=>i.created_by},{header:"products",value:i=>String(i.products)},{header:"entitlements",value:i=>String(i.entitlements)},{header:"offers",value:i=>String(i.offers)},{header:"written to stores",value:i=>L(i.applied_at)}]),a.next_cursor&&e.out.line(`Older: palbase purchases:catalog:revisions --cursor ${a.next_cursor}`)})}},_O={name:"purchases:catalog:revision",summary:"the catalog as it was saved at a revision",usage:"<revision> [--out <catalog.json>]",details:["--out writes that revision's catalog to a file, as catalog:get --out writes the newest."],args:{min:1,max:1},flags:{out:{type:"string",value:"catalog.json",description:"write the revision's catalog to this file"}},scope:"environment",async run(e){let t=await b(e),n=Lb(e),s=await h(e,t,"GET",`/purchases/catalog/revisions/${n}`),a=e.flags.out;if(a!==void 0){await md(Wa(e.io.cwd,a),`${JSON.stringify(s.catalog,null,2)}
|
|
692
692
|
`),e.out.result({file:a,revision:s.revision},()=>e.out.line(`Wrote revision ${s.revision} of the catalog to ${a}.`));return}e.out.result(s,()=>Mb(e,s))}},kO={name:"purchases:catalog:restore",summary:"put an older revision of the catalog back, as its next revision; nothing is written to a store",usage:"<revision>",details:["It is saved as an edit is: checked against today's rules, what customers bought kept in it \u2014 a revision that breaks one is refused with every problem.","The stores are brought to it by a plan, confirmed: palbase purchases:catalog:plan."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=Lb(e),s=await h(e,t,"GET","/purchases/catalog");await v(e,t,`put revision ${n} of the catalog back, over revision ${s.revision}`);let a;try{a=await h(e,t,"POST",`/purchases/catalog/revisions/${n}/restore`,void 0,{"if-match":Cb(s.revision),...j()})}catch(i){if(i instanceof E&&i.status===412)throw new f("catalog_changed",`the catalog moved past revision ${s.revision} while this ran \u2014 nothing was saved`,{hint:`run it again: palbase purchases:catalog:restore ${n}`});gd(e,i,`revision ${n} was not put back`)}e.out.result(a,()=>{e.out.line(`Saved revision ${n}'s catalog as revision ${a.revision}.`),e.out.line("Bring the stores to it: palbase purchases:catalog:plan")})}};function cd(e){return e===null?"for life":L(e)}function SO(e,t){e.out.line(`Customer ${t.customer_id}${t.guest?" (guest)":""}: revision ${t.revision}, as of ${L(t.requested_at)}`);let n=Object.entries(t.entitlements).sort(([s],[a])=>s<a?-1:s>a?1:0);e.out.line(n.length===0?"No entitlement.":"Entitlements:"),e.out.table(n,[{header:"entitlement",value:([s])=>s},{header:"active",value:([,s])=>s.active?"yes":"no"},{header:"until",value:([,s])=>cd(s.expires_at)},{header:"store",value:([,s])=>`${s.store}${s.is_sandbox?" (sandbox)":""}`},{header:"renews",value:([,s])=>s.will_renew?"yes":"no"},{header:"product",value:([,s])=>s.product??"\u2014"}]),t.subscriptions.length>0&&(e.out.line("Subscriptions:"),e.out.table(t.subscriptions,[{header:"product",value:s=>`${s.product??"\u2014"}${s.plan?`/${s.plan}`:""}`},{header:"store",value:s=>`${s.store}${s.is_sandbox?" (sandbox)":""}`},{header:"state",value:s=>s.state},{header:"until",value:s=>cd(s.expires_at)},{header:"renews",value:s=>s.will_renew?"yes":"no"},{header:"id",value:s=>s.id}])),t.purchases.length>0&&(e.out.line("Purchases:"),e.out.table(t.purchases,[{header:"product",value:s=>s.product??"\u2014"},{header:"store",value:s=>`${s.store}${s.is_sandbox?" (sandbox)":""}`},{header:"state",value:s=>s.state},{header:"bought",value:s=>L(s.purchased_at)}])),t.credits.length>0&&(e.out.line("Credits:"),e.out.table(t.credits,[{header:"credit",value:s=>s.currency},{header:"balance",value:s=>String(s.balance)},{header:"available",value:s=>String(s.available)},{header:"held",value:s=>String(s.reserved)},{header:"owed",value:s=>String(s.debt)},{header:"next expiry",value:s=>L(s.next_expiry)}])),t.limits.length>0&&(e.out.line("Limits:"),e.out.table(t.limits,[{header:"limit",value:s=>s.limit},{header:"used",value:s=>`${s.used} of ${s.max}`},{header:"held",value:s=>String(s.reserved)},{header:"left",value:s=>String(s.remaining)},{header:"resets",value:s=>L(s.resets_at)}]))}var $O={name:"purchases:customer:get",summary:"what a customer has, whatever store they bought in: entitlements, subscriptions, purchases, credits and limits",usage:"<customer id>",details:["The customer is the user's id; a guest merged into an account answers as the account."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=await h(e,t,"GET",`/purchases/customers/${k(n)}`);e.out.result(s,()=>SO(e,s))}};function yd(e){let t=e.flags.until,n=e.flags.for;if(t!==void 0&&n!==void 0)throw m("--until or --for, not both");if(t!==void 0){let s=Date.parse(t);if(!Number.isFinite(s))throw m(`--until ${t}: a date or time (2026-12-31, 2026-12-31T18:00:00Z)`);if(s<=e.io.now())throw m(`--until ${t} is not in the future`);return new Date(s).toISOString()}if(n!==void 0){let s=/^([1-9][0-9]{0,4})([hdw])$/.exec(n.trim());if(!s)throw m(`--for ${n}: a number of hours, days or weeks (12h, 30d, 2w)`);let a=Number(s[1])*{h:1,d:24,w:168}[s[2]];return new Date(e.io.now()+a*36e5).toISOString()}}var PO={name:"purchases:customer:grant",summary:"give a customer one of the catalog's entitlements, for a while or for life, saying why \u2014 a promotion, a support case, a tester",usage:"<customer id> <entitlement> --reason <why> [--for 30d | --until <date>]",details:["The reason is the record. Without --for or --until the grant is for life. It prints the grant's id: purchases:customer:revoke ends it.","A customer not seen before is made; nothing is charged, in any store."],args:{min:2,max:2},flags:{reason:{type:"string",value:"why",description:"why it is given (500 characters at most): the record"},for:{type:"string",value:"span",description:"how long: 12h, 30d, 2w"},until:{type:"string",value:"date",description:"when it ends (2026-12-31, or a time)"}},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=ce(e,1,"the entitlement"),a=e.flags.reason?.trim();if(!a)throw m("--reason says why it is given: the grant's record");if(a.length>500)throw m("--reason is 500 characters at most");let i=yd(e);await v(e,t,`give ${n} ${s} ${i?`until ${L(i)}`:"for life"}`);let r={entitlement:s,reason:a,...i?{expires_at:i}:{}},o=await h(e,t,"POST",`/purchases/customers/${k(n)}/grants`,r,j());e.out.result(o,()=>{e.out.line(`Gave ${o.customer_id} ${o.entitlement} ${o.expires_at?`until ${L(o.expires_at)}`:"for life"} (grant ${o.id}).`),e.out.line(`End it: palbase purchases:customer:revoke ${o.customer_id} ${o.id}`)})}},AO={name:"purchases:customer:revoke",summary:"end a granted entitlement now; what the customer bought is not touched",usage:"<customer id> <grant id>",details:["The grant's id is the one purchases:customer:grant printed. The entitlement stays on while a purchase still gives it."],args:{min:2,max:2},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=ce(e,1,"the grant's id");await v(e,t,`end the grant ${s} of ${n}`),await h(e,t,"DELETE",`/purchases/customers/${k(n)}/grants/${k(s)}`,void 0,j()),e.out.result({revoked:s,customer_id:n},()=>e.out.line(`Ended the grant ${s} of ${n}.`))}};function RO(e,t){return e==null?"":`${(e/1e6).toFixed(2)}${t?` ${t}`:""}`}var TO={name:"purchases:customers",summary:"find customers by what a person writing in has: their id, an id their store gave a purchase, or the email they bought with on the web",usage:"<query>",details:["The query is a customer's id; Apple's original transaction id or any transaction id; a Google order id (GPA.\u2026, a renewal's ..N or not); Stripe's subscription, payment intent, invoice or customer id; or an email address.","An email finds a buyer who had no account at checkout, matched whole (case aside): the address is never kept, an HMAC of it is."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"what to look for (an id, a store id, an email)"),s=await h(e,t,"GET",`/purchases/customers?q=${encodeURIComponent(n)}`);e.out.result(s,()=>{if(s.customers.length===0){e.out.line(`No customer found by ${s.query}.`);return}e.out.table(s.customers,[{header:"customer",value:i=>i.customer_id??"\u2014 (not redeemed yet)"},{header:"found by",value:i=>i.matched_by},{header:"store",value:i=>i.store?`${i.store}${i.is_sandbox?" (sandbox)":""}`:""},{header:"product",value:i=>i.product??""},{header:"since",value:i=>L(i.at)}]);let a=s.customers.find(i=>i.customer_id);a&&e.out.line(`What happened to them: palbase purchases:customer:history ${a.customer_id}`)})}},EO={name:"purchases:customer:history",summary:"what happened to a customer, the newest first: payments, refunds, cancellations, grants, credits, moves \u2014 with who did each, and why",usage:"<customer id> [--limit <n>] [--cursor <next>]",details:["Credits spent are the credits' own entries; here are the credits given, taken back, expired and forgiven."],args:{min:1,max:1},flags:{limit:{type:"string",value:"n",description:"events a page (default 50, at most 200)"},cursor:{type:"string",value:"next",description:"the next page, as the last one printed it"}},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=new URLSearchParams,a=se(e.flags.limit,"limit");a!==void 0&&s.set("limit",String(a)),e.flags.cursor!==void 0&&s.set("cursor",String(e.flags.cursor));let i=await h(e,t,"GET",`/purchases/customers/${k(n)}/history${s.size?`?${s}`:""}`);e.out.result(i,()=>{e.out.line(`History of ${i.customer_id}, the newest first:`),i.events.length===0&&e.out.line("Nothing yet."),e.out.table(i.events,[{header:"when",value:r=>L(r.at)},{header:"what",value:r=>r.kind},{header:"store",value:r=>r.store?`${r.store}${r.is_sandbox?" (sandbox)":""}`:""},{header:"product",value:r=>[r.product,r.plan].filter(Boolean).join("/")||r.entitlement||""},{header:"amount",value:r=>r.credits?`${r.credits.delta>0?"+":""}${r.credits.delta} ${r.credits.currency}`:RO(r.amount_micros,r.currency)},{header:"why",value:r=>r.credits?[r.credits.kind,r.reason].filter(Boolean).join(": "):r.reason??""},{header:"by",value:r=>r.actor}]),i.next_cursor&&e.out.line(`Older: palbase purchases:customer:history ${i.customer_id} --cursor ${i.next_cursor}`)})}},CO={name:"purchases:customer:grants",summary:"the entitlements given a customer \u2014 active, ended and revoked \u2014 with each grant's id, reason and who gave it",usage:"<customer id>",details:["End one: palbase purchases:customer:revoke <customer id> <grant id>."],args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=await h(e,t,"GET",`/purchases/customers/${k(n)}/grants`);e.out.result(s,()=>{if(s.grants.length===0){e.out.line(`${s.customer_id} was given nothing.`);return}e.out.table(s.grants,[{header:"grant",value:a=>a.id},{header:"entitlement",value:a=>a.entitlement},{header:"active",value:a=>a.active?"yes":"no"},{header:"ends",value:a=>a.revoked_at?`revoked ${L(a.revoked_at)}`:a.expires_at?L(a.expires_at):"for life"},{header:"why",value:a=>a.reason},{header:"by",value:a=>a.revoked_by?`${a.granted_by}, revoked by ${a.revoked_by}`:a.granted_by}])})}};function bd(e){let t=e.flags.note?.trim();if(t!==void 0&&t.length>500)throw m("--note is 500 characters at most");return t||void 0}function wd(e,t,n){let s=t.subscription;e.out.line(`${n} (${t.action.store}, by ${t.action.actor}).`),e.out.line(`${s.product??"\u2014"}${s.plan?`/${s.plan}`:""}: ${s.state}, ${s.active?"on":"off"} until ${cd(s.expires_at)}, ${s.will_renew?"renews":"does not renew"}.`)}var vd={note:{type:"string",value:"why",description:"what support writes of it (500 characters at most): the record"}},jO={name:"purchases:customer:extend",summary:"move a customer's subscription renewal days later, for free: the App Store's extension, Google Play's deferral, Stripe's next charge moved",usage:"<customer id> <subscription id> --days <1-90> --reason customer_satisfaction|service_issue|other [--note <why>]",details:["The subscription's id is the one purchases:customer:get prints. The App Store extends a paid, active subscription, at most 90 days and twice a year.","The store is asked again after: the new expiry is printed, and the customer's history keeps it with who did it."],args:{min:2,max:2},flags:{days:{type:"string",value:"n",description:"how many days (1 to 90)"},reason:{type:"string",value:"why",description:"customer_satisfaction, service_issue or other: as the App Store asks it"},...vd},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=ce(e,1,"the subscription's id (purchases:customer:get prints it)"),a=se(e.flags.days,"days");if(a===void 0||a<1||a>90)throw m("--days is 1 to 90");let i=e.flags.reason;if(i!=="customer_satisfaction"&&i!=="service_issue"&&i!=="other")throw m("--reason is customer_satisfaction, service_issue or other");let r=bd(e);await v(e,t,`extend ${n}'s subscription ${s} by ${a} day(s)`);let o={days:a,reason:i,...r?{note:r}:{}},l=await h(e,t,"POST",`/purchases/customers/${k(n)}/subscriptions/${k(s)}/extend`,o,j());e.out.result(l,()=>wd(e,l,`Extended ${n}'s subscription by ${a} day(s)`))}},OO={name:"purchases:customer:refund",summary:"refund a customer's subscription \u2014 its latest payment, or what is left of its period \u2014 and end it now: Google Play and Stripe",usage:"<customer id> <subscription id> --mode full|prorated [--note <why>]",details:["The customer's access ends as it answers. The App Store decides its own refunds: the customer asks Apple, which asks the app what they used \u2014 Palbase answers it when they consented in the app."],args:{min:2,max:2},flags:{mode:{type:"string",value:"kind",description:"full: the latest payment; prorated: what is left of its period"},...vd},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=ce(e,1,"the subscription's id (purchases:customer:get prints it)"),a=e.flags.mode;if(a!=="full"&&a!=="prorated")throw m("--mode is full (the latest payment) or prorated (what is left of its period)");let i=bd(e);await v(e,t,`refund ${n}'s subscription ${s} (${a}) and end it now`);let r={mode:a,...i?{note:i}:{}},o=await h(e,t,"POST",`/purchases/customers/${k(n)}/subscriptions/${k(s)}/refund`,r,j());e.out.result(o,()=>wd(e,o,`Refunded ${n}'s subscription (${a}); it ended`))}},MO={name:"purchases:customer:cancel",summary:"turn a customer's subscription renewal off: it ends at its period's end, the customer keeping what they paid for \u2014 Google Play and Stripe",usage:"<customer id> <subscription id> [--note <why>]",details:["An App Store subscription's renewal is the customer's to turn off (Settings \u203A Apple ID \u203A Subscriptions)."],args:{min:2,max:2},flags:{...vd},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=ce(e,1,"the subscription's id (purchases:customer:get prints it)"),a=bd(e);await v(e,t,`turn the renewal of ${n}'s subscription ${s} off`);let i=a?{note:a}:{},r=await h(e,t,"POST",`/purchases/customers/${k(n)}/subscriptions/${k(s)}/cancel`,i,j());e.out.result(r,()=>wd(e,r,`Turned the renewal of ${n}'s subscription off`))}},Db={source:{type:"string",value:"kind",description:"support (the default) or promotion"}};function xb(e){let t=e.flags.source??"support";if(t!=="support"&&t!=="promotion")throw m("--source is support or promotion");return t}function Kr(e,t){let n=e.flags.reason?.trim();if(!n)throw m(`--reason says why ${t}: the record`);if(n.length>500)throw m("--reason is 500 characters at most");return n}function Nb(e,t,n){let s=ce(e,t,n),a=Number(s);if(!Number.isInteger(a)||a<1)throw m(`${n} is a whole number above 0: ${s}`);return a}var IO={name:"purchases:customer:credits",summary:"a customer's credit entries, the newest first: given, spent, taken back, expired, forgiven \u2014 with who did each, and why",usage:"<customer id> [--credits <key>] [--limit <n>] [--cursor <next>]",args:{min:1,max:1},flags:{credits:{type:"string",value:"key",description:"one of the catalog's credits alone"},limit:{type:"string",value:"n",description:"entries a page (default 50, at most 200)"},cursor:{type:"string",value:"next",description:"the next page, as the last one printed it"}},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=new URLSearchParams;e.flags.credits!==void 0&&s.set("credits",String(e.flags.credits));let a=se(e.flags.limit,"limit");a!==void 0&&s.set("limit",String(a)),e.flags.cursor!==void 0&&s.set("cursor",String(e.flags.cursor));let i=await h(e,t,"GET",`/purchases/customers/${k(n)}/credits/entries${s.size?`?${s}`:""}`);e.out.result(i,()=>{i.entries.length===0&&e.out.line(`${n} has no credit entry.`),e.out.table(i.entries,[{header:"when",value:r=>L(r.created_at)},{header:"credit",value:r=>r.currency},{header:"what",value:r=>r.kind},{header:"amount",value:r=>`${r.delta>0?"+":""}${r.delta}`},{header:"owed",value:r=>r.debt_delta?`${r.debt_delta>0?"+":""}${r.debt_delta}`:""},{header:"why",value:r=>r.reason??""},{header:"by",value:r=>r.actor??""}]),i.next_cursor&&e.out.line(`Older: palbase purchases:customer:credits ${n} --cursor ${i.next_cursor}`)})}},LO={name:"purchases:customer:credits:give",summary:"give a customer credits, saying why \u2014 a support case, a promotion \u2014 for a while or until spent",usage:"<customer id> <credits> <amount> --reason <why> [--source support|promotion] [--for 30d | --until <date>]",details:["What they owe is paid first from what is given. Nothing is charged, in any store."],args:{min:3,max:3},flags:{reason:{type:"string",value:"why",description:"why they are given (500 characters at most): the record"},...Db,for:{type:"string",value:"span",description:"how long they last: 12h, 30d, 2w"},until:{type:"string",value:"date",description:"when they expire (2026-12-31, or a time)"}},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=ce(e,1,"the credits (the catalog's key)"),a=Nb(e,2,"the amount"),i=Kr(e,"they are given"),r=xb(e),o=yd(e);await v(e,t,`give ${n} ${a} ${s}${o?` until ${L(o)}`:""}`);let l={credits:s,amount:a,source:r,reason:i,...o?{expires_at:o}:{}},d=await h(e,t,"POST",`/purchases/customers/${k(n)}/credits`,l,j());e.out.result(d,()=>e.out.line(`Gave ${n} ${d.original} ${d.currency}${d.expires_at?` until ${L(d.expires_at)}`:""}; ${d.remaining} left of it.`))}},DO={name:"purchases:customer:credits:forgive",summary:"forgive what a customer owes of a credit \u2014 all of it, or an amount \u2014 saying why",usage:"<customer id> <credits> --reason <why> [--amount <n>]",args:{min:2,max:2},flags:{reason:{type:"string",value:"why",description:"why it is forgiven (500 characters at most): the record"},amount:{type:"string",value:"n",description:"how much of it (default: all they owe)"}},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=ce(e,1,"the credits (the catalog's key)"),a=Kr(e,"it is forgiven"),i=se(e.flags.amount,"amount");if(i===0)throw m("--amount is above 0");await v(e,t,`forgive ${i??"all"} of what ${n} owes of ${s}`);let r={credits:s,reason:a,...i!==void 0?{amount:i}:{}},o=await h(e,t,"POST",`/purchases/customers/${k(n)}/credits/forgive`,r,j());e.out.result(o,()=>e.out.line(`Forgave ${o.forgiven} ${o.credits} ${n} owed; they owe ${o.debt}, ${o.available} available.`))}};function _d(e,t,n){e.out.line(`${t}: ${n.used} of ${n.max} used, ${n.remaining} left, resets ${L(n.resets_at)}.`)}var xO={name:"purchases:customer:limit:set",summary:"set a customer's own maximum of a limit \u2014 above or below the catalog's \u2014 saying why, for a while or until cleared",usage:"<customer id> <limit> <max> --reason <why> [--for 30d | --until <date>]",args:{min:3,max:3},flags:{reason:{type:"string",value:"why",description:"why (500 characters at most): the record"},for:{type:"string",value:"span",description:"how long: 12h, 30d, 2w"},until:{type:"string",value:"date",description:"when it ends (2026-12-31, or a time)"}},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=ce(e,1,"the limit (the catalog's key)"),a=ce(e,2,"the maximum"),i=Number(a);if(!Number.isInteger(i)||i<0)throw m(`the maximum is a whole number: ${a}`);let r=Kr(e,"it is set"),o=yd(e);await v(e,t,`set ${n}'s ${s} to ${i}${o?` until ${L(o)}`:""}`);let l={max:i,reason:r,...o?{expires_at:o}:{}},d=await h(e,t,"PUT",`/purchases/customers/${k(n)}/limits/${k(s)}`,l,j());e.out.result(d,()=>_d(e,`Set ${n}'s ${d.limit} to ${d.max}`,d))}},NO={name:"purchases:customer:limit:clear",summary:"clear a customer's own maximum of a limit: the catalog's counts again",usage:"<customer id> <limit>",args:{min:2,max:2},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=ce(e,1,"the limit (the catalog's key)");await v(e,t,`clear ${n}'s own ${s}`);let a=await h(e,t,"DELETE",`/purchases/customers/${k(n)}/limits/${k(s)}`,void 0,j());e.out.result(a,()=>_d(e,`Cleared ${n}'s own ${a.limit}; the catalog's ${a.max} counts`,a))}},qO={name:"purchases:customer:limit:give",summary:"give a customer more of a limit for its current period, saying why \u2014 a gift on top of their maximum",usage:"<customer id> <limit> <amount> --reason <why> [--source support|promotion]",args:{min:3,max:3},flags:{reason:{type:"string",value:"why",description:"why it is given (500 characters at most): the record"},...Db},scope:"environment",async run(e){let t=await b(e),n=ce(e,0,"the customer's id (the user's id)"),s=ce(e,1,"the limit (the catalog's key)"),a=Nb(e,2,"the amount"),i=Kr(e,"it is given"),r=xb(e);await v(e,t,`give ${n} ${a} more ${s} this period`);let o={amount:a,source:r,reason:i},l=await h(e,t,"POST",`/purchases/customers/${k(n)}/limits/${k(s)}/grants`,o,j());e.out.result(l,()=>_d(e,`Gave ${n} ${a} more ${l.limit}`,l))}},KO={name:"purchases:stripe",summary:"the environment's Stripe account: whether one is connected, what Stripe last said of its key",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/purchases/stripe");e.out.result(n,()=>{if(!n.connected){e.out.line("No Stripe account is connected."),e.out.line("Connect one with one click: palbase purchases:stripe:install (Palbase's Stripe App), or with a restricted key: palbase purchases:stripe:grant");return}let s=n.via==="app"?"through Palbase's Stripe App":`key ${n.key_hint??"?"}`;e.out.line(`Stripe account ${n.account_id??"?"} (${n.livemode?"live":"test"} mode), ${s}`),e.out.line(`status: ${n.status??"not checked"}${n.checked_at?` (checked ${L(n.checked_at)})`:""}`),n.connected_at&&e.out.line(`connected ${L(n.connected_at)}${n.connected_by?` by ${n.connected_by}`:""}`),n.action&&e.out.line(`To do: ${n.action}`)})}},GO={name:"purchases:stripe:grant",summary:"a link that connects a Stripe restricted key: the key goes from the browser straight to the environment, never through Studio or this computer",details:["The link works once, for 30 minutes; a project holds 10 open at most."],scope:"environment",async run(e){let t=await b(e);await v(e,t,"make a link that connects a Stripe account");let n=await h(e,t,"POST","/purchases/stripe/grants",void 0,j());rn(e,t,n.connect_url,"the connect link"),e.out.result({connect_url:n.connect_url,expires_at:n.expires_at},()=>{e.out.line(n.connect_url),e.out.note(`Open it in a browser and paste the Stripe restricted key; it works once, until ${L(n.expires_at)}.`)})}},UO={name:"purchases:stripe:install",summary:"a link that connects the environment's Stripe account with one click: Palbase's Stripe App, installed at Stripe \u2014 no key pasted",details:["The link opens Palbase's install page, naming the project; from there Stripe: pick the account, accept what the App may do, and Stripe sends you back to Palbase, which connects it.","It works once, for 30 minutes; --live installs the App in live mode (Stripe test mode otherwise).","A restricted key connects an account too: palbase purchases:stripe:grant."],flags:{live:{type:"boolean",description:"install the App in live mode (test mode otherwise)"}},scope:"environment",async run(e){let t=await b(e),n=e.flags.live===!0;await v(e,t,`make a link that installs Palbase's Stripe App in ${n?"live":"test"} mode`);let s=await h(e,t,"POST","/purchases/stripe/app/grants",{livemode:n},j()),a=Jd(e.cloud),i;try{i=new URL(s.install_url)}catch{i=void 0}if(i?.origin!==a||i.pathname!=="/purchases/stripe/app/install"||!i.hash.startsWith("#grant="))throw new f("install_link_not_palbase",`the install link names ${i?i.origin+i.pathname:s.install_url}, not Palbase's install page at ${a}: it is not printed`);e.out.result({install_url:s.install_url,expires_at:s.expires_at},()=>{e.out.line(s.install_url),e.out.note(`Open it in a browser, pick the Stripe account and accept; it works once, until ${L(s.expires_at)}.`)})}};function BO(e){let t=n=>/^[\w./@:-]+$/.test(n)?n:JSON.stringify(n);return`${e.global.project!==void 0?` -P ${t(e.global.project)}`:""}${e.global.env!==void 0?` -E ${t(e.global.env)}`:""}`}async function kd(e,t){let n=(await et(e,t.project_id)).filter(o=>o.deleted_at===null),s=n.filter(o=>o.platform==="ios"),a=e.flags.app;if(a!==void 0){let o=mt(n,a);if(o.platform!=="ios")throw m(`${o.slug} is a ${o.platform} app: a StoreKit configuration is an iOS app's`,`the project's iOS apps: ${s.map(l=>l.slug).join(", ")||"none"}`);return o}let i=(await ir(e.io.cwd))?.apps.filter(o=>o.platform==="ios").map(o=>o.id)??[],r=s.filter(o=>i.includes(o.id));if(r.length===1)return r[0];if(s.length===1)return s[0];throw s.length===0?new f("no_ios_app",`${t.project_name} has no iOS app`,{hint:"register it: palbase apps:create ios <name> --team-id <team id>"}):m("name the iOS app the file is for: --app <app>",`the project's iOS apps: ${s.map(o=>o.slug).join(", ")}`)}function zO(e,t){let n=uO(e.io.cwd,Wa(e.io.cwd,t)).split(cO).join("/");if(!n.startsWith(`${z}/`)||n.split("/").includes(".."))throw m(`--out ${t}: the file goes under ${z}/, as the CLI writes nothing else in the checkout`,`palbase purchases:storekit --out ${z}/<name>.storekit`);if(!n.endsWith(".storekit"))throw m(`--out ${t}: Xcode takes a StoreKit configuration by its .storekit extension`);return n}function WO(e){let t=new Map;for(let n of e.products)for(let s of n.channels.ios?.plans??[])t.set(s.price.currency.toUpperCase(),(t.get(s.price.currency.toUpperCase())??0)+1);return[...t].sort(([n,s],[a,i])=>i-s||(n<a?-1:1))[0]?.[0]}var FO={name:"purchases:storekit",summary:"an Xcode StoreKit configuration of the environment's iOS products, under palbase/: a build Xcode runs buys them with no App Store",usage:"[--app <app>] [--out <palbase/\u2026.storekit>] [--storefront <code>]",details:["Each plan is the App Store product its store id names, with its text in every language the catalog has and its price; a subscription is in its group, at its tier's level, with its introductory offer and the catalog's offers on it as promotional offers (a grant has no store).","Prices are in the storefront's currency: the catalog's price, or the amount set by hand in that currency. The storefront is --storefront, else the one the file has, else the one the catalog's currency is the App Store's own price in (USD: USA, EUR: Germany, TRY: Turkey \u2026), else USA.","Made again, the file is made whole from the catalog \u2014 the same catalog, the same file \u2014 keeping the test settings Xcode's Editor menu wrote in it. Nothing outside palbase/ is written: Xcode is pointed at the file in the scheme."],flags:{app:{type:"string",value:"app",description:"the iOS app it is for (default: the one this checkout syncs, or the project's only one)"},out:{type:"string",value:"palbase/\u2026.storekit",description:"where under palbase/ (default: palbase/environments/<env>/<app>.storekit)"},storefront:{type:"string",value:"code",description:"the App Store storefront prices are in, by its three letters (USA, DEU, TUR, GBR, JPN \u2026)"}},scope:"environment",async run(e){let t=await b(e),n=e.flags.storefront?.trim().toUpperCase();if(n!==void 0&&!xs.has(n))throw m(`--storefront ${e.flags.storefront}: not an App Store storefront`,"a storefront is three letters, its country's ISO 3166-1 code: USA, DEU, TUR, GBR, JPN \u2026");let s=await kd(e,t);if(!/^[A-Za-z][A-Za-z0-9-]{0,38}$/.test(t.env_slug))throw new f("unexpected_answer",`the environment's slug ${JSON.stringify(t.env_slug)} is not one`);if(!/^[a-z][a-z0-9-]{0,38}[a-z0-9]$/.test(s.slug))throw new f("unexpected_answer",`the project answered app ${JSON.stringify(s.slug)}, which is not one`);let a=e.flags.out!==void 0?zO(e,e.flags.out):`${z}/environments/${t.env_slug}/${s.slug}.storekit`,i=await h(e,t,"GET","/purchases/offerings?channel=ios");if(!i.products.some(R=>(R.channels.ios?.plans.length??0)>0))throw new f("nothing_on_ios",`${t.env_name}'s catalog sells nothing on iOS yet: there is no product for Xcode to sell`,{hint:"give a product channels.ios in the catalog (palbase purchases:catalog:get --out catalog.json, then purchases:catalog:put)"});let r=await ge(e.io.cwd,a),o,l;try{o=await hd(r,"utf8");let R=JSON.parse(o);typeof R.settings=="object"&&R.settings!==null&&!Array.isArray(R.settings)&&(l=R.settings)}catch{}let d=typeof l?._storefront=="string"&&xs.has(l._storefront)?l._storefront:void 0,p=WO(i);n??=d??(p!==void 0?Df(p):void 0)??"USA";let{catalog:u}=await h(e,t,"GET","/purchases/catalog"),g=qf(i,{seed:`${t.env_ref}/${s.id}`,storefront:n,settings:l,offers:u.offers??[]}),y=o!==g.text;y&&(await lO(pO(r),{recursive:!0}),await ge(e.io.cwd,a),await md(r,g.text));for(let R of g.notes)e.out.warn(R);let w=t.env_slug===Be,_=BO(e),P=[`In Xcode: Product \u203A Scheme \u203A Edit Scheme\u2026 \u203A Run \u203A Options \u203A StoreKit Configuration \u2014 choose ${a} (not listed yet? add it from that menu).`,w?`${t.project_name} \u203A ${t.env_name} is the project's production environment: it never takes a purchase Xcode signs. Make the file for a test environment (-E <env>) to see a purchase reach the server.`:`Then select the file in Xcode, choose Editor \u203A Save Public Certificate, and let ${t.env_name} take the purchases Xcode signs: palbase purchases:apple:xcode-certificate <the saved .cer file>${_}`,`Run the app and buy: Xcode sells the products itself, nothing goes to the App Store. After the catalog changes: palbase purchases:storekit${e.flags.app!==void 0?` --app ${s.slug}`:""}${e.flags.out!==void 0?` --out ${a}`:""}${_}`],S=g.counts,$=[S.subscriptions>0?`${S.subscriptions} subscription${S.subscriptions===1?"":"s"} in ${S.groups} group${S.groups===1?"":"s"}`:"",S.products>0?`${S.products} in-app purchase${S.products===1?"":"s"}`:"",S.non_renewing>0?`${S.non_renewing} non-renewing subscription${S.non_renewing===1?"":"s"}`:""].filter(R=>R!=="").join(", ");e.out.result({file:a,app:s.slug,environment:t.env_slug,revision:i.revision,storefront:g.storefront,currency:g.currency,locale:g.locale,...S,written:y,next:P},()=>{e.out.line(`${y?"Wrote":"Up to date:"} ${a} \u2014 ${$}, priced in ${g.currency} (storefront ${g.storefront}), catalog revision ${i.revision}.`),e.out.line(""),P.forEach((R,T)=>e.out.line(`${T+1}. ${R}`))})}},JO=/^SubscriptionKey_([A-Z0-9]{10})\.p8$/,VO=/^AuthKey_[A-Z0-9]{10}\.p8$/,HO=8192,YO=16384;function qb(e,t){if(!t.connected)e.out.line("No In-App Purchase key is connected: the App Store's purchases are not taken."),e.out.line("Connect one: palbase purchases:apple:connect --key-file SubscriptionKey_<KEYID>.p8");else{e.out.line(`In-App Purchase key ${t.key_id??"?"} (issuer ${t.issuer_id??"?"}) for ${t.bundle_id??"?"}${t.app_apple_id?`, Apple ID ${t.app_apple_id}`:", its Apple ID not known yet"}`),e.out.line(`status: ${t.status??"not checked"}${t.checked_at?` (checked ${L(t.checked_at)})`:""}`);let s=t.notifications;s&&e.out.line(`notifications: ${s.url} \u2014 ${s.bound?`bound ${L(s.bound_at)}`:`not bound${s.error?`: ${s.error}`:""}`}; Apple's TEST notification ${s.verified_at?`arrived ${L(s.verified_at)}`:"not arrived yet"}`),t.connected_at&&e.out.line(`connected ${L(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.action&&e.out.line(`To do: ${t.action}`)}let n=t.xcode_certificate;e.out.line(n?`Xcode's StoreKit Testing purchases: taken, signed with ${n.subject} until ${L(n.not_after)} (sha256 ${n.fingerprint.slice(0,16)}\u2026)`:"Xcode's StoreKit Testing purchases: not taken (palbase purchases:apple:xcode-certificate <file> takes them)")}var XO={name:"purchases:apple",summary:"the environment's App Store connection: the In-App Purchase key, where the App Store reports, whether Xcode's purchases are taken",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/purchases/apple");e.out.result(n,()=>qb(e,n))}};function ZO(e,t){let n=e.environments.find(s=>s.ref===t.env_ref)?.ios?.bundle;if(n===void 0)throw new f("app_not_in_environment",`${e.slug} is not set in ${t.env_name}: the key is connected for the app's bundle there`,{hint:`palbase apps:env:set ${e.slug} -E ${t.env_slug} --bundle <bundle id>`});return n}var QO={name:"purchases:apple:connect",summary:"connect an In-App Purchase key for an iOS app: it goes from this computer straight to the environment, never through Studio",usage:"--key-file <SubscriptionKey_KEYID.p8> [--key-id <KEYID>] [--issuer-id <issuer id>] [--app <app>] | --print-link",details:["App Store Connect \u2192 Users and Access \u2192 Integrations \u2192 In-App Purchase makes the key (SubscriptionKey_<KEYID>.p8) and shows the Issuer ID \u2014 the team's, the same as its App Store Connect API keys': left out, the one stores:apple connected is taken.","The environment verifies the app's purchases and reads its subscriptions with it, and has the stores module point the App Store's notifications at the environment.","Studio is asked for a one-time grant alone; the key is posted with it to the environment's own address. --print-link prints a link that takes the key in a browser instead."],flags:{"key-file":{type:"string",value:"SubscriptionKey_KEYID.p8",description:"the .p8 file Apple gave when the key was made"},"key-id":{type:"string",value:"KEYID",description:"the key's id (default: from the file's name)"},"issuer-id":{type:"string",value:"issuer id",description:"the team's issuer id (default: the connected App Store Connect key's)"},app:{type:"string",value:"app",description:"the iOS app (default: the one this checkout syncs, or the project's only one)"},"print-link":{type:"boolean",description:"only print a link that takes the key in a browser (valid 30 minutes, once)"}},scope:"environment",async run(e){let t=await b(e);if(e.flags["print-link"]===!0){if(e.flags["key-file"]!==void 0)throw m("--print-link or --key-file, not both");await v(e,t,"make a link that connects an In-App Purchase key");let y=await h(e,t,"POST","/purchases/apple/grants",void 0,j());rn(e,t,y.connect_url,"the connect link"),e.out.result({connect_url:y.connect_url,expires_at:y.expires_at},()=>{e.out.line(y.connect_url),e.out.note(`Open it in a browser, pick the app and the .p8 file; it works once, until ${L(y.expires_at)}.`)});return}let n=e.flags["key-file"];if(n===void 0)throw m("--key-file names the In-App Purchase key's .p8 file","or --print-link for a link a browser opens");let s=dO(n),a=e.flags["key-id"];if(a===void 0){if(VO.test(s))throw m(`${s} is an App Store Connect API key (palbase stores:apple:connect takes it): this is the In-App Purchase key, SubscriptionKey_<KEYID>.p8`,"App Store Connect \u2192 Users and Access \u2192 Integrations \u2192 In-App Purchase makes one");if(a=JO.exec(s)?.[1],a===void 0)throw m(`--key-id is needed: ${s} is not named SubscriptionKey_<KEYID>.p8`)}let i;try{let y=Wa(e.io.cwd,n);if((await Eb(y)).size>HO)throw new f("not_a_key",`${n} is larger than a .p8 key`);i=await hd(y,"utf8")}catch(y){throw y instanceof f?y:new f("unreadable_file",`${n} could not be read: ${y instanceof Error?y.message:String(y)}`)}if(!i.includes("-----BEGIN PRIVATE KEY-----"))throw new f("not_a_key",`${n} is not a .p8 key (no "BEGIN PRIVATE KEY")`);let r=e.flags["issuer-id"]?.trim();if(r===void 0||r===""){let y=await h(e,t,"GET","/stores/apple");if(r=y.connected?y.issuer_id:void 0,r===void 0)throw m("--issuer-id is the team's issuer id (App Store Connect \u2192 Users and Access \u2192 Integrations): no App Store Connect key is connected to read it from")}let o=await kd(e,t),l=ZO(o,t);await v(e,t,`connect the In-App Purchase key ${a} for ${l}`);let d=await h(e,t,"POST","/purchases/apple/grants",void 0,j()),p=rn(e,t,d.connect_url,"the connect link"),u={grant:d.grant,issuer_id:r,key_id:a,private_key:i,bundle_id:l},g=await Da(e,`${p}/purchases/apple/connect`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(u)},"connecting the In-App Purchase key");e.out.result(g,()=>{e.out.line(`Connected key ${a} for ${l} to ${N(t)}.`),qb(e,g),e.out.line("Check what else the App Store needs: palbase purchases:doctor")})}},e1={name:"purchases:apple:disconnect",summary:"forget the environment's In-App Purchase key: the App Store's purchases and notifications are refused from then on (what was bought stays)",scope:"environment",async run(e){let t=await b(e);await v(e,t,"disconnect the In-App Purchase key"),await h(e,t,"DELETE","/purchases/apple",void 0,j()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected the In-App Purchase key from ${N(t)}.`))}};function Kb(e,t){if(t.service_account===void 0){e.out.line("The project has no Google Play connection: Palbase reads the app's purchases as the account your Play Console invites."),e.out.line("Connect it first: palbase stores:google:connect");return}if(e.out.line(`Play connection: ${t.service_account} (${t.play_status??"not checked"})`),!t.connected){e.out.line("Google Play purchases are not connected: palbase purchases:google:connect --app <android app>");return}e.out.line(`app: ${t.package_name??"?"}`),e.out.line(`topic: ${t.topic??"?"} (Play Console \u203A Monetize with Play \u203A Monetization setup \u203A Real-time developer notifications)`),e.out.line(`notifications: ${t.notification_url??"?"} \u2014 Play's test notification ${t.verified_at?`arrived ${L(t.verified_at)}`:"not arrived yet"}`),t.connected_at&&e.out.line(`connected ${L(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.action&&e.out.line(`To do: ${t.action}`)}var t1={name:"purchases:google",summary:"the environment's Google Play purchases: the app they are made in, the topic its Play Console names, whether Play's test notification arrived",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/purchases/google");e.out.result(n,()=>Kb(e,n))}};async function n1(e,t){let n=(await et(e,t.project_id)).filter(o=>o.deleted_at===null),s=n.filter(o=>o.platform==="android"),a=e.flags.app;if(a!==void 0){let o=mt(n,a);if(o.platform!=="android")throw m(`${o.slug} is a ${o.platform} app: Google Play purchases are an Android app's`,`the project's Android apps: ${s.map(l=>l.slug).join(", ")||"none"}`);return o}let i=(await ir(e.io.cwd))?.apps.filter(o=>o.platform==="android").map(o=>o.id)??[],r=s.filter(o=>i.includes(o.id));if(r.length===1)return r[0];if(s.length===1)return s[0];throw s.length===0?new f("no_android_app",`${t.project_name} has no Android app`,{hint:"register it: palbase apps:create android <name>"}):m("name the Android app: --app <app>",`the project's Android apps: ${s.map(o=>o.slug).join(", ")}`)}var s1={name:"purchases:google:connect",summary:"sell on Google Play in one of the project's Android apps: Palbase makes the app's notifications topic and has it pushed to this environment",usage:"[--app <app>]",details:["The project's Play connection (palbase stores:google:connect) is the account Palbase reads and acknowledges the app's purchases as: its Play Console invites it with View financial data and Manage orders and subscriptions.","Then, in Play Console: Monetize with Play \u203A Monetization setup \u203A Real-time developer notifications, the topic this prints, Save, and Send test notification \u2014 palbase purchases:google says when it arrived."],flags:{app:{type:"string",value:"app",description:"the Android app (default: the one this checkout syncs, or the project's only one)"}},scope:"environment",async run(e){let t=await b(e),n=await n1(e,t);await v(e,t,`connect Google Play purchases for ${n.slug}`);let s={app_id:n.id},a=await h(e,t,"POST","/purchases/google",s,j());e.out.result(a,()=>{e.out.line(`Google Play purchases connected for ${a.package_name??n.slug} in ${N(t)}.`),Kb(e,a)})}},a1={name:"purchases:google:disconnect",summary:"stop taking the environment's Google Play purchases: Play's notifications stop reaching it, and the app's reports are refused (what was bought stays)",scope:"environment",async run(e){let t=await b(e);await v(e,t,"disconnect Google Play purchases"),await h(e,t,"DELETE","/purchases/google",void 0,j()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected Google Play purchases from ${N(t)}.`))}};async function i1(e,t){let n=(await et(e,t.project_id)).find(s=>s.deleted_at===null&&s.environments.some(a=>a.ref===t.env_ref));return n===void 0?t.env_slug===Be:(await e.studio.get(`/environments/${t.env_ref}/apps/${n.id}/config`)).environment.production}async function r1(e,t){let n;try{let i=Wa(t,e);if((await Eb(i)).size>YO)throw new f("not_a_certificate",`${e} is larger than Xcode's certificate`);n=await hd(i)}catch(i){throw i instanceof f?i:new f("unreadable_file",`${e} could not be read: ${i instanceof Error?i.message:String(i)}`)}let s;try{s=new oO(n)}catch{throw new f("not_a_certificate",`${e} is not a certificate`,{hint:"the one Xcode saves: select the .storekit file, then Editor \u203A Save Public Certificate"})}let a=n.toString("latin1");return{certificate:a.includes("-----BEGIN CERTIFICATE-----")?a.trim():n.toString("base64"),x509:s}}var o1={name:"purchases:apple:xcode-certificate",summary:"take the purchases Xcode's StoreKit Testing signs with this certificate, as test purchases \u2014 never on production; --remove stops",usage:"<certificate.cer> | --remove",details:["Xcode saves the certificate: select the .storekit file (palbase purchases:storekit makes it), then Editor \u203A Save Public Certificate.","From then on what the app reports signed with it \u2014 Xcode's own purchases, on a developer's Mac \u2014 is a test purchase of the environment, with or without an In-App Purchase key; nothing of it is asked of Apple. Set again, it replaces the one before.","The production environment takes only what the App Store signed: it is refused there."],args:{min:0,max:1},flags:{remove:{type:"boolean",description:"stop taking Xcode's purchases (those taken stay)"}},scope:"environment",async run(e){let t=await b(e),n=e.flags.remove===!0,s=e.args[0];if(n===(s!==void 0))throw m("name the certificate file, or --remove","palbase purchases:apple:xcode-certificate StoreKitTestCertificate.cer");if(n){await v(e,t,"stop taking Xcode's StoreKit Testing purchases"),await h(e,t,"DELETE","/purchases/apple/xcode-certificate",void 0,j()),e.out.result({removed:!0},()=>e.out.line(`${N(t)} no longer takes Xcode's purchases; those it took stay.`));return}let a=await r1(s,e.io.cwd);if(await i1(e,t))throw new f("production_environment",`${t.project_name} \u203A ${t.env_name} is the project's production environment: it takes only purchases the App Store signed, never Xcode's`,{hint:"set the certificate on a test environment: palbase purchases:apple:xcode-certificate <file> -E <env>"});await v(e,t,`take the purchases Xcode signs with ${a.x509.subject.replaceAll(`
|
|
693
693
|
`,", ")}`);let i=await h(e,t,"PUT","/purchases/apple/xcode-certificate",{certificate:a.certificate},j());e.out.result(i,()=>{e.out.line(`${N(t)} takes the purchases Xcode signs with ${i.subject}, until ${L(i.not_after)} (sha256 ${i.fingerprint.slice(0,16)}\u2026).`),e.out.line("Run the app from Xcode and buy: each purchase is a test purchase of this environment.")})}},l1=new Set(["sandbox_access","xcode_certificate"]),d1={name:"purchases:doctor",summary:"whether the environment sells in the App Store now, check by check \u2014 the App Store Connect side and the purchases side \u2014 with the fix of each that fails",usage:"[--app <app>]",details:["Apple is asked now: the keys, the agreements, the app's App Store Connect record, where the App Store reports, the sandbox testers, each product's state, the catalog's last confirmation; and whether Xcode's purchases are taken.","It exits 1 while a check that is not informational fails: run it again until every line is \u2713."],flags:{app:{type:"string",value:"app",description:"the iOS app (default: the environment's one linked app)"}},scope:"environment",async run(e){let t=await b(e),n=e.flags.app!==void 0?await kd(e,t):void 0,s=n?`?${new URLSearchParams({app:n.id})}`:"",a=u=>u.then(g=>({value:g}),g=>({error:g})),[i,r]=await Promise.all([a(h(e,t,"GET",`/stores/apple/readiness${s}`)),a(h(e,t,"GET","/purchases/apple/readiness"))]),o=(u,g)=>{if(!(g instanceof E))throw g;return{module:u,id:`${u}_unanswered`,ok:!1,informational:!1,message:`The ${u} module could not answer: ${g.message}`,fix:g.status===503||g.status===502?"palbase purchases:doctor (again, in a moment)":""}},l=[..."value"in i?i.value.checks.map(u=>({module:"stores",id:u.id,ok:u.ok,informational:!1,message:u.message,fix:u.fix})):[o("stores",i.error)],..."value"in r?r.value.checks.map(u=>({module:"purchases",id:u.id,ok:u.ok,informational:l1.has(u.id),message:u.message,fix:u.fix})):[o("purchases",r.error)]],d=l.filter(u=>!u.ok&&!u.informational),p=d.length===0;return e.out.result({ready:p,checks:l,stores:"value"in i?i.value:null,purchases:"value"in r?r.value:null},()=>{let u=(g,y)=>{e.out.line(y);for(let w of l.filter(_=>_.module===g))e.out.line(` ${w.informational?"i":w.ok?"\u2713":"\u2717"} ${w.message}`),(!w.ok||w.informational)&&w.fix&&e.out.line(` \u2192 ${w.fix}`)};u("stores","App Store Connect (stores)"),u("purchases","In-App Purchases (purchases)"),e.out.line(""),e.out.line(p?`Ready: ${N(t)} sells in the App Store.`:`${d.length} of ${l.filter(g=>!g.informational).length} checks fail: fix each, then run palbase purchases:doctor again.`)}),p?void 0:1}},Gb=[hO,mO,gO,yO,bO,wO,vO,_O,kO,TO,$O,EO,CO,PO,AO,jO,OO,MO,IO,LO,DO,xO,NO,qO,KO,GO,UO,FO,XO,QO,e1,o1,t1,s1,a1,d1];import{readdir as p1,readFile as u1,stat as c1}from"node:fs/promises";import{join as h1,resolve as m1}from"node:path";var g1=1e3,Ub=900*1024,f1="palbase-argon2id";function y1(e,t){let n=e.trim();if(n.startsWith("{"))try{let s=JSON.parse(n);if(Array.isArray(s.users)){if(s.hash?.pepper!==void 0)throw m(`${t} holds a pepper: it goes on stdin, not in a file`);let a=s.hash&&typeof s.hash.algorithm=="string"?{algorithm:s.hash.algorithm,...typeof s.hash.recovery_code_prefix=="string"?{recovery_code_prefix:s.hash.recovery_code_prefix}:{}}:void 0;return{users:s.users,hash:a}}}catch(s){if(s instanceof Error&&s.name==="CliError")throw s}return{users:w1(e,t)}}function b1(e){let t=[],n=[],s=0;for(let a of e){let i=Buffer.byteLength(JSON.stringify(a))+1;if(i>Ub)throw new f("user_too_large",`the user ${String(a.id??"")} is larger than one call takes (${i} bytes)`);(n.length===g1||s+i>Ub)&&(t.push(n),n=[],s=0),n.push(a),s+=i}return n.length>0&&t.push(n),t}function w1(e,t){let n=e.trim();if(n==="")return[];if(n.startsWith("["))try{let s=JSON.parse(n);if(Array.isArray(s)&&s.every(a=>typeof a=="object"&&a!==null&&!Array.isArray(a)))return s}catch{}return n.split(`
|
|
694
|
-
`).flatMap((s,a)=>{if(s.trim()==="")return[];try{let i=JSON.parse(s);if(typeof i!="object"||i===null||Array.isArray(i))throw new Error("not an object");return[i]}catch(i){throw m(`${t}:${a+1} is not a user (one JSON object a line): ${i instanceof Error?i.message:String(i)}`)}})}var Bb={name:"auth:import",summary:"bring users over with what they sign in with: ids, addresses, password hashes, providers, second factors, passkeys, open sessions",usage:"<file|folder> [--pepper-stdin]",details:["A folder holds import bodies, one a file (users-0001.json\u2026, each without its pepper); a file holds one such body, JSON lines (a user each) or one JSON array.","Password and recovery-code hashes keep the source's pepper: give it on stdin with --pepper-stdin \u2014 never on the command line.","Users go 1000 a call. One refused does not stop the others; a user whose id or address the project has is refused, never overwritten."],args:{min:1,max:1},flags:{"pepper-stdin":{type:"boolean",description:"read the source's pepper from stdin"}},scope:"environment",async run(e){let t=await b(e),n=e.args[0],s=m1(e.io.cwd,n),a;try{a=(await c1(s)).isDirectory()?(await p1(s)).filter(u=>/^users-\d+\.json$/.test(u)).sort().map(u=>h1(s,u)):[s]}catch(u){throw m(`${n} could not be read: ${u instanceof Error?u.message:String(u)}`)}let i=[],r;for(let u of a){let g=y1(await u1(u,"utf8"),u);if(i.push(...g.users),g.hash){if(r&&JSON.stringify(r)!==JSON.stringify(g.hash))throw m(`${u} names another hash than the files before it`);r=g.hash}}if(i.length===0)throw m(`${n} holds no user`);let o=i.some(u=>u.password_hash!==void 0||Array.isArray(u.recovery_code_hashes)&&u.recovery_code_hashes.length>0),l;if(o){if(e.flags["pepper-stdin"]!==!0)throw m("these users carry password hashes: give the source's pepper with --pepper-stdin",`palbase auth:import ${n} --pepper-stdin < pepper.txt`);l={...r??{algorithm:f1},pepper:await Me(e,"the source's pepper")}}await v(e,t,`bring ${i.length} user${i.length===1?"":"s"} into ${N(t)}'s auth`);let d={imported:0,errors:[],sessions_imported:0,sessions_skipped:0},p=0;for(let u of b1(i)){let g=await h(e,t,"POST","/admin/users/import",{...l?{hash:l}:{},users:u});d.imported+=g.imported,d.sessions_imported+=g.sessions_imported,d.sessions_skipped+=g.sessions_skipped;for(let y of g.errors??[])d.errors.push({...y,index:y.index+p});p+=u.length,p<i.length&&e.out.note(`${p} of ${i.length}\u2026`)}if(e.out.result(d,()=>{e.out.line(`Imported ${d.imported} of ${i.length} users (${d.sessions_imported} open sessions; ${d.sessions_skipped} ended ones left behind).`);for(let u of d.errors.slice(0,50))e.out.line(` ${u.id??`#${u.index+1}`}: ${u.error} \u2014 ${u.message}`);d.errors.length>50&&e.out.line(` \u2026and ${d.errors.length-50} more (--json lists every one)`)}),d.errors.length>0)throw new f("import_incomplete",`${d.errors.length} user${d.errors.length===1?" was":"s were"} not imported`)}};import{writeFile as Fb}from"node:fs/promises";import{resolve as Jb}from"node:path";var v1=/^usr_[A-Za-z0-9-]{1,64}$/;function on(e){if(!v1.test(e))throw m(`${JSON.stringify(e)} is not a user's id (usr_\u2026)`,"palbase auth:users:list shows them");return e}function ss(e,t,n,s){if(e===void 0)return;let a=Number(e);if(!Number.isInteger(a)||a<n||a>s)throw m(`--${t} is a whole number from ${n} to ${s}`);return a}function Vb(e,t){if(e===void 0)return;let n=/^(\d+)([smhd])$/.exec(String(e));if(!n)throw m(`--${t} is a span: 30m, 2h, 7d`);return Number(n[1])*{s:1,m:60,h:3600,d:86400}[n[2]]}var Et=e=>e?e.slice(0,16).replace("T"," "):"";function Fa(e){let t=[e.invited?"invited":"",e.email_verified===!1&&!e.invited?"unverified":"",e.banned?`banned${e.ban_reason?` (${A(e.ban_reason)})`:""}`:"",e.is_test?"test":"",e.has_mfa?"mfa":""].filter(Boolean);return`${A(e.id)} ${A(e.email??e.phone??"")}${t.length?` [${t.join(", ")}]`:""}`}var _1={name:"auth:users:list",summary:"the environment's users: id, email, verified, last sign-in; --banned for the banned alone",usage:"[--banned] [--limit <n>]",flags:{banned:{type:"boolean",description:"only the banned"},limit:{type:"string",value:"n",description:"how many at most (default 100)"}},scope:"environment",async run(e){let t=await b(e),n=ss(e.flags.limit,"limit",1,1e4)??100,s=[],a;do{let i=new URLSearchParams({limit:String(Math.min(100,n-s.length)),...a?{cursor:a}:{},...e.flags.banned===!0?{banned:"true"}:{}}),r=await h(e,t,"GET",`/admin/users?${i}`);s.push(...r.users),a=r.next_cursor||void 0}while(a&&s.length<n);e.out.result({users:s},()=>{s.length===0?e.out.line("No user yet."):e.out.table(s,[{header:"id",value:i=>i.id},{header:"email",value:i=>A(i.email??i.phone??"")},{header:"verified",value:i=>i.email_verified?"yes":"no"},{header:"last sign-in",value:i=>Et(i.last_login_at)},{header:"notes",value:i=>[i.banned?"banned":"",i.is_test?"test":"",i.has_mfa?"mfa":""].filter(Boolean).join(", ")}])})}},k1={name:"auth:users:get",summary:"one user: their email and phone, how they sign in, whether verified or banned, their roles",usage:"<user-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]),[s,a]=await Promise.all([h(e,t,"GET",`/admin/users/${k(n)}`),h(e,t,"GET",`/admin/users/${k(n)}/roles`).then(i=>Array.isArray(i)?i:i.roles??[])]);e.out.result({...s,roles:a},()=>{e.out.line(Fa(s)),e.out.line(` signs in with ${s.providers?.length?A(s.providers.join(", ")):"a password"}; made ${A(Et(s.created_at))}, last ${A(Et(s.last_login_at))||"never"}`),e.out.line(` roles: ${a.length?a.map(A).join(", "):"none"}`)})}},S1={name:"auth:users:create",summary:"make a user with an email and a password (read from stdin, never the command line)",usage:"<email> [--verified]",args:{min:1,max:1},flags:{verified:{type:"boolean",description:"their email is taken as verified"}},scope:"environment",async run(e){let t=await b(e),n=await Me(e,"the password");await v(e,t,`make the user ${e.args[0]}`);let s=await h(e,t,"POST","/admin/users",{email:e.args[0],password:n,...e.flags.verified===!0?{email_verified:!0}:{}},j());e.out.result(s,()=>e.out.line(`Made ${Fa(s)}.`))}},$1={name:"auth:users:invite",summary:"invite a person to an account of the environment: Palbase emails them a link that sets its password, valid 7 days",usage:"<email> [--no-email] [--redirect-to <url>] [--locale <tag>]",details:["An address no account has gets one, invited: it has no password, and cannot sign in with one, until the person sets it from the link. An account invited that has not taken it up is invited again: a new link, the earlier ones no longer open it, seven days from now. An address with an account is refused with that account's id: nothing is sent and its password is left as it is \u2014 give it what you invited it for yourself (a role: the admin API's PUT /admin/users/{uid}/roles/{role}).","The link opens Palbase's page at the environment's own address, where the person chooses the password; --redirect-to sends it to a page of your app's on the redirect allow-list instead, which takes the token to POST /auth/invitations/accept.","--no-email sends nothing and prints the link, for you to deliver: it sets the account's password, so give it to the person alone."],args:{min:1,max:1},flags:{"no-email":{type:"boolean",description:"send nothing: print the link, for you to deliver"},"redirect-to":{type:"string",value:"url",description:"a page of your app's, on the redirect allow-list, the link opens instead of Palbase's"},locale:{type:"string",value:"tag",description:"the email's and the page's language: en, tr (default: the environment's)"}},scope:"environment",async run(e){let t=await b(e),n=e.args[0];await v(e,t,`invite ${n}`);let s={email:n,...e.flags["no-email"]===!0?{send_email:!1}:{},...typeof e.flags["redirect-to"]=="string"?{redirect_to:e.flags["redirect-to"]}:{},...typeof e.flags.locale=="string"?{locale:e.flags.locale}:{}},a;try{a=await h(e,t,"POST","/admin/users/invite",s)}catch(r){let o=r instanceof E&&r.status===409&&r.code==="user_exists"?r.body:void 0,l=o?.user_id;if(typeof l!="string")throw r;let d=o?.email_verified===!1;throw new f("user_exists",`${n} has an account already (${A(l)}): it was not invited, nothing was sent, and its password is as it was.${d?" Its address is not confirmed: whoever made the account may not own the address.":""}`,{hint:d?`give it a role only once its address is confirmed (palbase auth:users:get ${l} says email_verified)`:`give it what you invited it for yourself: palbase auth:users:get ${l}`})}let{invitation:i}=a;e.out.result(a,()=>{let r=i.again?"Invited again":"Invited";i.emailed?e.out.line(`${r} ${Fa(a.user)}: Palbase emailed the link, valid until ${A(i.expires_at)}${i.again?"; the earlier links open it no more":""}.`):(e.out.line(`${r} ${Fa(a.user)}: nothing was sent. The link, valid until ${A(i.expires_at)}, sets the account's password: give it to the person alone.`),e.out.line(A(i.accept_url??"")))})}};function Gr(e,t,n,s,a,i={}){return{name:e,summary:t,usage:"<user-id>"+(i&&"reason"in i?" [--reason <text>]":""),args:{min:1,max:1},flags:i,scope:"environment",async run(r){let o=await b(r),l=on(r.args[0]);await v(r,o,n(l)),await s(r,o,l),r.out.result({user:l,done:e},()=>r.out.line(a(l)))}}}var P1=Gr("auth:users:delete","delete a user: their account, sessions and sign-ins go; backends hear user.deleted",e=>`delete the user ${e}`,(e,t,n)=>h(e,t,"DELETE",`/admin/users/${k(n)}`),e=>`Deleted ${e}.`),A1=Gr("auth:users:ban","ban a user: their sessions end and they cannot sign in until unbanned",e=>`ban the user ${e}`,(e,t,n)=>h(e,t,"POST",`/admin/users/${k(n)}/ban`,e.flags.reason===void 0?{}:{reason:e.flags.reason}),e=>`Banned ${e}.`,{reason:{type:"string",value:"text",description:"why (kept with the ban)"}}),R1=Gr("auth:users:unban","let a banned user sign in again",e=>`unban the user ${e}`,(e,t,n)=>h(e,t,"POST",`/admin/users/${k(n)}/unban`,{}),e=>`${e} may sign in again.`),T1=Gr("auth:users:sign-out","end every session of a user's: each device signs in again",e=>`end every session of ${e}`,(e,t,n)=>h(e,t,"POST",`/admin/users/${k(n)}/sessions/revoke-all`,{}),e=>`Every session of ${e} is ended.`),E1=/^[0-9]{6}$/;function zb(e){let t={};e.email!==void 0&&(t.email=String(e.email)),e.password!==void 0&&(t.password=String(e.password)),e.passwordless===!0&&(t.passwordless=!0),e.phone!==void 0&&(t.phone=String(e.phone));for(let[n,s]of[["otp","otp"],["email-otp","email_otp"]])if(e[n]!==void 0){if(!E1.test(String(e[n])))throw m(`--${n} is six digits`);t[s]=String(e[n])}if(e.unverified===!0&&(t.email_verified=!1),e.mfa!==void 0){if(!["totp","sms","email"].includes(String(e.mfa)))throw m("--mfa is totp, sms or email");t.mfa=String(e.mfa)}if(t.passwordless&&t.password!==void 0)throw m("--passwordless makes a user with no password: leave --password out");if(t.otp!==void 0&&t.phone===void 0)throw m("--otp is the fixed code of --phone: give --phone too");if(t.mfa==="sms"&&t.phone===void 0)throw m("--mfa sms is the user's phone: give --phone too");return Object.keys(t).length>0?t:void 0}function C1(e){let t=[`${A(e.user_id)} ${A(e.email??"")} ${e.password?`password ${A(e.password)}`:"no password"}${e.email_verified===!1?" (unverified)":""}`];return e.phone&&t.push(` phone ${A(e.phone)}, its fixed code ${A(e.otp??"")} (texted nothing)`),e.email_otp&&t.push(` email's fixed code ${A(e.email_otp)}`),e.mfa&&t.push(` second factor ${A(e.mfa)}${e.totp_secret?`, its key ${A(e.totp_secret)}`:""}`),e.access_token&&t.push(` access token: ${A(e.access_token)}`),t}var j1=30*6e4,O1=15e3;async function Hb(e,t,n,s){let a=e.io.now()+j1,i="";for(;;){try{return await s()}catch(o){if(!(o instanceof E)||o.status!==409||o.code!=="build_in_progress")throw o;i===""&&e.out.note(`${n} is not serving its newest code yet: no user is made until it does \u2014 waiting for its build`)}let r=e.io.now();for(;;){if(e.io.now()>=a)throw new f("timeout",`${n} was not serving its newest build after 30 minutes: no test user was made`,{hint:`palbase machines:builds ${n}`});await e.io.sleep(2e3);let o=await h(e,t,"GET",`/machines/${k(n)}`),{builds:l}=await h(e,t,"GET",`/machines/${k(n)}/builds?limit=1`),d=l[0],p=d!==void 0&&d.running&&o.running_version===o.version,u=o.build_requested||!d?"a build of its head is asked for":`build ${A(d.id.slice(0,8))} (${A(d.commit.slice(0,7))}): ${A(d.state)}${p?", serving":d.running?", rolling out":""}`;if(u!==i&&e.out.note(` ${u}`),i=u,d&&!o.build_requested&&(d.state==="failed"||d.state==="cancelled"||d.state==="skipped"))throw new f("build_failed",`${n}'s build ${d.state}${d.reason?`: ${A(d.reason)}`:""} \u2014 no test user was made`,{hint:`palbase machines:builds:log ${d.id} --machine ${n}`});if(d&&!o.build_requested&&d.state==="waiting_config")throw new f("build_waiting_config",`${n}'s build waits for the variables its .env.example names${d.missing_env?.length?`: ${d.missing_env.map(A).join(", ")}`:""} \u2014 no test user was made`,{hint:`palbase machines:env:set <NAME>=<value> --machine ${n}`});if(d?.state==="succeeded"&&p&&!o.build_requested||e.io.now()-r>=O1)break}}}var M1=new Set(["no_template","not_a_test_user","template_failed"]);function I1(e,t,n){if(!e.deleted)return`palbase auth:test-users:delete ${e.user_id}`;let s=`then palbase auth:test-users:create --template ${n} --machine ${t}`,a=(e.template.error??"").split(":")[0];return a==="no_template"?`palbase machines:builds ${t} shows the code that serves \u2014 name a template it has, or push the one you added; ${s}`:a==="template_failed"?`palbase machines:logs ${t} --since 15m shows why it failed; ${s}`:`palbase machines:get ${t}; ${s}`}var L1=/^[a-z][a-z0-9_-]{0,63}$/,Yb={type:"string",value:"name",description:"the machine whose backend has the template (default: the environment's only one)"};function Xb(e){if(typeof e!="string"||!L1.test(e))throw m(`${JSON.stringify(e??"")} is not a template's name: lowercase letters, digits, _ and -, a letter first`,"the backend's @TestUserTemplate({ name }) says it");return e}var Zb=e=>e instanceof E&&e.status===403&&/scope|closed/.test(e.code);async function Qb(e,t){let{machines:n}=await h(e,t,"GET",`/machines?limit=100&environment=${encodeURIComponent(t.env_ref)}`);return n.map(s=>s.name)}async function ew(e,t){let n=e.flags.machine;if(n!==void 0)return n;let s;try{s=await Qb(e,t)}catch(a){throw Zb(a)?m("this token does not list the machines: name the one whose backend has the template","--machine <name>"):a}if(s.length===1)return s[0];throw s.length===0?new f("no_machine","the environment has no machine: a template is written by a backend running on one",{hint:"palbase machines:create"}):m("which machine? name it",`the environment's machines: ${s.join(", ")} \u2014 --machine <name>`)}function tw(e){if(e.error)return` template ${A(e.name)} not written: ${A(e.error)}`;let t=Object.entries(e.rows??{}).map(([s,a])=>`${A(s)} ${a}`),n=e.commit?` by commit ${A(e.commit.slice(0,7))}`:"";return` template ${A(e.name)}${e.again?` (written before${n})`:n?` (${n.trim()})`:""}: ${t.length>0?t.join(", "):"no rows"}`}var D1={name:"auth:test-users:list",summary:"the environment's test users (made with its secret key; their tokens say test: true)",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/admin/test-users"),s=Array.isArray(n)?n:n.users;e.out.result({users:s},()=>{s.length===0&&e.out.line("No test user yet: palbase auth:test-users:create makes some.");for(let a of s)e.out.line(Fa(a))})}},x1={name:"auth:test-users:create",summary:"make test users for a suite, of the kind a sign-in asks for: their passwords (and a second factor's key), and with --token an access token each, shown this once; --template has the backend write the data a screen needs for each",usage:"[--count <n>] [--token] [--email <address>] [--password <pw> | --passwordless] [--phone <e164> [--otp <code>]] [--email-otp <code>] [--unverified] [--mfa totp|sms|email] [--template <name> [--machine <name>]]",details:["A test user signs in as any user does; its tokens say test: true, so a backend can tell them apart. --token gives each an access token at once, for a test that calls the backend as that user.","Its mail and texts are kept for it, read with palbase auth:test-users:messages <id> \u2014 a sign-in link, a verification or second factor's code: a made address (\u2026@test.invalid) is mailed nothing and a phone texted nothing, while --email with an address of yours gets its mail too.","Of the kind a sign-in asks for: --passwordless (a link, a code or a passkey alone), --unverified (its verification is tested), --phone with its fixed code (--otp, made when left out), --email-otp (a fixed code its email accepts: a reviewer reads no inbox), --mfa (a second factor from the start; totp answers its key once).","--template <name> has the backend write the data of its @TestUserTemplate({ name }) for each user \u2014 its seed for one account, in its own code (palbase/backend), run on the machine --machine names or the environment's only one, for test users alone. Each user is answered with the rows written, by table, and the commit whose code wrote them. A user is made with its template or not at all: one whose template was not written (no_template, not_a_test_user, template_failed, template_timeout, machine_unavailable) is deleted again, why and what to run next said on stderr and in the JSON's error, and the command ends with 1. At most 10 users at once with a template.","Right after a push the machine may still be building or rolling out its new code: the command waits until it serves \u2014 following the build, 30 minutes at most \u2014 and makes the users then, so a template you just added is found. A build that fails makes no user.","palbase auth:test-users:template writes another template for a user made with one; palbase auth:test-users:delete has the template undone before the user is deleted.","A pull request's preview is a machine of the environment's (<name>-pr<number>, as machines:list shows) and signs in the environment's users: --machine backend-pr1 has the preview's code write the template, into the preview's own database (<database>-pr<number>)."],flags:{count:{type:"string",value:"n",description:"how many (default 1, at most 100; 10 with --template)"},token:{type:"boolean",description:"an access token for each, too"},email:{type:"string",value:"address",description:"its address \u2014 one of yours gets its mail too (default: a made \u2026@test.invalid)"},password:{type:"string",value:"pw",description:"its password (default: a made one)"},passwordless:{type:"boolean",description:"no password: it signs in by a link, a code or a passkey"},phone:{type:"string",value:"e164",description:"a verified phone, texted nothing"},otp:{type:"string",value:"code",description:"the phone's fixed code, six digits (default: a made one)"},"email-otp":{type:"string",value:"code",description:"a fixed code its email accepts, six digits"},unverified:{type:"boolean",description:"its email unverified"},mfa:{type:"string",value:"totp|sms|email",description:"a second factor from the start"},template:{type:"string",value:"name",description:"a @TestUserTemplate of the backend's: its data written for each user"},machine:Yb},scope:"environment",async run(e){let t=await b(e);if(e.flags.template===void 0){if(e.flags.machine!==void 0)throw m("--machine names where --template is written: give --template too");let u=ss(e.flags.count,"count",1,100)??1,g=zb(e.flags);if(g&&(g.email!==void 0||g.phone!==void 0)&&u>1)throw m("--email and --phone are one user's: leave --count out");await v(e,t,`make ${u} test user(s)`);let y=g?{users:Array.from({length:u},()=>({...g})),with_tokens:e.flags.token===!0}:{count:u,with_tokens:e.flags.token===!0},w=await h(e,t,"POST","/admin/test-users",y,j());e.out.result(w,()=>{for(let _ of w.users)for(let P of C1(_))e.out.line(P);e.out.line("Shown this once. Their mail and texts: palbase auth:test-users:messages <id>.")});return}if(zb(e.flags)!==void 0)throw m("--template's users are made as its machine makes them: leave the kind flags out");let n=Xb(e.flags.template),s=ss(e.flags.count,"count",1,10)??1,a=await ew(e,t);await v(e,t,`make ${s} test user(s) with ${a}'s template ${n}`);let i={users:[]},r;for(let u=0;u<s;u++)try{let g=await Hb(e,t,a,()=>h(e,t,"POST",`/machines/${k(a)}/test-users`,{count:1,template:n,with_tokens:e.flags.token===!0},j()));i.users.push(...g.users);let y=(g.users[0]?.template?.error??"").split(":")[0];if(u<s-1&&M1.has(y)){r=new f(y,`${y} would be the same for the rest`);break}}catch(g){if(i.users.length===0)throw g;r=g;break}for(let u of i.users)u.template??={name:n,error:"template_failed: the platform said nothing of it"};let o=i.users.filter(u=>u.template.error),l=o.filter(u=>!u.deleted).length,d=r===void 0?"":` \u2014 stopped after ${i.users.length} of ${s}: ${r instanceof Error?r.message:String(r)}`,p=o.length===0&&r===void 0?void 0:{code:o.length>0?(o[0].template.error??"").split(":")[0]||"template_failed":r instanceof f||r instanceof E?r.code:"stopped",message:o.length>0?`${o.length} of ${i.users.length} test user(s) not made with ${a}'s template ${n}${l>0?` (${l} kept: see each)`:": none was kept"}${d}`:`${i.users.length} of ${s} test user(s) made with ${a}'s template ${n}${d}`};if(e.out.result({machine:a,...i,...p?{error:p}:{}},()=>{for(let u of i.users)u.deleted?e.out.line(`${A(u.user_id)} ${A(u.email??"")} deleted again: its template was not written`):(e.out.line(`${A(u.user_id)} ${A(u.email??"")} password ${A(u.password??"")}`),u.access_token&&e.out.line(` access token: ${A(u.access_token)}`)),e.out.line(tw(u.template));i.users.some(u=>!u.deleted)&&e.out.line("Shown this once.")}),p){e.out.note(`error: ${p.message}`);for(let u of o)e.out.note(` ${u.user_id}: ${u.template.error}${u.deleted?" \u2014 the user was deleted again":""}`),e.out.note(` next: ${I1(u,a,n)}`);return 1}}},N1={name:"auth:test-users:messages",summary:"a test user's mail and texts of the last 7 days, the 50 newest first: to whom, the code and the link each carried",usage:"<user-id> [--channel email|sms]",details:["What a flow sent the user \u2014 a sign-in link, a verification or second factor's code, the project's own mail \u2014 is kept for it: a test reads the code or link here. --json answers each whole: its subject, text, HTML and the variables its template had.","A user who is no test user is refused (not_a_test_user): no one else's mail is kept."],args:{min:1,max:1},flags:{channel:{type:"string",value:"email|sms",description:"only this channel's"}},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]),s=new URLSearchParams;if(e.flags.channel!==void 0){if(e.flags.channel!=="email"&&e.flags.channel!=="sms")throw m("--channel is email or sms");s.set("channel",String(e.flags.channel))}let a=s.toString(),i=await h(e,t,"GET",`/notify/test-users/${k(n)}/messages${a?`?${a}`:""}`);e.out.result(i,()=>{i.messages.length===0&&e.out.line(`Nothing was sent to ${A(n)} in the last 7 days.`);for(let r of i.messages)e.out.line(`${A(r.created_at)} ${A(r.channel)} to ${A(r.to)}${r.template?` ${A(r.template)}`:""}${r.delivered?" (sent too)":""}`),r.subject&&e.out.line(` subject: ${A(r.subject)}`),r.code&&e.out.line(` code: ${A(r.code)}`),r.link&&e.out.line(` link: ${A(r.link)}`)})}},q1={name:"auth:test-users:address",summary:"an address for an app's sign-up to be tested with: the account a sign-up with it opens is a test user, its mail kept for palbase auth:test-users:messages",usage:"",details:["The address (signup-\u2026@test.invalid) is typed into the app's sign-up form: the account it opens is a test user \u2014 its tokens say test: true, it is not counted as an active user, its verification mail is kept, never sent. Used once.","It holds a place of the environment's test-user cap until it is used, or lapses a day after it was made. A sign-up with any other address opens an ordinary user."],scope:"environment",async run(e){let t=await b(e);await v(e,t,"make a sign-up address for a test");let n=await h(e,t,"POST","/admin/test-users/addresses");e.out.result(n,()=>{e.out.line(A(n.email)),e.out.line(`Sign up with it once; unused, it lapses at ${A(n.expires_at)}. Its mail: palbase auth:test-users:messages <the new user's id>.`)})}},K1={name:"auth:test-users:template",summary:"have the backend write a @TestUserTemplate's data for a test user made with a template \u2014 the same one again answers what it wrote then",usage:"<user-id> <template> [--machine <name>]",details:["The user is one auth:test-users:create --template made on that machine: a test user is the machine's that made it. Asked again for a template it wrote, the platform answers what it wrote then, and the backend is not called: a template runs once for a user. The answer names the commit that wrote it \u2014 and when the machine serves other code now, says so: its rows are the older code's, and a new test user has the serving code's data.","Right after a push it waits, as auth:test-users:create does, until the machine serves its newest code."],args:{min:2,max:2},flags:{machine:Yb},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]),s=Xb(e.args[1]),a=await ew(e,t);await v(e,t,`write ${a}'s template ${s} for the test user ${n}`);let i=await Hb(e,t,a,()=>h(e,t,"POST",`/machines/${k(a)}/test-users/${k(n)}/templates/${k(s)}`));if(e.out.result({user:n,machine:a,template:i},()=>e.out.line(`${A(n)}${tw(i)}`)),i.note&&e.out.note(`note: ${i.note}`),i.error)return 1}},G1={name:"auth:test-users:delete",summary:"delete a test user \u2014 one made with a template has the backend undo it first",usage:"<user-id> [--machine <name>]",details:["A test user made with --template is deleted through the machine that made it: the backend's undo of each template runs first \u2014 a template with none, or one the serving code no longer has, leaves its data to user.deleted (what ownedByUser() owns goes with the user), and a warning says that undo did not run \u2014 and an undo that fails keeps the user, for the delete to be asked again. Any other test user is deleted at once.","A pull request preview's test users (made with --machine <name>-pr<number>) are deleted with the preview: its own database, their data, went with it.","Without --machine the environment's machines are asked which made the user; a token that does not list the machines deletes it at once, its templates left to user.deleted."],args:{min:1,max:1},flags:{machine:{type:"string",value:"name",description:"the machine that made the user with a template (default: whichever did)"}},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]);await v(e,t,`delete the test user ${n}`);let s=e.flags.machine,a=[],i=!1;if(s!==void 0)a=[s];else try{a=await Qb(e,t)}catch(d){if(!Zb(d))throw d;i=!0}let r,o=[];for(let d of a)try{o=(await h(e,t,"DELETE",`/machines/${k(d)}/test-users/${k(n)}`,void 0,{prefer:"return=representation"}))?.undo??[],r=d;break}catch(p){if(p instanceof E&&p.status===404)continue;throw p}if(r===void 0&&s!==void 0)throw new f("not_found",`${n} is no test user ${s} made with a template`,{hint:"leave --machine out: the machine that made it is found, and a test user made without a template is deleted at once"});r===void 0&&await h(e,t,"DELETE",`/admin/test-users/${k(n)}`);let l=o.filter(d=>!d.ran);for(let d of l)e.out.warn(`the undo of template ${d.template} did not run: ${d.note??"the program did not say why"}`);e.out.result({user:n,done:"auth:test-users:delete",...r!==void 0?{machine:r,undo:o}:{}},()=>{i&&e.out.note("this token does not list the machines: no template's undo was asked (user.deleted forgets what the user owned) \u2014 --machine <name> asks it"),r===void 0?e.out.line(`Deleted the test user ${n}.`):l.length===0?e.out.line(`Deleted the test user ${n}: ${r}'s backend undid its templates first.`):e.out.line(`Deleted the test user ${n} through ${r}: the undo of ${l.map(d=>d.template).join(", ")} did not run (see the warning).`)})}},U1={name:"flags:users:get",summary:"every flag as one user gets it now \u2014 their own values, the targeting, the defaults \u2014 as their client reads them",usage:"<user-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]),s=await h(e,t,"GET",`/flags/users/${k(n)}`);e.out.result({user:n,values:s.values},()=>{let a=Object.keys(s.values??{});a.length===0&&e.out.line("The environment has no flag yet.");for(let i of a.sort())e.out.line(`${A(i)} = ${JSON.stringify(s.values[i])}`)})}},B1={name:"flags:users:set",summary:"give a user a flag's value of their own, whatever its default and targeting say",usage:"<user-id> <key> <value>",args:{min:3,max:3},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]),s=e.args[1],a=jt(e.args[2]);await v(e,t,`give ${n} the value ${JSON.stringify(a)} of ${s}`),await h(e,t,"PUT",`/flags/users/${k(n)}/${k(s)}`,{value:a}),e.out.result({user:n,key:s,value:a},()=>e.out.line(`${n} gets ${s} = ${JSON.stringify(a)}.`))}},z1={name:"flags:users:unset",summary:"take a user's own value of a flag away, or every one with no key: the flag decides for them again",usage:"<user-id> [key]",args:{min:1,max:2},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]),s=e.args[1];await v(e,t,s?`take ${n}'s own value of ${s} away`:`take every value of ${n}'s own away`),await h(e,t,"DELETE",s?`/flags/users/${k(n)}/${k(s)}`:`/flags/users/${k(n)}`),e.out.result({user:n,key:s??null},()=>e.out.line(s?`${n} gets ${s} as the flag says.`:`${n} gets every flag as it says.`))}};function W1(e){let t=e===void 0?[]:Array.isArray(e)?e:[String(e)];if(t.length===0)return;let n={};for(let s of t){let a=s.indexOf("=");if(a<=0)throw m(`--var is name=value, not ${JSON.stringify(s)}`);n[s.slice(0,a)]=s.slice(a+1)}return n}var F1={name:"notify:send",summary:"send an email or a text through the environment's providers: written here, or a template with its variables",usage:"<email|sms> <to> [--template <slug> --var name=value\u2026] [--subject <s> --text <t> --html <h>] [--body <text>]",details:["A message is sent as a backend sends it (POST /notify/email, /notify/sms): its delivery is in palbase notify:messages."],args:{min:2,max:2},flags:{template:{type:"string",value:"slug",description:"a template of the environment (notify:templates:list)"},var:{type:"string",value:"name=value",multiple:!0,description:"a template's variable (again for each)"},locale:{type:"string",value:"locale",description:"the template's locale"},subject:{type:"string",value:"text",description:"an email's subject"},text:{type:"string",value:"text",description:"an email's text"},html:{type:"string",value:"html",description:"an email's HTML"},body:{type:"string",value:"text",description:"a text's words"}},scope:"environment",async run(e){let[t,n]=e.args;if(t!=="email"&&t!=="sms")throw m("notify:send email <to> or notify:send sms <to>");let s=await b(e),a=e.flags,i=W1(a.var),r={to:n,...a.template?{template:a.template}:{},...i?{variables:i}:{},...a.locale?{locale:a.locale}:{}};if(t==="email"){if(!a.template&&(a.subject===void 0||a.text===void 0&&a.html===void 0))throw m("an email is a --template, or a --subject with --text or --html");Object.assign(r,a.subject!==void 0?{subject:a.subject}:{},a.text!==void 0?{text:a.text}:{},a.html!==void 0?{html:a.html}:{})}else{if(!a.template&&a.body===void 0)throw m("a text is a --template or a --body");a.body!==void 0&&(r.body=a.body)}await v(e,s,`send ${t==="email"?"an email":"a text"} to ${n}`);let o=await h(e,s,"POST",`/notify/${t}`,r,j());e.out.result(o,()=>e.out.line(o.skipped?`Not sent to ${A(n)}: the user does not take this category (${A(o.message_id??"")}).`:`Queued to ${A(n)} (${A(o.message_id??"")}): palbase notify:messages says what became of it.`))}},J1={name:"notify:messages",summary:"the messages the environment sent, newest first, and what became of each",usage:"[--limit <n>]",flags:{limit:{type:"string",value:"n",description:"how many (default 20)"}},scope:"environment",async run(e){let t=await b(e),n=ss(e.flags.limit,"limit",1,100)??20,s=await h(e,t,"GET",`/notify/messages?limit=${n}`);e.out.result(s,()=>{s.messages.length===0?e.out.line("Nothing sent yet."):e.out.table(s.messages,[{header:"sent",value:a=>Et(a.created_at)},{header:"channel",value:a=>a.channel},{header:"to",value:a=>A(a.recipient_hint??"")},{header:"template",value:a=>A(a.template??"")},{header:"status",value:a=>`${a.status}${a.error?` (${A(a.error)})`:""}`},{header:"id",value:a=>a.id}])})}},V1={name:"notify:deliverability",summary:"whether each channel can send now, through which providers, and what to do when it cannot",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/notify/deliverability");e.out.result(n,()=>e.out.table(n.channels,[{header:"channel",value:s=>s.channel},{header:"sends",value:s=>s.ok?"yes":"no"},{header:"via",value:s=>A(s.via.join(" \u2192 "))||"-"},{header:"reports",value:s=>s.reports?"yes":"no"},{header:"why / what to do",value:s=>A([s.because,s.remedy].filter(Boolean).join(" \u2014 "))}]))}},Wb=["android","ios","ios_voip","web"],H1={name:"notify:devices:list",summary:"the devices a push reaches, newest first: each user's, and the installations no one is signed in on \u2014 never a token",usage:"[--user <id>] [--platform android|ios|ios_voip|web] [--limit <n>]",flags:{user:{type:"string",value:"id",description:"one user's devices"},platform:{type:"string",value:"platform",description:"one platform's: android, ios, ios_voip or web"},limit:{type:"string",value:"n",description:"how many (default 50, at most 500)"}},scope:"environment",async run(e){let t=e.flags;if(t.platform!==void 0&&!Wb.includes(String(t.platform)))throw m(`the platforms: ${Wb.join(", ")}`);let n=ss(t.limit,"limit",1,500)??50,s=await b(e),a=new URLSearchParams({limit:String(n)});t.user!==void 0&&a.set("user_id",String(t.user)),t.platform!==void 0&&a.set("platform",String(t.platform));let i=await h(e,s,"GET",`/notify/devices?${a}`);e.out.result(i,()=>{i.devices.length===0?e.out.line("No device: an app registers its device when it asks for push."):e.out.table(i.devices,[{header:"device",value:r=>A(r.device_id)},{header:"platform",value:r=>r.platform},{header:"user",value:r=>A(r.user_id??"(no one signed in)")},{header:"app",value:r=>A(r.app_version??"")},{header:"registered",value:r=>Et(r.created_at)},{header:"last used",value:r=>Et(r.last_used_at)}]),i.next_cursor&&e.out.line(`More than ${n}: --limit shows more, --user or --platform fewer.`)})}},Y1={name:"notify:devices:delete",summary:"forget a device \u2014 every token it registered, whoever is signed in on it, no one included: a push reaches it no more",usage:"<device_id>",details:["The device's id is the app's own name for it (notify:devices:list). The app registers it again when it next asks for push."],args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0],n=await b(e);await v(e,n,`forget the device ${t}: a push reaches it no more`);try{await h(e,n,"DELETE",`/notify/devices/${k(t)}`,void 0,j())}catch(s){throw s instanceof E&&s.status===404?new f("device_not_found",`the environment has no device ${A(t)}`,{hint:"palbase notify:devices:list shows its devices"}):s}e.out.result({deleted:t},()=>e.out.line(`Forgot the device ${A(t)}: a push reaches it no more.`))}},X1={name:"auth:audit",summary:"who did what in the environment's auth, newest first: sign-ins, changes to users and settings, admin actions",usage:"[--event <type>] [--limit <n>]",flags:{event:{type:"string",value:"type",description:"only this kind of event (user.login, admin.user.update\u2026)"},limit:{type:"string",value:"n",description:"how many at most (default 50)"}},scope:"environment",async run(e){let t=await b(e),n=ss(e.flags.limit,"limit",1,1e4)??50,s=[],a;do{let i=new URLSearchParams({limit:String(Math.min(100,n-s.length)),...a?{cursor:a}:{},...typeof e.flags.event=="string"?{event_type:e.flags.event}:{}}),r=await h(e,t,"GET",`/admin/audit?${i}`);s.push(...r.events),a=r.next_cursor||void 0}while(a&&s.length<n);e.out.result({events:s},()=>{s.length===0?e.out.line("Nothing recorded yet."):e.out.table(s,[{header:"when",value:i=>Et(i.created_at)},{header:"event",value:i=>A(i.event_type)},{header:"result",value:i=>A(i.result??"")},{header:"by",value:i=>A(i.actor?.email??i.actor?.user_id??"")},{header:"from",value:i=>A(i.actor?.ip??"")},{header:"on",value:i=>A([i.target_type,i.target_id].filter(Boolean).join(" "))}])})}},Z1={name:"auth:audit:verify",summary:"whether the audit trail is whole: each event chained to the one before, none changed or taken out",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/admin/audit/verify");if(!n.valid){let s=n.broken_at?` at event ${A(n.broken_at.event_id??"?")} (number ${(n.broken_at.index??0)+1} of ${n.total}, oldest first)`:"";throw new f("audit_trail_broken",`the audit trail is broken${s}: an event there was changed or taken out`)}e.out.result(n,()=>e.out.line(`The audit trail is whole: ${n.total} events, each chained to the one before.`))}},Q1={name:"auth:audit:export",summary:"the audit trail as a file: JSON lines or CSV, a span of it, one kind of event",usage:"[--format ndjson|csv] [--from <time>] [--to <time>] [--event <type>] [--out <file>]",flags:{format:{type:"string",value:"ndjson|csv",description:"JSON lines (default) or CSV"},from:{type:"string",value:"time",description:"from this time on (RFC 3339: 2026-10-01T00:00:00Z)"},to:{type:"string",value:"time",description:"up to this time"},event:{type:"string",value:"type",description:"only this kind of event"},out:{type:"string",value:"file",description:"write it here instead of to standard output"}},scope:"environment",async run(e){let t=e.flags.format??"ndjson";if(t!=="ndjson"&&t!=="csv")throw m("--format is ndjson or csv");for(let r of["from","to"]){let o=e.flags[r];if(o!==void 0&&Number.isNaN(Date.parse(String(o))))throw m(`--${r} is a time: 2026-10-01T00:00:00Z`)}let n=await b(e),s=new URLSearchParams({format:String(t)});for(let[r,o]of[["from","from"],["to","to"],["event","event_type"]])typeof e.flags[r]=="string"&&s.set(o,e.flags[r]);let a=await h(e,n,"GET",`/admin/audit/export?${s}`),i=typeof a=="string"?a:t==="ndjson"&&Array.isArray(a)?a.map(r=>JSON.stringify(r)).join(`
|
|
694
|
+
`).flatMap((s,a)=>{if(s.trim()==="")return[];try{let i=JSON.parse(s);if(typeof i!="object"||i===null||Array.isArray(i))throw new Error("not an object");return[i]}catch(i){throw m(`${t}:${a+1} is not a user (one JSON object a line): ${i instanceof Error?i.message:String(i)}`)}})}var Bb={name:"auth:import",summary:"bring users over with what they sign in with: ids, addresses, password hashes, providers, second factors, passkeys, open sessions",usage:"<file|folder> [--pepper-stdin]",details:["A folder holds import bodies, one a file (users-0001.json\u2026, each without its pepper); a file holds one such body, JSON lines (a user each) or one JSON array.","Password and recovery-code hashes keep the source's pepper: give it on stdin with --pepper-stdin \u2014 never on the command line.","Users go 1000 a call. One refused does not stop the others; a user whose id or address the project has is refused, never overwritten."],args:{min:1,max:1},flags:{"pepper-stdin":{type:"boolean",description:"read the source's pepper from stdin"}},scope:"environment",async run(e){let t=await b(e),n=e.args[0],s=m1(e.io.cwd,n),a;try{a=(await c1(s)).isDirectory()?(await p1(s)).filter(u=>/^users-\d+\.json$/.test(u)).sort().map(u=>h1(s,u)):[s]}catch(u){throw m(`${n} could not be read: ${u instanceof Error?u.message:String(u)}`)}let i=[],r;for(let u of a){let g=y1(await u1(u,"utf8"),u);if(i.push(...g.users),g.hash){if(r&&JSON.stringify(r)!==JSON.stringify(g.hash))throw m(`${u} names another hash than the files before it`);r=g.hash}}if(i.length===0)throw m(`${n} holds no user`);let o=i.some(u=>u.password_hash!==void 0||Array.isArray(u.recovery_code_hashes)&&u.recovery_code_hashes.length>0),l;if(o){if(e.flags["pepper-stdin"]!==!0)throw m("these users carry password hashes: give the source's pepper with --pepper-stdin",`palbase auth:import ${n} --pepper-stdin < pepper.txt`);l={...r??{algorithm:f1},pepper:await Me(e,"the source's pepper")}}await v(e,t,`bring ${i.length} user${i.length===1?"":"s"} into ${N(t)}'s auth`);let d={imported:0,errors:[],sessions_imported:0,sessions_skipped:0},p=0;for(let u of b1(i)){let g=await h(e,t,"POST","/admin/users/import",{...l?{hash:l}:{},users:u});d.imported+=g.imported,d.sessions_imported+=g.sessions_imported,d.sessions_skipped+=g.sessions_skipped;for(let y of g.errors??[])d.errors.push({...y,index:y.index+p});p+=u.length,p<i.length&&e.out.note(`${p} of ${i.length}\u2026`)}if(e.out.result(d,()=>{e.out.line(`Imported ${d.imported} of ${i.length} users (${d.sessions_imported} open sessions; ${d.sessions_skipped} ended ones left behind).`);for(let u of d.errors.slice(0,50))e.out.line(` ${u.id??`#${u.index+1}`}: ${u.error} \u2014 ${u.message}`);d.errors.length>50&&e.out.line(` \u2026and ${d.errors.length-50} more (--json lists every one)`)}),d.errors.length>0)throw new f("import_incomplete",`${d.errors.length} user${d.errors.length===1?" was":"s were"} not imported`)}};import{writeFile as Fb}from"node:fs/promises";import{resolve as Jb}from"node:path";var v1=/^usr_[A-Za-z0-9-]{1,64}$/;function on(e){if(!v1.test(e))throw m(`${JSON.stringify(e)} is not a user's id (usr_\u2026)`,"palbase auth:users:list shows them");return e}function ss(e,t,n,s){if(e===void 0)return;let a=Number(e);if(!Number.isInteger(a)||a<n||a>s)throw m(`--${t} is a whole number from ${n} to ${s}`);return a}function Vb(e,t){if(e===void 0)return;let n=/^(\d+)([smhd])$/.exec(String(e));if(!n)throw m(`--${t} is a span: 30m, 2h, 7d`);return Number(n[1])*{s:1,m:60,h:3600,d:86400}[n[2]]}var gt=e=>e?e.slice(0,16).replace("T"," "):"";function Fa(e){let t=[e.invited?"invited":"",e.email_verified===!1&&!e.invited?"unverified":"",e.banned?`banned${e.ban_reason?` (${A(e.ban_reason)})`:""}`:"",e.is_test?"test":"",e.has_mfa?"mfa":""].filter(Boolean);return`${A(e.id)} ${A(e.email??e.phone??"")}${t.length?` [${t.join(", ")}]`:""}`}var _1={name:"auth:users:list",summary:"the environment's users: id, email, verified, last sign-in; --banned for the banned alone",usage:"[--banned] [--limit <n>]",flags:{banned:{type:"boolean",description:"only the banned"},limit:{type:"string",value:"n",description:"how many at most (default 100)"}},scope:"environment",async run(e){let t=await b(e),n=ss(e.flags.limit,"limit",1,1e4)??100,s=[],a;do{let i=new URLSearchParams({limit:String(Math.min(100,n-s.length)),...a?{cursor:a}:{},...e.flags.banned===!0?{banned:"true"}:{}}),r=await h(e,t,"GET",`/admin/users?${i}`);s.push(...r.users),a=r.next_cursor||void 0}while(a&&s.length<n);e.out.result({users:s},()=>{s.length===0?e.out.line("No user yet."):e.out.table(s,[{header:"id",value:i=>i.id},{header:"email",value:i=>A(i.email??i.phone??"")},{header:"verified",value:i=>i.email_verified?"yes":"no"},{header:"last sign-in",value:i=>gt(i.last_login_at)},{header:"notes",value:i=>[i.banned?"banned":"",i.is_test?"test":"",i.has_mfa?"mfa":""].filter(Boolean).join(", ")}])})}},k1={name:"auth:users:get",summary:"one user: their email and phone, how they sign in, whether verified or banned, their roles",usage:"<user-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]),[s,a]=await Promise.all([h(e,t,"GET",`/admin/users/${k(n)}`),h(e,t,"GET",`/admin/users/${k(n)}/roles`).then(i=>Array.isArray(i)?i:i.roles??[])]);e.out.result({...s,roles:a},()=>{e.out.line(Fa(s));let i=A(gt(s.invited_at)),r=s.invited?`no password yet: invited${i?` ${i}`:""}, it is set from the invitation's link`:`signs in with ${s.providers?.length?A(s.providers.join(", ")):"a password"}`;e.out.line(` ${r}; made ${A(gt(s.created_at))}, last ${A(gt(s.last_login_at))||"never"}`),e.out.line(` roles: ${a.length?a.map(A).join(", "):"none"}`)})}},S1={name:"auth:users:create",summary:"make a user with an email and a password (read from stdin, never the command line)",usage:"<email> [--verified]",args:{min:1,max:1},flags:{verified:{type:"boolean",description:"their email is taken as verified"}},scope:"environment",async run(e){let t=await b(e),n=await Me(e,"the password");await v(e,t,`make the user ${e.args[0]}`);let s=await h(e,t,"POST","/admin/users",{email:e.args[0],password:n,...e.flags.verified===!0?{email_verified:!0}:{}},j());e.out.result(s,()=>e.out.line(`Made ${Fa(s)}.`))}},$1={name:"auth:users:invite",summary:"invite a person to an account of the environment: Palbase emails them a link that sets its password, valid 7 days",usage:"<email> [--no-email] [--redirect-to <url>] [--locale <tag>]",details:["An address no account has gets one, invited: it has no password, and cannot sign in with one, until the person sets it from the link. An account invited that has not taken it up is invited again: a new link, the earlier ones no longer open it, seven days from now. An address with an account is refused with that account's id: nothing is sent and its password is left as it is \u2014 give it what you invited it for yourself (a role: the admin API's PUT /admin/users/{uid}/roles/{role}).","The link opens Palbase's page at the environment's own address, where the person chooses the password; --redirect-to sends it to a page of your app's on the redirect allow-list instead, which takes the token to POST /auth/invitations/accept.","--no-email sends nothing and prints the link, for you to deliver: it sets the account's password, so give it to the person alone."],args:{min:1,max:1},flags:{"no-email":{type:"boolean",description:"send nothing: print the link, for you to deliver"},"redirect-to":{type:"string",value:"url",description:"a page of your app's, on the redirect allow-list, the link opens instead of Palbase's"},locale:{type:"string",value:"tag",description:"the email's and the page's language: en, tr (default: the environment's)"}},scope:"environment",async run(e){let t=await b(e),n=e.args[0];await v(e,t,`invite ${n}`);let s={email:n,...e.flags["no-email"]===!0?{send_email:!1}:{},...typeof e.flags["redirect-to"]=="string"?{redirect_to:e.flags["redirect-to"]}:{},...typeof e.flags.locale=="string"?{locale:e.flags.locale}:{}},a;try{a=await h(e,t,"POST","/admin/users/invite",s)}catch(r){let o=r instanceof E&&r.status===409&&r.code==="user_exists"?r.body:void 0,l=o?.user_id;if(typeof l!="string")throw r;let d=o?.email_verified===!1;throw new f("user_exists",`${n} has an account already (${A(l)}): it was not invited, nothing was sent, and its password is as it was.${d?" Its address is not confirmed: whoever made the account may not own the address.":""}`,{hint:d?`give it a role only once its address is confirmed (palbase auth:users:get ${l} says email_verified)`:`give it what you invited it for yourself: palbase auth:users:get ${l}`})}let{invitation:i}=a;e.out.result(a,()=>{let r=i.again?"Invited again":"Invited";i.emailed?e.out.line(`${r} ${Fa(a.user)}: Palbase emailed the link, valid until ${A(i.expires_at)}${i.again?"; the earlier links open it no more":""}.`):(e.out.line(`${r} ${Fa(a.user)}: nothing was sent. The link, valid until ${A(i.expires_at)}, sets the account's password: give it to the person alone.`),e.out.line(A(i.accept_url??"")))})}};function Gr(e,t,n,s,a,i={}){return{name:e,summary:t,usage:"<user-id>"+(i&&"reason"in i?" [--reason <text>]":""),args:{min:1,max:1},flags:i,scope:"environment",async run(r){let o=await b(r),l=on(r.args[0]);await v(r,o,n(l)),await s(r,o,l),r.out.result({user:l,done:e},()=>r.out.line(a(l)))}}}var P1=Gr("auth:users:delete","delete a user: their account, sessions and sign-ins go; backends hear user.deleted",e=>`delete the user ${e}`,(e,t,n)=>h(e,t,"DELETE",`/admin/users/${k(n)}`),e=>`Deleted ${e}.`),A1=Gr("auth:users:ban","ban a user: their sessions end and they cannot sign in until unbanned",e=>`ban the user ${e}`,(e,t,n)=>h(e,t,"POST",`/admin/users/${k(n)}/ban`,e.flags.reason===void 0?{}:{reason:e.flags.reason}),e=>`Banned ${e}.`,{reason:{type:"string",value:"text",description:"why (kept with the ban)"}}),R1=Gr("auth:users:unban","let a banned user sign in again",e=>`unban the user ${e}`,(e,t,n)=>h(e,t,"POST",`/admin/users/${k(n)}/unban`,{}),e=>`${e} may sign in again.`),T1=Gr("auth:users:sign-out","end every session of a user's: each device signs in again",e=>`end every session of ${e}`,(e,t,n)=>h(e,t,"POST",`/admin/users/${k(n)}/sessions/revoke-all`,{}),e=>`Every session of ${e} is ended.`),E1=/^[0-9]{6}$/;function zb(e){let t={};e.email!==void 0&&(t.email=String(e.email)),e.password!==void 0&&(t.password=String(e.password)),e.passwordless===!0&&(t.passwordless=!0),e.phone!==void 0&&(t.phone=String(e.phone));for(let[n,s]of[["otp","otp"],["email-otp","email_otp"]])if(e[n]!==void 0){if(!E1.test(String(e[n])))throw m(`--${n} is six digits`);t[s]=String(e[n])}if(e.unverified===!0&&(t.email_verified=!1),e.mfa!==void 0){if(!["totp","sms","email"].includes(String(e.mfa)))throw m("--mfa is totp, sms or email");t.mfa=String(e.mfa)}if(t.passwordless&&t.password!==void 0)throw m("--passwordless makes a user with no password: leave --password out");if(t.otp!==void 0&&t.phone===void 0)throw m("--otp is the fixed code of --phone: give --phone too");if(t.mfa==="sms"&&t.phone===void 0)throw m("--mfa sms is the user's phone: give --phone too");return Object.keys(t).length>0?t:void 0}function C1(e){let t=[`${A(e.user_id)} ${A(e.email??"")} ${e.password?`password ${A(e.password)}`:"no password"}${e.email_verified===!1?" (unverified)":""}`];return e.phone&&t.push(` phone ${A(e.phone)}, its fixed code ${A(e.otp??"")} (texted nothing)`),e.email_otp&&t.push(` email's fixed code ${A(e.email_otp)}`),e.mfa&&t.push(` second factor ${A(e.mfa)}${e.totp_secret?`, its key ${A(e.totp_secret)}`:""}`),e.access_token&&t.push(` access token: ${A(e.access_token)}`),t}var j1=30*6e4,O1=15e3;async function Hb(e,t,n,s){let a=e.io.now()+j1,i="";for(;;){try{return await s()}catch(o){if(!(o instanceof E)||o.status!==409||o.code!=="build_in_progress")throw o;i===""&&e.out.note(`${n} is not serving its newest code yet: no user is made until it does \u2014 waiting for its build`)}let r=e.io.now();for(;;){if(e.io.now()>=a)throw new f("timeout",`${n} was not serving its newest build after 30 minutes: no test user was made`,{hint:`palbase machines:builds ${n}`});await e.io.sleep(2e3);let o=await h(e,t,"GET",`/machines/${k(n)}`),{builds:l}=await h(e,t,"GET",`/machines/${k(n)}/builds?limit=1`),d=l[0],p=d!==void 0&&d.running&&o.running_version===o.version,u=o.build_requested||!d?"a build of its head is asked for":`build ${A(d.id.slice(0,8))} (${A(d.commit.slice(0,7))}): ${A(d.state)}${p?", serving":d.running?", rolling out":""}`;if(u!==i&&e.out.note(` ${u}`),i=u,d&&!o.build_requested&&(d.state==="failed"||d.state==="cancelled"||d.state==="skipped"))throw new f("build_failed",`${n}'s build ${d.state}${d.reason?`: ${A(d.reason)}`:""} \u2014 no test user was made`,{hint:`palbase machines:builds:log ${d.id} --machine ${n}`});if(d&&!o.build_requested&&d.state==="waiting_config")throw new f("build_waiting_config",`${n}'s build waits for the variables its .env.example names${d.missing_env?.length?`: ${d.missing_env.map(A).join(", ")}`:""} \u2014 no test user was made`,{hint:`palbase machines:env:set <NAME>=<value> --machine ${n}`});if(d?.state==="succeeded"&&p&&!o.build_requested||e.io.now()-r>=O1)break}}}var M1=new Set(["no_template","not_a_test_user","template_failed"]);function I1(e,t,n){if(!e.deleted)return`palbase auth:test-users:delete ${e.user_id}`;let s=`then palbase auth:test-users:create --template ${n} --machine ${t}`,a=(e.template.error??"").split(":")[0];return a==="no_template"?`palbase machines:builds ${t} shows the code that serves \u2014 name a template it has, or push the one you added; ${s}`:a==="template_failed"?`palbase machines:logs ${t} --since 15m shows why it failed; ${s}`:`palbase machines:get ${t}; ${s}`}var L1=/^[a-z][a-z0-9_-]{0,63}$/,Yb={type:"string",value:"name",description:"the machine whose backend has the template (default: the environment's only one)"};function Xb(e){if(typeof e!="string"||!L1.test(e))throw m(`${JSON.stringify(e??"")} is not a template's name: lowercase letters, digits, _ and -, a letter first`,"the backend's @TestUserTemplate({ name }) says it");return e}var Zb=e=>e instanceof E&&e.status===403&&/scope|closed/.test(e.code);async function Qb(e,t){let{machines:n}=await h(e,t,"GET",`/machines?limit=100&environment=${encodeURIComponent(t.env_ref)}`);return n.map(s=>s.name)}async function ew(e,t){let n=e.flags.machine;if(n!==void 0)return n;let s;try{s=await Qb(e,t)}catch(a){throw Zb(a)?m("this token does not list the machines: name the one whose backend has the template","--machine <name>"):a}if(s.length===1)return s[0];throw s.length===0?new f("no_machine","the environment has no machine: a template is written by a backend running on one",{hint:"palbase machines:create"}):m("which machine? name it",`the environment's machines: ${s.join(", ")} \u2014 --machine <name>`)}function tw(e){if(e.error)return` template ${A(e.name)} not written: ${A(e.error)}`;let t=Object.entries(e.rows??{}).map(([s,a])=>`${A(s)} ${a}`),n=e.commit?` by commit ${A(e.commit.slice(0,7))}`:"";return` template ${A(e.name)}${e.again?` (written before${n})`:n?` (${n.trim()})`:""}: ${t.length>0?t.join(", "):"no rows"}`}var D1={name:"auth:test-users:list",summary:"the environment's test users (made with its secret key; their tokens say test: true)",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/admin/test-users"),s=Array.isArray(n)?n:n.users;e.out.result({users:s},()=>{s.length===0&&e.out.line("No test user yet: palbase auth:test-users:create makes some.");for(let a of s)e.out.line(Fa(a))})}},x1={name:"auth:test-users:create",summary:"make test users for a suite, of the kind a sign-in asks for: their passwords (and a second factor's key), and with --token an access token each, shown this once; --template has the backend write the data a screen needs for each",usage:"[--count <n>] [--token] [--email <address>] [--password <pw> | --passwordless] [--phone <e164> [--otp <code>]] [--email-otp <code>] [--unverified] [--mfa totp|sms|email] [--template <name> [--machine <name>]]",details:["A test user signs in as any user does; its tokens say test: true, so a backend can tell them apart. --token gives each an access token at once, for a test that calls the backend as that user.","Its mail and texts are kept for it, read with palbase auth:test-users:messages <id> \u2014 a sign-in link, a verification or second factor's code: a made address (\u2026@test.invalid) is mailed nothing and a phone texted nothing, while --email with an address of yours gets its mail too.","Of the kind a sign-in asks for: --passwordless (a link, a code or a passkey alone), --unverified (its verification is tested), --phone with its fixed code (--otp, made when left out), --email-otp (a fixed code its email accepts: a reviewer reads no inbox), --mfa (a second factor from the start; totp answers its key once).","--template <name> has the backend write the data of its @TestUserTemplate({ name }) for each user \u2014 its seed for one account, in its own code (palbase/backend), run on the machine --machine names or the environment's only one, for test users alone. Each user is answered with the rows written, by table, and the commit whose code wrote them. A user is made with its template or not at all: one whose template was not written (no_template, not_a_test_user, template_failed, template_timeout, machine_unavailable) is deleted again, why and what to run next said on stderr and in the JSON's error, and the command ends with 1. At most 10 users at once with a template.","Right after a push the machine may still be building or rolling out its new code: the command waits until it serves \u2014 following the build, 30 minutes at most \u2014 and makes the users then, so a template you just added is found. A build that fails makes no user.","palbase auth:test-users:template writes another template for a user made with one; palbase auth:test-users:delete has the template undone before the user is deleted.","A pull request's preview is a machine of the environment's (<name>-pr<number>, as machines:list shows) and signs in the environment's users: --machine backend-pr1 has the preview's code write the template, into the preview's own database (<database>-pr<number>)."],flags:{count:{type:"string",value:"n",description:"how many (default 1, at most 100; 10 with --template)"},token:{type:"boolean",description:"an access token for each, too"},email:{type:"string",value:"address",description:"its address \u2014 one of yours gets its mail too (default: a made \u2026@test.invalid)"},password:{type:"string",value:"pw",description:"its password (default: a made one)"},passwordless:{type:"boolean",description:"no password: it signs in by a link, a code or a passkey"},phone:{type:"string",value:"e164",description:"a verified phone, texted nothing"},otp:{type:"string",value:"code",description:"the phone's fixed code, six digits (default: a made one)"},"email-otp":{type:"string",value:"code",description:"a fixed code its email accepts, six digits"},unverified:{type:"boolean",description:"its email unverified"},mfa:{type:"string",value:"totp|sms|email",description:"a second factor from the start"},template:{type:"string",value:"name",description:"a @TestUserTemplate of the backend's: its data written for each user"},machine:Yb},scope:"environment",async run(e){let t=await b(e);if(e.flags.template===void 0){if(e.flags.machine!==void 0)throw m("--machine names where --template is written: give --template too");let u=ss(e.flags.count,"count",1,100)??1,g=zb(e.flags);if(g&&(g.email!==void 0||g.phone!==void 0)&&u>1)throw m("--email and --phone are one user's: leave --count out");await v(e,t,`make ${u} test user(s)`);let y=g?{users:Array.from({length:u},()=>({...g})),with_tokens:e.flags.token===!0}:{count:u,with_tokens:e.flags.token===!0},w=await h(e,t,"POST","/admin/test-users",y,j());e.out.result(w,()=>{for(let _ of w.users)for(let P of C1(_))e.out.line(P);e.out.line("Shown this once. Their mail and texts: palbase auth:test-users:messages <id>.")});return}if(zb(e.flags)!==void 0)throw m("--template's users are made as its machine makes them: leave the kind flags out");let n=Xb(e.flags.template),s=ss(e.flags.count,"count",1,10)??1,a=await ew(e,t);await v(e,t,`make ${s} test user(s) with ${a}'s template ${n}`);let i={users:[]},r;for(let u=0;u<s;u++)try{let g=await Hb(e,t,a,()=>h(e,t,"POST",`/machines/${k(a)}/test-users`,{count:1,template:n,with_tokens:e.flags.token===!0},j()));i.users.push(...g.users);let y=(g.users[0]?.template?.error??"").split(":")[0];if(u<s-1&&M1.has(y)){r=new f(y,`${y} would be the same for the rest`);break}}catch(g){if(i.users.length===0)throw g;r=g;break}for(let u of i.users)u.template??={name:n,error:"template_failed: the platform said nothing of it"};let o=i.users.filter(u=>u.template.error),l=o.filter(u=>!u.deleted).length,d=r===void 0?"":` \u2014 stopped after ${i.users.length} of ${s}: ${r instanceof Error?r.message:String(r)}`,p=o.length===0&&r===void 0?void 0:{code:o.length>0?(o[0].template.error??"").split(":")[0]||"template_failed":r instanceof f||r instanceof E?r.code:"stopped",message:o.length>0?`${o.length} of ${i.users.length} test user(s) not made with ${a}'s template ${n}${l>0?` (${l} kept: see each)`:": none was kept"}${d}`:`${i.users.length} of ${s} test user(s) made with ${a}'s template ${n}${d}`};if(e.out.result({machine:a,...i,...p?{error:p}:{}},()=>{for(let u of i.users)u.deleted?e.out.line(`${A(u.user_id)} ${A(u.email??"")} deleted again: its template was not written`):(e.out.line(`${A(u.user_id)} ${A(u.email??"")} password ${A(u.password??"")}`),u.access_token&&e.out.line(` access token: ${A(u.access_token)}`)),e.out.line(tw(u.template));i.users.some(u=>!u.deleted)&&e.out.line("Shown this once.")}),p){e.out.note(`error: ${p.message}`);for(let u of o)e.out.note(` ${u.user_id}: ${u.template.error}${u.deleted?" \u2014 the user was deleted again":""}`),e.out.note(` next: ${I1(u,a,n)}`);return 1}}},N1={name:"auth:test-users:messages",summary:"a test user's mail and texts of the last 7 days, the 50 newest first: to whom, the code and the link each carried",usage:"<user-id> [--channel email|sms]",details:["What a flow sent the user \u2014 a sign-in link, a verification or second factor's code, the project's own mail \u2014 is kept for it: a test reads the code or link here. --json answers each whole: its subject, text, HTML and the variables its template had.","A user who is no test user is refused (not_a_test_user): no one else's mail is kept."],args:{min:1,max:1},flags:{channel:{type:"string",value:"email|sms",description:"only this channel's"}},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]),s=new URLSearchParams;if(e.flags.channel!==void 0){if(e.flags.channel!=="email"&&e.flags.channel!=="sms")throw m("--channel is email or sms");s.set("channel",String(e.flags.channel))}let a=s.toString(),i=await h(e,t,"GET",`/notify/test-users/${k(n)}/messages${a?`?${a}`:""}`);e.out.result(i,()=>{i.messages.length===0&&e.out.line(`Nothing was sent to ${A(n)} in the last 7 days.`);for(let r of i.messages)e.out.line(`${A(r.created_at)} ${A(r.channel)} to ${A(r.to)}${r.template?` ${A(r.template)}`:""}${r.delivered?" (sent too)":""}`),r.subject&&e.out.line(` subject: ${A(r.subject)}`),r.code&&e.out.line(` code: ${A(r.code)}`),r.link&&e.out.line(` link: ${A(r.link)}`)})}},q1={name:"auth:test-users:address",summary:"an address for an app's sign-up to be tested with: the account a sign-up with it opens is a test user, its mail kept for palbase auth:test-users:messages",usage:"",details:["The address (signup-\u2026@test.invalid) is typed into the app's sign-up form: the account it opens is a test user \u2014 its tokens say test: true, it is not counted as an active user, its verification mail is kept, never sent. Used once.","It holds a place of the environment's test-user cap until it is used, or lapses a day after it was made. A sign-up with any other address opens an ordinary user."],scope:"environment",async run(e){let t=await b(e);await v(e,t,"make a sign-up address for a test");let n=await h(e,t,"POST","/admin/test-users/addresses");e.out.result(n,()=>{e.out.line(A(n.email)),e.out.line(`Sign up with it once; unused, it lapses at ${A(n.expires_at)}. Its mail: palbase auth:test-users:messages <the new user's id>.`)})}},K1={name:"auth:test-users:template",summary:"have the backend write a @TestUserTemplate's data for a test user made with a template \u2014 the same one again answers what it wrote then",usage:"<user-id> <template> [--machine <name>]",details:["The user is one auth:test-users:create --template made on that machine: a test user is the machine's that made it. Asked again for a template it wrote, the platform answers what it wrote then, and the backend is not called: a template runs once for a user. The answer names the commit that wrote it \u2014 and when the machine serves other code now, says so: its rows are the older code's, and a new test user has the serving code's data.","Right after a push it waits, as auth:test-users:create does, until the machine serves its newest code."],args:{min:2,max:2},flags:{machine:Yb},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]),s=Xb(e.args[1]),a=await ew(e,t);await v(e,t,`write ${a}'s template ${s} for the test user ${n}`);let i=await Hb(e,t,a,()=>h(e,t,"POST",`/machines/${k(a)}/test-users/${k(n)}/templates/${k(s)}`));if(e.out.result({user:n,machine:a,template:i},()=>e.out.line(`${A(n)}${tw(i)}`)),i.note&&e.out.note(`note: ${i.note}`),i.error)return 1}},G1={name:"auth:test-users:delete",summary:"delete a test user \u2014 one made with a template has the backend undo it first",usage:"<user-id> [--machine <name>]",details:["A test user made with --template is deleted through the machine that made it: the backend's undo of each template runs first \u2014 a template with none, or one the serving code no longer has, leaves its data to user.deleted (what ownedByUser() owns goes with the user), and a warning says that undo did not run \u2014 and an undo that fails keeps the user, for the delete to be asked again. Any other test user is deleted at once.","A pull request preview's test users (made with --machine <name>-pr<number>) are deleted with the preview: its own database, their data, went with it.","Without --machine the environment's machines are asked which made the user; a token that does not list the machines deletes it at once, its templates left to user.deleted."],args:{min:1,max:1},flags:{machine:{type:"string",value:"name",description:"the machine that made the user with a template (default: whichever did)"}},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]);await v(e,t,`delete the test user ${n}`);let s=e.flags.machine,a=[],i=!1;if(s!==void 0)a=[s];else try{a=await Qb(e,t)}catch(d){if(!Zb(d))throw d;i=!0}let r,o=[];for(let d of a)try{o=(await h(e,t,"DELETE",`/machines/${k(d)}/test-users/${k(n)}`,void 0,{prefer:"return=representation"}))?.undo??[],r=d;break}catch(p){if(p instanceof E&&p.status===404)continue;throw p}if(r===void 0&&s!==void 0)throw new f("not_found",`${n} is no test user ${s} made with a template`,{hint:"leave --machine out: the machine that made it is found, and a test user made without a template is deleted at once"});r===void 0&&await h(e,t,"DELETE",`/admin/test-users/${k(n)}`);let l=o.filter(d=>!d.ran);for(let d of l)e.out.warn(`the undo of template ${d.template} did not run: ${d.note??"the program did not say why"}`);e.out.result({user:n,done:"auth:test-users:delete",...r!==void 0?{machine:r,undo:o}:{}},()=>{i&&e.out.note("this token does not list the machines: no template's undo was asked (user.deleted forgets what the user owned) \u2014 --machine <name> asks it"),r===void 0?e.out.line(`Deleted the test user ${n}.`):l.length===0?e.out.line(`Deleted the test user ${n}: ${r}'s backend undid its templates first.`):e.out.line(`Deleted the test user ${n} through ${r}: the undo of ${l.map(d=>d.template).join(", ")} did not run (see the warning).`)})}},U1={name:"flags:users:get",summary:"every flag as one user gets it now \u2014 their own values, the targeting, the defaults \u2014 as their client reads them",usage:"<user-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]),s=await h(e,t,"GET",`/flags/users/${k(n)}`);e.out.result({user:n,values:s.values},()=>{let a=Object.keys(s.values??{});a.length===0&&e.out.line("The environment has no flag yet.");for(let i of a.sort())e.out.line(`${A(i)} = ${JSON.stringify(s.values[i])}`)})}},B1={name:"flags:users:set",summary:"give a user a flag's value of their own, whatever its default and targeting say",usage:"<user-id> <key> <value>",args:{min:3,max:3},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]),s=e.args[1],a=jt(e.args[2]);await v(e,t,`give ${n} the value ${JSON.stringify(a)} of ${s}`),await h(e,t,"PUT",`/flags/users/${k(n)}/${k(s)}`,{value:a}),e.out.result({user:n,key:s,value:a},()=>e.out.line(`${n} gets ${s} = ${JSON.stringify(a)}.`))}},z1={name:"flags:users:unset",summary:"take a user's own value of a flag away, or every one with no key: the flag decides for them again",usage:"<user-id> [key]",args:{min:1,max:2},scope:"environment",async run(e){let t=await b(e),n=on(e.args[0]),s=e.args[1];await v(e,t,s?`take ${n}'s own value of ${s} away`:`take every value of ${n}'s own away`),await h(e,t,"DELETE",s?`/flags/users/${k(n)}/${k(s)}`:`/flags/users/${k(n)}`),e.out.result({user:n,key:s??null},()=>e.out.line(s?`${n} gets ${s} as the flag says.`:`${n} gets every flag as it says.`))}};function W1(e){let t=e===void 0?[]:Array.isArray(e)?e:[String(e)];if(t.length===0)return;let n={};for(let s of t){let a=s.indexOf("=");if(a<=0)throw m(`--var is name=value, not ${JSON.stringify(s)}`);n[s.slice(0,a)]=s.slice(a+1)}return n}var F1={name:"notify:send",summary:"send an email or a text through the environment's providers: written here, or a template with its variables",usage:"<email|sms> <to> [--template <slug> --var name=value\u2026] [--subject <s> --text <t> --html <h>] [--body <text>]",details:["A message is sent as a backend sends it (POST /notify/email, /notify/sms): its delivery is in palbase notify:messages."],args:{min:2,max:2},flags:{template:{type:"string",value:"slug",description:"a template of the environment (notify:templates:list)"},var:{type:"string",value:"name=value",multiple:!0,description:"a template's variable (again for each)"},locale:{type:"string",value:"locale",description:"the template's locale"},subject:{type:"string",value:"text",description:"an email's subject"},text:{type:"string",value:"text",description:"an email's text"},html:{type:"string",value:"html",description:"an email's HTML"},body:{type:"string",value:"text",description:"a text's words"}},scope:"environment",async run(e){let[t,n]=e.args;if(t!=="email"&&t!=="sms")throw m("notify:send email <to> or notify:send sms <to>");let s=await b(e),a=e.flags,i=W1(a.var),r={to:n,...a.template?{template:a.template}:{},...i?{variables:i}:{},...a.locale?{locale:a.locale}:{}};if(t==="email"){if(!a.template&&(a.subject===void 0||a.text===void 0&&a.html===void 0))throw m("an email is a --template, or a --subject with --text or --html");Object.assign(r,a.subject!==void 0?{subject:a.subject}:{},a.text!==void 0?{text:a.text}:{},a.html!==void 0?{html:a.html}:{})}else{if(!a.template&&a.body===void 0)throw m("a text is a --template or a --body");a.body!==void 0&&(r.body=a.body)}await v(e,s,`send ${t==="email"?"an email":"a text"} to ${n}`);let o=await h(e,s,"POST",`/notify/${t}`,r,j());e.out.result(o,()=>e.out.line(o.skipped?`Not sent to ${A(n)}: the user does not take this category (${A(o.message_id??"")}).`:`Queued to ${A(n)} (${A(o.message_id??"")}): palbase notify:messages says what became of it.`))}},J1={name:"notify:messages",summary:"the messages the environment sent, newest first, and what became of each",usage:"[--limit <n>]",flags:{limit:{type:"string",value:"n",description:"how many (default 20)"}},scope:"environment",async run(e){let t=await b(e),n=ss(e.flags.limit,"limit",1,100)??20,s=await h(e,t,"GET",`/notify/messages?limit=${n}`);e.out.result(s,()=>{s.messages.length===0?e.out.line("Nothing sent yet."):e.out.table(s.messages,[{header:"sent",value:a=>gt(a.created_at)},{header:"channel",value:a=>a.channel},{header:"to",value:a=>A(a.recipient_hint??"")},{header:"template",value:a=>A(a.template??"")},{header:"status",value:a=>`${a.status}${a.error?` (${A(a.error)})`:""}`},{header:"id",value:a=>a.id}])})}},V1={name:"notify:deliverability",summary:"whether each channel can send now, through which providers, and what to do when it cannot",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/notify/deliverability");e.out.result(n,()=>e.out.table(n.channels,[{header:"channel",value:s=>s.channel},{header:"sends",value:s=>s.ok?"yes":"no"},{header:"via",value:s=>A(s.via.join(" \u2192 "))||"-"},{header:"reports",value:s=>s.reports?"yes":"no"},{header:"why / what to do",value:s=>A([s.because,s.remedy].filter(Boolean).join(" \u2014 "))}]))}},Wb=["android","ios","ios_voip","web"],H1={name:"notify:devices:list",summary:"the devices a push reaches, newest first: each user's, and the installations no one is signed in on \u2014 never a token",usage:"[--user <id>] [--platform android|ios|ios_voip|web] [--limit <n>]",flags:{user:{type:"string",value:"id",description:"one user's devices"},platform:{type:"string",value:"platform",description:"one platform's: android, ios, ios_voip or web"},limit:{type:"string",value:"n",description:"how many (default 50, at most 500)"}},scope:"environment",async run(e){let t=e.flags;if(t.platform!==void 0&&!Wb.includes(String(t.platform)))throw m(`the platforms: ${Wb.join(", ")}`);let n=ss(t.limit,"limit",1,500)??50,s=await b(e),a=new URLSearchParams({limit:String(n)});t.user!==void 0&&a.set("user_id",String(t.user)),t.platform!==void 0&&a.set("platform",String(t.platform));let i=await h(e,s,"GET",`/notify/devices?${a}`);e.out.result(i,()=>{i.devices.length===0?e.out.line("No device: an app registers its device when it asks for push."):e.out.table(i.devices,[{header:"device",value:r=>A(r.device_id)},{header:"platform",value:r=>r.platform},{header:"user",value:r=>A(r.user_id??"(no one signed in)")},{header:"app",value:r=>A(r.app_version??"")},{header:"registered",value:r=>gt(r.created_at)},{header:"last used",value:r=>gt(r.last_used_at)}]),i.next_cursor&&e.out.line(`More than ${n}: --limit shows more, --user or --platform fewer.`)})}},Y1={name:"notify:devices:delete",summary:"forget a device \u2014 every token it registered, whoever is signed in on it, no one included: a push reaches it no more",usage:"<device_id>",details:["The device's id is the app's own name for it (notify:devices:list). The app registers it again when it next asks for push."],args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0],n=await b(e);await v(e,n,`forget the device ${t}: a push reaches it no more`);try{await h(e,n,"DELETE",`/notify/devices/${k(t)}`,void 0,j())}catch(s){throw s instanceof E&&s.status===404?new f("device_not_found",`the environment has no device ${A(t)}`,{hint:"palbase notify:devices:list shows its devices"}):s}e.out.result({deleted:t},()=>e.out.line(`Forgot the device ${A(t)}: a push reaches it no more.`))}},X1={name:"auth:audit",summary:"who did what in the environment's auth, newest first: sign-ins, changes to users and settings, admin actions",usage:"[--event <type>] [--limit <n>]",flags:{event:{type:"string",value:"type",description:"only this kind of event (user.login, admin.user.update\u2026)"},limit:{type:"string",value:"n",description:"how many at most (default 50)"}},scope:"environment",async run(e){let t=await b(e),n=ss(e.flags.limit,"limit",1,1e4)??50,s=[],a;do{let i=new URLSearchParams({limit:String(Math.min(100,n-s.length)),...a?{cursor:a}:{},...typeof e.flags.event=="string"?{event_type:e.flags.event}:{}}),r=await h(e,t,"GET",`/admin/audit?${i}`);s.push(...r.events),a=r.next_cursor||void 0}while(a&&s.length<n);e.out.result({events:s},()=>{s.length===0?e.out.line("Nothing recorded yet."):e.out.table(s,[{header:"when",value:i=>gt(i.created_at)},{header:"event",value:i=>A(i.event_type)},{header:"result",value:i=>A(i.result??"")},{header:"by",value:i=>A(i.actor?.email??i.actor?.user_id??"")},{header:"from",value:i=>A(i.actor?.ip??"")},{header:"on",value:i=>A([i.target_type,i.target_id].filter(Boolean).join(" "))}])})}},Z1={name:"auth:audit:verify",summary:"whether the audit trail is whole: each event chained to the one before, none changed or taken out",scope:"environment",async run(e){let t=await b(e),n=await h(e,t,"GET","/admin/audit/verify");if(!n.valid){let s=n.broken_at?` at event ${A(n.broken_at.event_id??"?")} (number ${(n.broken_at.index??0)+1} of ${n.total}, oldest first)`:"";throw new f("audit_trail_broken",`the audit trail is broken${s}: an event there was changed or taken out`)}e.out.result(n,()=>e.out.line(`The audit trail is whole: ${n.total} events, each chained to the one before.`))}},Q1={name:"auth:audit:export",summary:"the audit trail as a file: JSON lines or CSV, a span of it, one kind of event",usage:"[--format ndjson|csv] [--from <time>] [--to <time>] [--event <type>] [--out <file>]",flags:{format:{type:"string",value:"ndjson|csv",description:"JSON lines (default) or CSV"},from:{type:"string",value:"time",description:"from this time on (RFC 3339: 2026-10-01T00:00:00Z)"},to:{type:"string",value:"time",description:"up to this time"},event:{type:"string",value:"type",description:"only this kind of event"},out:{type:"string",value:"file",description:"write it here instead of to standard output"}},scope:"environment",async run(e){let t=e.flags.format??"ndjson";if(t!=="ndjson"&&t!=="csv")throw m("--format is ndjson or csv");for(let r of["from","to"]){let o=e.flags[r];if(o!==void 0&&Number.isNaN(Date.parse(String(o))))throw m(`--${r} is a time: 2026-10-01T00:00:00Z`)}let n=await b(e),s=new URLSearchParams({format:String(t)});for(let[r,o]of[["from","from"],["to","to"],["event","event_type"]])typeof e.flags[r]=="string"&&s.set(o,e.flags[r]);let a=await h(e,n,"GET",`/admin/audit/export?${s}`),i=typeof a=="string"?a:t==="ndjson"&&Array.isArray(a)?a.map(r=>JSON.stringify(r)).join(`
|
|
695
695
|
`):JSON.stringify(a);typeof e.flags.out=="string"?(await Fb(Jb(e.io.cwd,e.flags.out),i.endsWith(`
|
|
696
696
|
`)||i===""?i:`${i}
|
|
697
697
|
`,{mode:384}),e.out.result({file:e.flags.out,bytes:Buffer.byteLength(i)},()=>e.out.line(`Wrote the audit trail to ${e.flags.out} (${Buffer.byteLength(i)} bytes).`))):e.io.stdout(i.endsWith(`
|
|
698
698
|
`)||i===""?i:`${i}
|
|
699
|
-
`)}},eM={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 b(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=>
|
|
700
|
-
`;typeof e.flags.out=="string"?(await Fb(Jb(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)}},sM={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 b(e),[n,s,a]=e.args,i=a===void 0?null:jt(a);await v(e,t,`broadcast ${s} on ${n}`);let r=await h(e,t,"POST","/realtime/broadcast",{messages:[{topic:n,event:s,payload:i}]});e.out.result(r??{sent:1},()=>e.out.line(`Broadcast ${A(s)} on ${A(n)}.`))}},aM={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 b(e),n=new URLSearchParams({window_seconds:String(Vb(e.flags.window,"window")??86400),limit:String(ss(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(Et(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)}`:""}`)})}},iM={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 b(e),n=await h(e,t,"GET",`/analytics/summary?window_seconds=${Vb(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))}`)})}},nw=[_1,k1,S1,$1,P1,A1,R1,T1,nM,X1,Z1,Q1,eM,tM,D1,x1,N1,q1,K1,G1,U1,B1,z1,F1,J1,V1,H1,Y1,sM,aM,iM];var Ja=["machines:read","machines:logs","machines:previews","apps:sync","auth:test-users","support"];function sw(e){return e.scopes===null?"its minter's role":e.scopes.join(", ")}var rM={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: ${Ja.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: ${Ja.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=oe(e.flags.scope),n=t===void 0?void 0:[...new Set(t)];if(n!==void 0&&n.length===0)throw m(`--scope names what the token is narrowed to: ${Ja.join(", ")}`);let s=(n??[]).filter(o=>!Ja.includes(o));if(s.length>0)throw m(`${s.join(", ")}: no scope of an environment's token (${Ja.join(", ")})`);let a=e.flags.minutes===void 0?60:Number(e.flags.minutes);if(!Number.isInteger(a)||a<5||a>240)throw m("--minutes is a whole number from 5 to 240");let i=await b(e),r=await e.studio.post(`/environments/${i.env_ref}/tokens`,{...n!==void 0?{scopes:n}:{},expires_in_minutes:a,...typeof e.flags.name=="string"?{name:e.flags.name}:{}});e.out.result(r,()=>{e.out.line(`Minted ${q(r.name)} for ${N(i)} (${sw(r)}; until ${r.expires_at.slice(0,16).replace("T"," ")} UTC).`),e.out.line(`token (shown this once \u2014 the program's PALBASE_TOKEN): ${r.token}`)})}},oM={name:"env:tokens:list",summary:"the environment's live tokens, by their hint (never their values)",scope:"environment",async run(e){let t=await b(e),{tokens:n}=await e.studio.get(`/environments/${t.env_ref}/tokens`);e.out.result({tokens:n},()=>{n.length===0&&e.out.line(`${N(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=>q(s.name)},{header:"can",value:s=>sw(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}`}])})}},lM={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 b(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 f("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/${x("the environment's ref",t.env_ref)}/tokens/${x("the token's id",n)}`),e.out.result({revoked:n},()=>e.out.line(`Revoked the environment token ${n} of ${N(t)}.`))}},aw=[oM,rM,lM];var Fs={org:{type:"string",value:"org",description:"the organization (name or id; the one of the project chosen here, or your only one)"}};function Le(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 dM(e,t){let n=typeof e=="string"?/^\s*\$?\s*(\d{1,9})(?:\.(\d{1,2}))?\s*$/.exec(e):null;if(!n)throw m(`${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 Ws=e=>`${(e/2**30).toFixed(2)} GiB`,iw=e=>`${(e/1e9).toFixed(2)} GB`,Sd=e=>e.toLocaleString("en-US"),rw={egress:Ws,storage:e=>`${Ws(e)} (month's peak)`,"db.backups":e=>`${Ws(e)} (month's peak)`,images:e=>`${Ws(e)} (month's peak)`,logs:Ws,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":iw,"db.disk":e=>`${(e/(730*3600)).toFixed(2)} GiB-month`,"db.traffic":iw,"db.disk.awake":e=>`${(e/(730*3600)).toFixed(2)} GB-month`,"sites.storage":e=>`${Ws(e)} (month's peak)`,domains:e=>`${Sd(e)} (month's most)`,tasks:Sd};function Ur(e,t){return e.startsWith("machine.")||e.startsWith("db.")&&!rw[e]?`${(t/3600).toFixed(1)} h`:(rw[e]??Sd)(t)}async function Js(e){let t=e.flags.org;return t===void 0&&(t=(await e.state.targetFor(e.io.cwd))?.target.org_id),_t(e,t)}async function pM(e,t){let n=await Pe(e.studio);if(t===void 0){let r=(await e.state.targetFor(e.io.cwd))?.target.env_ref;if(!r)throw m("name the environment: its ref, or project/env (palbase projects:list shows them)");t=r}let s=t.lastIndexOf("/"),a=n.filter(r=>r.ref===t||s>0&&r.slug===t.slice(s+1)&&(r.project_name===t.slice(0,s)||`${r.org_name}/${r.project_name}`===t.slice(0,s)));if(a.length===0)throw new f("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 f("ambiguous_environment",`${JSON.stringify(t)} names more than one environment`,{hint:"name it by its ref"});let i=a[0];return{ref:i.ref,organization_id:i.organization_id,where:`${i.org_name} \u203A ${i.project_name} \u203A ${i.name}`}}function ow(e,t){return e.gone?"purged":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 lw(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 ${q(t.name)}'s payment account`;return n&&s&&(a+=` \xB7 ${s.payment_method?`card ${q(s.payment_method)}`:"no card saved yet"}${s.stripe_mode==="test"?" \xB7 test mode":""}`),t.held&&(a+=" \xB7 HELD: its projects are on the Free quotas until it pays"),a}function uM(e){let t=[`owed, not yet charged: ${Le(e.owed_micros)} \u2014 charged at ${Le(e.threshold_micros)}, and at the month's end`];return e.unpaid_micros>0&&t.push(`unpaid: ${Le(e.unpaid_micros)}${e.free_on?` \u2014 its projects 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}var dw=e=>`${e.name} (${e.ref})${e.frozen?" frozen":e.deleted?" deleted":""}`;function cM(e,t,n){if(e.out.line(`${q(t)} \u2014 ${lw(n)}`),n.account&&n.paid_by?.organization_id===n.organization_id)for(let i of uM(n.account))e.out.line(i);let s=new Date(`${n.period}-01T00:00:00Z`).toLocaleDateString("en-US",{month:"long",year:"numeric",timeZone:"UTC"});n.owed_micros!==void 0&&e.out.line(`${s}: ${Le(n.exempt?n.charged_micros??0:n.owed_micros)} ${n.exempt?"priced, not charged":"owed by its projects so far"}`),e.out.line();let a=n.paid_by?.held??!1;e.out.table(n.projects.filter(i=>!i.gone),[{header:"project",value:i=>q(i.name)},{header:"environments",value:i=>q(i.environments.map(dw).join(", "))},{header:"plan",value:i=>ow(i,a)},{header:"this month",value:i=>i.charged_micros===void 0?"":Le(i.charged_micros)},{header:"limit",value:i=>i.monthly_limit_micros==null?"":Le(i.monthly_limit_micros)}])}function hM(e,t,n){e.out.line(`${q(t)} \u2014 ${ow(n,!1)}`),n.monthly_limit_micros!==void 0&&e.out.line(`monthly limit: ${n.monthly_limit_micros===null?"none":Le(n.monthly_limit_micros)}`),n.charged_micros!==void 0&&e.out.line(`this month: ${Le(n.charged_micros)} charged of ${Le(n.gross_micros??0)} at the price table (its free quota taken off)${n.owed_micros===void 0?"":`, ${Le(n.owed_micros)} owed`}`);let s=n.items.filter(i=>i.item!=="total");s.length>0&&(e.out.line(),e.out.table(s,[{header:"item",value:i=>i.item},{header:"used, its environments together",value:i=>Ur(i.item,i.units)},...s.some(i=>i.micros!==void 0)?[{header:"charged",value:i=>i.micros===void 0?"":Le(i.micros)}]:[]]));let a=n.environments.flatMap(i=>i.items.length===0?[{e:i,item:"",units:0}]:i.items.map(r=>({e:i,item:r.item,units:r.units})));a.length>0&&(e.out.line(),e.out.table(a,[{header:"environment",value:i=>q(dw(i.e))},{header:"item",value:i=>i.item},{header:"used",value:i=>i.item?Ur(i.item,i.units):""}]))}var mM={name:"billing",summary:"who pays for an organization, how its payment account stands, and each project's plan, month and limit \u2014 its environments together",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:Fs,scope:"account",async run(e){let t=await Js(e),n=await e.studio.get(`/orgs/${t.id}/billing`);e.out.result(n,()=>cM(e,t.name,n))}},pw={period:{type:"string",value:"YYYY-MM",description:"the month (this one by default)"},csv:{type:"boolean",description:"print it as CSV"}};function uw(e){let t=e.flags.period;if(t!==void 0&&!/^\d{4}-(0[1-9]|1[0-2])$/.test(t))throw m("--period is a month: YYYY-MM");return t?`?period=${t}`:""}var gM={name:"billing:charges",summary:"a month's charges, by project and item \u2014 used, at the price table, charged past each project's free quota \u2014 and what each of its environments used, as a table or as CSV",usage:"[--period <YYYY-MM>] [--csv] [--org <org>]",details:["--csv prints the CSV Studio downloads."],flags:{...Fs,...pw},scope:"account",async run(e){let t=uw(e),n=await Js(e);if(e.flags.csv===!0){e.io.stdout(q(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(`${q(n.name)} used nothing in ${s.period}.`);return}let a=l=>q(l.project??l.project_id);e.out.table(s.charges,[{header:"project",value:a},{header:"item",value:l=>l.item},{header:"used",value:l=>l.item==="total"?"":Ur(l.item,l.units)},{header:"at the price table",value:l=>Le(l.gross_micros)},{header:"charged",value:l=>Le(l.micros)}]);let i=Object.values(s.owed_micros).reduce((l,d)=>l+d,0);e.out.line(`${s.period}: ${Le(i)} owed to the payment account that pays for it.`);let r=new Map(s.charges.map(l=>[l.project_id,a(l)])),o=(s.environments??[]).flatMap(l=>l.items.map(d=>({e:l,i:d})));o.length>0&&(e.out.line(),e.out.table(o,[{header:"project",value:l=>r.get(l.e.project_id)??l.e.project_id},{header:"environment",value:l=>`${q(l.e.name)} (${l.e.ref})`},{header:"item",value:l=>l.i.item},{header:"used",value:l=>Ur(l.i.item,l.i.units)}]))})}},fM={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"},yM={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:Fs,scope:"account",async run(e){let t=await Js(e),{invoices:n}=await e.studio.get(`/orgs/${t.id}/billing/invoices`);e.out.result({invoices:n},()=>{n.length===0?e.out.line(`${q(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=>fM[s.kind]??s.kind},{header:"amount",value:s=>`${Le(s.amount_micros)}${s.tax_micros>0?` + ${Le(s.tax_micros)} tax`:""}`},{header:"status",value:s=>s.status==="open"?"unpaid":s.status},{header:"invoice",value:s=>s.hosted_url??""}])})}},bM={name:"billing:project",summary:"a project's place in the bill \u2014 its plan and its month's limit, all its environments' \u2014 read, or changed",usage:"[-P <project>] [--plan free|pay_as_you_go] [--limit <usd>|none]",details:["With no flag it shows the project: its plan, limit and month, item by item, and what each of its environments used.","A project is billed as one: its environments' usage together, past its one free quota. 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 \u2014 and every environment of it, a new one too, has the paid sizes. A project 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 projects go on."],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 its environments use past its free quota is charged)"},limit:{type:"string",value:"usd|none",description:"at most this much a month; none for no limit"}},scope:"environment",async run(e){let t={},n=e.flags.plan;if(n!==void 0){if(n!=="free"&&n!=="pay_as_you_go")throw m("--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:dM(e.flags.limit,"--limit"));let s=await jn(e),a=`${s.org_name} \u203A ${s.project_name}`,i=`/orgs/${s.org_id}/billing/projects/${s.project_id}`,r=Object.keys(t).length===0?await e.studio.get(i):await e.studio.request("PATCH",i,t);e.out.result(r,()=>hM(e,a,r))}},wM={name:"billing:env",summary:"an environment frozen or thawed \u2014 its requests refused, its machines and databases stopped, its data kept",usage:"[<project/env | ref>] --frozen yes|no [-y]",details:["Frozen, its requests are refused and its machines and databases stopped, its data kept; only what it stores is charged, with its project. Freezing asks first; -y does not.","Its plan and its limit are its project's: palbase billing:project."],args:{min:0,max:1},flags:{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=mn(e.flags.frozen,"frozen");if(t===void 0)throw m("say --frozen yes or --frozen no (its plan and limit are its project's: palbase billing:project)");let n=await pM(e,e.args[0]);if(t&&!e.global.yes){if(!e.interactive)throw new f("confirmation_needed","freezing an environment refuses its requests",{hint:"confirm with -y"});let a=(await e.io.prompt(q(`Freeze ${n.where}: its requests are refused until it is thawed. Go ahead? [y/N] `))).trim().toLowerCase();if(a!=="y"&&a!=="yes")throw new f("cancelled","nothing was changed")}let s=await e.studio.request("PATCH",`/orgs/${n.organization_id}/billing/environments/${n.ref}`,{frozen:t});e.out.result(s,()=>e.out.line(`${q(n.where)} \u2014 ${s.frozen?"frozen":"thawed"}`))}},vM={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 projects 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 projects on Pay as you go go Free; what they owed so far stays the account's."],args:{min:1,max:1},flags:Fs,scope:"account",async run(e){let t=await Js(e),n=e.args[0]==="none"?null:(await _t(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(`${q(t.name)} \u2014 ${lw(s)}`))}},_M={name:"billing:paid",summary:"the organizations an organization's payment account pays for \u2014 its managers'",usage:"[--org <org>]",flags:Fs,scope:"account",async run(e){let t=await Js(e),{organizations:n}=await e.studio.get(`/orgs/${t.id}/billing/paid`);e.out.result({organizations:n},()=>{n.length===0?e.out.line(`${q(t.name)}'s payment account pays for no organization.`):e.out.table(n,[{header:"organization",value:s=>q(s.name)},{header:"id",value:s=>s.organization_id},{header:"projects",value:s=>String(s.projects)},{header:"on Pay as you go",value:s=>String(s.pay_as_you_go)}])})}},kM={name:"billing:report",summary:"a payment account's month: each organization it paid for, each project, what it owes \u2014 as a table or as CSV (item by item, and each environment's units)",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 project, what the account is charged for it (owed), and what each of its environments used."],flags:{...Fs,...pw},scope:"account",async run(e){let t=uw(e),n=await Js(e);if(e.flags.csv===!0){e.io.stdout(q(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(i=>i.projects.map(r=>({org:i.name,p:r})));if(a.length===0){e.out.line(`${q(n.name)}'s payment account owes nothing for ${s.period}.`);return}e.out.table(a,[{header:"organization",value:i=>q(i.org)},{header:"project",value:i=>q(i.p.name)},{header:"environments",value:i=>q(i.p.environments.map(r=>`${r.name} (${r.ref})`).join(", "))},{header:"at the price table",value:i=>Le(i.p.gross_micros)},{header:"owed",value:i=>Le(i.p.owed_micros)}]),e.out.line(`${s.period}: ${Le(s.owed_micros)} owed by ${s.organizations.length} organization${s.organizations.length===1?"":"s"}.`)})}},cw=[mM,gM,yM,bM,wM,vM,_M,kM];import{lstat as SM,mkdir as $M,readFile as PM,rename as AM,rm as RM,writeFile as TM}from"node:fs/promises";import{dirname as hw,resolve as EM}from"node:path";var mw="// palbase:stack:begin",gw="// palbase:stack:end",CM=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Br=e=>CM.test(e)?e:JSON.stringify(e),as=e=>[...new Set(e)].sort();function zr(e,t){return t.length===0?[` interface ${e} {}`]:[` interface ${e} {`,...t.map(n=>` ${n}`)," }"]}function $d(e){let t=[...e.buckets].sort((n,s)=>n.name<s.name?-1:n.name>s.name?1:0);return[mw,'declare module "palbase/backend/stack" {',...zr("Secrets",as(e.secrets).map(n=>`${Br(n)}: true;`)),"",...zr("Flags",as(e.flags).map(n=>`${Br(n)}: true;`)),"",...zr("Buckets",t.map(n=>{let s=as(n.variants);return`${Br(n.name)}: { variants: ${s.length===0?"never":s.map(a=>JSON.stringify(a)).join(" | ")} };`})),"",...zr("Roles",as(e.roles).map(n=>`${Br(n)}: true;`)),"}",gw].join(`
|
|
699
|
+
`)}},eM={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 b(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=>gt(s.created_at)},{header:"retired",value:s=>gt(s.retired_at)}]),n.next_rotation&&e.out.line(`The next key starts signing ${gt(n.next_rotation)}.`)})}},tM={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 b(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.`))}},nM={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 b(e),n=on(e.args[0]),s=await h(e,t,"GET",`/admin/users/${k(n)}/export`),a=`${JSON.stringify(s,null,2)}
|
|
700
|
+
`;typeof e.flags.out=="string"?(await Fb(Jb(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)}},sM={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 b(e),[n,s,a]=e.args,i=a===void 0?null:jt(a);await v(e,t,`broadcast ${s} on ${n}`);let r=await h(e,t,"POST","/realtime/broadcast",{messages:[{topic:n,event:s,payload:i}]});e.out.result(r??{sent:1},()=>e.out.line(`Broadcast ${A(s)} on ${A(n)}.`))}},aM={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 b(e),n=new URLSearchParams({window_seconds:String(Vb(e.flags.window,"window")??86400),limit:String(ss(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(gt(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)}`:""}`)})}},iM={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 b(e),n=await h(e,t,"GET",`/analytics/summary?window_seconds=${Vb(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))}`)})}},nw=[_1,k1,S1,$1,P1,A1,R1,T1,nM,X1,Z1,Q1,eM,tM,D1,x1,N1,q1,K1,G1,U1,B1,z1,F1,J1,V1,H1,Y1,sM,aM,iM];var Ja=["machines:read","machines:logs","machines:previews","apps:sync","auth:test-users","support"];function sw(e){return e.scopes===null?"its minter's role":e.scopes.join(", ")}var rM={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: ${Ja.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: ${Ja.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=oe(e.flags.scope),n=t===void 0?void 0:[...new Set(t)];if(n!==void 0&&n.length===0)throw m(`--scope names what the token is narrowed to: ${Ja.join(", ")}`);let s=(n??[]).filter(o=>!Ja.includes(o));if(s.length>0)throw m(`${s.join(", ")}: no scope of an environment's token (${Ja.join(", ")})`);let a=e.flags.minutes===void 0?60:Number(e.flags.minutes);if(!Number.isInteger(a)||a<5||a>240)throw m("--minutes is a whole number from 5 to 240");let i=await b(e),r=await e.studio.post(`/environments/${i.env_ref}/tokens`,{...n!==void 0?{scopes:n}:{},expires_in_minutes:a,...typeof e.flags.name=="string"?{name:e.flags.name}:{}});e.out.result(r,()=>{e.out.line(`Minted ${q(r.name)} for ${N(i)} (${sw(r)}; until ${r.expires_at.slice(0,16).replace("T"," ")} UTC).`),e.out.line(`token (shown this once \u2014 the program's PALBASE_TOKEN): ${r.token}`)})}},oM={name:"env:tokens:list",summary:"the environment's live tokens, by their hint (never their values)",scope:"environment",async run(e){let t=await b(e),{tokens:n}=await e.studio.get(`/environments/${t.env_ref}/tokens`);e.out.result({tokens:n},()=>{n.length===0&&e.out.line(`${N(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=>q(s.name)},{header:"can",value:s=>sw(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}`}])})}},lM={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 b(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 f("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/${x("the environment's ref",t.env_ref)}/tokens/${x("the token's id",n)}`),e.out.result({revoked:n},()=>e.out.line(`Revoked the environment token ${n} of ${N(t)}.`))}},aw=[oM,rM,lM];var Fs={org:{type:"string",value:"org",description:"the organization (name or id; the one of the project chosen here, or your only one)"}};function Le(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 dM(e,t){let n=typeof e=="string"?/^\s*\$?\s*(\d{1,9})(?:\.(\d{1,2}))?\s*$/.exec(e):null;if(!n)throw m(`${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 Ws=e=>`${(e/2**30).toFixed(2)} GiB`,iw=e=>`${(e/1e9).toFixed(2)} GB`,Sd=e=>e.toLocaleString("en-US"),rw={egress:Ws,storage:e=>`${Ws(e)} (month's peak)`,"db.backups":e=>`${Ws(e)} (month's peak)`,images:e=>`${Ws(e)} (month's peak)`,logs:Ws,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":iw,"db.disk":e=>`${(e/(730*3600)).toFixed(2)} GiB-month`,"db.traffic":iw,"db.disk.awake":e=>`${(e/(730*3600)).toFixed(2)} GB-month`,"sites.storage":e=>`${Ws(e)} (month's peak)`,domains:e=>`${Sd(e)} (month's most)`,tasks:Sd};function Ur(e,t){return e.startsWith("machine.")||e.startsWith("db.")&&!rw[e]?`${(t/3600).toFixed(1)} h`:(rw[e]??Sd)(t)}async function Js(e){let t=e.flags.org;return t===void 0&&(t=(await e.state.targetFor(e.io.cwd))?.target.org_id),kt(e,t)}async function pM(e,t){let n=await Pe(e.studio);if(t===void 0){let r=(await e.state.targetFor(e.io.cwd))?.target.env_ref;if(!r)throw m("name the environment: its ref, or project/env (palbase projects:list shows them)");t=r}let s=t.lastIndexOf("/"),a=n.filter(r=>r.ref===t||s>0&&r.slug===t.slice(s+1)&&(r.project_name===t.slice(0,s)||`${r.org_name}/${r.project_name}`===t.slice(0,s)));if(a.length===0)throw new f("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 f("ambiguous_environment",`${JSON.stringify(t)} names more than one environment`,{hint:"name it by its ref"});let i=a[0];return{ref:i.ref,organization_id:i.organization_id,where:`${i.org_name} \u203A ${i.project_name} \u203A ${i.name}`}}function ow(e,t){return e.gone?"purged":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 lw(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 ${q(t.name)}'s payment account`;return n&&s&&(a+=` \xB7 ${s.payment_method?`card ${q(s.payment_method)}`:"no card saved yet"}${s.stripe_mode==="test"?" \xB7 test mode":""}`),t.held&&(a+=" \xB7 HELD: its projects are on the Free quotas until it pays"),a}function uM(e){let t=[`owed, not yet charged: ${Le(e.owed_micros)} \u2014 charged at ${Le(e.threshold_micros)}, and at the month's end`];return e.unpaid_micros>0&&t.push(`unpaid: ${Le(e.unpaid_micros)}${e.free_on?` \u2014 its projects 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}var dw=e=>`${e.name} (${e.ref})${e.frozen?" frozen":e.deleted?" deleted":""}`;function cM(e,t,n){if(e.out.line(`${q(t)} \u2014 ${lw(n)}`),n.account&&n.paid_by?.organization_id===n.organization_id)for(let i of uM(n.account))e.out.line(i);let s=new Date(`${n.period}-01T00:00:00Z`).toLocaleDateString("en-US",{month:"long",year:"numeric",timeZone:"UTC"});n.owed_micros!==void 0&&e.out.line(`${s}: ${Le(n.exempt?n.charged_micros??0:n.owed_micros)} ${n.exempt?"priced, not charged":"owed by its projects so far"}`),e.out.line();let a=n.paid_by?.held??!1;e.out.table(n.projects.filter(i=>!i.gone),[{header:"project",value:i=>q(i.name)},{header:"environments",value:i=>q(i.environments.map(dw).join(", "))},{header:"plan",value:i=>ow(i,a)},{header:"this month",value:i=>i.charged_micros===void 0?"":Le(i.charged_micros)},{header:"limit",value:i=>i.monthly_limit_micros==null?"":Le(i.monthly_limit_micros)}])}function hM(e,t,n){e.out.line(`${q(t)} \u2014 ${ow(n,!1)}`),n.monthly_limit_micros!==void 0&&e.out.line(`monthly limit: ${n.monthly_limit_micros===null?"none":Le(n.monthly_limit_micros)}`),n.charged_micros!==void 0&&e.out.line(`this month: ${Le(n.charged_micros)} charged of ${Le(n.gross_micros??0)} at the price table (its free quota taken off)${n.owed_micros===void 0?"":`, ${Le(n.owed_micros)} owed`}`);let s=n.items.filter(i=>i.item!=="total");s.length>0&&(e.out.line(),e.out.table(s,[{header:"item",value:i=>i.item},{header:"used, its environments together",value:i=>Ur(i.item,i.units)},...s.some(i=>i.micros!==void 0)?[{header:"charged",value:i=>i.micros===void 0?"":Le(i.micros)}]:[]]));let a=n.environments.flatMap(i=>i.items.length===0?[{e:i,item:"",units:0}]:i.items.map(r=>({e:i,item:r.item,units:r.units})));a.length>0&&(e.out.line(),e.out.table(a,[{header:"environment",value:i=>q(dw(i.e))},{header:"item",value:i=>i.item},{header:"used",value:i=>i.item?Ur(i.item,i.units):""}]))}var mM={name:"billing",summary:"who pays for an organization, how its payment account stands, and each project's plan, month and limit \u2014 its environments together",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:Fs,scope:"account",async run(e){let t=await Js(e),n=await e.studio.get(`/orgs/${t.id}/billing`);e.out.result(n,()=>cM(e,t.name,n))}},pw={period:{type:"string",value:"YYYY-MM",description:"the month (this one by default)"},csv:{type:"boolean",description:"print it as CSV"}};function uw(e){let t=e.flags.period;if(t!==void 0&&!/^\d{4}-(0[1-9]|1[0-2])$/.test(t))throw m("--period is a month: YYYY-MM");return t?`?period=${t}`:""}var gM={name:"billing:charges",summary:"a month's charges, by project and item \u2014 used, at the price table, charged past each project's free quota \u2014 and what each of its environments used, as a table or as CSV",usage:"[--period <YYYY-MM>] [--csv] [--org <org>]",details:["--csv prints the CSV Studio downloads."],flags:{...Fs,...pw},scope:"account",async run(e){let t=uw(e),n=await Js(e);if(e.flags.csv===!0){e.io.stdout(q(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(`${q(n.name)} used nothing in ${s.period}.`);return}let a=l=>q(l.project??l.project_id);e.out.table(s.charges,[{header:"project",value:a},{header:"item",value:l=>l.item},{header:"used",value:l=>l.item==="total"?"":Ur(l.item,l.units)},{header:"at the price table",value:l=>Le(l.gross_micros)},{header:"charged",value:l=>Le(l.micros)}]);let i=Object.values(s.owed_micros).reduce((l,d)=>l+d,0);e.out.line(`${s.period}: ${Le(i)} owed to the payment account that pays for it.`);let r=new Map(s.charges.map(l=>[l.project_id,a(l)])),o=(s.environments??[]).flatMap(l=>l.items.map(d=>({e:l,i:d})));o.length>0&&(e.out.line(),e.out.table(o,[{header:"project",value:l=>r.get(l.e.project_id)??l.e.project_id},{header:"environment",value:l=>`${q(l.e.name)} (${l.e.ref})`},{header:"item",value:l=>l.i.item},{header:"used",value:l=>Ur(l.i.item,l.i.units)}]))})}},fM={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"},yM={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:Fs,scope:"account",async run(e){let t=await Js(e),{invoices:n}=await e.studio.get(`/orgs/${t.id}/billing/invoices`);e.out.result({invoices:n},()=>{n.length===0?e.out.line(`${q(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=>fM[s.kind]??s.kind},{header:"amount",value:s=>`${Le(s.amount_micros)}${s.tax_micros>0?` + ${Le(s.tax_micros)} tax`:""}`},{header:"status",value:s=>s.status==="open"?"unpaid":s.status},{header:"invoice",value:s=>s.hosted_url??""}])})}},bM={name:"billing:project",summary:"a project's place in the bill \u2014 its plan and its month's limit, all its environments' \u2014 read, or changed",usage:"[-P <project>] [--plan free|pay_as_you_go] [--limit <usd>|none]",details:["With no flag it shows the project: its plan, limit and month, item by item, and what each of its environments used.","A project is billed as one: its environments' usage together, past its one free quota. 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 \u2014 and every environment of it, a new one too, has the paid sizes. A project 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 projects go on."],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 its environments use past its free quota is charged)"},limit:{type:"string",value:"usd|none",description:"at most this much a month; none for no limit"}},scope:"environment",async run(e){let t={},n=e.flags.plan;if(n!==void 0){if(n!=="free"&&n!=="pay_as_you_go")throw m("--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:dM(e.flags.limit,"--limit"));let s=await jn(e),a=`${s.org_name} \u203A ${s.project_name}`,i=`/orgs/${s.org_id}/billing/projects/${s.project_id}`,r=Object.keys(t).length===0?await e.studio.get(i):await e.studio.request("PATCH",i,t);e.out.result(r,()=>hM(e,a,r))}},wM={name:"billing:env",summary:"an environment frozen or thawed \u2014 its requests refused, its machines and databases stopped, its data kept",usage:"[<project/env | ref>] --frozen yes|no [-y]",details:["Frozen, its requests are refused and its machines and databases stopped, its data kept; only what it stores is charged, with its project. Freezing asks first; -y does not.","Its plan and its limit are its project's: palbase billing:project."],args:{min:0,max:1},flags:{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=mn(e.flags.frozen,"frozen");if(t===void 0)throw m("say --frozen yes or --frozen no (its plan and limit are its project's: palbase billing:project)");let n=await pM(e,e.args[0]);if(t&&!e.global.yes){if(!e.interactive)throw new f("confirmation_needed","freezing an environment refuses its requests",{hint:"confirm with -y"});let a=(await e.io.prompt(q(`Freeze ${n.where}: its requests are refused until it is thawed. Go ahead? [y/N] `))).trim().toLowerCase();if(a!=="y"&&a!=="yes")throw new f("cancelled","nothing was changed")}let s=await e.studio.request("PATCH",`/orgs/${n.organization_id}/billing/environments/${n.ref}`,{frozen:t});e.out.result(s,()=>e.out.line(`${q(n.where)} \u2014 ${s.frozen?"frozen":"thawed"}`))}},vM={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 projects 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 projects on Pay as you go go Free; what they owed so far stays the account's."],args:{min:1,max:1},flags:Fs,scope:"account",async run(e){let t=await Js(e),n=e.args[0]==="none"?null:(await kt(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(`${q(t.name)} \u2014 ${lw(s)}`))}},_M={name:"billing:paid",summary:"the organizations an organization's payment account pays for \u2014 its managers'",usage:"[--org <org>]",flags:Fs,scope:"account",async run(e){let t=await Js(e),{organizations:n}=await e.studio.get(`/orgs/${t.id}/billing/paid`);e.out.result({organizations:n},()=>{n.length===0?e.out.line(`${q(t.name)}'s payment account pays for no organization.`):e.out.table(n,[{header:"organization",value:s=>q(s.name)},{header:"id",value:s=>s.organization_id},{header:"projects",value:s=>String(s.projects)},{header:"on Pay as you go",value:s=>String(s.pay_as_you_go)}])})}},kM={name:"billing:report",summary:"a payment account's month: each organization it paid for, each project, what it owes \u2014 as a table or as CSV (item by item, and each environment's units)",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 project, what the account is charged for it (owed), and what each of its environments used."],flags:{...Fs,...pw},scope:"account",async run(e){let t=uw(e),n=await Js(e);if(e.flags.csv===!0){e.io.stdout(q(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(i=>i.projects.map(r=>({org:i.name,p:r})));if(a.length===0){e.out.line(`${q(n.name)}'s payment account owes nothing for ${s.period}.`);return}e.out.table(a,[{header:"organization",value:i=>q(i.org)},{header:"project",value:i=>q(i.p.name)},{header:"environments",value:i=>q(i.p.environments.map(r=>`${r.name} (${r.ref})`).join(", "))},{header:"at the price table",value:i=>Le(i.p.gross_micros)},{header:"owed",value:i=>Le(i.p.owed_micros)}]),e.out.line(`${s.period}: ${Le(s.owed_micros)} owed by ${s.organizations.length} organization${s.organizations.length===1?"":"s"}.`)})}},cw=[mM,gM,yM,bM,wM,vM,_M,kM];import{lstat as SM,mkdir as $M,readFile as PM,rename as AM,rm as RM,writeFile as TM}from"node:fs/promises";import{dirname as hw,resolve as EM}from"node:path";var mw="// palbase:stack:begin",gw="// palbase:stack:end",CM=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Br=e=>CM.test(e)?e:JSON.stringify(e),as=e=>[...new Set(e)].sort();function zr(e,t){return t.length===0?[` interface ${e} {}`]:[` interface ${e} {`,...t.map(n=>` ${n}`)," }"]}function $d(e){let t=[...e.buckets].sort((n,s)=>n.name<s.name?-1:n.name>s.name?1:0);return[mw,'declare module "palbase/backend/stack" {',...zr("Secrets",as(e.secrets).map(n=>`${Br(n)}: true;`)),"",...zr("Flags",as(e.flags).map(n=>`${Br(n)}: true;`)),"",...zr("Buckets",t.map(n=>{let s=as(n.variants);return`${Br(n.name)}: { variants: ${s.length===0?"never":s.map(a=>JSON.stringify(a)).join(" | ")} };`})),"",...zr("Roles",as(e.roles).map(n=>`${Br(n)}: true;`)),"}",gw].join(`
|
|
701
701
|
`)}function Vs(e,t,n={begin:mw,end:gw,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}
|
|
702
702
|
${t}
|
|
703
703
|
|