palbase 0.73.0 → 0.73.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/ai/index.js +2 -2
- package/dist/ai-sdk/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/{DIQMCEMJ.js → 2TKZTIMD.js} +2 -2
- package/dist/chunks/{YMIK6HLK.js → 3KCV4F4F.js} +2 -2
- package/dist/chunks/{PAQCJT7M.js → 4E4ABCSD.js} +2 -2
- package/dist/chunks/{IICQMY2Z.js → 5N5GHLUU.js} +2 -2
- package/dist/chunks/{EKOEK6LR.js → 5N6QKGPA.js} +2 -2
- package/dist/chunks/{MVKZWEHL.js → AXANFT2A.js} +2 -2
- package/dist/chunks/{P36C47FS.js → DNSLYLU6.js} +1 -1
- package/dist/chunks/{3DUDNEMM.js → GTKPHG5F.js} +2 -2
- package/dist/chunks/{757A6AR6.js → GWWU2FJ7.js} +2 -2
- package/dist/chunks/{PEQZDT6P.js → HRWVZ4PC.js} +2 -2
- package/dist/chunks/{LCDNCPQW.js → HYPCFC4K.js} +1 -1
- package/dist/chunks/{P4NZ4NZD.js → IVJOWYRE.js} +2 -2
- package/dist/chunks/{5OOA4R4H.js → MB7MHOQO.js} +1 -1
- package/dist/chunks/{VEL7X2G3.js → MFSC4OJV.js} +2 -2
- package/dist/chunks/{76W5ZO2L.js → SEICTPQP.js} +2 -2
- package/dist/chunks/{JG4V6LNY.js → SQNAPFXW.js} +2 -2
- package/dist/chunks/{4XSSQAES.js → SS2RVI27.js} +1 -1
- package/dist/chunks/{UFP6GLLW.js → TR2IPX2A.js} +2 -2
- package/dist/chunks/{25HECIZY.js → U3H6HER3.js} +1 -1
- package/dist/chunks/{SRN7N2WX.js → UOJVMV42.js} +2 -2
- package/dist/chunks/{SMECWMF7.js → UXHNXE3J.js} +2 -2
- package/dist/chunks/{CY6KUFZW.js → VCL3SAQL.js} +2 -2
- package/dist/chunks/{J7ZNBBRN.js → W2KD2I4Q.js} +1 -1
- package/dist/chunks/{J7Z2PYL4.js → YU3GFTZV.js} +1 -1
- package/dist/cli.js +8 -8
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai-sdk.js +1 -1
- 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/payments-ui.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/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
/*! palbase 0.73.
|
|
2
|
+
/*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
|
|
3
3
|
var Q0=Object.defineProperty;var wt=(e,t)=>{for(var n in t)Q0(e,n,{get:t[n],enumerable:!0})};import{parseArgs as MS}from"node:util";var eS=Symbol.for("palbase.data"),tS=globalThis,Ou=tS[eS]??=new WeakSet;function nS(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function Bi(e){let t=[e];for(;t.length>0;){let n=t.pop();if(!(typeof n!="object"||n===null||Ou.has(n)||nS(n))){Ou.add(n);for(let s of Array.isArray(n)?n:Object.values(n))t.push(s)}}return e}var sS="X-PoW-Challenge-ID",aS="X-PoW-Nonce";function xu(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 oS(e){return 8*2**e}var Oa;async function iS(){if(Oa)return Oa;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 Oa=a=>new Uint8Array(s("sha256").update(a).digest()),Oa}catch{}let t=new TextEncoder;return Oa=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),Oa}function rS(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var lS=4096,pS=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function Lu(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 iS(),s=oS(e.difficulty),a=Date.now()+(t.timeLimitMs??12e4);for(let o=0;o<s;o++){if(o%lS===0&&o>0){if(await pS(),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 ${o} attempts`)}let i=n(e.prefix+o),r=i instanceof Uint8Array?i:await i;if(rS(r)>=e.difficulty)return{[sS]:e.id,[aS]:String(o)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${s} attempts`)}var G=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 G({op:e,status:0,code:"invalid_path_parameter",message:`${e}: ${t} cannot be ${s===""?"empty":JSON.stringify(s)}`});return encodeURIComponent(s)}var dS=new Set(["apikey","authorization"]),cS=64*1024;function dp(e){let t=Ji(e.baseUrl),n=e.fetch??globalThis.fetch,s=e.solveProofOfWork??!0,a=async(o,i)=>{let r=gS(t,o),l=new Headers;for(let[y,w]of Object.entries(o.headers??{}))w!=null&&!dS.has(y.toLowerCase())&&l.set(y,String(w));for(let[y,w]of Object.entries(i))l.set(y,w);await hS(o,e.credentials,l),l.has("accept")||l.set("accept","application/json");let p={method:o.method,headers:l,redirect:"manual",signal:o.signal,...o.keepalive?{keepalive:!0}:{}};o.body&&o.body.value!==void 0&&(l.set("content-type",o.body.contentType),p.body=yS(o.body.kind,o.body.value),xa(p.body)||(p.duplex="half"));let d;try{d=o.onUploadProgress&&e.xmlHttpRequest?await uS(e.xmlHttpRequest,o.op,r,p,o.onUploadProgress):await n(r,p)}catch(y){throw o.signal?.aborted||y instanceof G?y:new G({op:o.op,status:0,code:"network_error",message:`${o.op}: the request did not reach ${t.origin}`,cause:y})}let u=o.answers[d.status]??(o.ownResponse&&d.status>=200&&d.status<300?"raw":void 0);if(u===void 0)throw d.status>=200&&d.status<300?(await d.body?.cancel(),new G({op:o.op,status:d.status,code:"undeclared_answer",message:`${o.op}: the server answered ${d.status}, which its contract does not declare; the request may have taken effect`})):await bS(o.op,d);let g;switch(u){case"json":try{g=Bi(await d.json())}catch(y){throw new G({op:o.op,status:d.status,code:"invalid_json",message:`${o.op}: the answer is not JSON`,cause:y})}break;case"raw":g=d;break;default:await d.body?.cancel(),g=void 0}return{status:d.status,data:g,headers:d.headers}};return{async send(o){try{return await a(o,{})}catch(i){let r=s&&i instanceof G&&i.status===403?xu(i.body):null,l=o.body?.value;if(!r||o.body?.kind==="raw"&&!xa(l))throw i;let p=i,d;try{d=await Lu(r,{signal:o.signal})}catch(u){throw o.signal?.aborted?u:new G({op:o.op,status:403,code:"pow_unsolved",message:`${o.op}: ${u instanceof Error?u.message:String(u)}`,requestId:p.requestId,body:p.body,cause:u})}return a(o,d)}}}}function uS(e,t,n,s,a){return new Promise((o,i)=>{let r=s.signal;if(r?.aborted)return i(r.reason);let l=new e,p=()=>l.abort();r?.addEventListener("abort",p,{once:!0});let d=u=>{r?.removeEventListener("abort",p),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=()=>d(()=>{if(l.responseURL!==""&&l.responseURL!==n.href){i(new G({op:t,status:0,code:"undeclared_redirect",message:`${t}: the server redirected; the answer is another address's, and was not read`}));return}if(l.status<200||l.status>599)return i(new TypeError(`${t}: answered ${l.status}`));let u=l.status===204||l.status===205||l.status===304;o(new Response(u?null:l.response,{status:l.status,statusText:l.statusText,headers:mS(l.getAllResponseHeaders())}))}),l.onerror=()=>d(()=>i(new TypeError(`${t}: the request failed`))),l.onabort=()=>d(()=>i(r?.reason??new DOMException("The request was aborted","AbortError"))),l.send(s.body)})}function mS(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 Ji(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 gS(e,t){if(!t.path.startsWith("/")||t.path.startsWith("//"))throw new G({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+fS(t.query),e);if(n.origin!==e.origin)throw new G({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path leaves the project's origin`});return n}async function hS(e,t,n){if(e.auth.length===0)return;let s=e.auth.some(i=>i.includes("userJWT"))?await t.accessToken?.():void 0,a=i=>{switch(i){case"ApiKeyAuth":return!!(t.publishableKey??t.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(t.secretKey??t.token);case"PalbaseBearer":return!!t.token;case"userJWT":return!!s&&!t.token;default:return!1}},o=e.auth.filter(i=>i.every(a)).reduce((i,r)=>i===void 0||r.length>i.length?r:i,void 0);if(!o)throw new G({op:e.op,status:0,code:"missing_credential",message:`${e.op} needs one of: ${e.auth.map(i=>i.length===0?"nothing":i.join(" + ")).join(" | ")}`});for(let i of o)i==="ApiKeyAuth"?n.set("apikey",t.publishableKey??t.secretKey):(i==="SecretKeyAuth"||i==="AdminAuth"||i==="PalbaseBearer")&&t.token?n.set("authorization",`Bearer ${t.token}`):i==="SecretKeyAuth"||i==="AdminAuth"?n.set("apikey",t.secretKey):i==="userJWT"&&n.set("authorization",`Bearer ${s}`)}function yS(e,t){switch(e){case"json":return JSON.stringify(t);case"form":{let n=new URLSearchParams;for(let[s,a]of Object.entries(t))cp(n,s,a);return n}case"raw":return t}}function xa(e){return!!(e==null||typeof e=="string"||e instanceof URLSearchParams||e instanceof Blob||e instanceof FormData||e instanceof ArrayBuffer||ArrayBuffer.isView(e))}function fS(e){if(!e)return"";let t=new URLSearchParams;for(let[s,a]of Object.entries(e))cp(t,s,a);let n=t.toString();return n===""?"":`?${n}`}function cp(e,t,n){if(n!=null){if(Array.isArray(n)){for(let s of n)cp(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 bS(e,t){let n=await wS(t,cS).catch(()=>""),s;try{s=n===""?void 0:JSON.parse(n)}catch{s=n}let a=vS(s)?s:void 0,o=Number(t.headers.get("retry-after")),i=t.status>=300&&t.status<400;return new G({op:e,status:t.status,code:a?.error??(i?"undeclared_redirect":`http_${t.status}`),message:a?.error_description??(i?`${e}: the server redirected (${t.status}); the request was not followed, its credentials stay here`:`${e}: ${t.status} ${t.statusText}`.trim()),requestId:a?.request_id??t.headers.get("x-request-id")??void 0,retryAfter:a?.retry_after??(Number.isFinite(o)&&o>0?o:void 0),body:s})}async function wS(e,t){if(!e.body)return"";let n=e.body.getReader(),s=[],a=0;for(;a<t;){let{done:r,value:l}=await n.read();if(r)break;s.push(l),a+=l.byteLength}await n.cancel().catch(()=>{});let o=new Uint8Array(Math.min(a,t)),i=0;for(let r of s){let l=Math.min(r.byteLength,o.byteLength-i);if(o.set(r.subarray(0,l),i),i+=l,i>=o.byteLength)break}return new TextDecoder().decode(o)}function vS(e){return typeof e=="object"&&e!==null&&typeof e.error=="string"}var Hi={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 b=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 h(e,t){return new b("usage",e,{hint:t,exitCode:2})}var Vi=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(`${le(t)}
|
|
5
5
|
`)}note(t){this.io.stderr(`${le(t)}
|
|
@@ -9,7 +9,7 @@ var Q0=Object.defineProperty;var wt=(e,t)=>{for(var n in t)Q0(e,n,{get:t[n],enum
|
|
|
9
9
|
`);let i;try{i=await this.io.fetch(t,{method:n.method,headers:{...n.headers,...a},body:n.body,signal:n.signal,...s?{}:{duplex:"half"},redirect:"manual"})}catch(l){throw n.signal?.aborted?l:new b("network_error",`${new URL(t).origin} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(this.debug&&this.io.stderr(`< ${i.status} ${i.headers.get("x-request-id")??""}
|
|
10
10
|
`),i.status!==503||!s||o>=LS||!xS.has(await hp(i)??""))return i;await i.body?.cancel();let r=Number(i.headers.get("retry-after")??"");await this.io.sleep((Number.isFinite(r)&&r>0?Math.min(r,30):1)*1e3)}}async exchange(t,n,s){let a=await this.token(),o=await this.send(t,n,s,a.value);if(o.status===401&&a.renewable){let i=await this.renew(await this.currentSession());o=await this.send(t,n,s,i.access_token)}return{res:o,renewable:a.renewable}}async answered(t,n,s,a){if(s.status===204)return;let o=await s.text(),i=o===""?void 0:IS(o);if(s.ok)return i;let r=i??{};throw s.status===401?r.error==="token_not_for_machines"?Vu(new URL(this.cloud.studioApi).host):a?La():this.tokenRefused("Studio"):new G({op:`${t} ${n}`,status:s.status,code:r.error??`http_${s.status}`,message:r.error_description??`Studio answered ${s.status}`,requestId:r.request_id??s.headers.get("x-request-id")??void 0,body:i})}tokenRefused(t){return(this.io.env.PALBASE_TOKEN??"").startsWith("pbe_")?new b("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 b("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 b("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 Fu(this.io,this.cloud,t);return await this.state.writeSession(n),this.session=n,n}async send(t,n,s,a){let o=`${this.cloud.studioApi}${OS}${n}`;this.debug&&this.io.stderr(`> ${t} ${o}
|
|
11
11
|
`);try{let i=await this.io.fetch(o,{method:t,headers:{...a===void 0?{}:{authorization:`Bearer ${a}`},accept:"application/json",...s===void 0?{}:{"content-type":"application/json"}},body:s===void 0?void 0:JSON.stringify(s),redirect:"manual"});return this.debug&&this.io.stderr(`< ${i.status} ${i.headers.get("x-request-id")??""}
|
|
12
|
-
`),i}catch(i){throw new b("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${i instanceof Error?i.message:String(i)}`)}}};function Vu(e){return new b("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 hp(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 IS(e){try{return JSON.parse(e)}catch{return e}}var Xu={version:"0.73.
|
|
12
|
+
`),i}catch(i){throw new b("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${i instanceof Error?i.message:String(i)}`)}}};function Vu(e){return new b("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 hp(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 IS(e){try{return JSON.parse(e)}catch{return e}}var Xu={version:"0.73.1"};var er=Xu.version;async function tm(e,t,n,s){let a=new Map(n.map(r=>[r.name,r])),o=e.includes("--json"),i=e.includes("--debug");try{let{name:r,at:l}=DS(e);if(r===void 0)return e.includes("--version")?(t.stdout(`palbase ${er}
|
|
13
13
|
`),0):(t.stdout(em(n)),e.length===0||e.includes("--help")||e.includes("-h")?0:2);if(r==="help"){let T=e[l+1],C=T===void 0?void 0:a.get(T);if(T!==void 0&&!C)throw Yu(T,n);return t.stdout(C?Qu(C):em(n)),0}let p=a.get(r);if(!p)throw Yu(r,n);let d=[...e.slice(0,l),...e.slice(l+1)],u=d.includes("--")?d.slice(0,d.indexOf("--")):d;if(u.includes("--help")||u.includes("-h"))return t.stdout(Qu(p)),0;let{flags:g,positionals:y}=zS(p,d),w=p.args??{min:0,max:0};if(y.length<w.min)throw h(`${p.name} needs ${w.min===1?"an argument":`${w.min} arguments`}`,fp(p));if(y.length>w.max)throw h(`${p.name} takes ${w.max===0?"no argument":`at most ${w.max}`}: ${JSON.stringify(y.slice(w.max))} is left over`,fp(p));let v={project:g.project,env:g.env,json:g.json===!0,nonInteractive:g["non-interactive"]===!0,yes:g.yes===!0,debug:g.debug===!0},R=qu(t.env),P=new Yi(Ku(t.configDir,R)),E={io:t,state:P,out:new Vi(t,v.json),global:v,args:y,flags:g,interactive:t.interactive&&!v.nonInteractive,cloud:R,studio:new Qi(t,R,P,v.debug,s?.callPlatform)};return await p.run(E)??0}catch(r){return qS(r,t,o,i)}}function DS(e){let t=new Set;for(let[n,s]of Object.entries(Hi))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 zS(e,t){let n={...Hi,...e.flags??{}},s={};for(let[a,o]of Object.entries(n))s[a]={type:o.type,...o.short?{short:o.short}:{},...o.multiple?{multiple:!0}:{}};try{let{values:a,positionals:o}=MS({args:t,options:s,strict:!0,allowPositionals:!0});return{flags:a,positionals:o}}catch(a){throw h(a instanceof Error?a.message.replace(/^.*?: /,""):String(a),`palbase help ${e.name}`)}}function qS(e,t,n,s){let a="error",o,i,r=1,l;return e instanceof b?(a=e.code,o=e.message,i=e.hint,r=e.exitCode):e instanceof G?(a=e.code,o=e.message,l=e.requestId,e.code==="token_out_of_scope"&&t.env.PALBASE_TOKEN&&(o=`${e.op} refused PALBASE_TOKEN: ${e.message}`,i="this is the token's reach, fixed when it was minted: a person's yes does not change it \u2014 mint a token whose scopes name this call, or have a person run it signed in")):o=e instanceof Error?e.message:String(e),n&&e instanceof b&&e.reported||(n&&t.stdout(`${JSON.stringify({error:a,message:o,...i?{hint:i}:{},...l?{request_id:l}:{}},null,2)}
|
|
14
14
|
`),t.stderr(`error: ${le(o)}${l?` (request ${le(l)})`:""}
|
|
15
15
|
`),i&&t.stderr(` ${le(i)}
|
|
@@ -49,10 +49,10 @@ ${i}`}function Kp(e,t){let n=[],s=new Set,a=o=>{s.has(o)||(s.add(o),n.push(o))};
|
|
|
49
49
|
`)+1;e.io.stdout(le(E.slice(0,T))),w=E.slice(T),y=R.log}if(R.state!=="queued"&&R.state!=="building")return w!==""&&e.io.stdout(`${le(w)}
|
|
50
50
|
`),e.out.result({site:a,url:n.url,build:R},()=>e.out.line(R.state==="succeeded"?`${a} serves the build of ${R.commit.slice(0,7)}: ${n.url}`:`The build ${R.state}${R.reason?`: ${R.reason}`:""} \u2014 ${a} serves what it served.`)),R.state==="succeeded"?0:1;if(v===900)throw new b("timeout",`the build ${u} was still ${R.state} after 30 minutes; it goes on`,{hint:`palbase hosting:builds ${u} --site ${a} --wait`});if(await p())return d(u)}}finally{process.removeListener("SIGINT",l)}}var yP={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.",Ce("site")],flags:{...tn,"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 en(e,$n(e),e.flags.site!==void 0);await k(e,t,`build ${n} from the head of its branch`);let a=e.flags["no-wait"]!==!0?new Set((await m(e,t,"GET",`/sites/${Fe(n)}/builds`)).builds.map(i=>i.id)):void 0,o=await m(e,t,"POST",`/sites/${Fe(n)}/builds`);if(a)return hP(e,t,o,a);e.out.result(o,()=>e.out.line(`${o.name}: a build of ${o.source?.branch??"its branch"}'s head is on its way (palbase hosting:builds --site ${o.name}).`))}},fP={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.",Ce("site")],flags:tn,scope:"environment",async run(e){let{t,site:{name:n}}=await en(e,$n(e),e.flags.site!==void 0),{previews:s,branches:a=[]}=await m(e,t,"GET",`/sites/${Fe(n)}/previews`);e.out.result({previews:s,branches:a},()=>{(s.length>0||a.length===0)&&Zp(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 o of a)e.out.line(`branch ${o.branch} ${o.state} ${o.commit.slice(0,7)} ${o.url}`)})}},bP={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:[Ce("site")],flags:tn,scope:"environment",async run(e){let{t,site:{name:n}}=await en(e,$n(e),e.flags.site!==void 0),{links:s}=await m(e,t,"GET",`/sites/${Fe(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}])})}},wP={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.",Ce("site")],flags:{...tn,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 h("--days is a whole number of days, 1 to 30");let n=e.flags.name;if(n!==void 0&&n.length>64)throw h("a link's --name is 64 characters at most");let{t:s,site:{name:a}}=await en(e,$n(e),e.flags.site!==void 0);await k(e,s,`make a share link that opens ${a}'s previews to whoever holds it${t!==void 0?`, for ${t} days`:""}`);let o=await m(e,s,"POST",`/sites/${Fe(a)}/previews/links`,{...n!==void 0?{name:n}:{},...t!==void 0?{days:t}:{}});e.out.result(o,()=>{e.out.line(`Made the share link ${o.id}${o.name?` (${o.name})`:""}: it opens ${a}'s previews until ${o.expires_at}. Its token:`),e.out.line(` ${o.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 ${o.id} --site ${a} closes the previews to it.`)})}},vP={name:"hosting:previews:unlink",summary:"delete a share link: the site's previews close to it at once",usage:"<link id> [--site <name>]",details:[Ce("site")],args:{min:1,max:1},flags:tn,scope:"environment",async run(e){let{t,site:{name:n}}=await en(e,$n(e),e.flags.site!==void 0);await k(e,t,`delete the share link ${e.args[0]} of ${n}'s previews`),await m(e,t,"DELETE",`/sites/${Fe(n)}/previews/links/${Q("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.`))}},kP={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.",Ce("site")],args:{min:1,max:1},flags:tn,scope:"environment",async run(e){let t;try{t=new URL(e.args[0])}catch{throw h(`${JSON.stringify(e.args[0])} is not an address: a preview's, as hosting:previews lists it`)}if(t.protocol!=="https:")throw h("a preview's address is https://\u2026");let{t:n,site:{name:s}}=await en(e,$n(e),e.flags.site!==void 0),a=await m(e,n,"POST",`/sites/${Fe(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}.`)})}},_P=Xp("site","hosting",Rr,tn),SP=Yp("site","hosting",Rr,tn),$P=ed("site","hosting",Rr,tn),AP=Qp("site","hosting",Rr,tn),tg=[aP,oP,iP,rP,lP,pP,dP,cP,uP,yP,$P,...AP,fP,SP,bP,wP,vP,kP,..._P];var ng={name:"auth:settings:get",summary:"the environment's auth settings: passwords, email confirmation, sessions, tokens, passkeys, risk",scope:"environment",async run(e){let t=await f(e),{body:n}=await Rt(e,t,"/admin/auth-settings");e.out.result(n,()=>Ma(e,n))}},sg={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"'.`,'app_name=Koz names your app in its invitations ("Koz invited you"); app_name= clears it.',"The change is made on the revision read: one made beside it in the meantime (Studio, another terminal) is refused, not overwritten.","palbase auth:settings:get lists the keys."],args:{min:1,max:50},scope:"environment",async run(e){let t=await f(e),n=Rs(e.args),{body:s,etag:a}=await Rt(e,t,"/admin/auth-settings"),o=js(s,n),i=os(s,o);if(i.length===0)return Dt(e,"the auth settings",s);await k(e,t,`set the auth settings ${i.join(", ")}`);let r=await m(e,t,"PUT","/admin/auth-settings",Object.fromEntries(i.map(l=>[l,o[l]])),vt(a));e.out.result({settings:r,changed:i},()=>{for(let l of i)e.out.line(`${l}: ${kt(s[l])} \u2192 ${kt(r[l])}`)})}},ta=["google","apple","github","microsoft"],PP={google:"web_client_id",apple:"services_id",microsoft:"application_id",github:"oauth_client_id"},RP=new Set(["organizations","consumers","common"]);function ag(e){return Object.fromEntries(ta.map(t=>[t,`${e.replace(/\/$/,"")}/auth/oauth/callback/${t}`]))}function td(e,t){for(let[n,s]of Object.entries(ag(t)))e.out.line(` ${n.padEnd(9)} ${s}`)}var og={name:"auth:providers:list",summary:"the sign-in methods: email, phone and the social providers, whether each is on, their clients, stored secrets (by name) and callback URLs",details:["Each social provider sends its people back to a callback at the address the environment signs in at \u2014 its own, or one of its own domains (auth:domains): register it at the provider (Google's Authorized redirect URIs, Apple's Services ID Return URLs, Microsoft's and GitHub's redirect URIs)."],scope:"environment",async run(e){let t=await f(e),[n,s]=await Promise.all([m(e,t,"GET","/admin/providers"),m(e,t,"GET","/admin/social-auth")]),a=n.auth_base_url??"",o=[...n.providers.map(r=>({provider:r.id,on:r.enabled,detail:r.settings?`codes by ${r.settings.sender??"sms"}, ${r.settings.otp_ttl_seconds}s, ${r.settings.otp_max_attempts} tries, sign-up ${r.settings.allow_signups?"on":"off"}`:"",secrets:""})),...ta.map(r=>{let l=s.providers[r]??{enabled:!1,browser_clients:[],native_clients:[]},p=[...l.browser_clients.map(d=>`${d.key} (${d.platform})`),...l.native_clients.map(d=>`${d.key} (${d.platform}, native)`)];return{provider:r,on:l.enabled,detail:p.length===0?"no client":p.join(", "),secrets:s.credentials.filter(d=>d.provider===r).map(d=>`${d.key} ${d.configured?"set":"not set"}`).join(", ")}})],i=a?ag(a):{};e.out.result({providers:n.providers,social:s.providers,credentials:s.credentials,auth_base_url:a,callback_urls:i},()=>{e.out.table(o,[{header:"provider",value:r=>r.provider},{header:"on",value:r=>r.on?"yes":"no"},{header:"clients / settings",value:r=>r.detail},{header:"secrets",value:r=>r.secrets}]),a&&(e.out.line(""),e.out.line(`Signs in at ${a}. Callback URLs to register at each provider:`),td(e,a))})}};function ig(e,t){Ua(e,t),t.sign_in&&e.out.line(t.state==="active"?" The environment signs in here.":" The environment signs in here once it answers again; at its own address meanwhile."),e.out.line(" Its callback URLs, to register at each provider before signing in here:"),td(e,`https://${t.host}`)}var nd=e=>e.trim().toLowerCase().replace(/\.$/,"");function rg(e,t){if(t){if(t.saved>0){e.out.line(`Passkeys are saved at ${t.host}: ${t.saved===1?"1 passkey is":`${t.saved} passkeys are`} there, and they stay there wherever the environment signs in.`);return}e.out.line(`Passkeys are saved at ${t.host}: none yet \u2014 they follow where the environment signs in, and the first one saved keeps them there for good.`)}}var lg={name:"auth:domains",summary:"the environment's own domains \u2014 auth.example.com \u2014 its sign-in answers at: whether each answers, what its DNS still needs, and where the environment signs in",details:["A domain of your own answers the environment's sign-in \u2014 its social providers' callbacks, its OpenID provider, its pages, its passkeys \u2014 so Google's consent screen, Apple's, the passkey sheet and your users' browsers show it, not the platform's address.","It says where the environment's passkeys are saved: while it has none they follow where it signs in, and the first one saved keeps them there for good."],scope:"environment",async run(e){let t=await f(e),{domains:n,passkeys:s}=await m(e,t,"GET","/domains");e.out.result({domains:n,...s?{passkeys:s}:{}},()=>{n.length===0&&e.out.line("No domain yet: palbase auth:domains:add auth.<your domain> adds one.");for(let o of n)ig(e,o);let a=n.find(o=>o.sign_in&&o.state==="active");e.out.line(a?`Signs in at https://${a.host}.`:"Signs in at the environment's own address: palbase auth:domains:use <host> moves it, once the domain answers."),rg(e,s)})}},pg={name:"auth:domains:add",summary:"have the environment's sign-in answer at a subdomain of your own too (auth.example.com)",usage:"<host>",details:["It answers once its DNS points at the platform (a CNAME) and says it is this environment's (the TXT record): both are printed. A subdomain only \u2014 your domain itself is your app's.","Then register its callback URLs at each social provider (printed), and move sign-in to it: palbase auth:domains:use <host>.","It counts among the project's domains, every environment's together."],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=nd(e.args[0]);await k(e,t,`add the domain ${n} to the environment's sign-in`);let s=await m(e,t,"POST","/domains",{host:n});e.out.result(s,()=>{ig(e,s),e.out.line(`Once it is active (palbase auth:domains) and the providers know its callbacks: palbase auth:domains:use ${s.host}.`)})}},dg={name:"auth:domains:use",summary:"sign the environment's people in at one of its own domains \u2014 or, with --none, at its own address again",usage:"<host> | --none",details:["It holds at once: a social sign-in begun after it sends its provider back to the domain's callback, which the provider must know first (auth:domains prints them) \u2014 one that does not refuses the sign-in. The environment's emails and pages name the domain, and an OpenID client that discovers it is answered as it.","Its own address keeps answering as before: a session begun there, and your backend's checks of its tokens, go on.","While the environment has no passkey saved, its passkeys follow: the passkey sheet names the domain, and the first one saved keeps them there for good. An iOS app lists webcredentials:<host> in its Associated Domains \u2014 palbase apps:sync writes it \u2014 so sync and ship a build first."],args:{min:0,max:1},flags:{none:{type:"boolean",description:"sign in at the environment's own address"}},scope:"environment",async run(e){let t=e.flags.none===!0;if(t===(e.args.length===1))throw h("name the domain to sign in at, or --none");let n=await f(e),s=t?"":nd(e.args[0]);if(t){let{domains:i}=await m(e,n,"GET","/domains"),r=i.find(l=>l.sign_in);if(!r){e.out.result({sign_in:null},()=>e.out.line("The environment signs in at its own address already."));return}s=r.host}await k(e,n,t?`sign in at the environment's own address, not ${s}`:`sign in at ${s}: the social providers must have its callback URLs (auth:domains)`);let a=await m(e,n,"PATCH",`/domains/${Q("the domain",s)}`,{sign_in:!t}),{passkeys:o}=e.out.json?{passkeys:void 0}:await m(e,n,"GET","/domains");e.out.result(a,()=>{t?e.out.line(`Signs in at the environment's own address; ${a.host} answers still.`):(e.out.line(`Signs in at https://${a.host}. Its callback URLs:`),td(e,`https://${a.host}`)),rg(e,o),o&&o.saved===0&&o.host===a.host&&e.out.line(`An iOS app lists webcredentials:${a.host} in its Associated Domains: palbase apps:sync, then ship a build.`)})}},cg={name:"auth:domains:remove",summary:"stop the environment's sign-in answering at one of its own domains: at once, and another environment may add it",usage:"<host>",details:["The one it signs in at is kept: move sign-in first (auth:domains:use).","The one the environment's passkeys are saved at is kept while it has any: they sign in only there."],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=nd(e.args[0]);await k(e,t,`remove the domain ${n}`),await m(e,t,"DELETE",`/domains/${Q("the domain",n)}`),e.out.result({removed:n},()=>e.out.line(`${n} answers no more.`))}},ug={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:{...Wo,client:{type:"string",value:"key",description:"the browser client --client-id, --return-uri and the secret go to (default web)"},"client-id":{type:"string",value:"id",description:"the provider's id of your app (Google web client id, Apple services id, Microsoft application id, GitHub client id)"},"return-uri":{type:"string",multiple:!0,value:"url",description:"where your app is sent back after sign-in (repeat it; replaces the list)"},application:{type:"string",value:"key",description:"the application the client is for (default app)"},variant:{type:"string",value:"name",description:"the build variant the client is for (default release)"},directory:{type:"string",value:"tenant",description:"microsoft: a tenant id, organizations, consumers or common (default common)"},"secret-stdin":{type:"boolean",description:"read the client's secret (Apple: the .p8 key) from stdin"},credential:{type:"string",value:"key",description:"the name the secret is kept under (default: the provider's)"},"team-id":{type:"string",value:"id",description:"apple: your team's id, with --secret-stdin"},"key-id":{type:"string",value:"id",description:"apple: the signing key's id, with --secret-stdin"},"clients-file":{type:"string",value:"path",description:"replace the provider's clients with the file's (JSON)"}},scope:"environment",async run(e){let t=e.args[0],n=await f(e);if(t==="email")throw new b("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 jP(e,n,e.args.slice(1));if(!ta.includes(t))throw h(`no provider ${JSON.stringify(t)}`,`the providers: email, phone, ${ta.join(", ")}`);if(e.args.length>1)throw h(`${t} takes flags, not settings: palbase help auth:providers:set`);await TP(e,n,t)}};async function jP(e,t,n){let s=Da(e),a=Rs(n);if(s===void 0&&a.length===0)throw h("nothing to change: --enable, --disable or setting=value","palbase help auth:providers:set");let o=await m(e,t,"GET","/admin/providers/phone/settings"),i=js(o,a),r=os(o,i);if(s===void 0&&r.length===0)return Dt(e,"the phone settings",o);await k(e,t,`phone sign-in: ${[...s===void 0?[]:[s?"turn it on":"turn it off"],...r.map(d=>`set ${d}`)].join(", ")}`);let l=r.length>0?await m(e,t,"PUT","/admin/providers/phone/settings",i):o,p=s===void 0?void 0:await m(e,t,"POST","/admin/providers/phone",{enabled:s});e.out.result({provider:"phone",...p?{enabled:p.enabled}:{},settings:l},()=>{p&&e.out.line(`phone sign-in is ${p.enabled?"on":"off"}.`);for(let d of r)e.out.line(`${d}: ${kt(o[d])} \u2192 ${kt(l[d])}`)})}function EP(e){if(RP.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 h("--directory is a tenant id, organizations, consumers or common")}async function TP(e,t,n){let s=e.flags,a=Da(e),o=await Rt(e,t,"/admin/social-auth"),i=o.etag,r=o.body.providers[n]??{enabled:!1,browser_clients:[],native_clients:[]},l={},p=[],d=s.credential??n,u;if(s["secret-stdin"]===!0){if(n==="apple"&&(s["team-id"]===void 0||s["key-id"]===void 0))throw h("Apple's signing key goes with --team-id and --key-id");u=await lt(e,n==="apple"?"Apple's .p8 signing key":`${n}'s client secret`),p.push(`keep its secret as ${d}`)}let g=["client","client-id","return-uri","application","variant","directory","credential"].filter(R=>s[R]!==void 0);if(s["clients-file"]!==void 0){if(g.length>0)throw h(`--clients-file and --${g[0]} are one or the other`);let R=Ne(await ze(e,s["clients-file"],"the clients"),"the clients file");if(typeof R!="object"||R===null||R.browser_clients===void 0&&R.native_clients===void 0)throw h('the clients file is {"browser_clients": [\u2026], "native_clients": [\u2026]}');l.browser_clients=R.browser_clients??r.browser_clients,l.native_clients=R.native_clients??r.native_clients,p.push(`set its clients from ${s["clients-file"]}`)}else if(g.length>0||u!==void 0){let R=s.client??"web",P=[...r.browser_clients],E=P.findIndex(C=>C.key===R),T=u!==void 0&&g.every(C=>C==="credential");if(E>=0||!T){let C=E>=0?{...P[E]}:{key:R,enabled:!0,application_key:"app",platform:"web",variant:"release",return_uris:[]},W=PP[n];if(s["client-id"]!==void 0&&(C[W]=s["client-id"]),!C[W])throw h(`the ${n} client ${R} is new: give it --client-id`);if(s["return-uri"]!==void 0&&(C.return_uris=s["return-uri"]),s.application!==void 0&&(C.application_key=s.application),s.variant!==void 0&&(C.variant=s.variant),n==="microsoft")C.directory=s.directory!==void 0?EP(s.directory):C.directory??{mode:"common"};else if(s.directory!==void 0)throw h("--directory is a Microsoft client's");(u!==void 0||s.credential!==void 0||!C.credential_ref)&&(C.credential_ref=d),P[E>=0?E:P.length]=C,l.browser_clients=P,p.push(`${E>=0?"change":"add"} its browser client ${R}`)}}if(a!==void 0&&(l.enabled=a,p.push(a?"turn it on":"turn it off")),p.length===0)throw h("nothing to change: give a flag","palbase help auth:providers:set");await k(e,t,`${n} sign-in: ${p.join(", ")}`);let y=o.body;if(u!==void 0){let R=n==="apple"?{provider:n,kind:"apple_signing_key",team_id:s["team-id"],key_id:s["key-id"],private_key:u}:{provider:n,kind:"oauth_client_secret",client_secret:u};i=(await Pt(e,t,"PUT",`/admin/social-auth/credentials/${A(d)}`,R,vt(i))).etag??i}Object.keys(l).length>0?y=await m(e,t,"PATCH",`/admin/social-auth/providers/${A(n)}`,l,vt(i)):y=await m(e,t,"GET","/admin/social-auth");let w=y.providers[n],v=y.credentials.filter(R=>R.provider===n);e.out.result({provider:n,...w,credentials:v},()=>{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 R of v)e.out.line(` secret ${R.key}: ${R.configured?"set":"not set"}`)})}var mg={name:"auth:providers:secret:delete",summary:"delete a sign-in provider's stored secret by its name; one a client still uses is refused",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0],n=await f(e),{body:s,etag:a}=await Rt(e,n,"/admin/social-auth");if(!s.credentials.some(o=>o.key===t))throw h(`the environment holds no provider secret ${JSON.stringify(t)}`,"palbase auth:providers:list names them");await k(e,n,`delete the provider secret ${t}`),await m(e,n,"DELETE",`/admin/social-auth/credentials/${A(t)}`,void 0,vt(a)),e.out.result({deleted:t},()=>e.out.line(`Deleted the provider secret ${t}.`))}},gg={name:"auth:providers:disable",summary:"turn a sign-in provider off (phone, google, apple, github, microsoft); its clients and secrets stay",usage:"<provider>",args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0],n=await f(e);if(t==="email")throw new b("always_on","email sign-in cannot be turned off");if(t==="phone"){await k(e,n,"turn phone sign-in off");let o=await m(e,n,"POST","/admin/providers/phone",{enabled:!1});e.out.result(o,()=>e.out.line("phone sign-in is off."));return}if(!ta.includes(t))throw h(`no provider ${JSON.stringify(t)}`,`the providers: phone, ${ta.join(", ")}`);let{etag:s}=await Rt(e,n,"/admin/social-auth");await k(e,n,`turn ${t} sign-in off`);let a=await m(e,n,"PATCH",`/admin/social-auth/providers/${A(t)}`,{enabled:!1},vt(s));e.out.result({provider:t,...a.providers[t]},()=>e.out.line(`${t} sign-in is off; its clients and secrets stay.`))}},hg={name:"auth:roles:list",summary:"the environment's roles: their permissions, which one new users get, how many users hold each",scope:"environment",async run(e){let t=await f(e),{roles:n}=await m(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}])})}},yg={name:"auth:roles:set",summary:"make a role, or change one: its permissions (the list is replaced), description, whether new users get it",usage:"<name> [--permissions <a.b,c.d>] [--description <text>] [--default yes|no]",args:{min:1,max:1},flags:{permissions:{type:"string",multiple:!0,value:"list",description:'resource.action permissions, comma-separated or repeated; replaces the list ("" for none)'},description:{type:"string",value:"text",description:"what the role is for"},default:{type:"string",value:"yes|no",description:"whether new users get it (one role at most)"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0],{roles:s}=await m(e,t,"GET","/admin/roles"),a=s.find(d=>d.name===n),o=Me(e.flags.permissions),i=Gn(e.flags.default,"default");if(a&&o===void 0&&e.flags.description===void 0&&i===void 0)throw h("nothing to change: give a flag","palbase help auth:roles:set");let r={permissions:o??a?.permissions??[],description:e.flags.description??a?.description??"",is_default:i??a?.is_default??!1};await k(e,t,`${a?"change":"make"} the role ${n}${a?.user_count?` (${a.user_count} users hold it)`:""}`);let l=await m(e,t,"PUT",`/admin/roles/${A(n)}`,r),p=l.roles.find(d=>d.name===n);e.out.result(p??l,()=>e.out.line(`${a?"Changed":"Made"} the role ${n}: ${(p?.permissions??r.permissions).join(", ")||"no permission"}${p?.is_default?", given to new users":""}.`))}},fg={name:"auth:roles:delete",summary:"delete a role; one users hold is deleted only with --force, and is taken from them",usage:"<name> [--force]",args:{min:1,max:1},flags:{force:{type:"boolean",description:"delete it although users hold it"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0];await k(e,t,`delete the role ${n}${e.flags.force===!0?", taking it from the users who hold it":""}`),await m(e,t,"DELETE",`/admin/roles/${A(n)}${e.flags.force===!0?"?confirm=true":""}`),e.out.result({deleted:n},()=>e.out.line(`Deleted the role ${n}.`))}},bg={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)"}},wg={name:"auth:hooks:list",summary:"the blocking hooks: what auth calls, and waits for, before a sign-up, a sign-in, a token",scope:"environment",async run(e){let t=await f(e),{hooks:n}=await m(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"}])})}},vg={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:{...bg,disable:{type:"boolean",description:"register it turned off"}},scope:"environment",async run(e){let t=await f(e);if(e.flags.event===void 0||e.flags.url===void 0)throw h("a hook needs --event and --url");let n=Pp({event:e.flags.event,url:e.flags.url,failure_mode:e.flags["failure-mode"],timeout_ms:we(e.flags.timeout,"timeout"),...e.flags.disable===!0?{enabled:!1}:{}});await k(e,t,`register a hook on ${String(n.event)} calling ${String(n.url)}`);let s=await m(e,t,"POST","/admin/hooks",n,D());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}`)})}},kg={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:{...bg,...Wo},scope:"environment",async run(e){let t=await f(e),{hooks:n}=await m(e,t,"GET","/admin/hooks"),s=n.find(r=>r.id===e.args[0]);if(!s)throw new b("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:we(e.flags.timeout,"timeout")??s.timeout_ms,enabled:Da(e)??s.enabled},o=os(CP(s),a);if(o.length===0)throw h("nothing to change: give a flag","palbase help auth:hooks:update");await k(e,t,`change the hook ${s.id}: ${o.join(", ")}`);let i=await m(e,t,"PUT",`/admin/hooks/${A(s.id)}`,a);e.out.result(i,()=>e.out.line(`${i.id}: ${i.event} \u2192 ${i.url}, ${i.failure_mode} on failure, ${i.timeout_ms} ms, ${i.enabled?"on":"off"}.`))}};function CP(e){return{event:e.event,url:e.url,failure_mode:e.failure_mode,timeout_ms:e.timeout_ms,enabled:e.enabled}}var _g={name:"auth:hooks:delete",summary:"delete a blocking hook; auth stops calling it",usage:"<id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e);await k(e,t,`delete the hook ${e.args[0]}`),await m(e,t,"DELETE",`/admin/hooks/${A(e.args[0])}`),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the hook ${e.args[0]}.`))}},Sg={name:"auth:oauth-clients:list",summary:"the OAuth clients of the environment's OpenID provider (apps that sign in with your users' accounts)",scope:"environment",async run(e){let t=await f(e),{clients:n}=await m(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(", ")}])})}},$g={name:"auth:oauth-clients:create",summary:"register an OAuth client; a confidential client's secret is printed this once",usage:"<name> [--public] [--redirect-uri <url>\u2026] [--grant <type>\u2026] [--scope <scope>\u2026] [--client-id <id>]",args:{min:1,max:1},flags:{public:{type:"boolean",description:"a public client (a CLI, a mobile app): it has no secret"},"redirect-uri":{type:"string",multiple:!0,value:"url",description:"where it may send the browser back (repeat it)"},grant:{type:"string",multiple:!0,value:"type",description:"authorization_code (default), refresh_token, client_credentials, urn:ietf:params:oauth:grant-type:device_code"},scope:{type:"string",multiple:!0,value:"scope",description:"what it may ask for (default openid, profile, email)"},"client-id":{type:"string",value:"id",description:"a client_id to use as it is (default: a random one)"}},scope:"environment",async run(e){let t=await f(e),n=Pp({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:Me(e.flags.grant),scopes:Me(e.flags.scope)});await k(e,t,`register the OAuth client ${e.args[0]}`);let s=await m(e,t,"POST","/admin/oauth-clients",n,D());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}`)})}},Ag={name:"auth:oauth-clients:delete",summary:"delete an OAuth client (by its id or its client_id)",usage:"<id|client-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),{clients:n}=await m(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 b("no_such_client",`no OAuth client ${JSON.stringify(e.args[0])}`,{hint:"palbase auth:oauth-clients:list shows them"});await k(e,t,`delete the OAuth client ${s.client_name} (${s.client_id})`),await m(e,t,"DELETE",`/admin/oauth-clients/${A(s.id)}`),e.out.result({deleted:s.id},()=>e.out.line(`Deleted the OAuth client ${s.client_name}.`))}};function OP(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 Pg={name:"auth",async read(e,t){let[n,s,a,o,i,r]=await Promise.all([m(e,t,"GET","/admin/auth-settings"),m(e,t,"GET","/admin/providers"),m(e,t,"GET","/admin/social-auth"),m(e,t,"GET","/admin/roles"),m(e,t,"GET","/admin/hooks"),m(e,t,"GET","/admin/oauth-clients")]),l={};for(let[d,u]of Object.entries(n))l[`settings.${d}`]=u;let p=s.providers.find(d=>d.id==="phone");p&&(l["phone.enabled"]=p.enabled,p.settings&&(l["phone.settings"]=p.settings));for(let d of ta){let u=a.providers[d];u&&(l[`social.${d}`]={enabled:u.enabled,browser_clients:u.browser_clients,native_clients:u.native_clients})}for(let d of a.credentials)l[`secrets.${d.key}`]={provider:d.provider,kind:d.kind,value:d.configured?"set":"not set"};for(let d of o.roles)l[`roles.${d.name}`]={description:d.description,is_default:d.is_default,permissions:[...d.permissions].sort()};for(let d of i.hooks)l[`hooks.${d.event} ${d.url}`]={failure_mode:d.failure_mode,timeout_ms:d.timeout_ms,enabled:d.enabled};for(let d of r.clients)l[`oauth_clients.${d.client_name}`]=OP(d);return l},async copy(e,t,n,s){await xP(e,t,Ze(n,"settings."),s);for(let o of Ze(n,"phone."))o.name==="enabled"&&await Te(s,`turn phone sign-in ${o.from?"on":"off"}`,async()=>{await m(e,t,"POST","/admin/providers/phone",{enabled:o.from===!0})}),o.name==="settings"&&o.from!==void 0&&await Te(s,"set the phone code settings",async()=>{await m(e,t,"PUT","/admin/providers/phone/settings",o.from)});await LP(e,t,Ze(n,"social."),Ze(n,"secrets."),s);let a=Ze(n,"roles.").sort((o,i)=>+(o.from?.is_default===!0)-+(i.from?.is_default===!0));for(let o of a)o.from===void 0?await Te(s,`delete the role ${o.name}`,async()=>{await m(e,t,"DELETE",`/admin/roles/${A(o.name)}`)}):await Te(s,`set the role ${o.name}`,async()=>{await m(e,t,"PUT",`/admin/roles/${A(o.name)}`,o.from)});await IP(e,t,Ze(n,"hooks."),s),await NP(e,t,Ze(n,"oauth_clients."),s)}};async function xP(e,t,n,s){let a=n.filter(i=>i.from!==void 0);for(let i of n.filter(r=>r.from===void 0))s.left(`auth settings ${i.name}: set in the target only, and a setting is not taken away (set it with auth:settings:set)`);if(a.length===0)return;let{etag:o}=await Rt(e,t,"/admin/auth-settings");await Te(s,`set the auth settings ${a.map(i=>i.name).join(", ")}`,async()=>{await m(e,t,"PUT","/admin/auth-settings",Object.fromEntries(a.map(i=>[i.name,i.from])),vt(o))})}async function LP(e,t,n,s,a){for(let l of s){let p=l.from;p===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} (${p.provider}): secrets are not copied \u2014 set it with palbase auth:providers:set ${p.provider} --secret-stdin --credential ${l.name}`)}if(n.length===0)return;let o=await Rt(e,t,"/admin/social-auth"),i=o.etag,r=new Set(o.body.credentials.filter(l=>l.configured).map(l=>l.key));for(let l of n){let p=l.from,d=[...new Set(p.browser_clients.map(u=>u.credential_ref).filter(u=>typeof u=="string"&&!r.has(u)))];if(d.length>0){a.left(`${l.name} sign-in: its clients use the secret ${d.join(", ")}, which the target does not hold \u2014 set it first (auth:providers:set ${l.name} --secret-stdin --credential ${d[0]})`);continue}await Te(a,`set ${l.name} sign-in (${p.enabled?"on":"off"}, ${p.browser_clients.length+p.native_clients.length} client(s))`,async()=>{i=(await Pt(e,t,"PATCH",`/admin/social-auth/providers/${A(l.name)}`,p,vt(i))).etag??i})}}async function IP(e,t,n,s){if(n.length===0)return;let{hooks:a}=await m(e,t,"GET","/admin/hooks");for(let o of n){let i=o.name.indexOf(" "),r=o.name.slice(0,i),l=o.name.slice(i+1),p=a.find(d=>d.event===r&&d.url===l);if(o.from===void 0)p&&await Te(s,`delete the hook ${r} \u2192 ${l}`,async()=>{await m(e,t,"DELETE",`/admin/hooks/${A(p.id)}`)});else if(p)await Te(s,`change the hook ${r} \u2192 ${l}`,async()=>{await m(e,t,"PUT",`/admin/hooks/${A(p.id)}`,{event:r,url:l,...o.from})});else{let d;await Te(s,`register the hook ${r} \u2192 ${l}`,async()=>{d=(await m(e,t,"POST","/admin/hooks",{event:r,url:l,...o.from},D())).secret}),d&&s.shown(`the hook ${r} \u2192 ${l} signs with`,d)}}}async function NP(e,t,n,s){if(n.length===0)return;let{clients:a}=await m(e,t,"GET","/admin/oauth-clients");for(let o of n){let i=a.find(l=>l.client_name===o.name),r=o.from;if(r===void 0)i&&await Te(s,`delete the OAuth client ${o.name}`,async()=>{await m(e,t,"DELETE",`/admin/oauth-clients/${A(i.id)}`)});else if(i)if(!Mt(r.is_public,i.is_public)||r.client_id!==void 0&&r.client_id!==i.client_id)s.left(`OAuth client ${o.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:p,...d}=r;await Te(s,`change the OAuth client ${o.name}`,async()=>{await m(e,t,"PATCH",`/admin/oauth-clients/${A(i.id)}`,d)})}else{let l;await Te(s,`register the OAuth client ${o.name}`,async()=>{l=await m(e,t,"POST","/admin/oauth-clients",{client_name:o.name,...r},D())}),l?.client_secret&&s.shown(`the OAuth client ${o.name} (${l.client_id}) has the secret`,l.client_secret)}}}var Rg=["bool","number","string","object"];async function Cs(e,t){return(await m(e,t,"GET","/flags/templates/capabilities")).publish_enabled}async function Ts(e,t,n){let s=await Rt(e,t,"/flags/templates/draft");if(s.body.draft||!n)return{draft:s.body.draft,etag:s.etag};let a=await Rt(e,t,"/flags/templates/active"),o=await Pt(e,t,"POST","/flags/templates/draft",{},vt(a.etag));return{draft:o.body.draft,etag:o.etag}}function jg(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 MP(e){return typeof e=="boolean"?"bool":typeof e=="number"?"number":typeof e=="string"?"string":"object"}function Eg(e,t){switch(t){case"bool":if(e==="true"||e==="false")return e==="true";throw h(`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 h(`a number flag's value is a number, not ${JSON.stringify(e)}`);return n}case"string":{let n=qn(e);return typeof n=="string"?n:e}default:{let n=qn(e);if(typeof n!="object"||n===null)throw h(`an object flag's value is a JSON object or list, not ${JSON.stringify(e)}`);return n}}}function DP(e,t){let n=e.lastIndexOf("=>");if(n<=0)throw h(`a condition is "<expression> => <value>", not ${JSON.stringify(e)}`,`--condition "client.platform == 'ios' => true"`);return{when:e.slice(0,n).trim(),value:Eg(e.slice(n+2).trim(),t)}}var Tg={name:"flags:list",summary:"the environment's flags as they are live: type, default, targeting (and the draft's state when it publishes)",scope:"environment",async run(e){let t=await f(e),n=await Cs(e,t),s,a,o;if(n){let[i,r]=await Promise.all([m(e,t,"GET","/flags/templates/active"),Ts(e,t,!1)]);s=Object.entries(i.definitions).map(([l,p])=>({key:l,...p})),a=i.version,o=r.draft}else s=await m(e,t,"GET","/flags/system");s.sort((i,r)=>i.key<r.key?-1:1),e.out.result({publishing:n,...a?{version:a}:{},flags:s,...o?{draft:{revision:o.revision,base_version:o.base_version}}:{}},()=>{n&&e.out.line(`Version ${a} is live${o?`; a draft (from ${o.base_version}) is in progress: palbase flags:publish shows and publishes it`:""}.`),s.length===0&&e.out.line("No flag yet: palbase flags:set <key> <value> makes one."),e.out.table(s,[{header:"flag",value:i=>i.key},{header:"type",value:i=>i.value_type},{header:"value",value:i=>JSON.stringify(i.value)},{header:"targeting",value:i=>i.conditions?.length?`${i.conditions.length} condition(s)`:""},{header:"description",value:i=>i.description??""}])})}},Cg={name:"flags:set",summary:"define a flag or change its default and targeting (into the draft when the environment publishes)",usage:'<key> <value> [--type bool|number|string|object] [--condition "<expression> => <value>"\u2026] [--description <text>]',details:["The value is read as the flag's type: true/false, a number, text, or a JSON object; a new flag's type is the value's unless --type says it.","--condition replaces the targeting (first match wins, 8 at most); --clear-conditions takes it away; without either it stays.","An environment that publishes takes the change into its shared draft (palbase flags:publish makes it live); one that does not, live at once."],args:{min:2,max:2},flags:{type:{type:"string",value:"type",description:"bool, number, string or object"},condition:{type:"string",multiple:!0,value:"rule",description:'"<expression> => <value>" (repeat it, in order)'},"clear-conditions":{type:"boolean",description:"take its targeting away"},variants:{type:"string",value:"list",description:"a string flag's allowed values, comma-separated"},description:{type:"string",value:"text",description:"what the flag is for"}},scope:"environment",async run(e){let t=await f(e),[n,s]=e.args,a=e.flags.type;if(a!==void 0&&!Rg.includes(a))throw h(`--type is one of ${Rg.join(", ")}`);if(e.flags.condition!==void 0&&e.flags["clear-conditions"]===!0)throw h("--condition and --clear-conditions are one or the other");let o=await Cs(e,t),i,r;o?(r=await Ts(e,t,!1),i=r.draft?.definitions[n]??(await m(e,t,"GET","/flags/templates/active")).definitions[n]):i=(await m(e,t,"GET","/flags/system")).find(u=>u.key===n);let l=a??i?.value_type??MP(qn(s)),p=e.flags["clear-conditions"]===!0?[]:e.flags.condition!==void 0?e.flags.condition.map(u=>DP(u,l)):i?.value_type===l?i.conditions??[]:[],d=jg({value_type:l,value:Eg(s,l),description:e.flags.description??i?.description,variants:Me(e.flags.variants)??(i?.value_type===l?i.variants:void 0),conditions:p});if(await k(e,t,o?`put ${n} = ${kt(d.value)} into the flags draft`:`set the flag ${n} = ${kt(d.value)}, live at once`),o){r?.draft||(r=await Ts(e,t,!0));let u=await Pt(e,t,"PUT",`/flags/templates/draft/parameters/${A(n)}`,d,vt(r.etag));e.out.result({key:n,...d,draft:{revision:u.body.draft?.revision}},()=>e.out.line(`${n} = ${JSON.stringify(d.value)} is in the draft: palbase flags:publish makes it live.`))}else{let u=await m(e,t,"PUT",`/flags/system/${A(n)}`,d);e.out.result(u,()=>e.out.line(`${n} = ${JSON.stringify(u.value)} (${u.value_type}) is live.`))}}},Og={name:"flags:delete",summary:"delete a flag, with every user's own value of it (from the draft when the environment publishes)",usage:"<key>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=e.args[0],s=await Cs(e,t);if(await k(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 Ts(e,t,!0);await m(e,t,"DELETE",`/flags/templates/draft/parameters/${A(n)}`,void 0,vt(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 m(e,t,"DELETE",`/flags/system/${A(n)}`),e.out.result({deleted:n},()=>e.out.line(`Deleted the flag ${n}.`))}};function sd(){return new b("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 zP(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 ad(e,t,n,s){return m(e,t,"POST","/flags/templates/publish",s===""?{}:{note:s},{...vt(n),...D()})}var xg={name:"flags:publish",summary:"show the flags draft's changes against the live version, then publish it as the next version",usage:"[-m <note>]",flags:{note:{type:"string",short:"m",value:"note",description:"why: kept with the version"}},scope:"environment",async run(e){let t=await f(e);if(!await Cs(e,t))throw sd();if(!(await Ts(e,t,!1)).draft)throw new b("no_draft","there is no draft to publish",{hint:"palbase flags:set puts a change into one"});let s=await Rt(e,t,"/flags/templates/draft/review");if(e.out.json||zP(e,s.body),!s.body.can_publish)throw new b("cannot_publish",`the draft cannot be published: ${s.body.issues.map(o=>o.message).join("; ")}`);if(s.body.changes.length===0){e.out.result({unchanged:!0,review:s.body},()=>e.out.line("Nothing to publish."));return}await k(e,t,`publish the flags draft (${s.body.changes.length} change(s)) as the version after ${s.body.active_version}`);let a=await ad(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}.`))}},Lg={name:"flags:publishing:enable",summary:"turn publishing on for the environment's flags: changes go into a shared draft, live once published \u2014 for good",details:["What is live now becomes version 1. From then on flags:set and flags:delete change the draft, flags:publish makes it live as the next version, and flags:rollback brings an earlier one back. It cannot be turned off."],scope:"environment",async run(e){let t=await f(e);if(await Cs(e,t)){e.out.result({publishing:!0,changed:!1},()=>e.out.line("The environment's flags are published through drafts already."));return}await k(e,t,"turn publishing on for the flags \u2014 what is live becomes version 1, and it cannot be turned off");let n=await m(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.`))}},Ig={name:"flags:versions",summary:"the published versions of the flags, newest first, and which one is live",usage:"[--limit <n>]",flags:{limit:{type:"string",value:"n",description:"how many (default 20)"}},scope:"environment",async run(e){let t=await f(e);if(!await Cs(e,t))throw sd();let n=Number(e.flags.limit??20);if(!Number.isInteger(n)||n<=0)throw h("--limit is a whole number");let s=await m(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}]))}},Ng={name:"flags:rollback",summary:"make an earlier version of the flags live again (published as the next version)",usage:"<version> [-m <note>]",args:{min:1,max:1},flags:{note:{type:"string",short:"m",value:"note",description:"why (default: rollback to <version>)"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0];if(!await Cs(e,t))throw sd();if((await Ts(e,t,!1)).draft)throw new b("draft_in_progress","a draft is in progress: publish it (flags:publish) before a rollback");let s=await Rt(e,t,"/flags/templates/active");await k(e,t,`make version ${n} of the flags live again (now ${s.body.version})`);let a=await Pt(e,t,"POST",`/flags/templates/restore/${A(n)}`,{},vt(s.etag)),o=await ad(e,t,a.etag,e.flags.note??`rollback to ${n}`);e.out.result(o,()=>e.out.line(o.unchanged?`Version ${n} is what is live already.`:`Version ${n} is live again, as version ${o.template.version}.`))}},Mg={name:"flags",async read(e,t){let n=await m(e,t,"GET","/flags/system"),s={};for(let a of n)s[`flags.${a.key}`]=jg(a);return s},async copy(e,t,n,s){let a=Ze(n,"flags.");if(a.length===0)return;if(!await Cs(e,t)){for(let i of a)i.from===void 0?await Te(s,`delete the flag ${i.name}`,async()=>{await m(e,t,"DELETE",`/flags/system/${A(i.name)}`)}):await Te(s,`set the flag ${i.name}`,async()=>{await m(e,t,"PUT",`/flags/system/${A(i.name)}`,i.from)});return}if((await Ts(e,t,!1)).draft){s.left("flags: the target has a draft in progress \u2014 publish it (flags:publish) and copy again");return}let o=(await Ts(e,t,!0)).etag;for(let i of a)await Te(s,`${i.from===void 0?"take":"put"} the flag ${i.name} ${i.from===void 0?"out of":"into"} the draft`,async()=>{let r=`/flags/templates/draft/parameters/${A(i.name)}`;o=(i.from===void 0?await Pt(e,t,"DELETE",r,void 0,vt(o)):await Pt(e,t,"PUT",r,i.from,vt(o))).etag??o});await Te(s,"publish the flags draft",async()=>{await ad(e,t,o,"config:copy")})}};var Dg=["email","sms","verify","whatsapp","push"],od=["email","sms","whatsapp"],zg={name:"notify:providers:list",summary:"the environment's own providers, by channel and the order they are tried (never their credentials)",scope:"environment",async run(e){let t=await f(e),{providers:n}=await m(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"}])})}},qg={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"},...Wo},scope:"environment",async run(e){let[t,n]=e.args;if(!Dg.includes(t))throw h(`the channels: ${Dg.join(", ")}`);let s=await f(e),a=Ne(await lt(e,`${n}'s credentials (JSON)`),"the credentials");if(typeof a!="object"||a===null||Array.isArray(a))throw h("the credentials are a JSON object");let o=Da(e),i=we(e.flags.priority,"priority");await k(e,s,`send ${t} through ${n}`);let r=await m(e,s,"PUT",`/notify/providers/${A(t)}/${A(n)}`,{credentials:a,...o!==void 0?{active:o}:{},...i!==void 0?{priority:i}:{}},D());e.out.result(r,()=>e.out.line(`${r.channel} goes through ${r.provider} (${r.active?"on":"off"}, priority ${r.priority}); its credentials are kept sealed.`))}},Gg={name:"notify:providers:remove",summary:"forget a provider and its credentials",usage:"<channel> <provider>",args:{min:2,max:2},scope:"environment",async run(e){let[t,n]=e.args,s=await f(e);await k(e,s,`forget the ${t} provider ${n} and its credentials`),await m(e,s,"DELETE",`/notify/providers/${A(t)}/${A(n)}`,void 0,D()),e.out.result({removed:{channel:t,provider:n}},()=>e.out.line(`${t} no longer goes through ${n}.`))}},rd={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 oi(e){let t=e.flags.channel??"email";if(!od.includes(t))throw h(`--channel is one of ${od.join(", ")}`);return t}function ld(e,t){let n=e.flags.locale;if(n===void 0)throw h("which locale? pass --locale <locale>");return`/notify/templates/${oi(e)}/${A(t)}/${A(n)}`}function qP(e,t){if(e==="sms"){let s=GP(t);return typeof s=="object"&&s!==null&&typeof s.body=="string"?{body:s.body}:{body:t.replace(/\n$/,"")}}let n=Ne(t,`the ${e} template`);if(e==="email"){for(let s of["subject","html_body","text_body"])if(typeof n[s]!="string")throw h(`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 h('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 GP(e){try{return JSON.parse(e)}catch{return e}}var Kg={name:"notify:templates:list",summary:"the templates messages render from: the platform's defaults and the ones the environment overrides",usage:"[--channel email|sms|whatsapp]",flags:{channel:{type:"string",value:"channel",description:"only this channel's (default: all three)"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.channel===void 0?od:[oi(e)],s=await Promise.all(n.map(o=>m(e,t,"GET",`/notify/templates/${o}`))),a=n.flatMap((o,i)=>s[i].templates.map(r=>({channel:o,...r})));e.out.result({templates:a},()=>e.out.table(a,[{header:"channel",value:o=>o.channel},{header:"slug",value:o=>o.slug},{header:"locale",value:o=>o.locale},{header:"yours",value:o=>"customized"in o?o.customized?"yes":"default":"yes"},{header:"subject / text / template",value:o=>"subject"in o?o.subject:"body"in o?o.body.split(`
|
|
51
51
|
`)[0].slice(0,60):`${o.name} (${o.language})`}]))}},Ug={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:rd,scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",ld(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(`
|
|
52
|
-
`))e.out.line(a)}})}},Wg={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:{...rd,file:{type:"string",value:"path",description:"the template (default: stdin)"}},scope:"environment",async run(e){let t=await f(e),n=oi(e),s=ld(e,e.args[0]),a=qP(n,await ze(e,e.flags.file,"the template"));await k(e,t,`override the ${n} template ${e.args[0]} (${e.flags.locale})`);let o=await m(e,t,"PUT",s,a,D());e.out.result(o,()=>e.out.line(`The ${n} template ${e.args[0]} (${e.flags.locale}) is yours now${typeof o.subject=="string"?`: "${o.subject}"`:""}.`))}},Fg={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:rd,scope:"environment",async run(e){let t=await f(e),n=ld(e,e.args[0]);await k(e,t,`remove the ${oi(e)} template ${e.args[0]} (${e.flags.locale})`),await m(e,t,"DELETE",n,void 0,D()),e.out.result({deleted:{channel:oi(e),slug:e.args[0],locale:e.flags.locale}},()=>e.out.line(`Removed the override of ${e.args[0]} (${e.flags.locale}).`))}};async function id(e,t){let n=[],s;do{let a=await m(e,t,"GET",`/notify/topics?limit=100${s?`&cursor=${A(s)}`:""}`);n.push(...a.topics),s=a.next_cursor}while(s);return n}var Bg={name:"notify:topics:list",summary:"the topics users follow, how many follow each, whether they follow it from the app",scope:"environment",async run(e){let t=await f(e),n=await id(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"}])})}},Jg={name:"notify:topics:create",summary:"make a topic users can follow; a push to it reaches its followers",usage:"<name> [--self-subscribe yes|no]",args:{min:1,max:1},flags:{"self-subscribe":{type:"string",value:"yes|no",description:"users follow it from the app (default no: the project adds them)"}},scope:"environment",async run(e){let t=await f(e),n=Gn(e.flags["self-subscribe"],"self-subscribe");await k(e,t,`make the topic ${e.args[0]}`);let s=await m(e,t,"POST","/notify/topics",{name:e.args[0],...n!==void 0?{self_subscribe:n}:{}},D());e.out.result(s,()=>e.out.line(`Made the topic ${s.name}${s.self_subscribe?", followed from the app":""}.`))}},Hg={name:"notify:topics:delete",summary:"delete a topic and who follows it",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e);await k(e,t,`delete the topic ${e.args[0]} and who follows it`),await m(e,t,"DELETE",`/notify/topics/${A(e.args[0])}`,void 0,D()),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the topic ${e.args[0]}.`))}},Vg={name:"notify:settings:get",summary:"the environment's message settings: the default locale, who email is from, where texts may go",scope:"environment",async run(e){let t=await f(e),{body:n}=await Rt(e,t,"/notify/settings");e.out.result(n,()=>Ma(e,n))}},Xg={name:"notify:settings:set",summary:'change message settings: key=value (from_email=\u2026, sms_countries=["+90","+44"], mx_check=true)',usage:"<key=value>\u2026",details:["The change is made on the revision read: one made beside it in the meantime is refused, not overwritten."],args:{min:1,max:20},scope:"environment",async run(e){let t=await f(e),n=Rs(e.args),{body:s,etag:a}=await Rt(e,t,"/notify/settings"),o=js(s,n),i=os(s,o);if(i.length===0)return Dt(e,"the message settings",s);await k(e,t,`set the message settings ${i.join(", ")}`);let r=await m(e,t,"PUT","/notify/settings",o,{...vt(a),...D()});e.out.result({settings:r,changed:i},()=>{for(let l of i)e.out.line(`${l}: ${kt(s[l])} \u2192 ${kt(r[l])}`)})}},KP=new Set(["sms_countries","sms_blocked_countries"]);function UP(e){return{...e,sms_countries:e.sms_countries??[],sms_blocked_countries:e.sms_blocked_countries??[],mx_check:e.mx_check??!1}}var Yg={name:"notify",async read(e,t){let[n,s,a,o,i,r]=await Promise.all([m(e,t,"GET","/notify/settings"),m(e,t,"GET","/notify/providers"),m(e,t,"GET","/notify/templates/email"),m(e,t,"GET","/notify/templates/sms"),m(e,t,"GET","/notify/templates/whatsapp"),id(e,t)]),l={};for(let[u,g]of Object.entries(UP(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 p=a.templates.filter(u=>u.customized),d=await Promise.all(p.map(u=>m(e,t,"GET",`/notify/templates/email/${A(u.slug)}/${A(u.locale)}`)));for(let u of d)l[`templates.email/${u.slug}/${u.locale}`]={subject:u.subject,html_body:u.html_body,text_body:u.text_body};for(let u of o.templates.filter(g=>g.customized))l[`templates.sms/${u.slug}/${u.locale}`]={body:u.body};for(let u of i.templates)l[`templates.whatsapp/${u.slug}/${u.locale}`]={name:u.name,language:u.language,variables:u.variables,code_button:u.code_button};for(let u of r)l[`topics.${u.name}`]={self_subscribe:u.self_subscribe};return l},async copy(e,t,n,s){let a=Ze(n,"settings.");if(a.length>0){let{body:r,etag:l}=await Rt(e,t,"/notify/settings"),p={...r};for(let d of a)p[d.name]=KP.has(d.name)&&Array.isArray(d.from)&&d.from.length===0?null:d.from;await Te(s,`set the message settings ${a.map(d=>d.name).join(", ")}`,async()=>{await m(e,t,"PUT","/notify/settings",p,{...vt(l),...D()})})}for(let r of Ze(n,"providers.")){let[l,p]=r.name.split("/");r.from===void 0?s.left(`the ${l} provider ${p}: only in the target, left as it is (it holds credentials)`):s.left(`the ${l} provider ${p}: credentials are not copied \u2014 set them with palbase notify:providers:set ${l} ${p} < credentials.json`)}for(let r of Ze(n,"templates.")){let l=`/notify/templates/${r.name.split("/").map(A).join("/")}`;r.from===void 0?await Te(s,`remove the template override ${r.name}`,async()=>{await m(e,t,"DELETE",l,void 0,D())}):await Te(s,`override the template ${r.name}`,async()=>{await m(e,t,"PUT",l,r.from,D())})}let o=Ze(n,"topics."),i=o.some(r=>r.from===void 0)?new Map((await id(e,t)).map(r=>[r.name,r.subscribers])):new Map;for(let r of o){let l=`/notify/topics/${A(r.name)}`,p=r.from?.self_subscribe;if(r.from===void 0){let d=i.get(r.name)??0;d>0?s.left(`the topic ${r.name}: only in the target, and ${d} users follow it \u2014 delete it with notify:topics:delete`):await Te(s,`delete the topic ${r.name}`,async()=>{await m(e,t,"DELETE",l,void 0,D())})}else r.change==="only_in_from"?await Te(s,`make the topic ${r.name}`,async()=>{await m(e,t,"POST","/notify/topics",{name:r.name,self_subscribe:p},D())}):await Te(s,`set the topic ${r.name} ${p?"followed from the app":"followed by the project's adding"}`,async()=>{await m(e,t,"PATCH",l,{self_subscribe:p},D())})}}};var Wa=["max_connections","max_events_per_second","max_joins_per_second","max_channels_per_connection"];function WP(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 pd(e){return Object.fromEntries(Wa.map(t=>[t,e[t]??null]))}var Zg={name:"realtime:channels:get",summary:"the channel declaration, in the order patterns are matched: who may join each, publish, read and write its state",scope:"environment",async run(e){let t=await f(e),n=await m(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=>WP(s)}])})}},Qg={name:"realtime:channels:set",summary:'replace the channel declaration with a JSON file or stdin ({"channels": [\u2026]} or the list)',usage:"[--file <path>]",details:['Each channel: {"pattern": "room:{id}", "kind": "public", "publish": true, "state_read": true, "state_write": false}, or {"pattern": "user:{uid}", "kind": "owner"}.',"realtime:channels:get --json gives the document to edit. Open sockets are decided again within a heartbeat."],flags:{file:{type:"string",value:"path",description:"the declaration (default: stdin)"}},scope:"environment",async run(e){let t=await f(e),n=Ne(await ze(e,e.flags.file,"the channel declaration"),"the channel declaration"),s=Array.isArray(n)?n:n.channels;if(!Array.isArray(s))throw h('the declaration is {"channels": [\u2026]} or a list of channels');let a=await m(e,t,"GET","/realtime/channels");if(Mt(a.channels,s))return Dt(e,"the channel declaration",a);await k(e,t,`declare ${s.length} channel pattern(s) (now ${a.channels.length})`);let o=await m(e,t,"PUT","/realtime/channels",{channels:s});e.out.result(o,()=>e.out.line(o.channels.length===0?"No channel is declared now.":`Declared ${o.channels.length} channel pattern(s): ${o.channels.map(i=>i.pattern).join(", ")}.`))}},eh={name:"realtime:limits:get",summary:"the limits the environment holds its clients to (null: the platform's), and the platform's",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/realtime/limits");e.out.result(n,()=>{let s=n.platform??{},a=Math.max(...Wa.map(o=>o.length));for(let o of Wa)e.out.line(`${o.padEnd(a)} ${n[o]===void 0||n[o]===null?"the platform's":kt(n[o])}${s[o]!==void 0?` (platform ${s[o]===0?"no ceiling":kt(s[o])})`:""}`)})}},th={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: ${Wa.join(", ")}. A value above the platform's has no effect beyond it.`],args:{min:1,max:4},scope:"environment",async run(e){let t=await f(e),n=Rs(e.args);for(let r of n)if(r.path.length!==1||!Wa.includes(r.path[0]))throw h(`no limit ${JSON.stringify(r.path.join("."))}`,`the limits: ${Wa.join(", ")}`);let s=pd(await m(e,t,"GET","/realtime/limits")),a=js(s,n),o=os(s,a);if(o.length===0)return Dt(e,"the realtime limits",s);await k(e,t,`set the realtime limits ${o.join(", ")}`);let i=await m(e,t,"PUT","/realtime/limits",a);e.out.result({limits:i,changed:o},()=>{for(let r of o)e.out.line(`${r}: ${kt(s[r]??"the platform's")} \u2192 ${kt(i[r]??"the platform's")}`)})}},nh={name:"realtime",async read(e,t){let[n,s]=await Promise.all([m(e,t,"GET","/realtime/channels"),m(e,t,"GET","/realtime/limits")]),a={channels:n.channels};for(let[o,i]of Object.entries(pd(s)))a[`limits.${o}`]=i;return a},async copy(e,t,n,s){let a=n.find(i=>i.key==="channels");a&&await Te(s,"declare the channels",async()=>{await m(e,t,"PUT","/realtime/channels",{channels:a.from??[]})});let o=Ze(n,"limits.");if(o.length>0){let i=pd(await m(e,t,"GET","/realtime/limits"));for(let r of o)i[r.name]=r.from??null;await Te(s,`set the realtime limits ${o.map(r=>r.name).join(", ")}`,async()=>{await m(e,t,"PUT","/realtime/limits",i)})}}},sh={name:"analytics:settings:get",summary:"how long analytics keeps events and console records, the share of performance samples kept, whether bodies are kept",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/analytics/settings");e.out.result(n,()=>Ma(e,n))}},ah={name:"analytics:settings:set",summary:"change analytics settings: key=value (retention_days=30, perf_sample_pct=10, console_bodies=false)",usage:"<key=value>\u2026",details:["A shorter retention removes what is older within minutes."],args:{min:1,max:4},scope:"environment",async run(e){let t=await f(e),n=Rs(e.args),s=await m(e,t,"GET","/analytics/settings"),a=js(s,n),o=os(s,a);if(o.length===0)return Dt(e,"the analytics settings",s);await k(e,t,`set the analytics settings ${o.join(", ")}`);let i=await m(e,t,"PUT","/analytics/settings",a);e.out.result({settings:i,changed:o},()=>{for(let r of o)e.out.line(`${r}: ${kt(s[r])} \u2192 ${kt(i[r])}`)})}},oh={name:"analytics",async read(e,t){let n=await m(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=Ze(n,"settings.");if(a.length===0)return;let o=await m(e,t,"GET","/analytics/settings");for(let i of a)i.from!==void 0&&(o[i.name]=i.from);await Te(s,`set the analytics settings ${a.map(i=>i.name).join(", ")}`,async()=>{await m(e,t,"PUT","/analytics/settings",o)})}};var nn="/messaging/settings",FP=/^[A-Z][A-Z0-9_]{0,127}$/,cd=["retention_days","push_preview","deleted_user_messages","search_by_meaning","event_text"];function Fa(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?ih(t):"none: anyone may reach anyone"}}function ih(e){return`${I(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 BP(e,t){let n=[...cd.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,o]of n)e.out.line(`${a.padEnd(s)} ${Fa(a,o)}`)}function dd(e,t){if(e!==void 0){if(e==="on")return!0;if(e==="off")return!1;throw h(`--${t} is on or off`)}}function JP(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 h("--retention-days is a whole number of days from 1 to 36500, or off (kept for good)");return t}var HP={name:"messaging:settings:get",summary:"how the environment runs its conversations: how long messages are kept, whether a push says what one says, what becomes of a deleted user's messages, whether they are found by what they mean, whether a message's event says what it says, the hook",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",nn);e.out.result(n,()=>BP(e,n))}},VP={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=JP(e.flags["retention-days"]);n!==void 0&&(t.retention_days=n);let s=dd(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 h("--deleted-user-messages is keep or delete");t.deleted_user_messages=a}let o=dd(e.flags["search-by-meaning"],"search-by-meaning");o!==void 0&&(t.search_by_meaning=o);let i=dd(e.flags["event-text"],"event-text");if(i!==void 0&&(t.event_text=i),Object.keys(t).length===0)throw h("nothing to change","pass --retention-days, --push-preview, --deleted-user-messages, --search-by-meaning or --event-text");let r=await f(e),l=await m(e,r,"GET",nn),p=cd.filter(u=>u in t&&!Mt(l[u],t[u]));if(p.length===0)return Dt(e,"the messaging settings",l);await k(e,r,`set the messaging settings ${p.join(", ")}`);let d=await m(e,r,"PUT",nn,Object.fromEntries(p.map(u=>[u,t[u]])));e.out.result({settings:d,changed:p},()=>{for(let u of p)e.out.line(`${u}: ${Fa(u,l[u])} \u2192 ${Fa(u,d[u])}`)})}},rh={"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 lh(e){let t=e.flags["secret-to"];if(t!==void 0&&!FP.test(t))throw h(`--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 h("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function ph(e,t,n,s,a){let{hook_secret:o,...i}=n;if(o===void 0){e.out.result({settings:i},()=>e.out.line(`${a}: ${Fa("hook",i.hook)}.`));return}if(s!==void 0){let r=await m(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:o});e.out.result({settings:i,secret_to:{set:s.set,name:s.name,version:r.version}},()=>e.out.line(`${a}: ${Fa("hook",i.hook)}; its signing secret is ${s.name} (${s.set}, v${r.version}) in ${ee(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${Fa("hook",i.hook)}.`),e.out.line(`signing secret (shown this once): ${o}`)})}var XP={name:"messaging:hook:get",summary:"the hook asked whom one may reach: where it is, how long it is waited for, what is done when it does not answer (never its secret)",scope:"environment",async run(e){let t=await f(e),{hook:n}=await m(e,t,"GET",nn);e.out.result({hook:n},()=>e.out.line(n?ih(n):"No hook: anyone may reach anyone. palbase messaging:hook:set --url <url> sets one."))}},YP={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)"},...rh},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw h("--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 h("--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 h("--on-error is allow or deny");if(t===void 0&&n===void 0&&s===void 0)throw h("nothing to change","pass --url, --timeout-ms or --on-error");let a=lh(e),o=await f(e),i=await m(e,o,"GET",nn),r=i.hook;if(!r&&t===void 0)throw h("the environment has no hook yet: --url names where it is asked");if(r&&a!==void 0)throw h("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??r.url},p=n??r?.timeout_ms;p!==void 0&&(l.timeout_ms=p);let d=s??r?.on_error;if(d!==void 0&&(l.on_error=d),r&&Mt(r,{...r,...l}))return Dt(e,"the hook",i);let u=r?["url","timeout_ms","on_error"].filter(y=>l[y]!==r[y]):[];await k(e,o,r?`change the messaging hook: ${u.join(", ")}`:`set the messaging hook ${l.url}${a?`, its secret kept in ${a.name} (${a.set})`:""}`);let g=await m(e,o,"PUT",nn,{hook:l});await ph(e,o,g,a,r?"Changed the hook":"Set the hook")}},ZP={name:"messaging:hook:remove",summary:"remove the hook: anyone may reach anyone, and its signing secret is forgotten",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",nn);if(!n.hook){e.out.result({settings:n,changed:[]},()=>e.out.line("Nothing to change: the environment has no hook."));return}await k(e,t,`remove the messaging hook ${n.hook.url}: anyone may reach anyone, and its signing secret is forgotten`);let s=await m(e,t,"PUT",nn,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may reach anyone."))}},QP={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:rh,scope:"environment",async run(e){let t=lh(e),n=await f(e);await k(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 m(e,n,"POST",`${nn}/hook-secret`);await ph(e,n,s,t,"Made the signing secret anew for the hook")}},dh={name:"messaging",async read(e,t){let n=await m(e,t,"GET",nn),s={};for(let a of cd)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=Ze(n,"settings.");a.length>0&&await Te(s,`set the messaging settings ${a.map(l=>l.name).join(", ")}`,async()=>{await m(e,t,"PUT",nn,Object.fromEntries(a.map(l=>[l.name,l.from])))});let o=n.find(l=>l.key==="hook");if(!o)return;if(o.from===void 0){await Te(s,`remove the hook ${o.to.url}`,async()=>{await m(e,t,"PUT",nn,{hook:null})});return}let i=o.from,r;await Te(s,`${o.change==="differs"?"change":"set"} the hook ${i.url}`,async()=>{r=(await m(e,t,"PUT",nn,{hook:i})).hook_secret}),r&&s.shown(`the hook ${i.url} signs with`,r)}},ch=[HP,VP,XP,YP,ZP,QP];var sn="/calls/settings",eR=/^[A-Z][A-Z0-9_]{0,127}$/,md=["max_participants","calls_per_hour"];function Ba(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?uh(t):"none: anyone may call anyone (blocks aside)"}}function uh(e){return`${I(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 tR(e,t){let n=[...md.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,o]of n)e.out.line(`${a.padEnd(s)} ${Ba(a,o)}`)}function ud(e,t,n,s){if(e===void 0)return;let a=Number(e);if(!/^[0-9]+$/.test(String(e))||a<n||a>s)throw h(`--${t} is a whole number from ${n} to ${s}`);return a}var nR={name:"calls:settings:get",summary:"how the environment runs its calls: how many a call holds, how many calls a person may start in an hour, the hook",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",sn);e.out.result(n,()=>tR(e,n))}},sR={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=ud(e.flags["max-participants"],"max-participants",2,100);n!==void 0&&(t.max_participants=n);let s=ud(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 h("nothing to change","pass --max-participants or --calls-per-hour");let a=await f(e),o=await m(e,a,"GET",sn),i=md.filter(l=>l in t&&!Mt(o[l],t[l]));if(i.length===0)return Dt(e,"the call settings",o);await k(e,a,`set the call settings ${i.join(", ")}`);let r=await m(e,a,"PUT",sn,Object.fromEntries(i.map(l=>[l,t[l]])));e.out.result({settings:r,changed:i},()=>{for(let l of i)e.out.line(`${l}: ${Ba(l,o[l])} \u2192 ${Ba(l,r[l])}`)})}},mh={"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 gh(e){let t=e.flags["secret-to"];if(t!==void 0&&!eR.test(t))throw h(`--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 h("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function hh(e,t,n,s,a){let{hook_secret:o,...i}=n;if(o===void 0){e.out.result({settings:i},()=>e.out.line(`${a}: ${Ba("hook",i.hook)}.`));return}if(s!==void 0){let r=await m(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:o});e.out.result({settings:i,secret_to:{set:s.set,name:s.name,version:r.version}},()=>e.out.line(`${a}: ${Ba("hook",i.hook)}; its signing secret is ${s.name} (${s.set}, v${r.version}) in ${ee(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${Ba("hook",i.hook)}.`),e.out.line(`signing secret (shown this once): ${o}`)})}var aR={name:"calls:hook:get",summary:"the hook asked whom one may call: where it is, how long it is waited for, what is done when it does not answer (never its secret)",scope:"environment",async run(e){let t=await f(e),{hook:n}=await m(e,t,"GET",sn);e.out.result({hook:n},()=>e.out.line(n?uh(n):"No hook: anyone may call anyone (blocks aside). palbase calls:hook:set --url <url> sets one."))}},oR={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)"},...mh},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw h("--url is where the hook is asked: a URL");let n=ud(e.flags["timeout-ms"],"timeout-ms",100,5e3),s=e.flags["on-error"];if(s!==void 0&&s!=="allow"&&s!=="deny")throw h("--on-error is allow or deny");let a=e.flags.places;if(a!==void 0&&a!=="on"&&a!=="off")throw h("--places is on or off");let o=a===void 0?void 0:a==="on";if(t===void 0&&n===void 0&&s===void 0&&o===void 0)throw h("nothing to change","pass --url, --timeout-ms, --on-error or --places");let i=gh(e),r=await f(e),l=await m(e,r,"GET",sn),p=l.hook;if(!p&&t===void 0)throw h("the environment has no hook yet: --url names where it is asked");if(p&&i!==void 0)throw h("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 d={url:t??p.url},u=n??p?.timeout_ms;u!==void 0&&(d.timeout_ms=u);let g=s??p?.on_error;g!==void 0&&(d.on_error=g);let y=o??p?.places;if(y!==void 0&&(d.places=y),p&&Mt(p,{...p,...d}))return Dt(e,"the hook",l);let w=p?["url","timeout_ms","on_error","places"].filter(R=>(d[R]??!1)!==(p[R]??!1)):[];await k(e,r,p?`change the calls hook: ${w.join(", ")}`:`set the calls hook ${d.url}${i?`, its secret kept in ${i.name} (${i.set})`:""}`);let v=await m(e,r,"PUT",sn,{hook:d});await hh(e,r,v,i,p?"Changed the hook":"Set the hook")}},iR={name:"calls:hook:remove",summary:"remove the hook: anyone may call anyone (blocks aside), and its signing secret is forgotten",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",sn);if(!n.hook){e.out.result({settings:n,changed:[]},()=>e.out.line("Nothing to change: the environment has no hook."));return}await k(e,t,`remove the calls hook ${n.hook.url}: anyone may call anyone, and its signing secret is forgotten`);let s=await m(e,t,"PUT",sn,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may call anyone (blocks aside)."))}},rR={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:mh,scope:"environment",async run(e){let t=gh(e),n=await f(e);await k(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 m(e,n,"POST",`${sn}/hook-secret`);await hh(e,n,s,t,"Made the signing secret anew for the hook")}},yh={name:"calls",async read(e,t){let n=await m(e,t,"GET",sn),s={};for(let a of md)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=Ze(n,"settings.");a.length>0&&await Te(s,`set the call settings ${a.map(l=>l.name).join(", ")}`,async()=>{await m(e,t,"PUT",sn,Object.fromEntries(a.map(l=>[l.name,l.from])))});let o=n.find(l=>l.key==="hook");if(!o)return;if(o.from===void 0){await Te(s,`remove the hook ${o.to.url}`,async()=>{await m(e,t,"PUT",sn,{hook:null})});return}let i=o.from,r;await Te(s,`${o.change==="differs"?"change":"set"} the hook ${i.url}`,async()=>{r=(await m(e,t,"PUT",sn,{hook:i})).hook_secret}),r&&s.shown(`the hook ${i.url} signs with`,r)}},fh=[nR,sR,aR,oR,iR,rR];var lR=/^[a-z][a-z0-9-]{1,62}$/;function Ja(e){if(!lR.test(e))throw h(`${JSON.stringify(e)} is not a bucket's name: lowercase letters, digits and dashes, starting with a letter (2\u201363)`);return`/storage/buckets/${A(e)}`}function hd(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 pR(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 h(`--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 gd(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 dR(e,t,n){try{return await m(e,t,"GET",Ja(n))}catch(s){if(s instanceof G&&s.status===404)return;throw s}}var bh={name:"storage:buckets:list",summary:"the environment's buckets: who may read each, the largest file and the types it takes",scope:"environment",async run(e){let t=await f(e),{buckets:n}=await m(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=>hd(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(", ")}])})}},wh={name:"storage:buckets:get",summary:"a bucket's declaration in full, with its renditions",usage:"<bucket>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",Ja(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 ${hd(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}`:""}`)})}},vh={name:"storage:buckets:set",summary:"make a bucket, or change one: public or private, the largest file, the content types, its renditions",usage:"<bucket> [--public|--private] [--max-size <size>] [--types <a/b,c/*>] [--variants-file <path>]",details:["What is not given is kept as it is (a new bucket: private, the platform's size, any type, no rendition)."],args:{min:1,max:1},flags:{public:{type:"boolean",description:"anyone may read its files at /storage/public/"},private:{type:"boolean",description:"its files are read with signed URLs and the rules"},"max-size":{type:"string",value:"size",description:"the largest file: 10MB, 512KiB, 1GB, bytes, or platform"},types:{type:"string",value:"list",description:'the content types it takes, comma-separated (image/* a family); "" for any'},"variants-file":{type:"string",value:"path",description:"its renditions, a JSON list of {name, width, height, fit, format, quality}"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0];if(e.flags.public===!0&&e.flags.private===!0)throw h("--public and --private are one or the other");let s=await dR(e,t,n),a=gd(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=pR(e.flags["max-size"])),e.flags.types!==void 0&&(a.allowed_mime_types=Me(e.flags.types)??[]),e.flags["variants-file"]!==void 0){let i=Ne(await ze(e,e.flags["variants-file"],"the renditions"),"the renditions file"),r=Array.isArray(i)?i:i.variants;if(!Array.isArray(r))throw h("the renditions file is a JSON list of {name, width, height, fit, format, quality}");a.variants=r}if(s&&Mt(gd(s),a)){e.out.result(s,()=>e.out.line(`Nothing to change: ${n} already is so.`));return}await k(e,t,`${s?"change":"make"} the bucket ${n} (${a.public?"public":"private"})`);let o=await m(e,t,"PUT",Ja(n),a);e.out.result(o,()=>e.out.line(`${s?"Changed":"Made"} the bucket ${o.name}: ${o.public?"public":"private"}, files up to ${hd(o.file_size_limit)}, ${o.allowed_mime_types.length===0?"any type":o.allowed_mime_types.join(", ")}.`))}},kh={name:"storage:buckets:delete",summary:"delete an empty bucket (one that still holds files is refused)",usage:"<bucket>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Ja(e.args[0]);await k(e,t,`delete the bucket ${e.args[0]}`),await m(e,t,"DELETE",n),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the bucket ${e.args[0]}.`))}},_h={name:"storage",async read(e,t){let{buckets:n}=await m(e,t,"GET","/storage/buckets"),s={};for(let a of n){let o=gd(a);s[`buckets.${a.name}`]={...o,allowed_mime_types:[...o.allowed_mime_types].sort()}}return s},async copy(e,t,n,s){for(let a of Ze(n,"buckets."))a.from===void 0?await Te(s,`delete the bucket ${a.name}`,async()=>{await m(e,t,"DELETE",Ja(a.name))}):await Te(s,`declare the bucket ${a.name}`,async()=>{await m(e,t,"PUT",Ja(a.name),a.from)})}};var na=[Pg,_h,Mg,Yg,nh,oh,dh,yh];function wd(e="<env>"){return new b("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 Sh={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: ${na.map(e=>e.name).join(",")} (the default)`}};async function $h(e){if(e.global.env!==void 0)throw h("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 h("name both environments: --from <env> --to <env>");let s=await rt(e.studio),a;if(e.global.project!==void 0)a=Ps(s,e.global.project);else{let l=await e.state.targetFor(e.io.cwd);if(!l)throw new b("no_target","which project? none is chosen for this directory",{hint:"pass -P <project>, or choose one here with palbase use"});a=s.filter(p=>p.project_id===l.target.project_id)}let o=l=>{let p=a.find(d=>d.slug===l||d.ref===l);if(!p)throw new b("no_such_environment",`the project has no environment ${JSON.stringify(l)}`,{hint:`its environments: ${a.map(d=>d.slug).join(", ")}`});return Ge(p)},i=o(t),r=o(n);if(i.env_ref===r.env_ref)throw h("--from and --to name the same environment");return{from:i,to:r}}function Ah(e,t){let n=Me(e.flags.only);if(n===void 0)return na;if(n.some(s=>s==="machines"||s==="databases"||s==="sites"))throw wd(t.env_slug);for(let s of n)if(!na.some(a=>a.name===s))throw h(`no module ${JSON.stringify(s)}`,`the modules: ${na.map(a=>a.name).join(", ")}`);return na.filter(s=>n.includes(s.name))}function cR(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),s=[];for(let a of n){let o=a in e,i=a in t;o&&!i?s.push({key:a,change:"only_in_from",from:e[a]}):!o&&i?s.push({key:a,change:"only_in_to",to:t[a]}):Mt(e[a],t[a])||s.push({key:a,change:"differs",from:e[a],to:t[a]})}return s}async function yd(e,t,n,s){let a=l=>Promise.all(t.map(p=>p.read(e,l))),[o,i]=await Promise.all([a(n),a(s)]),r=Object.fromEntries(t.map((l,p)=>[l.name,cR(o[p],i[p])]));return{from:n,to:s,modules:r,count:Object.values(r).reduce((l,p)=>l+p.length,0)}}function fd(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 jr(e){let t=JSON.stringify(e)??"undefined";return t.length>140?`${t.slice(0,139)}\u2026`:t}function bd(e,t){let n=t.from.env_slug,s=t.to.env_slug;for(let[o,i]of Object.entries(t.modules))if(i.length!==0){e.out.line(`${o} (${i.length})`);for(let r of i)r.change==="differs"?e.out.line(` ~ ${r.key}: ${n} ${jr(r.from)} \xB7 ${s} ${jr(r.to)}`):r.change==="only_in_from"?e.out.line(` - ${r.key}: only in ${n}: ${jr(r.from)}`):e.out.line(` + ${r.key}: only in ${s}: ${jr(r.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 uR={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:Sh,scope:"environment",async run(e){let{from:t,to:n}=await $h(e),s=await yd(e,Ah(e,n),t,n);return e.out.result(fd(s),()=>bd(e,s)),s.count===0?0:1}},mR={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:Sh,scope:"environment",async run(e){let{from:t,to:n}=await $h(e);return vd(e,Ah(e,n),t,n)}};async function vd(e,t,n,s,a={}){let o=await yd(e,t,n,s);if(o.count===0)return e.out.result({...a,copied:[],left:[],shown_once:[],after:fd(o)},()=>e.out.line(`Nothing to copy: ${n.env_slug} and ${s.env_slug} have the same settings.`)),0;e.out.json||bd(e,o);let i=t.filter(u=>o.modules[u.name].length>0).map(u=>u.name);await k(e,s,`make its ${i.join(", ")} settings equal to ${n.env_slug}'s (${o.count} difference(s))`);let r=[],l=[],p=[];e.out.json||e.out.line();for(let u of t){let g=o.modules[u.name];if(g.length===0)continue;let y={done(w){r.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,v){p.push({what:`${u.name}: ${w}`,value:v}),e.out.json||e.out.line(` ${u.name}: ${w} ${v} (shown this once)`)}};await u.copy(e,s,g,y)}let d=await yd(e,t,n,s);return e.out.result({...a,copied:r,left:l,shown_once:p,after:fd(d)},()=>{e.out.line(),e.out.line("Compared again:"),bd(e,d)}),d.count===0?0:1}var Ph=[ng,sg,og,ug,gg,mg,lg,pg,dg,cg,hg,yg,fg,wg,vg,kg,_g,Sg,$g,Ag,bh,wh,vh,kh,Tg,Cg,Og,xg,Ig,Ng,Lg,zg,qg,Gg,Kg,Ug,Wg,Fg,Bg,Jg,Hg,Vg,Xg,Zg,Qg,eh,th,sh,ah,...ch,...fh,uR,mR];async function kd(e){return(await e.studio.get("/orgs")).organizations}async function An(e,t){let n=await kd(e);if(t===void 0){if(n.length===1)return n[0];throw h(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 b("no_such_org",`no organization ${JSON.stringify(t)} among yours`,{hint:"palbase orgs:list shows them"});if(s.length>1)throw new b("ambiguous_org",`${JSON.stringify(t)} names more than one of your organizations`,{hint:"pass its id"});return s[0]}var Rh={name:"orgs:list",summary:"your organizations and your role in each",scope:"account",async run(e){let t=await kd(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}])})}},jh={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 ${le(t.name)} (${t.id}).`))}},Eh={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 An(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}]))})}},Th={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 An(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw h("--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 ${le(s.email)} to ${le(t.name)} as ${s.role}.`))}},Ch={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 An(e,e.flags.org),n=e.args[0],s=await e.studio.get(`/orgs/${t.id}/members`),a=s.members.find(i=>i.user_id===n||i.email!==null&&i.email.toLowerCase()===n.toLowerCase());if(a){await e.studio.request("DELETE",`/orgs/${Q("the organization's id",t.id)}/members/${Q("the member's id",a.user_id)}`),e.out.result({removed:a},()=>e.out.line(`${le(a.email??a.user_id)} is no longer in ${le(t.name)}.`));return}let o=s.invitations.find(i=>i.id===n||i.email.toLowerCase()===n.toLowerCase());if(!o)throw new b("no_such_member",`${JSON.stringify(n)} is neither a member of ${t.name} nor invited to it`);await e.studio.request("DELETE",`/orgs/${Q("the organization's id",t.id)}/invitations/${Q("the invitation's id",o.id)}`),e.out.result({withdrawn:o},()=>e.out.line(`The invitation of ${le(o.email)} is withdrawn.`))}},Oh={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 An(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(`${le(t.name)} has no access token yet: palbase tokens:create <name> makes one.`):e.out.table(n,[{header:"name",value:s=>le(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}])})}},xh={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 An(e,e.flags.org),n=e.flags.limit===void 0?50:Number(e.flags.limit);if(!Number.isInteger(n)||n<1||n>1e4)throw h("--limit is a whole number from 1 to 10000");let s=[],a=null;do{let o=new URLSearchParams({limit:String(Math.min(100,n-s.length)),...a?{before:a}:{}}),i=await e.studio.get(`/orgs/${t.id}/audit?${o}`);s.push(...i.entries),a=i.next_before}while(a&&s.length<n);e.out.result({entries:s},()=>{s.length===0?e.out.line(`Nothing changed at ${le(t.name)}'s environments yet.`):e.out.table(s,[{header:"when",value:o=>o.at.slice(0,16).replace("T"," ")},{header:"who",value:o=>le(o.actor_name??o.actor)},{header:"environment",value:o=>le(o.environment_ref)},{header:"what",value:o=>le(`${o.method} ${o.path}`)},{header:"answer",value:o=>String(o.status)}])})}},Lh={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 An(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw h("--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 h("--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 ${le(a.name)} of ${le(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}`)})}},Ih={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 An(e,e.flags.org),{tokens:n}=await e.studio.get(`/orgs/${t.id}/tokens`),s=n.filter(i=>i.id===e.args[0]||i.name===e.args[0]);if(s.length===0)throw new b("no_such_token",`${le(t.name)} has no access token ${JSON.stringify(e.args[0])}`,{hint:"palbase tokens:list shows them"});if(s.length>1)throw new b("ambiguous_token",`${JSON.stringify(e.args[0])} names more than one token`,{hint:"pass its id"});let a=`/orgs/${Q("the organization's id",t.id)}/tokens/${Q("the token's id",s[0].id)}`,{endpoints:o}=await e.studio.get(`${a}/webhooks`);await e.studio.request("DELETE",a),e.out.result({revoked:s[0].id,kept_webhooks:o},()=>{if(e.out.line(`Revoked the access token ${le(s[0].name)} of ${le(t.name)}.`),o.length>0){e.out.line("These webhook endpoints it made stay, and keep receiving events (palbase webhooks:delete <id> -E <env> removes one):");for(let i of o)e.out.line(` ${I(i.url)} \u2014 ${I(i.environment_ref)} (${I(i.id)})`)}})}},Nh={name:"projects:list",summary:"every project of your organizations, with its environments",scope:"account",async run(e){let t=await rt(e.studio),n=await e.state.targetFor(e.io.cwd),s=(await e.studio.get("/projects")).projects,a=new Map(t.map(o=>[o.organization_id,o.org_name]));for(let o of await kd(e))a.set(o.id,o.name);e.out.result({projects:s.map(o=>({...o,organization_name:a.get(o.organization_id)??null}))},()=>{s.length===0&&e.out.line("No project yet: palbase projects:create <name> makes one.");let o=s.flatMap(i=>i.environments.length===0?[{org:a.get(i.organization_id)??"",project:i.name,env:"(none)",ref:"",here:""}]:i.environments.map(r=>({org:a.get(i.organization_id)??"",project:i.name,env:r.slug,ref:r.ref,here:n?.target.env_ref===r.ref?"*":""})));e.out.table(o,[{header:"",value:i=>i.here},{header:"organization",value:i=>i.org},{header:"project",value:i=>i.project},{header:"env",value:i=>i.env},{header:"ref",value:i=>i.ref}])})}},Mh={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 An(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 ${le(t.name)} \u203A ${le(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.`)})}},Dh={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=Ps(await rt(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 b("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 b("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 ${le(n.project_name)}.`))}},zh={name:"envs:list",summary:"a project's environments (the project chosen here, or -P)",scope:"environment",async run(e){let t=await Pn(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}]))}},qh={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 wd(t);let n=await gR(e),s=e.flags.from,a=s===void 0?[]:(await rt(e.studio)).filter(p=>p.project_id===n.project_id),o=s===void 0?void 0:a.find(p=>p.slug===s||p.ref===s);if(s!==void 0&&!o)throw new b("no_such_environment",`the project has no environment ${JSON.stringify(s)}`,{hint:`its environments: ${a.map(p=>p.slug).join(", ")}`});let i=await e.studio.post(`/projects/${n.project_id}/environments`,{name:e.flags.name??t,slug:t}),r=()=>{e.out.line(`Made ${le(n.project_name)} \u203A ${i.environment.slug} (ref ${i.environment.ref}).`),i.keys&&(e.out.line(`publishable key: ${i.keys.publishable.key}`),e.out.line(`secret key (shown this once): ${i.keys.secret.key}`))};if(!o){e.out.result(i,r);return}e.out.json||r();let l=Ge({...o,ref:i.environment.ref,slug:i.environment.slug,name:i.environment.name});return e.out.json||e.out.line(),vd(e,na,Ge(o),l,{made:i})}},Gh={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 Pn(e),n=t.find(p=>p.slug===e.args[0]||p.ref===e.args[0]);if(!n)throw new b("no_such_environment",`the project has no environment ${JSON.stringify(e.args[0])}`);let s=Ge(n);if(e.out.note(`${ee(s)}: delete the environment, its users, data, machines and databases`),!e.global.yes){if(!e.interactive)throw new b("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 b("cancelled","nothing was deleted")}let a=e.flags["delete-bound"]===!0,o=typeof e.flags["move-to"]=="string"?e.flags["move-to"]:void 0;if(a&&o!==void 0)throw h("--delete-bound or --move-to: what is bound to it is deleted with it, or moved");let i=a?"?delete_bound=true":o!==void 0?`?move_to=${encodeURIComponent(o)}`:"",r=async()=>{let p=e.io.now()+6e5;for(;;)try{return await e.studio.request("DELETE",`/environments/${n.ref}${i}`)}catch(d){if(!(d instanceof G)||d.code!=="machines_still_moving"||e.io.now()>p)throw d;e.out.note(`still moving to ${decodeURIComponent(i.slice(9))}; asking again`),await e.io.sleep(5e3)}};try{await r()}catch(p){if(!(p instanceof G)||p.code!=="environment_has_resources"||i!=="")throw p;let d=p.body?.data??{},u=[d.machines?.length?`machines ${d.machines.join(", ")}`:"",d.databases?.length?`databases ${d.databases.join(", ")}`:"",d.sites?.length?`sites ${d.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 b("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")i="?delete_bound=true";else if(g.includes(y))i=`?move_to=${encodeURIComponent(y)}`;else throw new b("cancelled","nothing was deleted");await r()}if(i.startsWith("?move_to=")){let p=t.find(d=>d.slug===decodeURIComponent(i.slice(9))||d.ref===decodeURIComponent(i.slice(9)));p&&await e.state.moveDatabasePasswords(n.ref,p.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 ${ee(s)}.`))}},Kh={name:"use",summary:"choose the environment this directory acts on (kept on this computer)",usage:"[<project>[/<env>] | <org>/<project>/<env>] [--clear]",details:["Commands run in this directory, or a directory under it, then act on that environment unless -P/-E say otherwise.","Nothing is written into the project: two checkouts of it can each act on their own environment.","With no argument and a person at the terminal, it lists your environments to pick from."],args:{min:0,max:1},flags:{clear:{type:"boolean",description:"forget the choice made for this directory"}},scope:"account",async run(e){if(e.flags.clear===!0){let n=await e.state.clearTarget(e.io.cwd);e.out.result({cleared:n},()=>e.out.line(n?"This directory acts on no environment now.":"No environment was chosen for this directory."));return}let t;if(e.args.length===0)t=await f(e);else{let n=await rt(e.studio);t=Ge(hR(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 ${ee(t)}.`))}},Uh={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 f(e),n=await e.studio.get(`/environments/${t.env_ref}`),s={...t,env_slug:n.slug??t.env_slug,env_name:n.name??t.env_name},a=u=>et(e.studio,t.env_ref,"GET",u).then(g=>g.body,g=>g instanceof G?null:Promise.reject(g)),o=`limit=100&environment=${encodeURIComponent(t.env_ref)}`,[i,r]=await Promise.all([a(`/machines?${o}`),a(`/databases?${o}`)]),l=i?.machines??[],p=r?.databases??[],d=await e.state.targetFor(e.io.cwd);d&&d.target.env_ref===t.env_ref&&(d.target.env_slug!==s.env_slug||d.target.env_name!==s.env_name)&&await e.state.setTarget(d.dir,{...d.target,env_slug:s.env_slug,env_name:s.env_name}),e.out.result({target:s,role:n.role,address:`https://${s.env_ref}.${e.cloud.domain}`,machines:l,databases:p,chosen_for:d?.dir??null},()=>{e.out.line(ee(s)),e.out.line(` ref ${s.env_ref} \xB7 your role ${n.role} \xB7 https://${s.env_ref}.${e.cloud.domain}`),d&&d.target.env_ref===s.env_ref&&e.out.line(` chosen for ${d.dir}`),e.out.line(` machines: ${l.length===0?"none":l.map(u=>`${u.name} (${u.size}, ${u.state})`).join(", ")}`),e.out.line(` databases: ${p.length===0?"none":p.map(u=>`${u.name} (${u.size}, ${u.state})`).join(", ")}`)})}},Wh={name:"open",summary:"open the environment in Studio (its overview, or a section: auth, storage, flags, \u2026)",usage:"[section]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=e.args[0]?`/${e.args[0].replace(/^\/+/,"")}`:"",s=`${e.cloud.studioWeb}/projects/${t.project_id}/environments/${t.env_ref}${n}`,a=e.interactive&&await e.io.openBrowser(s);e.out.result({url:s,opened:a},()=>e.out.line(a?`Opened ${s}`:s))}},Fh={name:"keys:list",summary:"the environment's API keys (never their values)",scope:"environment",async run(e){let t=await f(e),{keys:n}=await e.studio.get(`/environments/${t.env_ref}/keys`);e.out.result({keys:n},()=>e.out.table(n,[{header:"id",value:s=>s.id},{header:"kind",value:s=>s.kind},{header:"label",value:s=>s.label},{header:"ends",value:s=>s.hint?`\u2026${s.hint}`:""},{header:"state",value:s=>s.revoked_at?`revoked ${s.revoked_at}`:s.expires_at?`until ${s.expires_at}`:"active"},{header:"created",value:s=>s.created_at}]))}},Bh={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 h("--kind is publishable or secret");let n=await f(e);await k(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)})}},Jh={name:"keys:revoke",summary:"revoke an API key of the environment; what holds it is refused from then on",usage:"<key-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=`/environments/${Q("the environment's ref",t.env_ref)}/keys/${Q("the key's id",e.args[0])}`;await k(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 gR(e){return(await Pn(e))[0]}async function Pn(e){if(wn(e.io))return[await Ko(e)];let t=await rt(e.studio);if(e.global.project!==void 0)return Ps(t,e.global.project);let n=await e.state.targetFor(e.io.cwd);if(!n)throw new b("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 b("no_such_project",`the project chosen here (${n.target.project_name}) is not among yours any more`,{hint:"palbase use another"});return s}function hR(e,t){let n=t.split("/");if(n.length>3||n.some(o=>o===""))throw h(`${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 o of s){let i;try{i=Ps(e,o.project)}catch(r){a=r;continue}if(o.env!==void 0){let r=i.find(l=>l.slug===o.env||l.ref===o.env);if(r)return r;a=new b("no_such_environment",`${i[0].project_name} has no environment ${JSON.stringify(o.env)}`,{hint:`its environments: ${i.map(l=>l.slug).join(", ")}`});continue}if(i.length===1)return i[0];throw new b("which_environment",`${i[0].project_name} has more than one environment`,{hint:`name one: ${i.map(r=>`${r.project_name}/${r.slug}`).join(", ")}`})}throw a}import{mkdtemp as yR,rm as fR}from"node:fs/promises";import{tmpdir as bR}from"node:os";import{extname as wR,join as Hh}from"node:path";var _d="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 Wn(e,t){let n=await $s(e),s=n.t,a=t??await Zh(e,s,cr(n,"/databases?limit=100"),n.by==="fallback"?"the project":`the environment ${s.env_slug}`),o=await Yh(e,s,a),i=()=>As(async r=>{let{body:l}=await et(e.studio,s.env_ref,"GET",`/databases?limit=100${r?`&cursor=${encodeURIComponent(r)}`:""}`);return{items:l.databases,next:l.next_cursor}});return await Xs(e,n,o.d,i,`the database ${o.d.name}`),o}async function Yh(e,t,n){let{body:s}=await et(e.studio,t.env_ref,"GET",`/databases/${Q("the database's name",n)}`);return{t:await Zs(e,t,s.environment,`the database ${s.name}`),d:s}}async function Zh(e,t,n,s){let{body:a}=await et(e.studio,t.env_ref,"GET",n);if(a.databases.length===1)return a.databases[0].name;throw a.databases.length===0?new b("no_database",`${s} has no database`,{hint:"palbase databases:create opens one"}):h("which database? name it",`${s}'s databases: ${a.databases.map(o=>o.name).join(", ")}`)}async function Rn(e,t,n,s,a){let{body:o}=await et(e.studio,t.env_ref,"GET",`/databases/${Q("the database's name",n)}/credentials`),i=(await e.state.databasePasswords(t.env_ref,n))[s];if(!i)throw new b("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 r=s==="owner"?o.owner:o.app,l=new URL(a?r.pooled_url:r.url);return l.password="",{url:l.toString(),password:i,role:s}}function vR(e){let t=new URL(e.url);return t.password=encodeURIComponent(e.password),t.toString()}var Qh={type:"string",value:"role",description:"owner (migrations, dumps) or app (what the machines use); default owner"};function ey(e){let t=e.flags.role??"owner";if(t!=="owner"&&t!=="app")throw h("--role is owner or app");return t}var ty={PGSSLROOTCERT:"system"};async function sa(e,t,n,s,a=!1){let o=await e.io.run(t,n,{env:{PGPASSWORD:s.password,...ty,PGAPPNAME:"palbase-cli"},inherit:a});if(o.code===127)throw new b("missing_tool",`${t} is not installed here`,{hint:"install the Postgres 18 client tools (brew install postgresql@18, apt install postgresql-client-18)"});return o}var ny={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:[Ce("database"),_d,"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:Qh,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 Wn(e,e.args[0]),s=n.name,a=await Rn(e,t,s,ey(e),e.flags.pooled===!0),o=e.flags["with-password"]===!0?vR(a):a.url;e.out.result({database:s,role:a.role,url:o,libpq_env:ty},()=>{e.io.stdout(`${o}
|
|
52
|
+
`))e.out.line(a)}})}},Wg={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:{...rd,file:{type:"string",value:"path",description:"the template (default: stdin)"}},scope:"environment",async run(e){let t=await f(e),n=oi(e),s=ld(e,e.args[0]),a=qP(n,await ze(e,e.flags.file,"the template"));await k(e,t,`override the ${n} template ${e.args[0]} (${e.flags.locale})`);let o=await m(e,t,"PUT",s,a,D());e.out.result(o,()=>e.out.line(`The ${n} template ${e.args[0]} (${e.flags.locale}) is yours now${typeof o.subject=="string"?`: "${o.subject}"`:""}.`))}},Fg={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:rd,scope:"environment",async run(e){let t=await f(e),n=ld(e,e.args[0]);await k(e,t,`remove the ${oi(e)} template ${e.args[0]} (${e.flags.locale})`),await m(e,t,"DELETE",n,void 0,D()),e.out.result({deleted:{channel:oi(e),slug:e.args[0],locale:e.flags.locale}},()=>e.out.line(`Removed the override of ${e.args[0]} (${e.flags.locale}).`))}};async function id(e,t){let n=[],s;do{let a=await m(e,t,"GET",`/notify/topics?limit=100${s?`&cursor=${A(s)}`:""}`);n.push(...a.topics),s=a.next_cursor}while(s);return n}var Bg={name:"notify:topics:list",summary:"the topics users follow, how many follow each, whether they follow it from the app",scope:"environment",async run(e){let t=await f(e),n=await id(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"}])})}},Jg={name:"notify:topics:create",summary:"make a topic users can follow; a push to it reaches its followers",usage:"<name> [--self-subscribe yes|no]",args:{min:1,max:1},flags:{"self-subscribe":{type:"string",value:"yes|no",description:"users follow it from the app (default no: the project adds them)"}},scope:"environment",async run(e){let t=await f(e),n=Gn(e.flags["self-subscribe"],"self-subscribe");await k(e,t,`make the topic ${e.args[0]}`);let s=await m(e,t,"POST","/notify/topics",{name:e.args[0],...n!==void 0?{self_subscribe:n}:{}},D());e.out.result(s,()=>e.out.line(`Made the topic ${s.name}${s.self_subscribe?", followed from the app":""}.`))}},Hg={name:"notify:topics:delete",summary:"delete a topic and who follows it",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e);await k(e,t,`delete the topic ${e.args[0]} and who follows it`),await m(e,t,"DELETE",`/notify/topics/${A(e.args[0])}`,void 0,D()),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the topic ${e.args[0]}.`))}},Vg={name:"notify:settings:get",summary:"the environment's message settings: the default locale, who email is from, where texts may go",scope:"environment",async run(e){let t=await f(e),{body:n}=await Rt(e,t,"/notify/settings");e.out.result(n,()=>Ma(e,n))}},Xg={name:"notify:settings:set",summary:'change message settings: key=value (from_email=\u2026, sms_countries=["+90","+44"], mx_check=true)',usage:"<key=value>\u2026",details:["The change is made on the revision read: one made beside it in the meantime is refused, not overwritten."],args:{min:1,max:20},scope:"environment",async run(e){let t=await f(e),n=Rs(e.args),{body:s,etag:a}=await Rt(e,t,"/notify/settings"),o=js(s,n),i=os(s,o);if(i.length===0)return Dt(e,"the message settings",s);await k(e,t,`set the message settings ${i.join(", ")}`);let r=await m(e,t,"PUT","/notify/settings",o,{...vt(a),...D()});e.out.result({settings:r,changed:i},()=>{for(let l of i)e.out.line(`${l}: ${kt(s[l])} \u2192 ${kt(r[l])}`)})}},KP=new Set(["sms_countries","sms_blocked_countries"]);function UP(e){return{...e,sms_countries:e.sms_countries??[],sms_blocked_countries:e.sms_blocked_countries??[],mx_check:e.mx_check??!1}}var Yg={name:"notify",async read(e,t){let[n,s,a,o,i,r]=await Promise.all([m(e,t,"GET","/notify/settings"),m(e,t,"GET","/notify/providers"),m(e,t,"GET","/notify/templates/email"),m(e,t,"GET","/notify/templates/sms"),m(e,t,"GET","/notify/templates/whatsapp"),id(e,t)]),l={};for(let[u,g]of Object.entries(UP(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 p=a.templates.filter(u=>u.customized),d=await Promise.all(p.map(u=>m(e,t,"GET",`/notify/templates/email/${A(u.slug)}/${A(u.locale)}`)));for(let u of d)l[`templates.email/${u.slug}/${u.locale}`]={subject:u.subject,html_body:u.html_body,text_body:u.text_body};for(let u of o.templates.filter(g=>g.customized))l[`templates.sms/${u.slug}/${u.locale}`]={body:u.body};for(let u of i.templates)l[`templates.whatsapp/${u.slug}/${u.locale}`]={name:u.name,language:u.language,variables:u.variables,code_button:u.code_button};for(let u of r)l[`topics.${u.name}`]={self_subscribe:u.self_subscribe};return l},async copy(e,t,n,s){let a=Ze(n,"settings.");if(a.length>0){let{body:r,etag:l}=await Rt(e,t,"/notify/settings"),p={...r};for(let d of a)p[d.name]=KP.has(d.name)&&Array.isArray(d.from)&&d.from.length===0?null:d.from;await Te(s,`set the message settings ${a.map(d=>d.name).join(", ")}`,async()=>{await m(e,t,"PUT","/notify/settings",p,{...vt(l),...D()})})}for(let r of Ze(n,"providers.")){let[l,p]=r.name.split("/");r.from===void 0?s.left(`the ${l} provider ${p}: only in the target, left as it is (it holds credentials)`):s.left(`the ${l} provider ${p}: credentials are not copied \u2014 set them with palbase notify:providers:set ${l} ${p} < credentials.json`)}for(let r of Ze(n,"templates.")){let l=`/notify/templates/${r.name.split("/").map(A).join("/")}`;r.from===void 0?await Te(s,`remove the template override ${r.name}`,async()=>{await m(e,t,"DELETE",l,void 0,D())}):await Te(s,`override the template ${r.name}`,async()=>{await m(e,t,"PUT",l,r.from,D())})}let o=Ze(n,"topics."),i=o.some(r=>r.from===void 0)?new Map((await id(e,t)).map(r=>[r.name,r.subscribers])):new Map;for(let r of o){let l=`/notify/topics/${A(r.name)}`,p=r.from?.self_subscribe;if(r.from===void 0){let d=i.get(r.name)??0;d>0?s.left(`the topic ${r.name}: only in the target, and ${d} users follow it \u2014 delete it with notify:topics:delete`):await Te(s,`delete the topic ${r.name}`,async()=>{await m(e,t,"DELETE",l,void 0,D())})}else r.change==="only_in_from"?await Te(s,`make the topic ${r.name}`,async()=>{await m(e,t,"POST","/notify/topics",{name:r.name,self_subscribe:p},D())}):await Te(s,`set the topic ${r.name} ${p?"followed from the app":"followed by the project's adding"}`,async()=>{await m(e,t,"PATCH",l,{self_subscribe:p},D())})}}};var Wa=["max_connections","max_events_per_second","max_joins_per_second","max_channels_per_connection"];function WP(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 pd(e){return Object.fromEntries(Wa.map(t=>[t,e[t]??null]))}var Zg={name:"realtime:channels:get",summary:"the channel declaration, in the order patterns are matched: who may join each, publish, read and write its state",scope:"environment",async run(e){let t=await f(e),n=await m(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=>WP(s)}])})}},Qg={name:"realtime:channels:set",summary:'replace the channel declaration with a JSON file or stdin ({"channels": [\u2026]} or the list)',usage:"[--file <path>]",details:['Each channel: {"pattern": "room:{id}", "kind": "public", "publish": true, "state_read": true, "state_write": false}, or {"pattern": "user:{uid}", "kind": "owner"}.',"realtime:channels:get --json gives the document to edit. Open sockets are decided again within a heartbeat."],flags:{file:{type:"string",value:"path",description:"the declaration (default: stdin)"}},scope:"environment",async run(e){let t=await f(e),n=Ne(await ze(e,e.flags.file,"the channel declaration"),"the channel declaration"),s=Array.isArray(n)?n:n.channels;if(!Array.isArray(s))throw h('the declaration is {"channels": [\u2026]} or a list of channels');let a=await m(e,t,"GET","/realtime/channels");if(Mt(a.channels,s))return Dt(e,"the channel declaration",a);await k(e,t,`declare ${s.length} channel pattern(s) (now ${a.channels.length})`);let o=await m(e,t,"PUT","/realtime/channels",{channels:s});e.out.result(o,()=>e.out.line(o.channels.length===0?"No channel is declared now.":`Declared ${o.channels.length} channel pattern(s): ${o.channels.map(i=>i.pattern).join(", ")}.`))}},eh={name:"realtime:limits:get",summary:"the limits the environment holds its clients to (null: the platform's), and the platform's",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/realtime/limits");e.out.result(n,()=>{let s=n.platform??{},a=Math.max(...Wa.map(o=>o.length));for(let o of Wa)e.out.line(`${o.padEnd(a)} ${n[o]===void 0||n[o]===null?"the platform's":kt(n[o])}${s[o]!==void 0?` (platform ${s[o]===0?"no ceiling":kt(s[o])})`:""}`)})}},th={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: ${Wa.join(", ")}. A value above the platform's has no effect beyond it.`],args:{min:1,max:4},scope:"environment",async run(e){let t=await f(e),n=Rs(e.args);for(let r of n)if(r.path.length!==1||!Wa.includes(r.path[0]))throw h(`no limit ${JSON.stringify(r.path.join("."))}`,`the limits: ${Wa.join(", ")}`);let s=pd(await m(e,t,"GET","/realtime/limits")),a=js(s,n),o=os(s,a);if(o.length===0)return Dt(e,"the realtime limits",s);await k(e,t,`set the realtime limits ${o.join(", ")}`);let i=await m(e,t,"PUT","/realtime/limits",a);e.out.result({limits:i,changed:o},()=>{for(let r of o)e.out.line(`${r}: ${kt(s[r]??"the platform's")} \u2192 ${kt(i[r]??"the platform's")}`)})}},nh={name:"realtime",async read(e,t){let[n,s]=await Promise.all([m(e,t,"GET","/realtime/channels"),m(e,t,"GET","/realtime/limits")]),a={channels:n.channels};for(let[o,i]of Object.entries(pd(s)))a[`limits.${o}`]=i;return a},async copy(e,t,n,s){let a=n.find(i=>i.key==="channels");a&&await Te(s,"declare the channels",async()=>{await m(e,t,"PUT","/realtime/channels",{channels:a.from??[]})});let o=Ze(n,"limits.");if(o.length>0){let i=pd(await m(e,t,"GET","/realtime/limits"));for(let r of o)i[r.name]=r.from??null;await Te(s,`set the realtime limits ${o.map(r=>r.name).join(", ")}`,async()=>{await m(e,t,"PUT","/realtime/limits",i)})}}},sh={name:"analytics:settings:get",summary:"how long analytics keeps events and console records, the share of performance samples kept, whether bodies are kept",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/analytics/settings");e.out.result(n,()=>Ma(e,n))}},ah={name:"analytics:settings:set",summary:"change analytics settings: key=value (retention_days=30, perf_sample_pct=10, console_bodies=false)",usage:"<key=value>\u2026",details:["A shorter retention removes what is older within minutes."],args:{min:1,max:4},scope:"environment",async run(e){let t=await f(e),n=Rs(e.args),s=await m(e,t,"GET","/analytics/settings"),a=js(s,n),o=os(s,a);if(o.length===0)return Dt(e,"the analytics settings",s);await k(e,t,`set the analytics settings ${o.join(", ")}`);let i=await m(e,t,"PUT","/analytics/settings",a);e.out.result({settings:i,changed:o},()=>{for(let r of o)e.out.line(`${r}: ${kt(s[r])} \u2192 ${kt(i[r])}`)})}},oh={name:"analytics",async read(e,t){let n=await m(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=Ze(n,"settings.");if(a.length===0)return;let o=await m(e,t,"GET","/analytics/settings");for(let i of a)i.from!==void 0&&(o[i.name]=i.from);await Te(s,`set the analytics settings ${a.map(i=>i.name).join(", ")}`,async()=>{await m(e,t,"PUT","/analytics/settings",o)})}};var nn="/messaging/settings",FP=/^[A-Z][A-Z0-9_]{0,127}$/,cd=["retention_days","push_preview","deleted_user_messages","search_by_meaning","event_text"];function Fa(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?ih(t):"none: anyone may reach anyone"}}function ih(e){return`${I(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 BP(e,t){let n=[...cd.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,o]of n)e.out.line(`${a.padEnd(s)} ${Fa(a,o)}`)}function dd(e,t){if(e!==void 0){if(e==="on")return!0;if(e==="off")return!1;throw h(`--${t} is on or off`)}}function JP(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 h("--retention-days is a whole number of days from 1 to 36500, or off (kept for good)");return t}var HP={name:"messaging:settings:get",summary:"how the environment runs its conversations: how long messages are kept, whether a push says what one says, what becomes of a deleted user's messages, whether they are found by what they mean, whether a message's event says what it says, the hook",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",nn);e.out.result(n,()=>BP(e,n))}},VP={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=JP(e.flags["retention-days"]);n!==void 0&&(t.retention_days=n);let s=dd(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 h("--deleted-user-messages is keep or delete");t.deleted_user_messages=a}let o=dd(e.flags["search-by-meaning"],"search-by-meaning");o!==void 0&&(t.search_by_meaning=o);let i=dd(e.flags["event-text"],"event-text");if(i!==void 0&&(t.event_text=i),Object.keys(t).length===0)throw h("nothing to change","pass --retention-days, --push-preview, --deleted-user-messages, --search-by-meaning or --event-text");let r=await f(e),l=await m(e,r,"GET",nn),p=cd.filter(u=>u in t&&!Mt(l[u],t[u]));if(p.length===0)return Dt(e,"the messaging settings",l);await k(e,r,`set the messaging settings ${p.join(", ")}`);let d=await m(e,r,"PUT",nn,Object.fromEntries(p.map(u=>[u,t[u]])));e.out.result({settings:d,changed:p},()=>{for(let u of p)e.out.line(`${u}: ${Fa(u,l[u])} \u2192 ${Fa(u,d[u])}`)})}},rh={"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 lh(e){let t=e.flags["secret-to"];if(t!==void 0&&!FP.test(t))throw h(`--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 h("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function ph(e,t,n,s,a){let{hook_secret:o,...i}=n;if(o===void 0){e.out.result({settings:i},()=>e.out.line(`${a}: ${Fa("hook",i.hook)}.`));return}if(s!==void 0){let r=await m(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:o});e.out.result({settings:i,secret_to:{set:s.set,name:s.name,version:r.version}},()=>e.out.line(`${a}: ${Fa("hook",i.hook)}; its signing secret is ${s.name} (${s.set}, v${r.version}) in ${ee(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${Fa("hook",i.hook)}.`),e.out.line(`signing secret (shown this once): ${o}`)})}var XP={name:"messaging:hook:get",summary:"the hook asked whom one may reach: where it is, how long it is waited for, what is done when it does not answer (never its secret)",scope:"environment",async run(e){let t=await f(e),{hook:n}=await m(e,t,"GET",nn);e.out.result({hook:n},()=>e.out.line(n?ih(n):"No hook: anyone may reach anyone. palbase messaging:hook:set --url <url> sets one."))}},YP={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)"},...rh},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw h("--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 h("--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 h("--on-error is allow or deny");if(t===void 0&&n===void 0&&s===void 0)throw h("nothing to change","pass --url, --timeout-ms or --on-error");let a=lh(e),o=await f(e),i=await m(e,o,"GET",nn),r=i.hook;if(!r&&t===void 0)throw h("the environment has no hook yet: --url names where it is asked");if(r&&a!==void 0)throw h("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??r.url},p=n??r?.timeout_ms;p!==void 0&&(l.timeout_ms=p);let d=s??r?.on_error;if(d!==void 0&&(l.on_error=d),r&&Mt(r,{...r,...l}))return Dt(e,"the hook",i);let u=r?["url","timeout_ms","on_error"].filter(y=>l[y]!==r[y]):[];await k(e,o,r?`change the messaging hook: ${u.join(", ")}`:`set the messaging hook ${l.url}${a?`, its secret kept in ${a.name} (${a.set})`:""}`);let g=await m(e,o,"PUT",nn,{hook:l});await ph(e,o,g,a,r?"Changed the hook":"Set the hook")}},ZP={name:"messaging:hook:remove",summary:"remove the hook: anyone may reach anyone, and its signing secret is forgotten",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",nn);if(!n.hook){e.out.result({settings:n,changed:[]},()=>e.out.line("Nothing to change: the environment has no hook."));return}await k(e,t,`remove the messaging hook ${n.hook.url}: anyone may reach anyone, and its signing secret is forgotten`);let s=await m(e,t,"PUT",nn,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may reach anyone."))}},QP={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:rh,scope:"environment",async run(e){let t=lh(e),n=await f(e);await k(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 m(e,n,"POST",`${nn}/hook-secret`);await ph(e,n,s,t,"Made the signing secret anew for the hook")}},dh={name:"messaging",async read(e,t){let n=await m(e,t,"GET",nn),s={};for(let a of cd)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=Ze(n,"settings.");a.length>0&&await Te(s,`set the messaging settings ${a.map(l=>l.name).join(", ")}`,async()=>{await m(e,t,"PUT",nn,Object.fromEntries(a.map(l=>[l.name,l.from])))});let o=n.find(l=>l.key==="hook");if(!o)return;if(o.from===void 0){await Te(s,`remove the hook ${o.to.url}`,async()=>{await m(e,t,"PUT",nn,{hook:null})});return}let i=o.from,r;await Te(s,`${o.change==="differs"?"change":"set"} the hook ${i.url}`,async()=>{r=(await m(e,t,"PUT",nn,{hook:i})).hook_secret}),r&&s.shown(`the hook ${i.url} signs with`,r)}},ch=[HP,VP,XP,YP,ZP,QP];var sn="/calls/settings",eR=/^[A-Z][A-Z0-9_]{0,127}$/,md=["max_participants","calls_per_hour"];function Ba(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?uh(t):"none: anyone may call anyone (blocks aside)"}}function uh(e){return`${I(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 tR(e,t){let n=[...md.map(a=>[a,t[a]]),["hook",t.hook]],s=Math.max(...n.map(([a])=>a.length));for(let[a,o]of n)e.out.line(`${a.padEnd(s)} ${Ba(a,o)}`)}function ud(e,t,n,s){if(e===void 0)return;let a=Number(e);if(!/^[0-9]+$/.test(String(e))||a<n||a>s)throw h(`--${t} is a whole number from ${n} to ${s}`);return a}var nR={name:"calls:settings:get",summary:"how the environment runs its calls: how many a call holds, how many calls a person may start in an hour, the hook",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",sn);e.out.result(n,()=>tR(e,n))}},sR={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=ud(e.flags["max-participants"],"max-participants",2,100);n!==void 0&&(t.max_participants=n);let s=ud(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 h("nothing to change","pass --max-participants or --calls-per-hour");let a=await f(e),o=await m(e,a,"GET",sn),i=md.filter(l=>l in t&&!Mt(o[l],t[l]));if(i.length===0)return Dt(e,"the call settings",o);await k(e,a,`set the call settings ${i.join(", ")}`);let r=await m(e,a,"PUT",sn,Object.fromEntries(i.map(l=>[l,t[l]])));e.out.result({settings:r,changed:i},()=>{for(let l of i)e.out.line(`${l}: ${Ba(l,o[l])} \u2192 ${Ba(l,r[l])}`)})}},mh={"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 gh(e){let t=e.flags["secret-to"];if(t!==void 0&&!eR.test(t))throw h(`--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 h("--dev goes with --secret-to <NAME>");return t===void 0?void 0:{name:t,set:e.flags.dev===!0?"development":"production"}}async function hh(e,t,n,s,a){let{hook_secret:o,...i}=n;if(o===void 0){e.out.result({settings:i},()=>e.out.line(`${a}: ${Ba("hook",i.hook)}.`));return}if(s!==void 0){let r=await m(e,t,"PUT",`/secrets/${s.set}/${s.name}`,{value:o});e.out.result({settings:i,secret_to:{set:s.set,name:s.name,version:r.version}},()=>e.out.line(`${a}: ${Ba("hook",i.hook)}; its signing secret is ${s.name} (${s.set}, v${r.version}) in ${ee(t)}.`));return}e.out.result(n,()=>{e.out.line(`${a}: ${Ba("hook",i.hook)}.`),e.out.line(`signing secret (shown this once): ${o}`)})}var aR={name:"calls:hook:get",summary:"the hook asked whom one may call: where it is, how long it is waited for, what is done when it does not answer (never its secret)",scope:"environment",async run(e){let t=await f(e),{hook:n}=await m(e,t,"GET",sn);e.out.result({hook:n},()=>e.out.line(n?uh(n):"No hook: anyone may call anyone (blocks aside). palbase calls:hook:set --url <url> sets one."))}},oR={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)"},...mh},scope:"environment",async run(e){let t=e.flags.url;if(t!==void 0&&t.trim()==="")throw h("--url is where the hook is asked: a URL");let n=ud(e.flags["timeout-ms"],"timeout-ms",100,5e3),s=e.flags["on-error"];if(s!==void 0&&s!=="allow"&&s!=="deny")throw h("--on-error is allow or deny");let a=e.flags.places;if(a!==void 0&&a!=="on"&&a!=="off")throw h("--places is on or off");let o=a===void 0?void 0:a==="on";if(t===void 0&&n===void 0&&s===void 0&&o===void 0)throw h("nothing to change","pass --url, --timeout-ms, --on-error or --places");let i=gh(e),r=await f(e),l=await m(e,r,"GET",sn),p=l.hook;if(!p&&t===void 0)throw h("the environment has no hook yet: --url names where it is asked");if(p&&i!==void 0)throw h("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 d={url:t??p.url},u=n??p?.timeout_ms;u!==void 0&&(d.timeout_ms=u);let g=s??p?.on_error;g!==void 0&&(d.on_error=g);let y=o??p?.places;if(y!==void 0&&(d.places=y),p&&Mt(p,{...p,...d}))return Dt(e,"the hook",l);let w=p?["url","timeout_ms","on_error","places"].filter(R=>(d[R]??!1)!==(p[R]??!1)):[];await k(e,r,p?`change the calls hook: ${w.join(", ")}`:`set the calls hook ${d.url}${i?`, its secret kept in ${i.name} (${i.set})`:""}`);let v=await m(e,r,"PUT",sn,{hook:d});await hh(e,r,v,i,p?"Changed the hook":"Set the hook")}},iR={name:"calls:hook:remove",summary:"remove the hook: anyone may call anyone (blocks aside), and its signing secret is forgotten",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",sn);if(!n.hook){e.out.result({settings:n,changed:[]},()=>e.out.line("Nothing to change: the environment has no hook."));return}await k(e,t,`remove the calls hook ${n.hook.url}: anyone may call anyone, and its signing secret is forgotten`);let s=await m(e,t,"PUT",sn,{hook:null});e.out.result({settings:s,changed:["hook"]},()=>e.out.line("Removed the hook: anyone may call anyone (blocks aside)."))}},rR={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:mh,scope:"environment",async run(e){let t=gh(e),n=await f(e);await k(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 m(e,n,"POST",`${sn}/hook-secret`);await hh(e,n,s,t,"Made the signing secret anew for the hook")}},yh={name:"calls",async read(e,t){let n=await m(e,t,"GET",sn),s={};for(let a of md)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=Ze(n,"settings.");a.length>0&&await Te(s,`set the call settings ${a.map(l=>l.name).join(", ")}`,async()=>{await m(e,t,"PUT",sn,Object.fromEntries(a.map(l=>[l.name,l.from])))});let o=n.find(l=>l.key==="hook");if(!o)return;if(o.from===void 0){await Te(s,`remove the hook ${o.to.url}`,async()=>{await m(e,t,"PUT",sn,{hook:null})});return}let i=o.from,r;await Te(s,`${o.change==="differs"?"change":"set"} the hook ${i.url}`,async()=>{r=(await m(e,t,"PUT",sn,{hook:i})).hook_secret}),r&&s.shown(`the hook ${i.url} signs with`,r)}},fh=[nR,sR,aR,oR,iR,rR];var lR=/^[a-z][a-z0-9-]{1,62}$/;function Ja(e){if(!lR.test(e))throw h(`${JSON.stringify(e)} is not a bucket's name: lowercase letters, digits and dashes, starting with a letter (2\u201363)`);return`/storage/buckets/${A(e)}`}function hd(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 pR(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 h(`--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 gd(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 dR(e,t,n){try{return await m(e,t,"GET",Ja(n))}catch(s){if(s instanceof G&&s.status===404)return;throw s}}var bh={name:"storage:buckets:list",summary:"the environment's buckets: who may read each, the largest file and the types it takes",scope:"environment",async run(e){let t=await f(e),{buckets:n}=await m(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=>hd(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(", ")}])})}},wh={name:"storage:buckets:get",summary:"a bucket's declaration in full, with its renditions",usage:"<bucket>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",Ja(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 ${hd(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}`:""}`)})}},vh={name:"storage:buckets:set",summary:"make a bucket, or change one: public or private, the largest file, the content types, its renditions",usage:"<bucket> [--public|--private] [--max-size <size>] [--types <a/b,c/*>] [--variants-file <path>]",details:["What is not given is kept as it is (a new bucket: private, the platform's size, any type, no rendition)."],args:{min:1,max:1},flags:{public:{type:"boolean",description:"anyone may read its files at /storage/public/"},private:{type:"boolean",description:"its files are read with signed URLs and the rules"},"max-size":{type:"string",value:"size",description:"the largest file: 10MB, 512KiB, 1GB, bytes, or platform"},types:{type:"string",value:"list",description:'the content types it takes, comma-separated (image/* a family); "" for any'},"variants-file":{type:"string",value:"path",description:"its renditions, a JSON list of {name, width, height, fit, format, quality}"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0];if(e.flags.public===!0&&e.flags.private===!0)throw h("--public and --private are one or the other");let s=await dR(e,t,n),a=gd(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=pR(e.flags["max-size"])),e.flags.types!==void 0&&(a.allowed_mime_types=Me(e.flags.types)??[]),e.flags["variants-file"]!==void 0){let i=Ne(await ze(e,e.flags["variants-file"],"the renditions"),"the renditions file"),r=Array.isArray(i)?i:i.variants;if(!Array.isArray(r))throw h("the renditions file is a JSON list of {name, width, height, fit, format, quality}");a.variants=r}if(s&&Mt(gd(s),a)){e.out.result(s,()=>e.out.line(`Nothing to change: ${n} already is so.`));return}await k(e,t,`${s?"change":"make"} the bucket ${n} (${a.public?"public":"private"})`);let o=await m(e,t,"PUT",Ja(n),a);e.out.result(o,()=>e.out.line(`${s?"Changed":"Made"} the bucket ${o.name}: ${o.public?"public":"private"}, files up to ${hd(o.file_size_limit)}, ${o.allowed_mime_types.length===0?"any type":o.allowed_mime_types.join(", ")}.`))}},kh={name:"storage:buckets:delete",summary:"delete an empty bucket (one that still holds files is refused)",usage:"<bucket>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Ja(e.args[0]);await k(e,t,`delete the bucket ${e.args[0]}`),await m(e,t,"DELETE",n),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the bucket ${e.args[0]}.`))}},_h={name:"storage",async read(e,t){let{buckets:n}=await m(e,t,"GET","/storage/buckets"),s={};for(let a of n){let o=gd(a);s[`buckets.${a.name}`]={...o,allowed_mime_types:[...o.allowed_mime_types].sort()}}return s},async copy(e,t,n,s){for(let a of Ze(n,"buckets."))a.from===void 0?await Te(s,`delete the bucket ${a.name}`,async()=>{await m(e,t,"DELETE",Ja(a.name))}):await Te(s,`declare the bucket ${a.name}`,async()=>{await m(e,t,"PUT",Ja(a.name),a.from)})}};var na=[Pg,_h,Mg,Yg,nh,oh,dh,yh];function wd(e="<env>"){return new b("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 Sh={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: ${na.map(e=>e.name).join(",")} (the default)`}};async function $h(e){if(e.global.env!==void 0)throw h("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 h("name both environments: --from <env> --to <env>");let s=await rt(e.studio),a;if(e.global.project!==void 0)a=Ps(s,e.global.project);else{let l=await e.state.targetFor(e.io.cwd);if(!l)throw new b("no_target","which project? none is chosen for this directory",{hint:"pass -P <project>, or choose one here with palbase use"});a=s.filter(p=>p.project_id===l.target.project_id)}let o=l=>{let p=a.find(d=>d.slug===l||d.ref===l);if(!p)throw new b("no_such_environment",`the project has no environment ${JSON.stringify(l)}`,{hint:`its environments: ${a.map(d=>d.slug).join(", ")}`});return Ge(p)},i=o(t),r=o(n);if(i.env_ref===r.env_ref)throw h("--from and --to name the same environment");return{from:i,to:r}}function Ah(e,t){let n=Me(e.flags.only);if(n===void 0)return na;if(n.some(s=>s==="machines"||s==="databases"||s==="sites"))throw wd(t.env_slug);for(let s of n)if(!na.some(a=>a.name===s))throw h(`no module ${JSON.stringify(s)}`,`the modules: ${na.map(a=>a.name).join(", ")}`);return na.filter(s=>n.includes(s.name))}function cR(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),s=[];for(let a of n){let o=a in e,i=a in t;o&&!i?s.push({key:a,change:"only_in_from",from:e[a]}):!o&&i?s.push({key:a,change:"only_in_to",to:t[a]}):Mt(e[a],t[a])||s.push({key:a,change:"differs",from:e[a],to:t[a]})}return s}async function yd(e,t,n,s){let a=l=>Promise.all(t.map(p=>p.read(e,l))),[o,i]=await Promise.all([a(n),a(s)]),r=Object.fromEntries(t.map((l,p)=>[l.name,cR(o[p],i[p])]));return{from:n,to:s,modules:r,count:Object.values(r).reduce((l,p)=>l+p.length,0)}}function fd(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 jr(e){let t=JSON.stringify(e)??"undefined";return t.length>140?`${t.slice(0,139)}\u2026`:t}function bd(e,t){let n=t.from.env_slug,s=t.to.env_slug;for(let[o,i]of Object.entries(t.modules))if(i.length!==0){e.out.line(`${o} (${i.length})`);for(let r of i)r.change==="differs"?e.out.line(` ~ ${r.key}: ${n} ${jr(r.from)} \xB7 ${s} ${jr(r.to)}`):r.change==="only_in_from"?e.out.line(` - ${r.key}: only in ${n}: ${jr(r.from)}`):e.out.line(` + ${r.key}: only in ${s}: ${jr(r.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 uR={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:Sh,scope:"environment",async run(e){let{from:t,to:n}=await $h(e),s=await yd(e,Ah(e,n),t,n);return e.out.result(fd(s),()=>bd(e,s)),s.count===0?0:1}},mR={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:Sh,scope:"environment",async run(e){let{from:t,to:n}=await $h(e);return vd(e,Ah(e,n),t,n)}};async function vd(e,t,n,s,a={}){let o=await yd(e,t,n,s);if(o.count===0)return e.out.result({...a,copied:[],left:[],shown_once:[],after:fd(o)},()=>e.out.line(`Nothing to copy: ${n.env_slug} and ${s.env_slug} have the same settings.`)),0;e.out.json||bd(e,o);let i=t.filter(u=>o.modules[u.name].length>0).map(u=>u.name);await k(e,s,`make its ${i.join(", ")} settings equal to ${n.env_slug}'s (${o.count} difference(s))`);let r=[],l=[],p=[];e.out.json||e.out.line();for(let u of t){let g=o.modules[u.name];if(g.length===0)continue;let y={done(w){r.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,v){p.push({what:`${u.name}: ${w}`,value:v}),e.out.json||e.out.line(` ${u.name}: ${w} ${v} (shown this once)`)}};await u.copy(e,s,g,y)}let d=await yd(e,t,n,s);return e.out.result({...a,copied:r,left:l,shown_once:p,after:fd(d)},()=>{e.out.line(),e.out.line("Compared again:"),bd(e,d)}),d.count===0?0:1}var Ph=[ng,sg,og,ug,gg,mg,lg,pg,dg,cg,hg,yg,fg,wg,vg,kg,_g,Sg,$g,Ag,bh,wh,vh,kh,Tg,Cg,Og,xg,Ig,Ng,Lg,zg,qg,Gg,Kg,Ug,Wg,Fg,Bg,Jg,Hg,Vg,Xg,Zg,Qg,eh,th,sh,ah,...ch,...fh,uR,mR];async function kd(e){return(await e.studio.get("/orgs")).organizations}async function An(e,t){let n=await kd(e);if(t===void 0){if(n.length===1)return n[0];throw h(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 b("no_such_org",`no organization ${JSON.stringify(t)} among yours`,{hint:"palbase orgs:list shows them"});if(s.length>1)throw new b("ambiguous_org",`${JSON.stringify(t)} names more than one of your organizations`,{hint:"pass its id"});return s[0]}var Rh={name:"orgs:list",summary:"your organizations and your role in each",scope:"account",async run(e){let t=await kd(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}])})}},jh={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 ${le(t.name)} (${t.id}).`))}},Eh={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 An(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}]))})}},Th={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 An(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw h("--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 ${le(s.email)} to ${le(t.name)} as ${s.role}.`))}},Ch={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 An(e,e.flags.org),n=e.args[0],s=await e.studio.get(`/orgs/${t.id}/members`),a=s.members.find(i=>i.user_id===n||i.email!==null&&i.email.toLowerCase()===n.toLowerCase());if(a){await e.studio.request("DELETE",`/orgs/${Q("the organization's id",t.id)}/members/${Q("the member's id",a.user_id)}`),e.out.result({removed:a},()=>e.out.line(`${le(a.email??a.user_id)} is no longer in ${le(t.name)}.`));return}let o=s.invitations.find(i=>i.id===n||i.email.toLowerCase()===n.toLowerCase());if(!o)throw new b("no_such_member",`${JSON.stringify(n)} is neither a member of ${t.name} nor invited to it`);await e.studio.request("DELETE",`/orgs/${Q("the organization's id",t.id)}/invitations/${Q("the invitation's id",o.id)}`),e.out.result({withdrawn:o},()=>e.out.line(`The invitation of ${le(o.email)} is withdrawn.`))}},Oh={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 An(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(`${le(t.name)} has no access token yet: palbase tokens:create <name> makes one.`):e.out.table(n,[{header:"name",value:s=>le(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}])})}},xh={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 An(e,e.flags.org),n=e.flags.limit===void 0?50:Number(e.flags.limit);if(!Number.isInteger(n)||n<1||n>1e4)throw h("--limit is a whole number from 1 to 10000");let s=[],a=null;do{let o=new URLSearchParams({limit:String(Math.min(100,n-s.length)),...a?{before:a}:{}}),i=await e.studio.get(`/orgs/${t.id}/audit?${o}`);s.push(...i.entries),a=i.next_before}while(a&&s.length<n);e.out.result({entries:s},()=>{s.length===0?e.out.line(`Nothing changed at ${le(t.name)}'s environments yet.`):e.out.table(s,[{header:"when",value:o=>o.at.slice(0,16).replace("T"," ")},{header:"who",value:o=>le(o.actor_name??o.actor)},{header:"environment",value:o=>le(o.environment_ref)},{header:"what",value:o=>le(`${o.method} ${o.path}`)},{header:"answer",value:o=>String(o.status)}])})}},Lh={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 An(e,e.flags.org),n=e.flags.role??"member";if(n!=="admin"&&n!=="member")throw h("--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 h("--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 ${le(a.name)} of ${le(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}`)})}},Ih={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 An(e,e.flags.org),{tokens:n}=await e.studio.get(`/orgs/${t.id}/tokens`),s=n.filter(i=>i.id===e.args[0]||i.name===e.args[0]);if(s.length===0)throw new b("no_such_token",`${le(t.name)} has no access token ${JSON.stringify(e.args[0])}`,{hint:"palbase tokens:list shows them"});if(s.length>1)throw new b("ambiguous_token",`${JSON.stringify(e.args[0])} names more than one token`,{hint:"pass its id"});let a=`/orgs/${Q("the organization's id",t.id)}/tokens/${Q("the token's id",s[0].id)}`,{endpoints:o}=await e.studio.get(`${a}/webhooks`);await e.studio.request("DELETE",a),e.out.result({revoked:s[0].id,kept_webhooks:o},()=>{if(e.out.line(`Revoked the access token ${le(s[0].name)} of ${le(t.name)}.`),o.length>0){e.out.line("These webhook endpoints it made stay, and keep receiving events (palbase webhooks:delete <id> -E <env> removes one):");for(let i of o)e.out.line(` ${I(i.url)} \u2014 ${I(i.environment_ref)} (${I(i.id)})`)}})}},Nh={name:"projects:list",summary:"every project of your organizations, with its environments",scope:"account",async run(e){let t=await rt(e.studio),n=await e.state.targetFor(e.io.cwd),s=(await e.studio.get("/projects")).projects,a=new Map(t.map(o=>[o.organization_id,o.org_name]));for(let o of await kd(e))a.set(o.id,o.name);e.out.result({projects:s.map(o=>({...o,organization_name:a.get(o.organization_id)??null}))},()=>{s.length===0&&e.out.line("No project yet: palbase projects:create <name> makes one.");let o=s.flatMap(i=>i.environments.length===0?[{org:a.get(i.organization_id)??"",project:i.name,env:"(none)",ref:"",here:""}]:i.environments.map(r=>({org:a.get(i.organization_id)??"",project:i.name,env:r.slug,ref:r.ref,here:n?.target.env_ref===r.ref?"*":""})));e.out.table(o,[{header:"",value:i=>i.here},{header:"organization",value:i=>i.org},{header:"project",value:i=>i.project},{header:"env",value:i=>i.env},{header:"ref",value:i=>i.ref}])})}},Mh={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 An(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 ${le(t.name)} \u203A ${le(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.`)})}},Dh={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=Ps(await rt(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 b("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 b("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 ${le(n.project_name)}.`))}},zh={name:"envs:list",summary:"a project's environments (the project chosen here, or -P)",scope:"environment",async run(e){let t=await Pn(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}]))}},qh={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 wd(t);let n=await gR(e),s=e.flags.from,a=s===void 0?[]:(await rt(e.studio)).filter(p=>p.project_id===n.project_id),o=s===void 0?void 0:a.find(p=>p.slug===s||p.ref===s);if(s!==void 0&&!o)throw new b("no_such_environment",`the project has no environment ${JSON.stringify(s)}`,{hint:`its environments: ${a.map(p=>p.slug).join(", ")}`});let i=await e.studio.post(`/projects/${n.project_id}/environments`,{name:e.flags.name??t,slug:t}),r=()=>{e.out.line(`Made ${le(n.project_name)} \u203A ${i.environment.slug} (ref ${i.environment.ref}).`),i.keys&&(e.out.line(`publishable key: ${i.keys.publishable.key}`),e.out.line(`secret key (shown this once): ${i.keys.secret.key}`))};if(!o){e.out.result(i,r);return}e.out.json||r();let l=Ge({...o,ref:i.environment.ref,slug:i.environment.slug,name:i.environment.name});return e.out.json||e.out.line(),vd(e,na,Ge(o),l,{made:i})}},Gh={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 Pn(e),n=t.find(p=>p.slug===e.args[0]||p.ref===e.args[0]);if(!n)throw new b("no_such_environment",`the project has no environment ${JSON.stringify(e.args[0])}`);let s=Ge(n);if(e.out.note(`${ee(s)}: delete the environment, its users, data, machines and databases`),!e.global.yes){if(!e.interactive)throw new b("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 b("cancelled","nothing was deleted")}let a=e.flags["delete-bound"]===!0,o=typeof e.flags["move-to"]=="string"?e.flags["move-to"]:void 0;if(a&&o!==void 0)throw h("--delete-bound or --move-to: what is bound to it is deleted with it, or moved");let i=a?"?delete_bound=true":o!==void 0?`?move_to=${encodeURIComponent(o)}`:"",r=async()=>{let p=e.io.now()+6e5;for(;;)try{return await e.studio.request("DELETE",`/environments/${n.ref}${i}`)}catch(d){if(!(d instanceof G)||d.code!=="machines_still_moving"||e.io.now()>p)throw d;e.out.note(`still moving to ${decodeURIComponent(i.slice(9))}; asking again`),await e.io.sleep(5e3)}};try{await r()}catch(p){if(!(p instanceof G)||p.code!=="environment_has_resources"||i!=="")throw p;let d=p.body?.data??{},u=[d.machines?.length?`machines ${d.machines.join(", ")}`:"",d.databases?.length?`databases ${d.databases.join(", ")}`:"",d.sites?.length?`sites ${d.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 b("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")i="?delete_bound=true";else if(g.includes(y))i=`?move_to=${encodeURIComponent(y)}`;else throw new b("cancelled","nothing was deleted");await r()}if(i.startsWith("?move_to=")){let p=t.find(d=>d.slug===decodeURIComponent(i.slice(9))||d.ref===decodeURIComponent(i.slice(9)));p&&await e.state.moveDatabasePasswords(n.ref,p.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 ${ee(s)}.`))}},Kh={name:"use",summary:"choose the environment this directory acts on (kept on this computer)",usage:"[<project>[/<env>] | <org>/<project>/<env>] [--clear]",details:["Commands run in this directory, or a directory under it, then act on that environment unless -P/-E say otherwise.","Nothing is written into the project: two checkouts of it can each act on their own environment.","With no argument and a person at the terminal, it lists your environments to pick from."],args:{min:0,max:1},flags:{clear:{type:"boolean",description:"forget the choice made for this directory"}},scope:"account",async run(e){if(e.flags.clear===!0){let n=await e.state.clearTarget(e.io.cwd);e.out.result({cleared:n},()=>e.out.line(n?"This directory acts on no environment now.":"No environment was chosen for this directory."));return}let t;if(e.args.length===0)t=await f(e);else{let n=await rt(e.studio);t=Ge(hR(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 ${ee(t)}.`))}},Uh={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 f(e),n=await e.studio.get(`/environments/${t.env_ref}`),s={...t,env_slug:n.slug??t.env_slug,env_name:n.name??t.env_name},a=u=>et(e.studio,t.env_ref,"GET",u).then(g=>g.body,g=>g instanceof G?null:Promise.reject(g)),o=`limit=100&environment=${encodeURIComponent(t.env_ref)}`,[i,r]=await Promise.all([a(`/machines?${o}`),a(`/databases?${o}`)]),l=i?.machines??[],p=r?.databases??[],d=await e.state.targetFor(e.io.cwd);d&&d.target.env_ref===t.env_ref&&(d.target.env_slug!==s.env_slug||d.target.env_name!==s.env_name)&&await e.state.setTarget(d.dir,{...d.target,env_slug:s.env_slug,env_name:s.env_name}),e.out.result({target:s,role:n.role,address:`https://${s.env_ref}.${e.cloud.domain}`,machines:l,databases:p,chosen_for:d?.dir??null},()=>{e.out.line(ee(s)),e.out.line(` ref ${s.env_ref} \xB7 your role ${n.role} \xB7 https://${s.env_ref}.${e.cloud.domain}`),d&&d.target.env_ref===s.env_ref&&e.out.line(` chosen for ${d.dir}`),e.out.line(` machines: ${l.length===0?"none":l.map(u=>`${u.name} (${u.size}, ${u.state})`).join(", ")}`),e.out.line(` databases: ${p.length===0?"none":p.map(u=>`${u.name} (${u.size}, ${u.state})`).join(", ")}`)})}},Wh={name:"open",summary:"open the environment in Studio (its overview, or a section: auth, storage, flags, \u2026)",usage:"[section]",args:{min:0,max:1},scope:"environment",async run(e){let t=await f(e),n=e.args[0]?`/${e.args[0].replace(/^\/+/,"")}`:"",s=`${e.cloud.studioWeb}/projects/${t.project_id}/environments/${t.env_ref}${n}`,a=e.interactive&&await e.io.openBrowser(s);e.out.result({url:s,opened:a},()=>e.out.line(a?`Opened ${s}`:s))}},Fh={name:"keys:list",summary:"the environment's API keys (never their values)",scope:"environment",async run(e){let t=await f(e),{keys:n}=await e.studio.get(`/environments/${t.env_ref}/keys`);e.out.result({keys:n},()=>e.out.table(n,[{header:"id",value:s=>s.id},{header:"kind",value:s=>s.kind},{header:"label",value:s=>s.label},{header:"ends",value:s=>s.hint?`\u2026${s.hint}`:""},{header:"state",value:s=>s.revoked_at?`revoked ${s.revoked_at}`:s.expires_at?`until ${s.expires_at}`:"active"},{header:"created",value:s=>s.created_at}]))}},Bh={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 h("--kind is publishable or secret");let n=await f(e);await k(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)})}},Jh={name:"keys:revoke",summary:"revoke an API key of the environment; what holds it is refused from then on",usage:"<key-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=`/environments/${Q("the environment's ref",t.env_ref)}/keys/${Q("the key's id",e.args[0])}`;await k(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 gR(e){return(await Pn(e))[0]}async function Pn(e){if(wn(e.io))return[await Ko(e)];let t=await rt(e.studio);if(e.global.project!==void 0)return Ps(t,e.global.project);let n=await e.state.targetFor(e.io.cwd);if(!n)throw new b("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 b("no_such_project",`the project chosen here (${n.target.project_name}) is not among yours any more`,{hint:"palbase use another"});return s}function hR(e,t){let n=t.split("/");if(n.length>3||n.some(o=>o===""))throw h(`${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 o of s){let i;try{i=Ps(e,o.project)}catch(r){a=r;continue}if(o.env!==void 0){let r=i.find(l=>l.slug===o.env||l.ref===o.env);if(r)return r;a=new b("no_such_environment",`${i[0].project_name} has no environment ${JSON.stringify(o.env)}`,{hint:`its environments: ${i.map(l=>l.slug).join(", ")}`});continue}if(i.length===1)return i[0];throw new b("which_environment",`${i[0].project_name} has more than one environment`,{hint:`name one: ${i.map(r=>`${r.project_name}/${r.slug}`).join(", ")}`})}throw a}import{mkdtemp as yR,rm as fR}from"node:fs/promises";import{tmpdir as bR}from"node:os";import{extname as wR,join as Hh}from"node:path";var _d="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 Wn(e,t){let n=await $s(e),s=n.t,a=t??await Zh(e,s,cr(n,"/databases?limit=100"),n.by==="fallback"?"the project":`the environment ${s.env_slug}`),o=await Yh(e,s,a),i=()=>As(async r=>{let{body:l}=await et(e.studio,s.env_ref,"GET",`/databases?limit=100${r?`&cursor=${encodeURIComponent(r)}`:""}`);return{items:l.databases,next:l.next_cursor}});return await Xs(e,n,o.d,i,`the database ${o.d.name}`),o}async function Yh(e,t,n){let{body:s}=await et(e.studio,t.env_ref,"GET",`/databases/${Q("the database's name",n)}`);return{t:await Zs(e,t,s.environment,`the database ${s.name}`),d:s}}async function Zh(e,t,n,s){let{body:a}=await et(e.studio,t.env_ref,"GET",n);if(a.databases.length===1)return a.databases[0].name;throw a.databases.length===0?new b("no_database",`${s} has no database`,{hint:"palbase databases:create opens one"}):h("which database? name it",`${s}'s databases: ${a.databases.map(o=>o.name).join(", ")}`)}async function Rn(e,t,n,s,a){let{body:o}=await et(e.studio,t.env_ref,"GET",`/databases/${Q("the database's name",n)}/credentials`),i=(await e.state.databasePasswords(t.env_ref,n))[s];if(!i)throw new b("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 r=s==="owner"?o.owner:o.app,l=new URL(a?r.pooled_url:r.url);return l.password="",{url:l.toString(),password:i,role:s}}function vR(e){let t=new URL(e.url);return t.password=encodeURIComponent(e.password),t.toString()}var Qh={type:"string",value:"role",description:"owner (migrations, dumps) or app (what the machines use); default owner"};function ey(e){let t=e.flags.role??"owner";if(t!=="owner"&&t!=="app")throw h("--role is owner or app");return t}var ty={PGSSLROOTCERT:"system"};async function sa(e,t,n,s,a=!1){let o=await e.io.run(t,n,{env:{PGPASSWORD:s.password,...ty,PGAPPNAME:"palbase-cli"},inherit:a});if(o.code===127)throw new b("missing_tool",`${t} is not installed here`,{hint:"install the Postgres 18 client tools (brew install postgresql@18, apt install postgresql-client-18)"});return o}var ny={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:[Ce("database"),_d,"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:Qh,pooled:{type:"boolean",description:"the pooled port (transaction pooling): 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 Wn(e,e.args[0]),s=n.name,a=await Rn(e,t,s,ey(e),e.flags.pooled===!0),o=e.flags["with-password"]===!0?vR(a):a.url;e.out.result({database:s,role:a.role,url:o,libpq_env:ty},()=>{e.io.stdout(`${o}
|
|
53
53
|
`),e.out.note("psql, pg_dump and other libpq tools: PGSSLROOTCERT=system (Postgres 16+), or they cannot check the certificate")})}},sy={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:[Ce("database"),_d],args:{min:0,max:1},flags:{role:Qh,command:{type:"string",short:"c",value:"sql",description:"run this and end"}},scope:"environment",async run(e){let{t,d:n}=await Wn(e,e.args[0]),s=n.name,a=await Rn(e,t,s,ey(e),!1),o=e.flags.command;if(o!==void 0){let r=await sa(e,"psql",[a.url,"-v","ON_ERROR_STOP=1","-X","-c",o],a);if(r.stdout&&e.io.stdout(r.stdout),r.code!==0)throw new b("psql_failed",r.stderr.trim()||`psql ended with ${r.code}`);return}if(!e.interactive)throw h("db:shell with no person at the terminal needs --command <sql>");return e.out.note(`${ee(t)} \u203A ${s} as ${a.role}`),(await sa(e,"psql",[a.url],a,!0)).code}},ay={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:[Ce("database"),_d],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 Wn(e,e.args[0]),s=n.name,a=await Rn(e,t,s,"owner",!1),o=e.flags.file??`${s}-${new Date(e.io.now()).toISOString().replaceAll(":","-").slice(0,19)}.dump`,i=await sa(e,"pg_dump",["--format=custom","--no-owner","--no-acl",...e.flags["schema-only"]===!0?["--schema-only"]:[],"--file",o,a.url],a);if(i.code!==0)throw new b("pg_dump_failed",i.stderr.trim()||`pg_dump ended with ${i.code}`);e.out.result({database:s,file:o},()=>e.out.line(`Wrote ${o}.`))}},oy={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).",Ce("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 Wn(e,e.flags.db),s=n.name,a=e.args[0];await k(e,t,`load ${a} into the database ${s}`);let o=await Rn(e,t,s,"owner",!1);await iy(e,o,a,e.flags.clean===!0),e.out.result({database:s,loaded:a},()=>e.out.line(`Loaded ${a} into ${s}.`))}};async function iy(e,t,n,s){let a=wR(n).toLowerCase()===".sql",o=a?await sa(e,"psql",[t.url,"-v","ON_ERROR_STOP=1","-X","--single-transaction","-f",n],t):await sa(e,"pg_restore",["--no-owner","--no-acl","--exit-on-error","--single-transaction",...s?["--clean","--if-exists"]:[],"--dbname",t.url,n],t);if(o.code!==0)throw new b("restore_failed",o.stderr.trim()||`${a?"psql":"pg_restore"} ended with ${o.code}`)}var Vh="\u2022\u2022\u2022";async function kR(e,t,n){let s=async l=>{let p=await sa(e,"psql",[n.url,"-v","ON_ERROR_STOP=1","-X","-At","-F"," ","-c",l],n);if(p.code!==0)throw new b("redact_failed",p.stderr.trim()||`psql ended with ${p.code}`);return p.stdout.split(`
|
|
54
|
-
`).filter(d=>d!=="").map(d=>d.split(" "))},a=l=>`"${l.replace(/"/g,'""')}"`,o=l=>`'${l.replace(/'/g,"''")}'`,i=await s("SELECT c.table_schema, c.table_name, c.column_name, EXISTS (SELECT 1 FROM information_schema.columns l WHERE l.table_schema = c.table_schema AND l.table_name = c.table_name AND l.column_name = c.column_name || '_lookup') FROM information_schema.columns c JOIN information_schema.tables t ON t.table_schema = c.table_schema AND t.table_name = c.table_name AND t.table_type = 'BASE TABLE' WHERE c.data_type = 'text' AND c.table_schema NOT IN ('pg_catalog', 'information_schema', 'palgres', 'palgres_search', 'palbase') AND c.table_schema NOT LIKE 'palgres\\_%' ORDER BY 1, 2, 3"),r=[];if(i.length>0){let l=await s(i.map(([p,d,u])=>`SELECT ${o(`${p} ${d} ${u}`)} WHERE EXISTS (SELECT 1 FROM ${a(p)}.${a(d)} WHERE ${a(u)} LIKE 'pbe1.%')`).join(" UNION ALL "));for(let[p,d,u]of l){let g=i.find(R=>R[0]===p&&R[1]===d&&R[2]===u)?.[3]==="t",y=p==="public"?`${d}.${u}`:`${p}.${d}.${u}`,{value:w}=await m(e,t,"POST","/secrets/fields/placeholder",{address:y}),[[v]]=await s(`WITH done AS (UPDATE ${a(p)}.${a(d)} SET ${a(u)} = ${o(w)}${g?`, ${a(`${u}_lookup`)} = NULL`:""} WHERE ${a(u)} LIKE 'pbe1.%' RETURNING 1) SELECT count(*) FROM done`);r.push({address:y,rows:Number(v)})}}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 $$"),r}async function Xh(e,t,n){let s=n??await Zh(e,t,`/databases?limit=100&environment=${encodeURIComponent(t.env_ref)}`,t.env_slug),{t:a,d:o}=await Yh(e,t,s);if(a.env_ref!==t.env_ref)throw new b("database_elsewhere",`the database ${o.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 o.name}var ry={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 ${Vh}, 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 h("db:copy needs --from <env> and --to <env>");if(t===n)throw h("--from and --to are two environments");let s=await Pn(e),a=s.find(w=>w.slug===t),o=s.find(w=>w.slug===n);if(!a||!o)throw new b("no_such_environment",`the project has no environment ${JSON.stringify(a?n:t)}`);let i=Ge(a),r=Ge(o),l=await Xh(e,i,e.flags.db),p=await Xh(e,r,e.flags["to-db"]);await k(e,r,`overwrite the database ${p} with ${i.env_slug}'s ${l}`);let d=await Rn(e,i,l,"owner",!1),u=await Rn(e,r,p,"owner",!1),g=await yR(Hh(bR(),"palbase-copy-"));try{let w=Hh(g,"copy.dump"),v=await sa(e,"pg_dump",["--format=custom","--no-owner","--no-acl","--file",w,d.url],d);if(v.code!==0)throw new b("pg_dump_failed",v.stderr.trim()||`pg_dump ended with ${v.code}`);await iy(e,u,w,!0)}finally{await fR(g,{recursive:!0,force:!0})}let y=await kR(e,r,u);e.out.result({from:{env:i.env_slug,database:l},to:{env:r.env_slug,database:p},redacted:y},()=>{e.out.line(`Copied ${i.env_slug}/${l} into ${r.env_slug}/${p}.`);for(let w of y)e.out.line(` ${w.address}: ${w.rows} encrypted value(s) copied as ${Vh}`)})}};function py(e){return`its last push (${I(e.commit.slice(0,7))}) did not roll out \u2014 ${I(Va(e.reason))}`}function dy(e){return e.config_version!==void 0&&e.running_config_version!==void 0&&e.running_config_version<e.config_version}var cy="new secrets or config rolling out";function _R(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
|
|
55
|
-
${" ".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 $R=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/;async function ge(e,t,n,s,a,o){return(await et(e.studio,t.env_ref,n,s,a,o)).body}function Oe(e){if(!$R.test(e))throw h(`${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 $s(e),s=n.t,{body:a,etag:o}=await et(e.studio,s.env_ref,"GET",`/machines/${Oe(t??await PR(e,n))}`);return await Xs(e,n,a,()=>AR(e,s),`the machine ${a.name}`),{t:await Zs(e,s,a.environment,`the machine ${a.name}`),name:a.name,machine:a,etag:o}}async function AR(e,t){return As(async n=>{let s=await ge(e,t,"GET",`/machines?limit=100${n?`&cursor=${encodeURIComponent(n)}`:""}`);return{items:s.machines,next:s.next_cursor}})}async function uy(e,t,n){return As(async s=>{let a=await ge(e,t,"GET",ur(e,t,`/${n}?limit=100${s?`&cursor=${encodeURIComponent(s)}`:""}`));return{items:a[n],next:a.next_cursor}})}async function PR(e,t){let{machines:n}=await ge(e,t.t,"GET",cr(t,"/machines?limit=100"));if(n.length===1)return n[0].name;let s=await Ia(e.io,e.io.cwd),a=s?.repository?n.filter(i=>i.source.repository.toLowerCase()===s.repository?.toLowerCase()&&(i.source.path??"")===s.path):[];if(a.length===1)return a[0].name;let o=t.by==="fallback"?"the project":`the environment ${t.t.env_slug}`;throw n.length===0?new b("no_machine",`${o} has no machine yet`,{hint:"make one with palbase machines:create"}):h("which machine? name it",`${o}'s machines: ${n.map(i=>i.name).join(", ")}`)}var Cr=async e=>{let{t,name:n}=await Ue(e,e.flags.machine);return{t,path:`/machines/${Oe(n)}`}},jt={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)"}},RR="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.",Qe=[Ce("machine"),RR];function my(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 jR(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 ER(e){return`$${(e/1e6).toFixed(2)}`}function gy(e){return e>=1024&&e%1024===0?`${e/1024} GiB`:`${e} MiB`}function Er(e){return e<1e9?`${Number((e/1e6).toFixed(1)).toLocaleString("en-US")} MB`:`${Number((e/1e9).toFixed(2)).toLocaleString("en-US")} GB`}var hy={name:"machines:sizes",summary:"the machine sizes, and which of them this environment may open now",scope:"environment",async run(e){let t=await f(e),{sizes:n}=await ge(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=>gy(s.memory_mib)},{header:"sleeps",value:s=>s.sleeps?"when idle":"never"},{header:"price",value:s=>my(s)},{header:"open",value:s=>s.available?"yes":`no \u2014 ${s.reason??""}`}]))}},yy={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 f(e),{sizes:n}=await ge(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=>gy(a.memory_mib)},{header:"storage",value:a=>jR(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=>`${my(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: ${ER(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).`))})}},fy={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 Vs(e),[n,s]=await Promise.all([uy(e,t,"machines"),Na(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=>`${as(s,a.environment)}${a.moving_to?` \u2192 ${as(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=>Tr(a)},{header:"version",value:a=>`${a.running_version===a.version?`${a.version}`:`${a.running_version} \u2192 ${a.version}`}${dy(a)?` (${cy})`:""}`},{header:"source",value:a=>`${a.source.repository}@${a.source.branch}${a.source.path?`/${a.source.path}`:""}`},{header:"url",value:a=>a.url}])})}},by={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 h("--to names the environment of the project it moves to");let{t:n,name:s}=await Ue(e,e.args[0]),a=await Uo(e,n,t);await k(e,n,`move the machine ${s} out of this environment, into ${a.slug}`),await k(e,Ge(a),`move the machine ${s} into this environment: it starts here with this environment's settings, secrets and modules`);let o=await ge(e,n,"POST",`/machines/${Oe(s)}/move`,{environment:a.ref});e.out.result(o,()=>e.out.line(`${o.name} moves to ${a.slug}: it starts there in a moment (palbase machines:get ${o.name}).`))}},wy={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:Qe,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 ${Tr(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 ${CR(n.replicas,n.autoscaling)}`),e.out.line(` version ${_R(n)}`),n.failed_build&&e.out.line(` last push ${I(`${n.failed_build.commit.slice(0,7)} ${n.failed_build.state}: ${Va(n.failed_build.reason)}`)} (palbase machines:builds:log ${I(n.failed_build.id)} --machine ${n.name})`),e.out.line(` contract ${SR(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${dy(n)?` \u2014 ${cy}: 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(", ")}`)})}},vy={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"},...ni,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 ky(e,t){e.flags["test-command"]!==void 0&&(t.test_command=e.flags["test-command"]),e.flags["test-users"]!==void 0&&(t.test_users=Hp(e.flags["test-users"]))}function _y(e){if(!e)return;let t={};for(let n of e){let s=n.indexOf("=");if(s<=0)throw h(`a setting is K=V, not ${JSON.stringify(n)}`);t[n.slice(0,s)]=n.slice(s+1)}return t}function Sy(e,t){let n=ln(e.flags["max-replicas"],"max-replicas"),s=ln(e.flags["cpu-percent"],"cpu-percent"),a=ln(e.flags["memory-percent"],"memory-percent");if(e.flags["no-autoscaling"]===!0){if(n!==void 0||s!==void 0||a!==void 0)throw h("--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 o=n??t?.max_replicas;if(o===void 0)throw h("--cpu-percent and --memory-percent go with --max-replicas: the most copies its load may run");let i=s??t?.cpu_percent,r=a??t?.memory_percent;if(i===void 0&&r===void 0)throw h("with --max-replicas give --cpu-percent, --memory-percent or both: what a copy is kept near");return{max_replicas:o,...i!==void 0?{cpu_percent:i}:{},...r!==void 0?{memory_percent:r}:{}}}function TR(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 CR(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 ln(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw h(`--${t} is a whole number`);return n}async function $y(e,t){let{sizes:n}=await ge(e,t,"GET","/machines/sizes"),s=n.find(a=>a.available)?.name;if(!s)throw new b("no_size_open","no machine size is open to this environment",{hint:"palbase machines:sizes says why"});return s}function Ay(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 Py={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.",`${Qs} 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:{...vy,wait:{type:"boolean",description:"follow the first build until the machine serves"}},scope:"environment",async run(e){let t=await Ys(e),n=await Ia(e.io,e.io.cwd),s=e.flags.repo??n?.repository,a=e.flags.branch??n?.branch;if(!s)throw h("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!a)throw h("which branch? none is checked out here","pass --branch <branch>");let o=e.flags.size??await $y(e,t),i=e.flags.path??n?.path??"",r=Ay(e.args[0],{repository:s,branch:a,path:i,context:e.flags.context},o),l=ln(e.flags.replicas,"replicas"),p=ln(e.flags.port,"port");l!==void 0&&(r.replicas=l),p!==void 0&&(r.port=p),e.flags["always-on"]===!0&&(r.always_on=!0),e.flags["no-always-on"]===!0&&(r.always_on=!1);let d=Sy(e);d!==void 0&&(r.autoscaling=d),ai(e,r),e.flags.health!==void 0&&(r.health_path=e.flags.health),e.flags["openapi-path"]!==void 0&&(r.openapi_path=e.flags["openapi-path"]),e.flags.secrets!==void 0&&(r.secrets=e.flags.secrets);let u=_y(e.flags.var);if(u&&(r.env=u),e.flags.db!==void 0)r.database={name:e.flags.db,migrations:e.flags.migrations===!0};else if(e.flags.migrations===!0)throw h("--migrations goes with --db <database>");ky(e,r),await k(e,t,`make a machine from ${s}@${a}${i?`/${i}`:""} (${o})`);let g=await ge(e,t,"POST","/machines",r);e.flags.wait===!0&&(g=await LR(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}`))}},Ry={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:Qe,args:{min:0,max:1},flags:vy,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 o=ln(e.flags.replicas,"replicas"),i=ln(e.flags.port,"port");o!==void 0&&(a.replicas=o),i!==void 0&&(a.port=i),e.flags["always-on"]===!0&&(a.always_on=!0),e.flags["no-always-on"]===!0&&(a.always_on=!1);let r=Sy(e,s.autoscaling);if(r!==void 0&&(a.autoscaling=r),ai(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 h("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}),ky(e,a),Object.keys(a).length===0)throw h("nothing to change: give a flag","palbase help machines:update");await k(e,t,`change the machine ${n}: ${Object.keys(a).join(", ")}`);let l=await ge(e,t,"PATCH",`/machines/${Oe(n)}`,a);e.out.result(l,()=>e.out.line(TR(l)))}},jy={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:Qe,args:{min:0,max:1},scope:"environment",async run(e){let{t,machine:n}=await Ue(e,e.args[0]),s=n.secrets?(await ea(e,t,Q("the machine's secret set",n.secrets))).map(i=>i.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"]:[]],o=a.map(i=>({name:i,from:"platform",note:s.includes(i)||i in n.env?`in place of the ${i} set by hand`:""}));for(let i of Object.keys(n.env).sort())a.includes(i)||o.push({name:i,from:"machine",note:s.includes(i)?`shadows the secret ${i}`:""});for(let i of s.sort())a.includes(i)||i in n.env||o.push({name:i,from:`secrets (${n.secrets})`,note:""});e.out.result({machine:n.name,env:o},()=>e.out.table(o,[{header:"name",value:i=>i.name},{header:"from",value:i=>i.from},{header:"",value:i=>i.note}]))}};async function Ey(e,t){let{t:n,name:s,machine:a,etag:o}=await Ue(e,e.flags.machine),i={body:a,etag:o};for(let r=1;;r++){r>1&&(i=await et(e.studio,n.env_ref,"GET",`/machines/${Oe(s)}`));let l={...i.body.env},p=t(l);if(r===1){if(i.body.secrets){let d=i.body.secrets,u=await ea(e,n,Q("the machine's secret set",d)).then(g=>g.map(y=>y.name),g=>(e.out.warn(`the ${d} 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 k(e,n,`${p.join(", ")} on the machine ${s}`)}try{let d=await ge(e,n,"PATCH",`/machines/${Oe(s)}`,{env:l},i.etag?{"if-match":i.etag}:void 0);e.out.result({machine:d.name,env:Object.keys(d.env).sort()},()=>e.out.line(`${d.name}: version ${d.version} rolls out with it.`));return}catch(d){if(!(d instanceof G&&d.status===412)||r===3)throw d;e.out.note(`${s} changed meanwhile: making the change again on what it is now\u2026`)}}}var Ty={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:Qe,args:{min:1,max:50},flags:jt,scope:"environment",async run(e){let t=_y(e.args);await Ey(e,n=>(Object.assign(n,t),Object.keys(t).map(s=>`set ${s}`)))}},Cy={name:"machines:env:unset",summary:"take settings away from what a machine of the project is started with",usage:"K\u2026 [--machine <name>]",details:Qe,args:{min:1,max:50},flags:jt,scope:"environment",async run(e){await Ey(e,t=>{for(let n of e.args){if(!(n in t))throw new b("no_such_setting",`the machine is not started with ${n}`);delete t[n]}return e.args.map(n=>`unset ${n}`)})}},Oy={name:"machines:builds",summary:"a machine's builds, newest first",usage:"[name]",details:Qe,args:{min:0,max:1},scope:"environment",async run(e){let{t,name:n}=await Ue(e,e.args[0]),{builds:s}=await ge(e,t,"GET",`/machines/${Oe(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 ${Va(a.reason)}`:""}`},{header:"message",value:a=>a.message.split(`
|
|
54
|
+
`).filter(d=>d!=="").map(d=>d.split(" "))},a=l=>`"${l.replace(/"/g,'""')}"`,o=l=>`'${l.replace(/'/g,"''")}'`,i=await s("SELECT c.table_schema, c.table_name, c.column_name, EXISTS (SELECT 1 FROM information_schema.columns l WHERE l.table_schema = c.table_schema AND l.table_name = c.table_name AND l.column_name = c.column_name || '_lookup') FROM information_schema.columns c JOIN information_schema.tables t ON t.table_schema = c.table_schema AND t.table_name = c.table_name AND t.table_type = 'BASE TABLE' WHERE c.data_type = 'text' AND c.table_schema NOT IN ('pg_catalog', 'information_schema', 'palgres', 'palgres_search', 'palbase') AND c.table_schema NOT LIKE 'palgres\\_%' ORDER BY 1, 2, 3"),r=[];if(i.length>0){let l=await s(i.map(([p,d,u])=>`SELECT ${o(`${p} ${d} ${u}`)} WHERE EXISTS (SELECT 1 FROM ${a(p)}.${a(d)} WHERE ${a(u)} LIKE 'pbe1.%')`).join(" UNION ALL "));for(let[p,d,u]of l){let g=i.find(R=>R[0]===p&&R[1]===d&&R[2]===u)?.[3]==="t",y=p==="public"?`${d}.${u}`:`${p}.${d}.${u}`,{value:w}=await m(e,t,"POST","/secrets/fields/placeholder",{address:y}),[[v]]=await s(`WITH done AS (UPDATE ${a(p)}.${a(d)} SET ${a(u)} = ${o(w)}${g?`, ${a(`${u}_lookup`)} = NULL`:""} WHERE ${a(u)} LIKE 'pbe1.%' RETURNING 1) SELECT count(*) FROM done`);r.push({address:y,rows:Number(v)})}}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 $$"),r}async function Xh(e,t,n){let s=n??await Zh(e,t,`/databases?limit=100&environment=${encodeURIComponent(t.env_ref)}`,t.env_slug),{t:a,d:o}=await Yh(e,t,s);if(a.env_ref!==t.env_ref)throw new b("database_elsewhere",`the database ${o.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 o.name}var ry={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 ${Vh}, 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 h("db:copy needs --from <env> and --to <env>");if(t===n)throw h("--from and --to are two environments");let s=await Pn(e),a=s.find(w=>w.slug===t),o=s.find(w=>w.slug===n);if(!a||!o)throw new b("no_such_environment",`the project has no environment ${JSON.stringify(a?n:t)}`);let i=Ge(a),r=Ge(o),l=await Xh(e,i,e.flags.db),p=await Xh(e,r,e.flags["to-db"]);await k(e,r,`overwrite the database ${p} with ${i.env_slug}'s ${l}`);let d=await Rn(e,i,l,"owner",!1),u=await Rn(e,r,p,"owner",!1),g=await yR(Hh(bR(),"palbase-copy-"));try{let w=Hh(g,"copy.dump"),v=await sa(e,"pg_dump",["--format=custom","--no-owner","--no-acl","--file",w,d.url],d);if(v.code!==0)throw new b("pg_dump_failed",v.stderr.trim()||`pg_dump ended with ${v.code}`);await iy(e,u,w,!0)}finally{await fR(g,{recursive:!0,force:!0})}let y=await kR(e,r,u);e.out.result({from:{env:i.env_slug,database:l},to:{env:r.env_slug,database:p},redacted:y},()=>{e.out.line(`Copied ${i.env_slug}/${l} into ${r.env_slug}/${p}.`);for(let w of y)e.out.line(` ${w.address}: ${w.rows} encrypted value(s) copied as ${Vh}`)})}};function py(e){return`its last push (${I(e.commit.slice(0,7))}) did not roll out \u2014 ${I(Va(e.reason))}`}function dy(e){return e.config_version!==void 0&&e.running_config_version!==void 0&&e.running_config_version<e.config_version}var cy="new secrets or config rolling out";function _R(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 capacity"}[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 Tr(e){return e.state_reason_kind==="no_room"?`${e.state}, waiting for capacity`:e.state}function Va(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t!=="").join(" \xB7 ")}function SR(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(I).join(`
|
|
55
|
+
${" ".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 $R=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/;async function ge(e,t,n,s,a,o){return(await et(e.studio,t.env_ref,n,s,a,o)).body}function Oe(e){if(!$R.test(e))throw h(`${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 $s(e),s=n.t,{body:a,etag:o}=await et(e.studio,s.env_ref,"GET",`/machines/${Oe(t??await PR(e,n))}`);return await Xs(e,n,a,()=>AR(e,s),`the machine ${a.name}`),{t:await Zs(e,s,a.environment,`the machine ${a.name}`),name:a.name,machine:a,etag:o}}async function AR(e,t){return As(async n=>{let s=await ge(e,t,"GET",`/machines?limit=100${n?`&cursor=${encodeURIComponent(n)}`:""}`);return{items:s.machines,next:s.next_cursor}})}async function uy(e,t,n){return As(async s=>{let a=await ge(e,t,"GET",ur(e,t,`/${n}?limit=100${s?`&cursor=${encodeURIComponent(s)}`:""}`));return{items:a[n],next:a.next_cursor}})}async function PR(e,t){let{machines:n}=await ge(e,t.t,"GET",cr(t,"/machines?limit=100"));if(n.length===1)return n[0].name;let s=await Ia(e.io,e.io.cwd),a=s?.repository?n.filter(i=>i.source.repository.toLowerCase()===s.repository?.toLowerCase()&&(i.source.path??"")===s.path):[];if(a.length===1)return a[0].name;let o=t.by==="fallback"?"the project":`the environment ${t.t.env_slug}`;throw n.length===0?new b("no_machine",`${o} has no machine yet`,{hint:"make one with palbase machines:create"}):h("which machine? name it",`${o}'s machines: ${n.map(i=>i.name).join(", ")}`)}var Cr=async e=>{let{t,name:n}=await Ue(e,e.flags.machine);return{t,path:`/machines/${Oe(n)}`}},jt={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)"}},RR="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.",Qe=[Ce("machine"),RR];function my(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 jR(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 ER(e){return`$${(e/1e6).toFixed(2)}`}function gy(e){return e>=1024&&e%1024===0?`${e/1024} GiB`:`${e} MiB`}function Er(e){return e<1e9?`${Number((e/1e6).toFixed(1)).toLocaleString("en-US")} MB`:`${Number((e/1e9).toFixed(2)).toLocaleString("en-US")} GB`}var hy={name:"machines:sizes",summary:"the machine sizes, and which of them this environment may open now",scope:"environment",async run(e){let t=await f(e),{sizes:n}=await ge(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=>gy(s.memory_mib)},{header:"sleeps",value:s=>s.sleeps?"when idle":"never"},{header:"price",value:s=>my(s)},{header:"open",value:s=>s.available?"yes":`no \u2014 ${s.reason??""}`}]))}},yy={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 f(e),{sizes:n}=await ge(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=>gy(a.memory_mib)},{header:"storage",value:a=>jR(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=>`${my(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: ${ER(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).`))})}},fy={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 Vs(e),[n,s]=await Promise.all([uy(e,t,"machines"),Na(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=>`${as(s,a.environment)}${a.moving_to?` \u2192 ${as(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=>Tr(a)},{header:"version",value:a=>`${a.running_version===a.version?`${a.version}`:`${a.running_version} \u2192 ${a.version}`}${dy(a)?` (${cy})`:""}`},{header:"source",value:a=>`${a.source.repository}@${a.source.branch}${a.source.path?`/${a.source.path}`:""}`},{header:"url",value:a=>a.url}])})}},by={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 h("--to names the environment of the project it moves to");let{t:n,name:s}=await Ue(e,e.args[0]),a=await Uo(e,n,t);await k(e,n,`move the machine ${s} out of this environment, into ${a.slug}`),await k(e,Ge(a),`move the machine ${s} into this environment: it starts here with this environment's settings, secrets and modules`);let o=await ge(e,n,"POST",`/machines/${Oe(s)}/move`,{environment:a.ref});e.out.result(o,()=>e.out.line(`${o.name} moves to ${a.slug}: it starts there in a moment (palbase machines:get ${o.name}).`))}},wy={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:Qe,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 ${Tr(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 ${CR(n.replicas,n.autoscaling)}`),e.out.line(` version ${_R(n)}`),n.failed_build&&e.out.line(` last push ${I(`${n.failed_build.commit.slice(0,7)} ${n.failed_build.state}: ${Va(n.failed_build.reason)}`)} (palbase machines:builds:log ${I(n.failed_build.id)} --machine ${n.name})`),e.out.line(` contract ${SR(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${dy(n)?` \u2014 ${cy}: 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(", ")}`)})}},vy={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), spread for high availability \u2014 with --max-replicas, the fewest its load runs (2 at least)"},"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"},...ni,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 ky(e,t){e.flags["test-command"]!==void 0&&(t.test_command=e.flags["test-command"]),e.flags["test-users"]!==void 0&&(t.test_users=Hp(e.flags["test-users"]))}function _y(e){if(!e)return;let t={};for(let n of e){let s=n.indexOf("=");if(s<=0)throw h(`a setting is K=V, not ${JSON.stringify(n)}`);t[n.slice(0,s)]=n.slice(s+1)}return t}function Sy(e,t){let n=ln(e.flags["max-replicas"],"max-replicas"),s=ln(e.flags["cpu-percent"],"cpu-percent"),a=ln(e.flags["memory-percent"],"memory-percent");if(e.flags["no-autoscaling"]===!0){if(n!==void 0||s!==void 0||a!==void 0)throw h("--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 o=n??t?.max_replicas;if(o===void 0)throw h("--cpu-percent and --memory-percent go with --max-replicas: the most copies its load may run");let i=s??t?.cpu_percent,r=a??t?.memory_percent;if(i===void 0&&r===void 0)throw h("with --max-replicas give --cpu-percent, --memory-percent or both: what a copy is kept near");return{max_replicas:o,...i!==void 0?{cpu_percent:i}:{},...r!==void 0?{memory_percent:r}:{}}}function TR(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 CR(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 ln(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw h(`--${t} is a whole number`);return n}async function $y(e,t){let{sizes:n}=await ge(e,t,"GET","/machines/sizes"),s=n.find(a=>a.available)?.name;if(!s)throw new b("no_size_open","no machine size is open to this environment",{hint:"palbase machines:sizes says why"});return s}function Ay(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 Py={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.",`${Qs} 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:{...vy,wait:{type:"boolean",description:"follow the first build until the machine serves"}},scope:"environment",async run(e){let t=await Ys(e),n=await Ia(e.io,e.io.cwd),s=e.flags.repo??n?.repository,a=e.flags.branch??n?.branch;if(!s)throw h("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!a)throw h("which branch? none is checked out here","pass --branch <branch>");let o=e.flags.size??await $y(e,t),i=e.flags.path??n?.path??"",r=Ay(e.args[0],{repository:s,branch:a,path:i,context:e.flags.context},o),l=ln(e.flags.replicas,"replicas"),p=ln(e.flags.port,"port");l!==void 0&&(r.replicas=l),p!==void 0&&(r.port=p),e.flags["always-on"]===!0&&(r.always_on=!0),e.flags["no-always-on"]===!0&&(r.always_on=!1);let d=Sy(e);d!==void 0&&(r.autoscaling=d),ai(e,r),e.flags.health!==void 0&&(r.health_path=e.flags.health),e.flags["openapi-path"]!==void 0&&(r.openapi_path=e.flags["openapi-path"]),e.flags.secrets!==void 0&&(r.secrets=e.flags.secrets);let u=_y(e.flags.var);if(u&&(r.env=u),e.flags.db!==void 0)r.database={name:e.flags.db,migrations:e.flags.migrations===!0};else if(e.flags.migrations===!0)throw h("--migrations goes with --db <database>");ky(e,r),await k(e,t,`make a machine from ${s}@${a}${i?`/${i}`:""} (${o})`);let g=await ge(e,t,"POST","/machines",r);e.flags.wait===!0&&(g=await LR(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}`))}},Ry={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:Qe,args:{min:0,max:1},flags:vy,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 o=ln(e.flags.replicas,"replicas"),i=ln(e.flags.port,"port");o!==void 0&&(a.replicas=o),i!==void 0&&(a.port=i),e.flags["always-on"]===!0&&(a.always_on=!0),e.flags["no-always-on"]===!0&&(a.always_on=!1);let r=Sy(e,s.autoscaling);if(r!==void 0&&(a.autoscaling=r),ai(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 h("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}),ky(e,a),Object.keys(a).length===0)throw h("nothing to change: give a flag","palbase help machines:update");await k(e,t,`change the machine ${n}: ${Object.keys(a).join(", ")}`);let l=await ge(e,t,"PATCH",`/machines/${Oe(n)}`,a);e.out.result(l,()=>e.out.line(TR(l)))}},jy={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:Qe,args:{min:0,max:1},scope:"environment",async run(e){let{t,machine:n}=await Ue(e,e.args[0]),s=n.secrets?(await ea(e,t,Q("the machine's secret set",n.secrets))).map(i=>i.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"]:[]],o=a.map(i=>({name:i,from:"platform",note:s.includes(i)||i in n.env?`in place of the ${i} set by hand`:""}));for(let i of Object.keys(n.env).sort())a.includes(i)||o.push({name:i,from:"machine",note:s.includes(i)?`shadows the secret ${i}`:""});for(let i of s.sort())a.includes(i)||i in n.env||o.push({name:i,from:`secrets (${n.secrets})`,note:""});e.out.result({machine:n.name,env:o},()=>e.out.table(o,[{header:"name",value:i=>i.name},{header:"from",value:i=>i.from},{header:"",value:i=>i.note}]))}};async function Ey(e,t){let{t:n,name:s,machine:a,etag:o}=await Ue(e,e.flags.machine),i={body:a,etag:o};for(let r=1;;r++){r>1&&(i=await et(e.studio,n.env_ref,"GET",`/machines/${Oe(s)}`));let l={...i.body.env},p=t(l);if(r===1){if(i.body.secrets){let d=i.body.secrets,u=await ea(e,n,Q("the machine's secret set",d)).then(g=>g.map(y=>y.name),g=>(e.out.warn(`the ${d} 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 k(e,n,`${p.join(", ")} on the machine ${s}`)}try{let d=await ge(e,n,"PATCH",`/machines/${Oe(s)}`,{env:l},i.etag?{"if-match":i.etag}:void 0);e.out.result({machine:d.name,env:Object.keys(d.env).sort()},()=>e.out.line(`${d.name}: version ${d.version} rolls out with it.`));return}catch(d){if(!(d instanceof G&&d.status===412)||r===3)throw d;e.out.note(`${s} changed meanwhile: making the change again on what it is now\u2026`)}}}var Ty={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:Qe,args:{min:1,max:50},flags:jt,scope:"environment",async run(e){let t=_y(e.args);await Ey(e,n=>(Object.assign(n,t),Object.keys(t).map(s=>`set ${s}`)))}},Cy={name:"machines:env:unset",summary:"take settings away from what a machine of the project is started with",usage:"K\u2026 [--machine <name>]",details:Qe,args:{min:1,max:50},flags:jt,scope:"environment",async run(e){await Ey(e,t=>{for(let n of e.args){if(!(n in t))throw new b("no_such_setting",`the machine is not started with ${n}`);delete t[n]}return e.args.map(n=>`unset ${n}`)})}},Oy={name:"machines:builds",summary:"a machine's builds, newest first",usage:"[name]",details:Qe,args:{min:0,max:1},scope:"environment",async run(e){let{t,name:n}=await Ue(e,e.args[0]),{builds:s}=await ge(e,t,"GET",`/machines/${Oe(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 ${Va(a.reason)}`:""}`},{header:"message",value:a=>a.message.split(`
|
|
56
56
|
`)[0].slice(0,60)},{header:"created",value:a=>a.created_at}]))}},xy={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:Qe,args:{min:0,max:1},scope:"environment",async run(e){let{t,name:n}=await Ue(e,e.args[0]),{previews:s}=await ge(e,t,"GET",`/machines/${Oe(n)}/previews`);e.out.result({previews:s},()=>Zp(e,s,`${n} has no preview: machines:update ${n} --previews previews its pull requests (in a preview environment).`))}},Ly=Xp("machine","machines",Cr,jt),Iy=Yp("machine","machines",Cr,jt),Ny=ed("machine","machines",Cr,jt),My=Qp("machine","machines",Cr,jt),Dy={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).",...Qe],args:{min:1,max:1},flags:jt,scope:"environment",async run(e){let t=Number(e.args[0].replace(/^#/,""));if(!Number.isInteger(t)||t<=0)throw h("the pull request is its number: 12, or #12");let{t:n,name:s}=await Ue(e,e.flags.machine),a=await ge(e,n,"POST",`/machines/${Oe(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}).`))}},zy={name:"machines:builds:log",summary:"a build's log (the newest build's when none is named)",usage:"[build] [--machine <name>]",details:Qe,args:{min:0,max:1},flags:jt,scope:"environment",async run(e){let{t,name:n}=await Ue(e,e.flags.machine),s=e.args[0];if(!s){let{builds:i}=await ge(e,t,"GET",`/machines/${Oe(n)}/builds?limit=1`);if(i.length===0)throw new b("no_build",`${n} has no build yet`);s=i[0].id}let a;try{a=await ge(e,t,"GET",`/machines/${Oe(n)}/builds/${Q("the build's id",s)}/log`)}catch(i){if(!(i instanceof G))throw i;if(i.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(i.code==="no_log"){let r=await ge(e,t,"GET",`/machines/${Oe(n)}/builds/${Q("the build's id",s)}`);throw new b("no_log",`the build ${s} ended before it ran, so it has no log: ${r.state}${r.reason?` \u2014 ${Va(r.reason)}`:""}`)}throw i}let o=typeof a=="string"?a:a==null?"":JSON.stringify(a);e.out.result({build:s,log:o},()=>{if(o==="")e.out.note(`The build ${s} has written no log yet (palbase machines:builds ${n}).`);else for(let i of o.split(`
|
|
57
57
|
`))e.out.line(i)})}},qy={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>.",...Qe],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=ln(e.flags.lines,"lines")??200,a=e.flags.since?IR(e.flags.since,e.io.now()):void 0,o=e.flags.search,i=new Set,r=async p=>{let d=new URLSearchParams({lines:String(s),order:p,...a?{since:a}:{},...o?{q:o}:{}}),u=await ge(e,t,"GET",`/machines/${Oe(n)}/logs?${d}`),g=u!==null&&typeof u=="object"?[u]:String(u??"").split(`
|
|
58
58
|
`).filter(y=>y.trim()!=="").map(y=>JSON.parse(y));return p==="desc"?g.reverse():g},l=p=>{for(let d of p)i.has(d.id)||(i.add(d.id),e.global.json?e.io.stdout(`${JSON.stringify(d)}
|
|
@@ -638,7 +638,7 @@ ${ke}`,he=a===void 0||gt===a;for(let[ne,ke]of T){he&&(ke.has(gt)?(d.set(`${ue}/$
|
|
|
638
638
|
`)),d.set(`${ue}/${ne}.ssr.${xe}.ts`,re(xe,`export * from './environments/${xe}/${ne}.ssr';
|
|
639
639
|
`))}if(he)for(let{machine:ne}of fe.get(gt)??[])d.set(`${ue}/palbe/${ne}.ts`,M(`export * from '../environments/${gt}/palbe/${ne}';
|
|
640
640
|
`));for(let ne of mt)for(let{machine:ke}of fe.get(ne)??[])d.set(`${ue}/palbe/${ke}.${ne}.ts`,re(ne,`export * from '../environments/${ne}/palbe/${ke}';
|
|
641
|
-
`))}let Po={schema:1,project:{id:s.id,name:s.name},apps:p.map(M=>({id:M.id,slug:M.slug,name:M.name,platform:M.platform})),...gt!==void 0&&(mt.length>0||a!==void 0)?{types_environment:gt}:{},...Object.keys(J).length>0?{clients:Object.fromEntries(Object.entries(J).sort(([M],[re])=>M.localeCompare(re)))}:{}};return d.set(`${ue}/project.json`,to(Po)),{files:d,notes:u,project:Po,scopedEnv:a}}async function TT(e,t,n,s=[]){let a=`${ue}/environments/${t}`,o;try{o=await ga(await Be(e,`${a}/contracts/${n}.openapi.json`),"utf8")}catch(d){if(d.code==="ENOENT")return;throw d}let i=`contracts/${n}.openapi.json, sha256 `,r=qb("sha256").update(o).digest("hex"),l=d=>{let u=d.indexOf(i);if(u<0)return;let g=d.indexOf(")",u+i.length);return g>u+i.length?d.slice(u+i.length,g):void 0},p=!1;for(let d of[`${a}/palbe/${n}.ts`,`${a}/palbe/${n}.kt`]){let u=await Be(e,d).then(y=>ga(y,"utf8")).catch(()=>""),g=l(u);if(g!==void 0){r=g,p=!0;break}}if(!p)for(let d of s){let u=await Be(e,`${ue}/${d}.palbase`).then(g=>ga(g,"utf8")).catch(()=>"");if(u)try{let y=JSON.parse(u)?.environments?.[t]?.swift,w=typeof y=="string"?l(y):void 0;if(w!==void 0){r=w;break}}catch{}}return{doc:JSON.parse(o),digest:r}}function CT(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 OT(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 zb(e,t,n,s,a){for(let o of t){let i=e.get(o);if(i!==void 0&&i!==n)throw new b("backends_collide",`${i} and ${n} both declare ${o} 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(o,n)}}async function xT(e){let t=new Map,n=async s=>{let a;try{a=await Ud(cn(e,s),{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}for(let o of a){let i=`${s}/${o.name}`;if(o.isDirectory()){(s!==ue||o.name==="environments"||o.name==="palbe")&&await n(i);continue}if(!o.isFile()||o.name.endsWith(".storekit"))continue;let r=await ga(cn(e,i),"utf8");(s!==ue||o.name==="project.json"||o.name.endsWith(".palbase")||r.startsWith(no))&&t.set(i,r)}};return await n(ue),t}function LT(e,t,n){if(e===`${ue}/project.json`||e.endsWith(".palbase"))return!0;if(e.startsWith(`${ue}/environments/`))return e.startsWith(`${ue}/environments/${t}/`);if(e.startsWith(`${ue}/palbe/`)){let a=e.slice(`${ue}/palbe/`.length);return a.endsWith(`.${t}.ts`)?!0:a.split(".").length===2?n:!1}let s=e.slice(`${ue}/`.length);return s.endsWith(`.${t}.ts`)?!0:s.endsWith(".ssr.ts")||s.split(".").length===2?n:!1}async function sl(e){try{return JSON.parse(await ga(cn(e,ue,"project.json"),"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw new b("unreadable_project_file",`${ue}/project.json is not what palbase apps:sync writes: ${t.message}`)}}async function IT(e,t){let n=`${e}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2,8)}.tmp`;await wT(n,t,{flag:"wx"});try{await fT(n,e)}catch(s){throw await Wd(n,{force:!0}),s}}async function Gb(e){let t=e.io.cwd,n=e.flags.check===!0,s=await sl(t),a=await ET(e,s),o=await xT(t),i=a.scopedEnv!==void 0&&a.project.types_environment===a.scopedEnv,r=a.scopedEnv===void 0?o:new Map([...o].filter(([y])=>LT(y,a.scopedEnv,i))),l=[],p=[],d=[];for(let[y,w]of a.files){let v=r.get(y);v===void 0?l.push(y):v!==w&&p.push(y)}for(let y of r.keys())a.files.has(y)||d.push(y);let u=l.length+p.length+d.length>0;if(!n){for(let y of[...l,...p]){let w=await Be(t,y);await hT(kT(w),{recursive:!0}),await Be(t,y),await IT(w,a.files.get(y))}for(let y of d)await Wd(await Be(t,y));await Kb(t,cn(t,ue))}let g={project:a.project.project.name,apps:a.project.apps.map(y=>y.slug),added:l,changed:p,removed:d,unchanged:a.files.size-l.length-p.length,check:n,differs:u};for(let y of a.notes)e.out.note(y);return e.out.result(g,()=>{let y=(w,v)=>v.forEach(R=>e.out.line(` ${w} ${R}`));if(!u){e.out.line(`${ue}/ is what ${a.project.project.name} gives now (${a.files.size} files)`);return}e.out.line(n?`${ue}/ differs from what ${a.project.project.name} gives now:`:`${ue}/ written for ${a.project.apps.map(w=>w.slug).join(", ")}:`),y(n?"missing":"added",l),y(n?"differs":"changed",p),y(n?"not given":"removed",d),n&&e.out.note("palbase apps:sync brings it up to date")}),n&&u?1:void 0}async function Be(e,t){let n=cn(e,ue),s=cn(e,...t.split("/")),a=tl(n,s);if(a===""||a.startsWith(`..${el}`)||a===".."||a.split(el).some(i=>i===".."||i===""))throw new b("outside_palbase",`${t} is not under ${ue}/`);let o=e;for(let i of[ue,...a.split(el)]){o=cn(o,i);try{if((await gT(o)).isSymbolicLink())throw new b("linked_path",`${tl(e,o)} is a link: palbase writes only into ${ue}/ itself`,{hint:"remove the link, and run it again"})}catch(r){if(r.code==="ENOENT")break;throw r}}return s}async function Kb(e,t){let n;try{n=await Ud(t,{withFileTypes:!0})}catch{return}for(let s of n)s.isDirectory()&&await Kb(e,cn(t,s.name));tl(cn(e,ue),t)===""||tl(cn(e,ue),t).startsWith(`..${el}`)||(await Ud(t)).length===0&&await bT(t)}var gi=["ios","android","web","macos"],mi=e=>e==="ios"||e==="macos";async function ao(e){let t=await Pn(e);return{id:t[0].project_id,name:t[0].project_name,org:t[0].org_name}}async function Vt(e,t){return(await e.studio.get(`/projects/${t}/apps`)).apps}function un(e,t){let n=e.find(s=>s.slug===t||s.id===t);if(!n)throw new b("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 al(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.macos?e.macos.bundle: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 Ub={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 ao(e),n=await Vt(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 ${gi.join("|")} <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}: ${al(a)}`).join("; ")||"\u2014"}])})}},Wb={name:"apps:create",summary:"register an app of the project (an iOS or Mac app names its Apple team); then set it in each environment (apps:env:set)",usage:`${gi.join("|")} <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 or Mac app's Apple team: 10 characters, Apple Developer \u203A Membership"},"app-id-prefix":{type:"string",value:"prefix",description:"an iOS or Mac 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(!gi.includes(t))throw h(`the platform is ${gi.slice(0,-1).join(", ")} or ${gi.at(-1)}`);let s=await ao(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> ${mi(t)?"--bundle <bundle id>":t==="android"?"--package <application id> --sha256 <label>=<fingerprint>":"--origin <https://\u2026>"}`)})}},Fb={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 ao(e),n=un(await Vt(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=>al(s)},{header:"publishable key",value:s=>s.key?.key??"\u2014"}])})}},Bb={name:"apps:update",summary:"rename an app, or change an iOS or Mac 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 or Mac 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 ao(e),n=un(await Vt(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 h("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)`))}},Jb={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 ao(e),n=un(await Vt(e,t.id),e.args[0]);if(!e.global.yes){if(!e.interactive)throw new b("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 b("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}`))}},Hb={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 ao(e),n=un(await Vt(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)`))}},NT=/^([a-z][a-z0-9_-]{0,31})=(.+)$/,Vb={name:"apps:env:set",summary:"what an app is in the environment: its bundle (iOS, Mac), 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.","Mac: the app's bundle in this environment, alone \u2014 a Mac app has no App Clip or watch app. Its extensions and helpers 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 or Mac 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 f(e),n=un(await Vt(e,t.project_id),e.args[0]),s=i=>(e.flags[i]??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean),a;if(n.platform==="ios"){if(!e.flags.bundle)throw h(`${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==="macos"){if(e.flags["app-clip"]||e.flags.watch)throw h(`${n.name} is a Mac app: it has no App Clip or watch app (--app-clip and --watch are an iOS app's)`);if(!e.flags.bundle)throw h(`${n.name} is a Mac app: give its bundle here (--bundle)`);a={macos:{bundle:e.flags.bundle}}}else if(n.platform==="android"){if(!e.flags.package)throw h(`${n.name} is an Android app: give its package here (--package)`);let i=(e.flags.sha256??[]).map(r=>{let l=NT.exec(r.trim());if(!l)throw h(`--sha256 ${JSON.stringify(r)}: label=fingerprint, like play_signing=AB:CD:\u2026`);return{label:l[1],sha256:l[2]}});a={android:{package:e.flags.package,fingerprints:i}}}else{let i=s("origin");if(i.length===0)throw h(`${n.name} is a web app: give its origins here (--origin)`);let r=s("redirect");a={web:{origins:i,...r.length?{redirects:r}:{}}}}await k(e,t,`set ${n.name} (${n.slug}) here: ${al(a)}`);let o=await e.studio.request("PUT",`/environments/${t.env_ref}/apps/${n.id}`,a);for(let i of o.warnings)e.out.warn(i);e.out.result(o,()=>{e.out.line(`${n.name} in ${t.env_name}: ${al(o)}`),o.key&&e.out.line(`its publishable key here: ${o.key.key}`),e.out.note("palbase apps:sync writes its settings into this checkout")})}},Xb={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 f(e),n=un(await Vt(e,t.project_id),e.args[0]);await k(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}`))}},Yb={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 f(e),n=un(await Vt(e,t.project_id),e.args[0]),s=e.flags.format??"json";if(s!=="json"&&s!=="env")throw h("--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))})}},Zb={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>] [--remove <app>]\u2026 [--backend [<machine>=]<dir> [--entry <file>]] [--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. --remove unlinks an app from palbase/project.json and removes its generated files.","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 or Mac app (in palbase/<app>.palbase), Kotlin for an Android app. A web app imports pb from palbase/<app>.ts (or createBrowser / createServer from palbase/<app>.ssr.ts for Next.js / SSR): 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. With an environment token (pbe_\u2026), only that environment's files are synced or checked; other environments stay untouched.","--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. It applies to one environment (-E, or the active/types non-production environment) and never overwrites production unless -E main is passed.","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)"},remove:{type:"string",multiple:!0,value:"app",description:"unlink an app (slug or id) from palbase/project.json and remove its generated files"},backend:{type:"string",value:"[machine=]dir",description:"a backend's checkout here: its Palbe made from the contract it writes for one environment (-E or non-production), never overwriting production unasked"},entry:{type:"string",value:"file",description:"with --backend, the backend's entry file (default src/main.ts)"},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 Gb(e)}};function ol(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 il(e,t){let n=we(e.flags.limit,"limit");if(n!==void 0&&(n<1||n>t))throw h(`--limit is a whole number from 1 to ${t}`);return n}function rl(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 ps=e=>e?e.slice(0,19).replace("T"," "):"",ha=(e,t)=>e||t;function ll(e,t,n){t&&e.out.line(`More: palbase ${n} --cursor ${t}`)}function ew(e){e.out.note("This read is in the project's access log (palbase messaging:access-log).")}function tw(e){return e.map(t=>`${t.name?I(t.name):"a file"} (${I(t.content_type)}, ${t.size} bytes)`).join(", ")}var Qb="A report is deleted, with what it carries, 190 days after it is resolved; one never resolved, 2 years after it was made.",MT={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"},...rl(100,30)},scope:"environment",async run(e){let t=e.flags.status;if(t!==void 0&&t!=="open"&&t!=="resolved")throw h("--status is open or resolved");let n=il(e,100),s=await f(e),a=await m(e,s,"GET",`/messaging/admin/reports${ol({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:o=>o.id},{header:"made",value:o=>ps(o.created_at)},{header:"status",value:o=>o.status==="resolved"?`resolved: ${o.resolution??""}`:"open"},{header:"reason",value:o=>o.reason},{header:"reported",value:o=>ha(o.reported_user_id,"")},{header:"by",value:o=>ha(o.reporter_id,"(deleted)")},{header:"messages",value:o=>String(o.message_ids.length)}]),ll(e,a.next_cursor,`messaging:reports:list${t?` --status ${t}`:""}`)})}},DT={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.",Qb],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",`/messaging/admin/reports/${Q("the report's id",e.args[0])}`);ew(e),e.out.note(Qb),e.out.result(n,()=>{e.out.line(`report ${n.id} (${n.status==="resolved"?`resolved ${ps(n.resolved_at)}: ${I(n.resolution??"")}`:"open"})`),e.out.line(`made ${ps(n.created_at)} by ${ha(n.reporter_id,"a user since deleted")}`),e.out.line(`reported ${ha(n.reported_user_id,"no one in particular")}`),e.out.line(`reason ${I(n.reason)}`),e.out.line(`conversation ${n.conversation_id}${n.conversation_deleted_at?` (group deleted by ${ha(n.conversation_deleted_by,"a user since deleted")} at ${ps(n.conversation_deleted_at)})`:""}`),n.note&&e.out.line(`note ${I(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} ${ps(a.created_at)} ${ha(a.sender_id,"the server")} ${a.kind==="text"||a.text?I(a.text??""):`(${a.kind})`}`),a.attachments.length>0&&e.out.line(` files: ${tw(a.attachments)}`);for(let o of a.earlier_versions)e.out.line(` before it was edited: ${I(o.text)}, until ${ps(o.replaced_at)}`)}}})}},zT={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 h("--resolution says what came of it: 1 to 64 characters");let n=await f(e),s=Q("the report's id",e.args[0]);await k(e,n,`resolve the report ${e.args[0]}: ${t}`);let a=await m(e,n,"POST",`/messaging/admin/reports/${s}/resolve`,{resolution:t});e.out.result(a,()=>e.out.line(`Resolved the report ${a.id}: ${I(a.resolution??t)}.`))}},qT={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:rl(200,50),scope:"environment",async run(e){let t=il(e,200),n=await f(e),s=await m(e,n,"GET",`/messaging/admin/access-log${ol({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=>ps(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??""}]),ll(e,s.next_cursor,"messaging:access-log")})}},GT={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>)"},...rl(100,30)},scope:"environment",async run(e){let t=e.flags.user;if(t!==void 0&&t.trim()==="")throw h("--user is a person's id");let n=e.flags.space;if(n!==void 0&&!/^[A-Za-z0-9:_./@-]{1,128}$/.test(n))throw h("--space is 1 to 128 letters, digits and : _ . / @ - (as org:<id>)");let s=il(e,100),a=await f(e),o=await m(e,a,"GET",`/messaging/admin/conversations${ol({user_id:t,space:n,limit:s,cursor:e.flags.cursor})}`);e.out.result(o,()=>{o.data.length===0&&e.out.line(t===void 0?"No conversation yet.":`${t} is in no conversation.`),e.out.table(o.data,[{header:"conversation",value:i=>i.id},{header:"kind",value:i=>i.kind==="group"&&i.visibility==="open"?"group (open)":i.kind},{header:"space",value:i=>i.space??""},{header:"title",value:i=>i.kind==="group"?i.title??"":(i.members??[]).map(r=>r.user_id).join(" \xB7 ")},{header:"people",value:i=>String(i.member_count)},{header:"messages",value:i=>String(i.last_seq)},{header:"last moved",value:i=>ps(i.last_message_at??i.created_at)}]),ll(e,o.next_cursor,`messaging:conversations:list${t!==void 0?` --user ${t}`:""}${n!==void 0?` --space ${n}`:""}`)})}},KT={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:rl(100,50),scope:"environment",async run(e){let t=il(e,100),n=await f(e),s=Q("the conversation's id",e.args[0]),a=await m(e,n,"GET",`/messaging/admin/conversations/${s}/messages${ol({limit:t,cursor:e.flags.cursor})}`);ew(e),e.out.result(a,()=>{a.data.length===0&&e.out.line("The conversation has said nothing yet.");for(let o of a.data){let i=o.deleted?`(removed${o.removed_reason?`: ${o.removed_reason}`:""})`:o.kind==="system"?`(${o.system?.type??"system"})`:o.text!==null?I(o.text):`(${o.kind})`;e.out.line(`#${o.seq} ${ps(o.created_at)} ${ha(o.sender_id,"the server")} ${o.id} ${i}`),!o.deleted&&o.attachments.length>0&&e.out.line(` files: ${tw(o.attachments)}`)}ll(e,a.next_cursor,`messaging:messages:list ${e.args[0]}`)})}},UT={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=Q("the conversation's id",t),a=Q("the message's id",n),o=await f(e);await k(e,o,`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 m(e,o,"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 ${ee(o)}; the removal is in the access log.`))}},nw=[MT,DT,zT,qT,GT,KT,UT];function WT(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 FT(e,t){let n=we(e.flags.limit,"limit");if(n!==void 0&&(n<1||n>t))throw h(`--limit is a whole number from 1 to ${t}`);return n}function BT(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 pl=e=>e?e.slice(0,19).replace("T"," "):"";function JT(e,t,n){t&&e.out.line(`More: palbase ${n} --cursor ${t}`)}function Fd(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 sw=e=>e.video?"video":"voice";function HT(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 VT=["ringing","active","ended"],XT={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)"},...BT(100,20)},scope:"environment",async run(e){let t=e.flags.user;if(t!==void 0&&t.trim()==="")throw h("--user is a person's id");let n=e.flags.missed===!0;if(n&&t===void 0)throw h("--missed says whose: give --user with it");let s=e.flags.state;if(s!==void 0&&!VT.includes(s))throw h("--state is ringing, active or ended");let a=FT(e,100),o=await f(e),i=await m(e,o,"GET",`/calls/admin/calls${WT({user_id:t,missed:n?"true":void 0,state:s,limit:a,cursor:e.flags.cursor})}`);e.out.result(i,()=>{i.calls.length===0&&e.out.line(`No ${n?"missed ":""}${s?`${s} `:""}call${t!==void 0?` of ${t}`:n||s?"":" yet"}.`),e.out.table(i.calls,[{header:"call",value:l=>l.id},{header:"started",value:l=>pl(l.created_at)},{header:"kind",value:l=>l.kind},{header:"media",value:sw},{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:Fd}]);let r=[t!==void 0?` --user ${t}`:"",n?" --missed":"",s?` --state ${s}`:""].join("");JT(e,i.next_cursor,`calls:list${r}`)})}},YT={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 f(e),n=await m(e,t,"GET",`/calls/admin/calls/${Q("the call's id",e.args[0])}`);e.out.result(n,()=>{e.out.line(`call ${n.id}`),e.out.line(`kind ${n.kind}, ${sw(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 ${pl(n.created_at)}`),n.answered_at&&e.out.line(`answered ${pl(n.answered_at)}`),n.ended_at&&e.out.line(`ended ${pl(n.ended_at)}${Fd(n)?`, after ${Fd(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=>HT(s.bytes)}])})}},ZT={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=Q("the call's id",e.args[0]),n=await f(e);await k(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 m(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 ${ee(n)}.`))}},aw=[XT,YT,ZT];var QT=/^[A-Z][A-Z0-9_]{0,127}$/;function Ls(e,t){return`/environments/${Q("the environment's ref",e.env_ref)}/webhooks${t!==void 0?`/${Q("the webhook's id",t)}`:""}`}function ow(e){return Me(e.flags.events)}function dl(e){let t=e.machine?`, the machine ${I(e.machine)}'s \u2014 kept by the platform to what its app takes`:"",n=e.created_by?`, made by ${I(e.created_by.name)}${e.created_by.id.startsWith("tok_")?" (access token)":e.created_by.id.startsWith("etk_")?" (environment token)":""}`:"";return`${I(e.url)} \u2014 ${e.events.length===0?"every event":I(e.events.join(", "))} (${I(e.id)}${t}${n})`}function eC(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 ${I(e.redelivered_at)}`:e.redeliver_asked_at?"; redelivery asked":e.redelivery_error?`; redelivery failed: ${I(e.redelivery_error)}`:"";return`${I(e.id)} ${I(e.event_type)} ${I(e.event_id)} \u2192 ${I(n)} \u2014 ${I(e.last_error)} (${I(String(e.attempts))} tries, given up ${I(e.failed_at)})${s}`}var tC={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 f(e),{endpoints:n}=await e.studio.get(Ls(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(dl(s))})}},nC={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 f(e),n=e.flags["secret-to"];if(n!==void 0&&!QT.test(n))throw h(`--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 h("--dev goes with --secret-to <NAME>");let s=e.flags.dev===!0?"development":"production";await k(e,t,`add the webhook endpoint ${e.args[0]}${n?`, its secret kept in ${n} (${s})`:""}`);let a=await e.studio.post(Ls(t),{url:e.args[0],events:ow(e)??[]}),{secret:o,...i}=a;if(n!==void 0){let r=await m(e,t,"PUT",`/secrets/${s}/${n}`,{value:o});e.out.result({endpoint:i,secret_to:{set:s,name:n,version:r.version}},()=>e.out.line(`Added ${dl(i)}; its secret is ${n} (${s}, v${r.version}) in ${ee(t)}.`));return}e.out.result(a,()=>{e.out.line(`Added ${dl(i)}.`),e.out.line(`signing secret (shown this once): ${o}`)})}},sC={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 f(e);if(e.flags.url===void 0&&e.flags.events===void 0)throw h("nothing to change: --url or --events");let{endpoints:n}=await e.studio.get(Ls(t)),s=n.find(o=>o.id===e.args[0]);if(!s)throw h(`the environment has no webhook endpoint ${JSON.stringify(e.args[0])}`,"palbase webhooks:list shows them");await k(e,t,`change the webhook endpoint ${s.url}`);let a=await e.studio.request("PUT",Ls(t,s.id),{url:e.flags.url??s.url,events:ow(e)??s.events});e.out.result(a,()=>e.out.line(`Changed: ${dl(a)}.`))}},aC={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 f(e);await k(e,t,`remove the webhook endpoint ${e.args[0]}`),await e.studio.request("DELETE",Ls(t,e.args[0])),e.out.result({deleted:e.args[0]},()=>e.out.line(`Removed the webhook endpoint ${e.args[0]}.`))}},oC={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 f(e),[{deliveries:n},{endpoints:s}]=await Promise.all([e.studio.get(`${Ls(t)}/deliveries${e.flags.all===!0?"?all=true":"?failed=true"}`),e.studio.get(Ls(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(eC(a,s))})}},iC={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 f(e);await k(e,t,`send the failed delivery ${e.args[0]} again`);let n=await e.studio.post(`${Ls(t)}/deliveries/${Q("the delivery's id",e.args[0])}/redeliver`,{});e.out.result(n,()=>e.out.line(`Asked: ${I(n.event_type)} ${I(n.event_id)} goes to its endpoint again within seconds (palbase webhooks:deliveries:list --all shows when it went).`))}},iw=[tC,nC,sC,aC,oC,iC];import{constants as cl,createReadStream as rC}from"node:fs";import{mkdir as lC,open as pC,readdir as dC,realpath as rw,stat as cw}from"node:fs/promises";import{dirname as lw,extname as cC,join as uw,relative as uC,resolve as pw,sep as ul}from"node:path";import{Readable as mw}from"node:stream";import{pipeline as mC}from"node:stream/promises";var gw=600;function hi(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 ml(e){if(e.split("/").some(n=>n===""||n==="."||n===".."))throw new b("unsafe_path",`the object ${JSON.stringify(e)} has a name no request can carry`);return encodeURIComponent(e)}async function Bd(e,t,n,s){let a=[],o;do{let i=new URLSearchParams({limit:"1000",...s?{prefix:s}:{},...o?{cursor:o}:{}}),r=await m(e,t,"GET",`/storage/buckets/${Q("the bucket",n)}/objects?${i}`);a.push(...r.objects),o=r.next_cursor}while(o);return a}async function hw(e,t,n,s){let a;try{a=await e.io.fetch(t,{...n,redirect:"manual"})}catch(o){throw new b("network_error",`${s}: ${o instanceof Error?o.message:String(o)}`)}if(!a.ok){let o=await a.json().catch(()=>({}));throw new b(o.error??`http_${a.status}`,`${s}: ${o.error_description??o.error??`answered ${a.status}`}`)}return a}var gC={".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 dw(e){return gC[cC(e).toLowerCase()]}async function Jd(e,t,n,s,a,o){let i=(await cw(n)).size,r=await m(e,t,"POST",`/storage/buckets/${Q("the bucket",s)}/upload-urls`,{path:a,expires_in:gw,...o?{owner_id:o}:{}});return await hw(e,r.url,{method:"PUT",body:mw.toWeb(rC(n)),headers:{"content-length":String(i),...dw(n)?{"content-type":dw(n)}:{}},duplex:"half"},`${n} \u2192 ${s}:${a}`),i}function hC(e,t){let n=t.split("/");if(t===""||n.some(a=>a===""||a==="."||a===".."||a.includes("\\")||a.includes("\0")))throw new b("unsafe_path",`the object ${JSON.stringify(t)} has a name no file here can take`);let s=uw(e,...n);if(!s.startsWith(e+ul))throw new b("unsafe_path",`${t} would land outside ${e}`);return s}async function yC(e,t,n,s,a,o){let i=await m(e,t,"POST",`/storage/buckets/${Q("the bucket",n)}/signed-urls`,{path:s,expires_in:gw}),r=await hw(e,i.url,{method:"GET"},`${n}:${s} \u2192 ${a}`);if(await lC(lw(a),{recursive:!0}),o!==void 0){let[g,y]=await Promise.all([rw(o),rw(lw(a))]);if(y!==g&&!y.startsWith(g+ul))throw new b("unsafe_path",`${s} would land outside ${o} (through a link)`)}let p=(await pC(a,cl.O_WRONLY|cl.O_CREAT|cl.O_TRUNC|cl.O_NOFOLLOW)).createWriteStream();if(!r.body)return await new Promise((g,y)=>p.on("error",y).end(g)),0;let d=0,u=mw.fromWeb(r.body).on("data",g=>{d+=g.length});return await mC(u,p),d}async function yw(e){let t=[];for(let n of await dC(e,{withFileTypes:!0})){let s=uw(e,n.name);n.isDirectory()?t.push(...await yw(s)):n.isFile()&&t.push(s)}return t}var fC={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 f(e),n=hi(e.args[0].includes(":")?e.args[0]:`${e.args[0]}:`);if(!n)throw h(`${e.args[0]} is not a bucket (bucket or bucket:prefix)`);let s=await Bd(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??""}`)})}},bC={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 f(e),[n,s]=e.args,a=hi(n),o=hi(s),i=e.flags.recursive===!0,r=e.flags.owner;if(a&&o)throw h("one side is a bucket and the other this computer (bucket-to-bucket: the storage API copies within a bucket)");if(!a&&!o)throw h("one side is bucket:path");let l=0,p=0;if(o){let d=pw(e.io.cwd,n),u=i?await yw(d):[d];if(!i&&(await cw(d)).isDirectory())throw h(`${n} is a folder: copy it with -r`);await k(e,t,`upload ${u.length} file${u.length===1?"":"s"} to ${o.bucket}:${o.path} in ${ee(t)}`);for(let g of u){let y=i?uC(d,g).split(ul).join("/"):g.split(ul).pop(),w=i||o.path===""||o.path.endsWith("/")?`${o.path.replace(/\/?$/,o.path?"/":"")}${y}`:o.path;p+=await Jd(e,t,g,o.bucket,w,r),l++,u.length>1&&e.out.note(`${l}/${u.length} ${w}`)}}else if(a){let d=pw(e.io.cwd,s),u=i?await Bd(e,t,a.bucket,a.path):[{path:a.path,size:0}];for(let g of u){let y=i?g.path.slice(a.path.length).replace(/^\/+/,""):"",w=i?hC(d,y):d;p+=await yC(e,t,a.bucket,g.path,w,i?d:void 0),l++,u.length>1&&e.out.note(`${l}/${u.length} ${g.path}`)}}e.out.result({copied:l,bytes:p},()=>e.out.line(`Copied ${l} file${l===1?"":"s"} (${p} bytes).`))}},wC={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 f(e),n=hi(e.args[0]);if(!n||!n.path&&e.flags.recursive!==!0)throw h(`${e.args[0]} is not bucket:path`);let s=e.flags.recursive===!0?(await Bd(e,t,n.bucket,n.path)).map(a=>a.path):[n.path];await k(e,t,`delete ${s.length} object${s.length===1?"":"s"} from ${n.bucket} in ${ee(t)}`);for(let a of s)await m(e,t,"DELETE",`/storage/buckets/${Q("the bucket",n.bucket)}/objects/${ml(a)}`);e.out.result({deleted:s.length},()=>e.out.line(`Deleted ${s.length} object${s.length===1?"":"s"}.`))}},vC={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 f(e),n=hi(e.args[0]);if(!n||!n.path)throw h(`${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 h("--expires is 1 to 604800 seconds");let a=await m(e,t,"POST",`/storage/buckets/${Q("the bucket",n.bucket)}/signed-urls`,{path:n.path,expires_in:s});e.out.result(a,()=>e.out.line(a.url))}},fw=[fC,bC,wC,vC];function bw(e){if(e<1024)return`${e} B`;let t=["KiB","MiB","GiB","TiB"],n=e/1024,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;return`${n>=100?Math.round(n):Math.round(n*10)/10} ${t[s]}`}var gl=e=>e?e.slice(0,19).replace("T"," "):"",Hd={endpoint:{type:"string",value:"https-url",description:"S3-compatible HTTPS endpoint (e.g. https://<account>.r2.cloudflarestorage.com)"},bucket:{type:"string",value:"bucket",description:"S3 bucket name"},region:{type:"string",value:"region",description:"S3 region (default: auto)"},prefix:{type:"string",value:"prefix",description:"optional object key prefix inside the bucket"},"access-key-id":{type:"string",value:"key-id",description:"S3 access key ID (secret access key is read from stdin)"},"presign-endpoint":{type:"string",value:"https-url",description:"optional public HTTPS endpoint used for presigned transfer URLs"},"virtual-host":{type:"boolean",description:"use virtual-hosted-style bucket URLs instead of path-style"}};async function Vd(e){let t=e.flags.endpoint,n=e.flags.bucket,s=e.flags["access-key-id"];if(!t||!n||!s)throw h("BYOS requires --endpoint, --bucket and --access-key-id (with the secret access key piped on stdin)");let a=await lt(e,"the BYOS S3 secret access key"),o=e.flags.region,i=e.flags.prefix,r=e.flags["presign-endpoint"];return{kind:"byos",endpoint:t,bucket:n,access_key_id:s,secret_access_key:a,...o?{region:o}:{},...i?{prefix:i}:{},...r?{presign_endpoint:r}:{},force_path_style:e.flags["virtual-host"]!==!0}}var kC={name:"workspaces:list",summary:"the environment's synchronized workspaces: name, id, storage, seq, files, size",usage:"",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/workspaces");e.out.result(n,()=>{if(n.workspaces.length===0){e.out.line(`No workspaces in ${ee(t)} yet. Create one with: palbase workspaces:create <name>`);return}e.out.table(n.workspaces,[{header:"name",value:s=>s.name},{header:"id",value:s=>s.id},{header:"storage",value:s=>s.storage_kind==="byos"&&s.storage?.bucket?`byos (${s.storage.bucket})`:s.storage_kind},{header:"seq",value:s=>String(s.seq)},{header:"files",value:s=>String(s.total_files)},{header:"size",value:s=>bw(s.total_bytes)},{header:"updated",value:s=>gl(s.updated_at)}])})}},_C={name:"workspaces:get",summary:"one workspace: storage configuration, head revision, file count and byte size",usage:"<id-or-name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Q("workspace",e.args[0]),s=await m(e,t,"GET",`/workspaces/${n}`);e.out.result(s,()=>{e.out.line(`id ${s.id}`),e.out.line(`name ${s.name}`),e.out.line(`storage ${s.storage_kind}`),s.storage_kind==="byos"&&s.storage&&(s.storage.endpoint&&e.out.line(`endpoint ${s.storage.endpoint}`),s.storage.bucket&&e.out.line(`bucket ${s.storage.bucket}${s.storage.prefix?`/${s.storage.prefix}`:""}`),s.storage.region&&e.out.line(`region ${s.storage.region}`),s.storage.access_key_preview&&e.out.line(`access key ${s.storage.access_key_preview}`)),e.out.line(`seq ${s.seq}`),e.out.line(`files ${s.total_files} (${bw(s.total_bytes)})`),e.out.line(`updated ${gl(s.updated_at)}`)})}},SC={name:"workspaces:create",summary:"create a workspace on Palbase managed R2, or on your own S3 bucket with --byos",usage:"[name] [--byos --endpoint <url> --bucket <name> --access-key-id <key>]",details:["Without --byos, the workspace stores blobs in Palbase managed Cloudflare R2.",'With --byos, pipe the S3 secret access key on stdin (never passed as a flag): printf "%s" "$SECRET" | palbase workspaces:create app-ios --byos --endpoint https://\u2026 --bucket my-bucket --access-key-id AKIA\u2026'],args:{min:0,max:1},flags:{byos:{type:"boolean",description:"back this workspace with your own S3-compatible bucket (secret read from stdin)"},...Hd},scope:"environment",async run(e){let t=await f(e),n=e.args[0],s={};n&&(s.name=n),e.flags.byos===!0&&(s.storage=await Vd(e));let a=await m(e,t,"POST","/workspaces",s);e.out.result(a,()=>{e.out.line(`Created workspace ${a.name} (${a.id}, ${a.storage_kind}) in ${ee(t)}.`)})}},$C={name:"workspaces:delete",summary:"delete a workspace (refused if attached unless --force is passed)",usage:"<id-or-name> [--force]",args:{min:1,max:1},flags:{force:{type:"boolean",description:"delete even when attached resources still reference this workspace"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0],s=Q("workspace",n),a=e.flags.force===!0;await k(e,t,`delete workspace ${n}${a?" (forced)":""} in ${ee(t)}`,"All workspace history, files and tokens are deleted and cannot be recovered"),await m(e,t,"DELETE",`/workspaces/${s}${a?"?force=true":""}`),e.out.result({deleted:n,force:a},()=>e.out.line(`Deleted workspace ${n} in ${ee(t)}.`))}},AC={name:"workspaces:storage:set",summary:"rotate BYOS S3 credentials or update BYOS endpoint settings on a BYOS workspace",usage:"<id-or-name> --endpoint <url> --bucket <name> --access-key-id <key>",details:["Pipe the new S3 secret access key on stdin. The bucket is probed before saving."],args:{min:1,max:1},flags:Hd,scope:"environment",async run(e){let t=await f(e),n=Q("workspace",e.args[0]),s=await Vd(e),a=await m(e,t,"PUT",`/workspaces/${n}/storage`,s);e.out.result(a,()=>{e.out.line(`Updated BYOS storage for ${a.name} (${a.id}, key ${a.storage?.access_key_preview??"updated"}).`)})}},PC={name:"workspaces:byos:test",summary:"test a BYOS S3 bucket connection (SSRF check + live write/head/delete/presign probe)",usage:"--endpoint <url> --bucket <name> --access-key-id <key>",details:["Pipe the S3 secret access key on stdin; nothing is persisted."],flags:Hd,scope:"environment",async run(e){let t=await f(e),n=await Vd(e),s=await m(e,t,"POST","/workspaces/byos/test",n);e.out.result(s,()=>{e.out.line(`BYOS connection OK (${s.latency_ms} ms).`)})}},RC={name:"workspaces:tokens:list",summary:"a workspace's sync tokens and workspace-scoped S3 keys",usage:"<id-or-name> [--kind sync|s3]",args:{min:1,max:1},flags:{kind:{type:"string",value:"sync|s3",description:"filter by token kind"}},scope:"environment",async run(e){let t=await f(e),n=Q("workspace",e.args[0]),s=e.flags.kind;if(s!==void 0&&s!=="sync"&&s!=="s3")throw h("--kind is sync or s3");let a=s?`?kind=${s}`:"",o=await m(e,t,"GET",`/workspaces/${n}/tokens${a}`);e.out.result(o,()=>{if(o.tokens.length===0){e.out.line(`No tokens on ${e.args[0]}.`);return}e.out.table(o.tokens,[{header:"id",value:i=>i.id},{header:"kind",value:i=>i.kind},{header:"access",value:i=>i.access},{header:"label",value:i=>i.label??""},{header:"key id",value:i=>i.access_key_id??""},{header:"expires",value:i=>i.expires_at?gl(i.expires_at):"never"}])})}},jC={name:"workspaces:tokens:create",summary:"mint a workspace sync token (pwt_\u2026) or workspace-scoped S3 key pair (shown once)",usage:"<id-or-name> [--kind sync|s3] [--access rw|ro] [--label <text>] [--ttl <seconds>]",args:{min:1,max:1},flags:{kind:{type:"string",value:"sync|s3",description:"sync (default) or s3"},access:{type:"string",value:"rw|ro",description:"rw (default) or ro"},label:{type:"string",value:"text",description:"optional human label (e.g. mac-builder)"},ttl:{type:"string",value:"seconds",description:"time-to-live in seconds"}},scope:"environment",async run(e){let t=await f(e),n=Q("workspace",e.args[0]),s=e.flags.kind??"sync";if(s!=="sync"&&s!=="s3")throw h("--kind is sync or s3");let a=e.flags.access??"rw";if(a!=="rw"&&a!=="ro")throw h("--access is rw or ro");let o=we(e.flags.ttl,"ttl"),i=e.flags.label,r=await m(e,t,"POST",`/workspaces/${n}/tokens`,{kind:s,access:a,...i?{label:i}:{},...o!==void 0?{ttl_seconds:o}:{}});e.out.result(r,()=>{e.out.line(`id ${r.id}`),e.out.line(`kind ${r.kind} (${r.access})`),r.token&&(e.out.line(`token ${r.token}`),r.sync_url&&e.out.line(`sync ${r.sync_url}`)),r.access_key_id&&(e.out.line(`key id ${r.access_key_id}`),e.out.line(`secret ${r.secret_access_key??""}`),r.endpoint&&e.out.line(`s3 ${r.endpoint}/${r.bucket??e.args[0]}`)),e.out.line("Shown once \u2014 save it now.")})}},EC={name:"workspaces:tokens:revoke",summary:"revoke a workspace sync token or workspace-scoped S3 key immediately",usage:"<id-or-name> <token-id>",args:{min:2,max:2},scope:"environment",async run(e){let t=await f(e),n=Q("workspace",e.args[0]),s=Q("token",e.args[1]);await m(e,t,"DELETE",`/workspaces/${n}/tokens/${s}`),e.out.result({revoked:e.args[1]},()=>e.out.line(`Revoked token ${e.args[1]}.`))}},TC={name:"workspaces:s3-keys:list",summary:"list project-wide S3 access keys spanning all workspaces in the environment",usage:"",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/workspaces/s3-keys");e.out.result(n,()=>{if(n.keys.length===0){e.out.line(`No project-wide workspace S3 keys in ${ee(t)}.`);return}e.out.table(n.keys,[{header:"id",value:s=>s.id},{header:"key id",value:s=>s.access_key_id??""},{header:"access",value:s=>s.access},{header:"label",value:s=>s.label??""},{header:"expires",value:s=>s.expires_at?gl(s.expires_at):"never"}])})}},CC={name:"workspaces:s3-keys:create",summary:"mint a project-wide S3 access key pair spanning every workspace in the environment (shown once)",usage:"[--access rw|ro] [--label <text>] [--ttl <seconds>]",flags:{access:{type:"string",value:"rw|ro",description:"rw (default) or ro"},label:{type:"string",value:"text",description:"optional human label (e.g. ci-rclone)"},ttl:{type:"string",value:"seconds",description:"optional time-to-live in seconds"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.access??"rw";if(n!=="rw"&&n!=="ro")throw h("--access is rw or ro");let s=we(e.flags.ttl,"ttl"),a=e.flags.label,o=await m(e,t,"POST","/workspaces/s3-keys",{access:n,...a?{label:a}:{},...s!==void 0?{ttl_seconds:s}:{}});e.out.result(o,()=>{e.out.line(`id ${o.id}`),e.out.line(`access ${o.access}`),e.out.line(`key id ${o.access_key_id??""}`),e.out.line(`secret ${o.secret_access_key??""}`),o.endpoint&&e.out.line(`endpoint ${o.endpoint}`),e.out.line("Shown once \u2014 save it now.")})}},OC={name:"workspaces:s3-keys:revoke",summary:"revoke a project-wide workspace S3 key immediately",usage:"<key-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Q("key",e.args[0]);await m(e,t,"DELETE",`/workspaces/s3-keys/${n}`),e.out.result({revoked:e.args[0]},()=>e.out.line(`Revoked S3 key ${e.args[0]}.`))}},ww=[kC,_C,SC,$C,AC,PC,RC,jC,EC,TC,CC,OC];import{readFile as MC}from"node:fs/promises";import{resolve as DC}from"node:path";var vw=`ac
|
|
641
|
+
`))}let Po={schema:1,project:{id:s.id,name:s.name},apps:p.map(M=>({id:M.id,slug:M.slug,name:M.name,platform:M.platform})),...gt!==void 0&&(mt.length>0||a!==void 0)?{types_environment:gt}:{},...Object.keys(J).length>0?{clients:Object.fromEntries(Object.entries(J).sort(([M],[re])=>M.localeCompare(re)))}:{}};return d.set(`${ue}/project.json`,to(Po)),{files:d,notes:u,project:Po,scopedEnv:a}}async function TT(e,t,n,s=[]){let a=`${ue}/environments/${t}`,o;try{o=await ga(await Be(e,`${a}/contracts/${n}.openapi.json`),"utf8")}catch(d){if(d.code==="ENOENT")return;throw d}let i=`contracts/${n}.openapi.json, sha256 `,r=qb("sha256").update(o).digest("hex"),l=d=>{let u=d.indexOf(i);if(u<0)return;let g=d.indexOf(")",u+i.length);return g>u+i.length?d.slice(u+i.length,g):void 0},p=!1;for(let d of[`${a}/palbe/${n}.ts`,`${a}/palbe/${n}.kt`]){let u=await Be(e,d).then(y=>ga(y,"utf8")).catch(()=>""),g=l(u);if(g!==void 0){r=g,p=!0;break}}if(!p)for(let d of s){let u=await Be(e,`${ue}/${d}.palbase`).then(g=>ga(g,"utf8")).catch(()=>"");if(u)try{let y=JSON.parse(u)?.environments?.[t]?.swift,w=typeof y=="string"?l(y):void 0;if(w!==void 0){r=w;break}}catch{}}return{doc:JSON.parse(o),digest:r}}function CT(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 OT(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 zb(e,t,n,s,a){for(let o of t){let i=e.get(o);if(i!==void 0&&i!==n)throw new b("backends_collide",`${i} and ${n} both declare ${o} 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(o,n)}}async function xT(e){let t=new Map,n=async s=>{let a;try{a=await Ud(cn(e,s),{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}for(let o of a){let i=`${s}/${o.name}`;if(o.isDirectory()){(s!==ue||o.name==="environments"||o.name==="palbe")&&await n(i);continue}if(!o.isFile()||o.name.endsWith(".storekit"))continue;let r=await ga(cn(e,i),"utf8");(s!==ue||o.name==="project.json"||o.name.endsWith(".palbase")||r.startsWith(no))&&t.set(i,r)}};return await n(ue),t}function LT(e,t,n){if(e===`${ue}/project.json`||e.endsWith(".palbase"))return!0;if(e.startsWith(`${ue}/environments/`))return e.startsWith(`${ue}/environments/${t}/`);if(e.startsWith(`${ue}/palbe/`)){let a=e.slice(`${ue}/palbe/`.length);return a.endsWith(`.${t}.ts`)?!0:a.split(".").length===2?n:!1}let s=e.slice(`${ue}/`.length);return s.endsWith(`.${t}.ts`)?!0:s.endsWith(".ssr.ts")||s.split(".").length===2?n:!1}async function sl(e){try{return JSON.parse(await ga(cn(e,ue,"project.json"),"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw new b("unreadable_project_file",`${ue}/project.json is not what palbase apps:sync writes: ${t.message}`)}}async function IT(e,t){let n=`${e}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2,8)}.tmp`;await wT(n,t,{flag:"wx"});try{await fT(n,e)}catch(s){throw await Wd(n,{force:!0}),s}}async function Gb(e){let t=e.io.cwd,n=e.flags.check===!0,s=await sl(t),a=await ET(e,s),o=await xT(t),i=a.scopedEnv!==void 0&&a.project.types_environment===a.scopedEnv,r=a.scopedEnv===void 0?o:new Map([...o].filter(([y])=>LT(y,a.scopedEnv,i))),l=[],p=[],d=[];for(let[y,w]of a.files){let v=r.get(y);v===void 0?l.push(y):v!==w&&p.push(y)}for(let y of r.keys())a.files.has(y)||d.push(y);let u=l.length+p.length+d.length>0;if(!n){for(let y of[...l,...p]){let w=await Be(t,y);await hT(kT(w),{recursive:!0}),await Be(t,y),await IT(w,a.files.get(y))}for(let y of d)await Wd(await Be(t,y));await Kb(t,cn(t,ue))}let g={project:a.project.project.name,apps:a.project.apps.map(y=>y.slug),added:l,changed:p,removed:d,unchanged:a.files.size-l.length-p.length,check:n,differs:u};for(let y of a.notes)e.out.note(y);return e.out.result(g,()=>{let y=(w,v)=>v.forEach(R=>e.out.line(` ${w} ${R}`));if(!u){e.out.line(`${ue}/ is what ${a.project.project.name} gives now (${a.files.size} files)`);return}e.out.line(n?`${ue}/ differs from what ${a.project.project.name} gives now:`:`${ue}/ written for ${a.project.apps.map(w=>w.slug).join(", ")}:`),y(n?"missing":"added",l),y(n?"differs":"changed",p),y(n?"not given":"removed",d),n&&e.out.note("palbase apps:sync brings it up to date")}),n&&u?1:void 0}async function Be(e,t){let n=cn(e,ue),s=cn(e,...t.split("/")),a=tl(n,s);if(a===""||a.startsWith(`..${el}`)||a===".."||a.split(el).some(i=>i===".."||i===""))throw new b("outside_palbase",`${t} is not under ${ue}/`);let o=e;for(let i of[ue,...a.split(el)]){o=cn(o,i);try{if((await gT(o)).isSymbolicLink())throw new b("linked_path",`${tl(e,o)} is a link: palbase writes only into ${ue}/ itself`,{hint:"remove the link, and run it again"})}catch(r){if(r.code==="ENOENT")break;throw r}}return s}async function Kb(e,t){let n;try{n=await Ud(t,{withFileTypes:!0})}catch{return}for(let s of n)s.isDirectory()&&await Kb(e,cn(t,s.name));tl(cn(e,ue),t)===""||tl(cn(e,ue),t).startsWith(`..${el}`)||(await Ud(t)).length===0&&await bT(t)}var gi=["ios","android","web","macos"],mi=e=>e==="ios"||e==="macos";async function ao(e){let t=await Pn(e);return{id:t[0].project_id,name:t[0].project_name,org:t[0].org_name}}async function Vt(e,t){return(await e.studio.get(`/projects/${t}/apps`)).apps}function un(e,t){let n=e.find(s=>s.slug===t||s.id===t);if(!n)throw new b("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 al(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.macos?e.macos.bundle: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 Ub={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 ao(e),n=await Vt(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 ${gi.join("|")} <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}: ${al(a)}`).join("; ")||"\u2014"}])})}},Wb={name:"apps:create",summary:"register an app of the project (an iOS or Mac app names its Apple team); then set it in each environment (apps:env:set)",usage:`${gi.join("|")} <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 or Mac app's Apple team: 10 characters, Apple Developer \u203A Membership"},"app-id-prefix":{type:"string",value:"prefix",description:"an iOS or Mac 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(!gi.includes(t))throw h(`the platform is ${gi.slice(0,-1).join(", ")} or ${gi.at(-1)}`);let s=await ao(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> ${mi(t)?"--bundle <bundle id>":t==="android"?"--package <application id> --sha256 <label>=<fingerprint>":"--origin <https://\u2026>"}`)})}},Fb={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 ao(e),n=un(await Vt(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=>al(s)},{header:"publishable key",value:s=>s.key?.key??"\u2014"}])})}},Bb={name:"apps:update",summary:"rename an app, or change an iOS or Mac 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 or Mac 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 ao(e),n=un(await Vt(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 h("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)`))}},Jb={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 ao(e),n=un(await Vt(e,t.id),e.args[0]);if(!e.global.yes){if(!e.interactive)throw new b("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 b("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}`))}},Hb={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 ao(e),n=un(await Vt(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)`))}},NT=/^([a-z][a-z0-9_-]{0,31})=(.+)$/,Vb={name:"apps:env:set",summary:"what an app is in the environment: its bundle (iOS, Mac), 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.","Mac: the app's bundle in this environment, alone \u2014 a Mac app has no App Clip or watch app. Its extensions and helpers 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 or Mac 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 f(e),n=un(await Vt(e,t.project_id),e.args[0]),s=i=>(e.flags[i]??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean),a;if(n.platform==="ios"){if(!e.flags.bundle)throw h(`${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==="macos"){if(e.flags["app-clip"]||e.flags.watch)throw h(`${n.name} is a Mac app: it has no App Clip or watch app (--app-clip and --watch are an iOS app's)`);if(!e.flags.bundle)throw h(`${n.name} is a Mac app: give its bundle here (--bundle)`);a={macos:{bundle:e.flags.bundle}}}else if(n.platform==="android"){if(!e.flags.package)throw h(`${n.name} is an Android app: give its package here (--package)`);let i=(e.flags.sha256??[]).map(r=>{let l=NT.exec(r.trim());if(!l)throw h(`--sha256 ${JSON.stringify(r)}: label=fingerprint, like play_signing=AB:CD:\u2026`);return{label:l[1],sha256:l[2]}});a={android:{package:e.flags.package,fingerprints:i}}}else{let i=s("origin");if(i.length===0)throw h(`${n.name} is a web app: give its origins here (--origin)`);let r=s("redirect");a={web:{origins:i,...r.length?{redirects:r}:{}}}}await k(e,t,`set ${n.name} (${n.slug}) here: ${al(a)}`);let o=await e.studio.request("PUT",`/environments/${t.env_ref}/apps/${n.id}`,a);for(let i of o.warnings)e.out.warn(i);e.out.result(o,()=>{e.out.line(`${n.name} in ${t.env_name}: ${al(o)}`),o.key&&e.out.line(`its publishable key here: ${o.key.key}`),e.out.note("palbase apps:sync writes its settings into this checkout")})}},Xb={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 f(e),n=un(await Vt(e,t.project_id),e.args[0]);await k(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}`))}},Yb={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 f(e),n=un(await Vt(e,t.project_id),e.args[0]),s=e.flags.format??"json";if(s!=="json"&&s!=="env")throw h("--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))})}},Zb={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>] [--remove <app>]\u2026 [--backend [<machine>=]<dir> [--entry <file>]] [--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. --remove unlinks an app from palbase/project.json and removes its generated files.","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 or Mac app (in palbase/<app>.palbase), Kotlin for an Android app. A web app imports pb from palbase/<app>.ts (or createBrowser / createServer from palbase/<app>.ssr.ts for Next.js / SSR): 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. With an environment token (pbe_\u2026), only that environment's files are synced or checked; other environments stay untouched.","--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. It applies to one environment (-E, or the active/types non-production environment) and never overwrites production unless -E main is passed.","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)"},remove:{type:"string",multiple:!0,value:"app",description:"unlink an app (slug or id) from palbase/project.json and remove its generated files"},backend:{type:"string",value:"[machine=]dir",description:"a backend's checkout here: its Palbe made from the contract it writes for one environment (-E or non-production), never overwriting production unasked"},entry:{type:"string",value:"file",description:"with --backend, the backend's entry file (default src/main.ts)"},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 Gb(e)}};function ol(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 il(e,t){let n=we(e.flags.limit,"limit");if(n!==void 0&&(n<1||n>t))throw h(`--limit is a whole number from 1 to ${t}`);return n}function rl(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 ps=e=>e?e.slice(0,19).replace("T"," "):"",ha=(e,t)=>e||t;function ll(e,t,n){t&&e.out.line(`More: palbase ${n} --cursor ${t}`)}function ew(e){e.out.note("This read is in the project's access log (palbase messaging:access-log).")}function tw(e){return e.map(t=>`${t.name?I(t.name):"a file"} (${I(t.content_type)}, ${t.size} bytes)`).join(", ")}var Qb="A report is deleted, with what it carries, 190 days after it is resolved; one never resolved, 2 years after it was made.",MT={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"},...rl(100,30)},scope:"environment",async run(e){let t=e.flags.status;if(t!==void 0&&t!=="open"&&t!=="resolved")throw h("--status is open or resolved");let n=il(e,100),s=await f(e),a=await m(e,s,"GET",`/messaging/admin/reports${ol({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:o=>o.id},{header:"made",value:o=>ps(o.created_at)},{header:"status",value:o=>o.status==="resolved"?`resolved: ${o.resolution??""}`:"open"},{header:"reason",value:o=>o.reason},{header:"reported",value:o=>ha(o.reported_user_id,"")},{header:"by",value:o=>ha(o.reporter_id,"(deleted)")},{header:"messages",value:o=>String(o.message_ids.length)}]),ll(e,a.next_cursor,`messaging:reports:list${t?` --status ${t}`:""}`)})}},DT={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.",Qb],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET",`/messaging/admin/reports/${Q("the report's id",e.args[0])}`);ew(e),e.out.note(Qb),e.out.result(n,()=>{e.out.line(`report ${n.id} (${n.status==="resolved"?`resolved ${ps(n.resolved_at)}: ${I(n.resolution??"")}`:"open"})`),e.out.line(`made ${ps(n.created_at)} by ${ha(n.reporter_id,"a user since deleted")}`),e.out.line(`reported ${ha(n.reported_user_id,"no one in particular")}`),e.out.line(`reason ${I(n.reason)}`),e.out.line(`conversation ${n.conversation_id}${n.conversation_deleted_at?` (group deleted by ${ha(n.conversation_deleted_by,"a user since deleted")} at ${ps(n.conversation_deleted_at)})`:""}`),n.note&&e.out.line(`note ${I(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} ${ps(a.created_at)} ${ha(a.sender_id,"the server")} ${a.kind==="text"||a.text?I(a.text??""):`(${a.kind})`}`),a.attachments.length>0&&e.out.line(` files: ${tw(a.attachments)}`);for(let o of a.earlier_versions)e.out.line(` before it was edited: ${I(o.text)}, until ${ps(o.replaced_at)}`)}}})}},zT={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 h("--resolution says what came of it: 1 to 64 characters");let n=await f(e),s=Q("the report's id",e.args[0]);await k(e,n,`resolve the report ${e.args[0]}: ${t}`);let a=await m(e,n,"POST",`/messaging/admin/reports/${s}/resolve`,{resolution:t});e.out.result(a,()=>e.out.line(`Resolved the report ${a.id}: ${I(a.resolution??t)}.`))}},qT={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:rl(200,50),scope:"environment",async run(e){let t=il(e,200),n=await f(e),s=await m(e,n,"GET",`/messaging/admin/access-log${ol({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=>ps(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??""}]),ll(e,s.next_cursor,"messaging:access-log")})}},GT={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>)"},...rl(100,30)},scope:"environment",async run(e){let t=e.flags.user;if(t!==void 0&&t.trim()==="")throw h("--user is a person's id");let n=e.flags.space;if(n!==void 0&&!/^[A-Za-z0-9:_./@-]{1,128}$/.test(n))throw h("--space is 1 to 128 letters, digits and : _ . / @ - (as org:<id>)");let s=il(e,100),a=await f(e),o=await m(e,a,"GET",`/messaging/admin/conversations${ol({user_id:t,space:n,limit:s,cursor:e.flags.cursor})}`);e.out.result(o,()=>{o.data.length===0&&e.out.line(t===void 0?"No conversation yet.":`${t} is in no conversation.`),e.out.table(o.data,[{header:"conversation",value:i=>i.id},{header:"kind",value:i=>i.kind==="group"&&i.visibility==="open"?"group (open)":i.kind},{header:"space",value:i=>i.space??""},{header:"title",value:i=>i.kind==="group"?i.title??"":(i.members??[]).map(r=>r.user_id).join(" \xB7 ")},{header:"people",value:i=>String(i.member_count)},{header:"messages",value:i=>String(i.last_seq)},{header:"last moved",value:i=>ps(i.last_message_at??i.created_at)}]),ll(e,o.next_cursor,`messaging:conversations:list${t!==void 0?` --user ${t}`:""}${n!==void 0?` --space ${n}`:""}`)})}},KT={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:rl(100,50),scope:"environment",async run(e){let t=il(e,100),n=await f(e),s=Q("the conversation's id",e.args[0]),a=await m(e,n,"GET",`/messaging/admin/conversations/${s}/messages${ol({limit:t,cursor:e.flags.cursor})}`);ew(e),e.out.result(a,()=>{a.data.length===0&&e.out.line("The conversation has said nothing yet.");for(let o of a.data){let i=o.deleted?`(removed${o.removed_reason?`: ${o.removed_reason}`:""})`:o.kind==="system"?`(${o.system?.type??"system"})`:o.text!==null?I(o.text):`(${o.kind})`;e.out.line(`#${o.seq} ${ps(o.created_at)} ${ha(o.sender_id,"the server")} ${o.id} ${i}`),!o.deleted&&o.attachments.length>0&&e.out.line(` files: ${tw(o.attachments)}`)}ll(e,a.next_cursor,`messaging:messages:list ${e.args[0]}`)})}},UT={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=Q("the conversation's id",t),a=Q("the message's id",n),o=await f(e);await k(e,o,`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 m(e,o,"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 ${ee(o)}; the removal is in the access log.`))}},nw=[MT,DT,zT,qT,GT,KT,UT];function WT(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 FT(e,t){let n=we(e.flags.limit,"limit");if(n!==void 0&&(n<1||n>t))throw h(`--limit is a whole number from 1 to ${t}`);return n}function BT(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 pl=e=>e?e.slice(0,19).replace("T"," "):"";function JT(e,t,n){t&&e.out.line(`More: palbase ${n} --cursor ${t}`)}function Fd(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 sw=e=>e.video?"video":"voice";function HT(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 VT=["ringing","active","ended"],XT={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)"},...BT(100,20)},scope:"environment",async run(e){let t=e.flags.user;if(t!==void 0&&t.trim()==="")throw h("--user is a person's id");let n=e.flags.missed===!0;if(n&&t===void 0)throw h("--missed says whose: give --user with it");let s=e.flags.state;if(s!==void 0&&!VT.includes(s))throw h("--state is ringing, active or ended");let a=FT(e,100),o=await f(e),i=await m(e,o,"GET",`/calls/admin/calls${WT({user_id:t,missed:n?"true":void 0,state:s,limit:a,cursor:e.flags.cursor})}`);e.out.result(i,()=>{i.calls.length===0&&e.out.line(`No ${n?"missed ":""}${s?`${s} `:""}call${t!==void 0?` of ${t}`:n||s?"":" yet"}.`),e.out.table(i.calls,[{header:"call",value:l=>l.id},{header:"started",value:l=>pl(l.created_at)},{header:"kind",value:l=>l.kind},{header:"media",value:sw},{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:Fd}]);let r=[t!==void 0?` --user ${t}`:"",n?" --missed":"",s?` --state ${s}`:""].join("");JT(e,i.next_cursor,`calls:list${r}`)})}},YT={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 f(e),n=await m(e,t,"GET",`/calls/admin/calls/${Q("the call's id",e.args[0])}`);e.out.result(n,()=>{e.out.line(`call ${n.id}`),e.out.line(`kind ${n.kind}, ${sw(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 ${pl(n.created_at)}`),n.answered_at&&e.out.line(`answered ${pl(n.answered_at)}`),n.ended_at&&e.out.line(`ended ${pl(n.ended_at)}${Fd(n)?`, after ${Fd(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=>HT(s.bytes)}])})}},ZT={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=Q("the call's id",e.args[0]),n=await f(e);await k(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 m(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 ${ee(n)}.`))}},aw=[XT,YT,ZT];var QT=/^[A-Z][A-Z0-9_]{0,127}$/;function Ls(e,t){return`/environments/${Q("the environment's ref",e.env_ref)}/webhooks${t!==void 0?`/${Q("the webhook's id",t)}`:""}`}function ow(e){return Me(e.flags.events)}function dl(e){let t=e.machine?`, the machine ${I(e.machine)}'s \u2014 kept by the platform to what its app takes`:"",n=e.created_by?`, made by ${I(e.created_by.name)}${e.created_by.id.startsWith("tok_")?" (access token)":e.created_by.id.startsWith("etk_")?" (environment token)":""}`:"";return`${I(e.url)} \u2014 ${e.events.length===0?"every event":I(e.events.join(", "))} (${I(e.id)}${t}${n})`}function eC(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 ${I(e.redelivered_at)}`:e.redeliver_asked_at?"; redelivery asked":e.redelivery_error?`; redelivery failed: ${I(e.redelivery_error)}`:"";return`${I(e.id)} ${I(e.event_type)} ${I(e.event_id)} \u2192 ${I(n)} \u2014 ${I(e.last_error)} (${I(String(e.attempts))} tries, given up ${I(e.failed_at)})${s}`}var tC={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 f(e),{endpoints:n}=await e.studio.get(Ls(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(dl(s))})}},nC={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 f(e),n=e.flags["secret-to"];if(n!==void 0&&!QT.test(n))throw h(`--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 h("--dev goes with --secret-to <NAME>");let s=e.flags.dev===!0?"development":"production";await k(e,t,`add the webhook endpoint ${e.args[0]}${n?`, its secret kept in ${n} (${s})`:""}`);let a=await e.studio.post(Ls(t),{url:e.args[0],events:ow(e)??[]}),{secret:o,...i}=a;if(n!==void 0){let r=await m(e,t,"PUT",`/secrets/${s}/${n}`,{value:o});e.out.result({endpoint:i,secret_to:{set:s,name:n,version:r.version}},()=>e.out.line(`Added ${dl(i)}; its secret is ${n} (${s}, v${r.version}) in ${ee(t)}.`));return}e.out.result(a,()=>{e.out.line(`Added ${dl(i)}.`),e.out.line(`signing secret (shown this once): ${o}`)})}},sC={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 f(e);if(e.flags.url===void 0&&e.flags.events===void 0)throw h("nothing to change: --url or --events");let{endpoints:n}=await e.studio.get(Ls(t)),s=n.find(o=>o.id===e.args[0]);if(!s)throw h(`the environment has no webhook endpoint ${JSON.stringify(e.args[0])}`,"palbase webhooks:list shows them");await k(e,t,`change the webhook endpoint ${s.url}`);let a=await e.studio.request("PUT",Ls(t,s.id),{url:e.flags.url??s.url,events:ow(e)??s.events});e.out.result(a,()=>e.out.line(`Changed: ${dl(a)}.`))}},aC={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 f(e);await k(e,t,`remove the webhook endpoint ${e.args[0]}`),await e.studio.request("DELETE",Ls(t,e.args[0])),e.out.result({deleted:e.args[0]},()=>e.out.line(`Removed the webhook endpoint ${e.args[0]}.`))}},oC={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 f(e),[{deliveries:n},{endpoints:s}]=await Promise.all([e.studio.get(`${Ls(t)}/deliveries${e.flags.all===!0?"?all=true":"?failed=true"}`),e.studio.get(Ls(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(eC(a,s))})}},iC={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 f(e);await k(e,t,`send the failed delivery ${e.args[0]} again`);let n=await e.studio.post(`${Ls(t)}/deliveries/${Q("the delivery's id",e.args[0])}/redeliver`,{});e.out.result(n,()=>e.out.line(`Asked: ${I(n.event_type)} ${I(n.event_id)} goes to its endpoint again within seconds (palbase webhooks:deliveries:list --all shows when it went).`))}},iw=[tC,nC,sC,aC,oC,iC];import{constants as cl,createReadStream as rC}from"node:fs";import{mkdir as lC,open as pC,readdir as dC,realpath as rw,stat as cw}from"node:fs/promises";import{dirname as lw,extname as cC,join as uw,relative as uC,resolve as pw,sep as ul}from"node:path";import{Readable as mw}from"node:stream";import{pipeline as mC}from"node:stream/promises";var gw=600;function hi(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 ml(e){if(e.split("/").some(n=>n===""||n==="."||n===".."))throw new b("unsafe_path",`the object ${JSON.stringify(e)} has a name no request can carry`);return encodeURIComponent(e)}async function Bd(e,t,n,s){let a=[],o;do{let i=new URLSearchParams({limit:"1000",...s?{prefix:s}:{},...o?{cursor:o}:{}}),r=await m(e,t,"GET",`/storage/buckets/${Q("the bucket",n)}/objects?${i}`);a.push(...r.objects),o=r.next_cursor}while(o);return a}async function hw(e,t,n,s){let a;try{a=await e.io.fetch(t,{...n,redirect:"manual"})}catch(o){throw new b("network_error",`${s}: ${o instanceof Error?o.message:String(o)}`)}if(!a.ok){let o=await a.json().catch(()=>({}));throw new b(o.error??`http_${a.status}`,`${s}: ${o.error_description??o.error??`answered ${a.status}`}`)}return a}var gC={".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 dw(e){return gC[cC(e).toLowerCase()]}async function Jd(e,t,n,s,a,o){let i=(await cw(n)).size,r=await m(e,t,"POST",`/storage/buckets/${Q("the bucket",s)}/upload-urls`,{path:a,expires_in:gw,...o?{owner_id:o}:{}});return await hw(e,r.url,{method:"PUT",body:mw.toWeb(rC(n)),headers:{"content-length":String(i),...dw(n)?{"content-type":dw(n)}:{}},duplex:"half"},`${n} \u2192 ${s}:${a}`),i}function hC(e,t){let n=t.split("/");if(t===""||n.some(a=>a===""||a==="."||a===".."||a.includes("\\")||a.includes("\0")))throw new b("unsafe_path",`the object ${JSON.stringify(t)} has a name no file here can take`);let s=uw(e,...n);if(!s.startsWith(e+ul))throw new b("unsafe_path",`${t} would land outside ${e}`);return s}async function yC(e,t,n,s,a,o){let i=await m(e,t,"POST",`/storage/buckets/${Q("the bucket",n)}/signed-urls`,{path:s,expires_in:gw}),r=await hw(e,i.url,{method:"GET"},`${n}:${s} \u2192 ${a}`);if(await lC(lw(a),{recursive:!0}),o!==void 0){let[g,y]=await Promise.all([rw(o),rw(lw(a))]);if(y!==g&&!y.startsWith(g+ul))throw new b("unsafe_path",`${s} would land outside ${o} (through a link)`)}let p=(await pC(a,cl.O_WRONLY|cl.O_CREAT|cl.O_TRUNC|cl.O_NOFOLLOW)).createWriteStream();if(!r.body)return await new Promise((g,y)=>p.on("error",y).end(g)),0;let d=0,u=mw.fromWeb(r.body).on("data",g=>{d+=g.length});return await mC(u,p),d}async function yw(e){let t=[];for(let n of await dC(e,{withFileTypes:!0})){let s=uw(e,n.name);n.isDirectory()?t.push(...await yw(s)):n.isFile()&&t.push(s)}return t}var fC={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 f(e),n=hi(e.args[0].includes(":")?e.args[0]:`${e.args[0]}:`);if(!n)throw h(`${e.args[0]} is not a bucket (bucket or bucket:prefix)`);let s=await Bd(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??""}`)})}},bC={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 f(e),[n,s]=e.args,a=hi(n),o=hi(s),i=e.flags.recursive===!0,r=e.flags.owner;if(a&&o)throw h("one side is a bucket and the other this computer (bucket-to-bucket: the storage API copies within a bucket)");if(!a&&!o)throw h("one side is bucket:path");let l=0,p=0;if(o){let d=pw(e.io.cwd,n),u=i?await yw(d):[d];if(!i&&(await cw(d)).isDirectory())throw h(`${n} is a folder: copy it with -r`);await k(e,t,`upload ${u.length} file${u.length===1?"":"s"} to ${o.bucket}:${o.path} in ${ee(t)}`);for(let g of u){let y=i?uC(d,g).split(ul).join("/"):g.split(ul).pop(),w=i||o.path===""||o.path.endsWith("/")?`${o.path.replace(/\/?$/,o.path?"/":"")}${y}`:o.path;p+=await Jd(e,t,g,o.bucket,w,r),l++,u.length>1&&e.out.note(`${l}/${u.length} ${w}`)}}else if(a){let d=pw(e.io.cwd,s),u=i?await Bd(e,t,a.bucket,a.path):[{path:a.path,size:0}];for(let g of u){let y=i?g.path.slice(a.path.length).replace(/^\/+/,""):"",w=i?hC(d,y):d;p+=await yC(e,t,a.bucket,g.path,w,i?d:void 0),l++,u.length>1&&e.out.note(`${l}/${u.length} ${g.path}`)}}e.out.result({copied:l,bytes:p},()=>e.out.line(`Copied ${l} file${l===1?"":"s"} (${p} bytes).`))}},wC={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 f(e),n=hi(e.args[0]);if(!n||!n.path&&e.flags.recursive!==!0)throw h(`${e.args[0]} is not bucket:path`);let s=e.flags.recursive===!0?(await Bd(e,t,n.bucket,n.path)).map(a=>a.path):[n.path];await k(e,t,`delete ${s.length} object${s.length===1?"":"s"} from ${n.bucket} in ${ee(t)}`);for(let a of s)await m(e,t,"DELETE",`/storage/buckets/${Q("the bucket",n.bucket)}/objects/${ml(a)}`);e.out.result({deleted:s.length},()=>e.out.line(`Deleted ${s.length} object${s.length===1?"":"s"}.`))}},vC={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 f(e),n=hi(e.args[0]);if(!n||!n.path)throw h(`${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 h("--expires is 1 to 604800 seconds");let a=await m(e,t,"POST",`/storage/buckets/${Q("the bucket",n.bucket)}/signed-urls`,{path:n.path,expires_in:s});e.out.result(a,()=>e.out.line(a.url))}},fw=[fC,bC,wC,vC];function bw(e){if(e<1024)return`${e} B`;let t=["KiB","MiB","GiB","TiB"],n=e/1024,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;return`${n>=100?Math.round(n):Math.round(n*10)/10} ${t[s]}`}var gl=e=>e?e.slice(0,19).replace("T"," "):"",Hd={endpoint:{type:"string",value:"https-url",description:"S3-compatible HTTPS endpoint (e.g. https://s3.example.com)"},bucket:{type:"string",value:"bucket",description:"S3 bucket name"},region:{type:"string",value:"region",description:"S3 region (default: auto)"},prefix:{type:"string",value:"prefix",description:"optional object key prefix inside the bucket"},"access-key-id":{type:"string",value:"key-id",description:"S3 access key ID (secret access key is read from stdin)"},"presign-endpoint":{type:"string",value:"https-url",description:"optional public HTTPS endpoint used for presigned transfer URLs"},"virtual-host":{type:"boolean",description:"use virtual-hosted-style bucket URLs instead of path-style"}};async function Vd(e){let t=e.flags.endpoint,n=e.flags.bucket,s=e.flags["access-key-id"];if(!t||!n||!s)throw h("BYOS requires --endpoint, --bucket and --access-key-id (with the secret access key piped on stdin)");let a=await lt(e,"the BYOS S3 secret access key"),o=e.flags.region,i=e.flags.prefix,r=e.flags["presign-endpoint"];return{kind:"byos",endpoint:t,bucket:n,access_key_id:s,secret_access_key:a,...o?{region:o}:{},...i?{prefix:i}:{},...r?{presign_endpoint:r}:{},force_path_style:e.flags["virtual-host"]!==!0}}var kC={name:"workspaces:list",summary:"the environment's synchronized workspaces: name, id, storage, seq, files, size",usage:"",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/workspaces");e.out.result(n,()=>{if(n.workspaces.length===0){e.out.line(`No workspaces in ${ee(t)} yet. Create one with: palbase workspaces:create <name>`);return}e.out.table(n.workspaces,[{header:"name",value:s=>s.name},{header:"id",value:s=>s.id},{header:"storage",value:s=>s.storage_kind==="byos"&&s.storage?.bucket?`byos (${s.storage.bucket})`:s.storage_kind},{header:"seq",value:s=>String(s.seq)},{header:"files",value:s=>String(s.total_files)},{header:"size",value:s=>bw(s.total_bytes)},{header:"updated",value:s=>gl(s.updated_at)}])})}},_C={name:"workspaces:get",summary:"one workspace: storage configuration, head revision, file count and byte size",usage:"<id-or-name>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Q("workspace",e.args[0]),s=await m(e,t,"GET",`/workspaces/${n}`);e.out.result(s,()=>{e.out.line(`id ${s.id}`),e.out.line(`name ${s.name}`),e.out.line(`storage ${s.storage_kind}`),s.storage_kind==="byos"&&s.storage&&(s.storage.endpoint&&e.out.line(`endpoint ${s.storage.endpoint}`),s.storage.bucket&&e.out.line(`bucket ${s.storage.bucket}${s.storage.prefix?`/${s.storage.prefix}`:""}`),s.storage.region&&e.out.line(`region ${s.storage.region}`),s.storage.access_key_preview&&e.out.line(`access key ${s.storage.access_key_preview}`)),e.out.line(`seq ${s.seq}`),e.out.line(`files ${s.total_files} (${bw(s.total_bytes)})`),e.out.line(`updated ${gl(s.updated_at)}`)})}},SC={name:"workspaces:create",summary:"create a workspace on Palbase managed storage, or on your own S3 bucket with --byos",usage:"[name] [--byos --endpoint <url> --bucket <name> --access-key-id <key>]",details:["Without --byos, the workspace stores blobs in Palbase managed object storage.",'With --byos, pipe the S3 secret access key on stdin (never passed as a flag): printf "%s" "$SECRET" | palbase workspaces:create app-ios --byos --endpoint https://\u2026 --bucket my-bucket --access-key-id AKIA\u2026'],args:{min:0,max:1},flags:{byos:{type:"boolean",description:"back this workspace with your own S3-compatible bucket (secret read from stdin)"},...Hd},scope:"environment",async run(e){let t=await f(e),n=e.args[0],s={};n&&(s.name=n),e.flags.byos===!0&&(s.storage=await Vd(e));let a=await m(e,t,"POST","/workspaces",s);e.out.result(a,()=>{e.out.line(`Created workspace ${a.name} (${a.id}, ${a.storage_kind}) in ${ee(t)}.`)})}},$C={name:"workspaces:delete",summary:"delete a workspace (refused if attached unless --force is passed)",usage:"<id-or-name> [--force]",args:{min:1,max:1},flags:{force:{type:"boolean",description:"delete even when attached resources still reference this workspace"}},scope:"environment",async run(e){let t=await f(e),n=e.args[0],s=Q("workspace",n),a=e.flags.force===!0;await k(e,t,`delete workspace ${n}${a?" (forced)":""} in ${ee(t)}`,"All workspace history, files and tokens are deleted and cannot be recovered"),await m(e,t,"DELETE",`/workspaces/${s}${a?"?force=true":""}`),e.out.result({deleted:n,force:a},()=>e.out.line(`Deleted workspace ${n} in ${ee(t)}.`))}},AC={name:"workspaces:storage:set",summary:"rotate BYOS S3 credentials or update BYOS endpoint settings on a BYOS workspace",usage:"<id-or-name> --endpoint <url> --bucket <name> --access-key-id <key>",details:["Pipe the new S3 secret access key on stdin. The bucket is probed before saving."],args:{min:1,max:1},flags:Hd,scope:"environment",async run(e){let t=await f(e),n=Q("workspace",e.args[0]),s=await Vd(e),a=await m(e,t,"PUT",`/workspaces/${n}/storage`,s);e.out.result(a,()=>{e.out.line(`Updated BYOS storage for ${a.name} (${a.id}, key ${a.storage?.access_key_preview??"updated"}).`)})}},PC={name:"workspaces:byos:test",summary:"test a BYOS S3 bucket connection (SSRF check + live write/head/delete/presign probe)",usage:"--endpoint <url> --bucket <name> --access-key-id <key>",details:["Pipe the S3 secret access key on stdin; nothing is persisted."],flags:Hd,scope:"environment",async run(e){let t=await f(e),n=await Vd(e),s=await m(e,t,"POST","/workspaces/byos/test",n);e.out.result(s,()=>{e.out.line(`BYOS connection OK (${s.latency_ms} ms).`)})}},RC={name:"workspaces:tokens:list",summary:"a workspace's sync tokens and workspace-scoped S3 keys",usage:"<id-or-name> [--kind sync|s3]",args:{min:1,max:1},flags:{kind:{type:"string",value:"sync|s3",description:"filter by token kind"}},scope:"environment",async run(e){let t=await f(e),n=Q("workspace",e.args[0]),s=e.flags.kind;if(s!==void 0&&s!=="sync"&&s!=="s3")throw h("--kind is sync or s3");let a=s?`?kind=${s}`:"",o=await m(e,t,"GET",`/workspaces/${n}/tokens${a}`);e.out.result(o,()=>{if(o.tokens.length===0){e.out.line(`No tokens on ${e.args[0]}.`);return}e.out.table(o.tokens,[{header:"id",value:i=>i.id},{header:"kind",value:i=>i.kind},{header:"access",value:i=>i.access},{header:"label",value:i=>i.label??""},{header:"key id",value:i=>i.access_key_id??""},{header:"expires",value:i=>i.expires_at?gl(i.expires_at):"never"}])})}},jC={name:"workspaces:tokens:create",summary:"mint a workspace sync token (pwt_\u2026) or workspace-scoped S3 key pair (shown once)",usage:"<id-or-name> [--kind sync|s3] [--access rw|ro] [--label <text>] [--ttl <seconds>]",args:{min:1,max:1},flags:{kind:{type:"string",value:"sync|s3",description:"sync (default) or s3"},access:{type:"string",value:"rw|ro",description:"rw (default) or ro"},label:{type:"string",value:"text",description:"optional human label (e.g. mac-builder)"},ttl:{type:"string",value:"seconds",description:"time-to-live in seconds"}},scope:"environment",async run(e){let t=await f(e),n=Q("workspace",e.args[0]),s=e.flags.kind??"sync";if(s!=="sync"&&s!=="s3")throw h("--kind is sync or s3");let a=e.flags.access??"rw";if(a!=="rw"&&a!=="ro")throw h("--access is rw or ro");let o=we(e.flags.ttl,"ttl"),i=e.flags.label,r=await m(e,t,"POST",`/workspaces/${n}/tokens`,{kind:s,access:a,...i?{label:i}:{},...o!==void 0?{ttl_seconds:o}:{}});e.out.result(r,()=>{e.out.line(`id ${r.id}`),e.out.line(`kind ${r.kind} (${r.access})`),r.token&&(e.out.line(`token ${r.token}`),r.sync_url&&e.out.line(`sync ${r.sync_url}`)),r.access_key_id&&(e.out.line(`key id ${r.access_key_id}`),e.out.line(`secret ${r.secret_access_key??""}`),r.endpoint&&e.out.line(`s3 ${r.endpoint}/${r.bucket??e.args[0]}`)),e.out.line("Shown once \u2014 save it now.")})}},EC={name:"workspaces:tokens:revoke",summary:"revoke a workspace sync token or workspace-scoped S3 key immediately",usage:"<id-or-name> <token-id>",args:{min:2,max:2},scope:"environment",async run(e){let t=await f(e),n=Q("workspace",e.args[0]),s=Q("token",e.args[1]);await m(e,t,"DELETE",`/workspaces/${n}/tokens/${s}`),e.out.result({revoked:e.args[1]},()=>e.out.line(`Revoked token ${e.args[1]}.`))}},TC={name:"workspaces:s3-keys:list",summary:"list project-wide S3 access keys spanning all workspaces in the environment",usage:"",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/workspaces/s3-keys");e.out.result(n,()=>{if(n.keys.length===0){e.out.line(`No project-wide workspace S3 keys in ${ee(t)}.`);return}e.out.table(n.keys,[{header:"id",value:s=>s.id},{header:"key id",value:s=>s.access_key_id??""},{header:"access",value:s=>s.access},{header:"label",value:s=>s.label??""},{header:"expires",value:s=>s.expires_at?gl(s.expires_at):"never"}])})}},CC={name:"workspaces:s3-keys:create",summary:"mint a project-wide S3 access key pair spanning every workspace in the environment (shown once)",usage:"[--access rw|ro] [--label <text>] [--ttl <seconds>]",flags:{access:{type:"string",value:"rw|ro",description:"rw (default) or ro"},label:{type:"string",value:"text",description:"optional human label (e.g. ci-rclone)"},ttl:{type:"string",value:"seconds",description:"optional time-to-live in seconds"}},scope:"environment",async run(e){let t=await f(e),n=e.flags.access??"rw";if(n!=="rw"&&n!=="ro")throw h("--access is rw or ro");let s=we(e.flags.ttl,"ttl"),a=e.flags.label,o=await m(e,t,"POST","/workspaces/s3-keys",{access:n,...a?{label:a}:{},...s!==void 0?{ttl_seconds:s}:{}});e.out.result(o,()=>{e.out.line(`id ${o.id}`),e.out.line(`access ${o.access}`),e.out.line(`key id ${o.access_key_id??""}`),e.out.line(`secret ${o.secret_access_key??""}`),o.endpoint&&e.out.line(`endpoint ${o.endpoint}`),e.out.line("Shown once \u2014 save it now.")})}},OC={name:"workspaces:s3-keys:revoke",summary:"revoke a project-wide workspace S3 key immediately",usage:"<key-id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=Q("key",e.args[0]);await m(e,t,"DELETE",`/workspaces/s3-keys/${n}`),e.out.result({revoked:e.args[0]},()=>e.out.line(`Revoked S3 key ${e.args[0]}.`))}},ww=[kC,_C,SC,$C,AC,PC,RC,jC,EC,TC,CC,OC];import{readFile as MC}from"node:fs/promises";import{resolve as DC}from"node:path";var vw=`ac
|
|
642
642
|
com.ac
|
|
643
643
|
edu.ac
|
|
644
644
|
gov.ac
|
|
@@ -11092,7 +11092,7 @@ zone.id
|
|
|
11092
11092
|
nett.to
|
|
11093
11093
|
zabc.net`;var xC=["palbase.studio","palbase.app"],LC=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/,hl;function IC(){if(hl)return hl;let e=new Set,t=new Set,n=new Set;for(let s of vw.split(`
|
|
11094
11094
|
`))s.startsWith("!")?n.add(s.slice(1)):s.startsWith("*.")?t.add(s.slice(2)):e.add(s);return hl={exact:e,wild:t,except:n},hl}function NC(e){return e.length>0&&e.length<=253&&e.split(".").length>=2&&e.split(".").every(t=>LC.test(t))}function yl(e){if(!NC(e))return;for(let l of xC)if(e.endsWith(`.${l}`))return e;let{exact:t,wild:n,except:s}=IC(),a=e.split("."),o=a.length;if(!t.has(a[o-1])&&!n.has(a[o-1]))return;let i=1,r=-1;for(let l=0;l<o;l++){let p=a.slice(l).join(".");if(s.has(p)){r=o-l-1;break}t.has(p)&&(i=Math.max(i,o-l)),l+1<o&&n.has(a.slice(l+1).join("."))&&(i=Math.max(i,o-l))}if(r>=0&&(i=r),!(i>=o))return a.slice(o-i-1).join(".")}var ec=/^[a-z][a-z0-9_-]{0,63}$/,kw=["backend","client","https","mcp","platform"];function xn(e,t,n=0){let s=e.args[n];if(!ec.test(s))throw h(`${JSON.stringify(s)} is not ${t}'s name: lowercase letters, digits, _ and -, a letter first, at most 64`);return s}function qt(e,t){let n=we(e,t);if(n===0)throw h(`--${t} is a whole number from 1`);return n}function cs(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 _w(e,t,n){let s;try{s=await MC(DC(e.io.cwd,t),"utf8")}catch(a){throw new b("unreadable_file",`${t} could not be read: ${a instanceof Error?a.message:String(a)}`)}return Ne(s,n)}var fl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wl=e=>`$${e<.01&&e>0?e.toPrecision(2):e.toFixed(e<1?4:2)}`,vl=e=>`$${e.toFixed(2)}`,Rw="or connect the environment's own key for the model's provider, which its provider bills: palbase ai:providers:set <provider>",Xd=`raise the budget in Studio \u203A AI \u203A Settings or with palbase ai:settings:set --monthly-budget <usd>; ${Rw}`,Yd=`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); ${Rw}`;function jw(e){if(!(e instanceof G))return e;switch(e.code){case"ai_budget_reached":return new b(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:Xd});case"ai_payment_required":return new b(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:Yd});case"provider_key_required":return new b(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 b(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 zC(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 h(`--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 qC={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 h("--kind is text, embedding or image");let n=zC(e.flags.metadata),s=qt(e.flags.limit,"limit"),a=await f(e),o=await m(e,a,"GET",`/ai/usage${cs({kind:t,limit:s,cursor:e.flags.cursor,metadata:n&&JSON.stringify(n)})}`);e.out.result(o,()=>{o.usage.length===0&&e.out.line("No use of a model yet."),e.out.table(o.usage,[{header:"when",value:i=>i.created_at},{header:"kind",value:i=>i.kind},{header:"model",value:i=>i.model},{header:"tokens",value:i=>`${i.kind==="image"?`${i.items} picture(s)`:`${i.input_tokens} in / ${i.output_tokens} out`}${i.estimated?" (estimate)":""}`},{header:"cost",value:i=>wl(i.cost_nano_usd/1e9)},{header:"key",value:i=>i.connection_owner==="project"?"project's":"platform's"},{header:"labels",value:i=>Object.entries(i.metadata??{}).map(([r,l])=>`${r}=${l}`).join(" ")}]),o.usage.some(i=>i.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."),o.next_cursor&&e.out.line(`More: palbase ai:usage --cursor ${o.next_cursor}`)})}},GC={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 f(e),n=await m(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(", ")}`)})}},KC={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"},UC={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 f(e),n=await m(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 ${KC[n.plan]??n.plan}`),e.out.line(`spent ${wl(n.spent_usd)} on Palbase's models, at what it is billed, before the free dollar`),e.out.line(`free ${vl(n.free_usd)} this month: what its project's other environments left of its free dollar${n.free_left_usd===null?"":` \u2014 ${wl(n.free_left_usd)} left`}`),e.out.line(`monthly budget ${n.monthly_budget_usd===null?"none":vl(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(` ${Xd[0].toUpperCase()}${Xd.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(` ${Yd[0].toUpperCase()}${Yd.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>."))})}},WC={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 f(e),{providers:n}=await m(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"}])})}},FC={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 h(`${JSON.stringify(t)} is not a provider's name (openai, anthropic, google\u2026)`);if(e.flags["key-stdin"]!==!0&&!e.interactive)throw h(`${t}'s key is read from stdin`,`pipe it in: palbase ai:providers:set ${t} --key-stdin < key.txt`);let n=await f(e),s=await lt(e,`${t}'s key`);await k(e,n,`call ${t} with the environment's own key`);let a=await m(e,n,"PUT",`/ai/providers/${A(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.`))}},BC={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 f(e);await k(e,n,`forget the environment's own ${t} key`),await m(e,n,"DELETE",`/ai/providers/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`${t}'s calls go out with the platform's key again.`))}};function Ew(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":`${vl(n)} a month on Palbase's models`}`),e.out.line(`open secrets ${t.open_secrets_for_app_users?"the app's users' work has them too: anyone who signs in to the app can drive an agent to read them":"only the work the environment's developers and its server start has them"}`)}var JC="With it on, anyone who signs in to the app can drive an agent to read the environment's open secrets";function io(e,t,n){if((e.io.env.PALBASE_TOKEN??"")!=="")throw new b("person_required",`a key or a token cannot ${t}: a person does \u2014 an owner or an admin of the organization, signed in as themselves \u2014 and the CLI acts with PALBASE_TOKEN`,{hint:`sign in as yourself: unset PALBASE_TOKEN, then palbase login${n?` \u2014 or ${n}`:""}`})}function ro(e,t,n){return!(e instanceof G)||e.code!=="person_required"&&e.code!=="token_out_of_scope"?e:new b(e.code,`only an owner or an admin of the organization, signed in as themselves, may ${t}: a member's call is refused, and so is a key's or a token's`,{hint:`ask an owner or an admin \u2014 in Studio, or with this command signed in as themselves (palbase login)${n?`; or ${n}`:""}`})}var Sw="say whether the app's users' work has the environment's open secrets";function HC(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 h(`--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 VC={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, whether their work has its open secrets \u2014 and its monthly AI budget",scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/ai/settings");e.out.result(n,()=>Ew(e,n))}},XC={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] [--open-secrets-for-app-users yes|no]",details:["--open-secrets-for-app-users yes lets the work an app's user starts (a member's message, goal or voice) have the environment's open secrets (ai:env:set --open): anyone who signs in to the app can then drive an agent to read them \u2014 asked of you wherever it is turned on (-y confirms it). Off (the default), only the work its developers and its server start has them. Said, yes or no, by an owner or an admin of the organization signed in as themselves, never with a key or a token (PALBASE_TOKEN): refused before anything is sent.","--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"},"open-secrets-for-app-users":{type:"string",value:"yes|no",description:"the work an app's user starts has the environment's open secrets"}},scope:"environment",async run(e){let t={},n=e.flags.clients;if(n!==void 0){if(!["on","off"].includes(n))throw h("--clients is on or off");t.clients=n==="on"}let s=qt(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=qt(a,"history-limit"));let o=HC(e.flags["monthly-budget"]);o!==void 0&&(t.monthly_budget_usd=o);let i=Gn(e.flags["open-secrets-for-app-users"],"open-secrets-for-app-users");if(i!==void 0&&(t.open_secrets_for_app_users=i),Object.keys(t).length===0)throw h("nothing to change","pass --clients, --messages-per-minute, --history-limit, --monthly-budget or --open-secrets-for-app-users");i!==void 0&&io(e,Sw,"set it in Studio \u203A AI \u203A Settings");let r=await f(e),l=Object.keys(t).filter(u=>u!=="monthly_budget_usd"&&u!=="open_secrets_for_app_users"),p=[...l.length>0?[`change what the chats are allowed: ${l.join(", ")}`]:[],...o===void 0?[]:[o===null?"take away the monthly AI budget":`set the monthly AI budget to ${vl(o)}`],...i===void 0?[]:[i?"let the work of the app's users have the open secrets: anyone who signs in to the app can then drive an agent to read them":"keep the open secrets from the work of the app's users"]];await k(e,r,p.join("; "),i===!0?JC:void 0);let d;try{d=await m(e,r,"PUT","/ai/settings",t)}catch(u){throw i!==void 0&&u instanceof G&&(u.code==="person_required"||u.code==="token_out_of_scope")?ro(u,Sw):o===void 0?u:YC(u)}e.out.result(d,()=>Ew(e,d))}};function YC(e){return e instanceof G?e.status===403?new b(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 b(e.code,"this stack bills no AI, so it keeps no monthly AI budget: nothing was changed"):e.code==="registry_unavailable"?new b(e.code,"Palbase's billing did not answer: nothing was changed",{hint:"run the command again shortly"}):e:e}function Zd(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 ZC={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 f(e),{agents:n}=await m(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 QC(e,t,n,s){let a;for(let o=0;o<100;o++){let i=await m(e,t,"GET",`/ai/agents/${A(n)}/versions${cs({limit:100,cursor:a})}`),r=i.versions.find(l=>l.version===s);if(r)return r;if(!i.next_cursor||i.versions.every(l=>l.version<s))break;a=i.next_cursor}throw new b("not_found",`${n} has no version ${s}`,{hint:`palbase ai:agents:versions ${n}`})}function oo(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(`
|
|
11095
|
-
`))e.out.line(` ${s}`)}var e2={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=xn(e,"an agent"),n=qt(e.flags.version,"version");if(n!==void 0&&e.flags.draft===!0)throw h("--draft or --version, not both");let s=await f(e);if(n!==void 0){let o=await QC(e,s,t,n);e.out.result(o,()=>oo(e,`${t} version ${o.version}, published ${o.published_at} by ${o.published_by}:`,o.definition));return}let a=await m(e,s,"GET",`/ai/agents/${A(t)}`);if(e.flags.draft===!0&&a.source==="code")throw new b("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}: ${Zd(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"?oo(e,`Its last turn${a.defined_at?` (${a.defined_at})`:""} was defined as:`,a.definition):e.flags.draft===!0||a.published===void 0?oo(e,`The draft (revision ${a.revision}):`,a.draft):oo(e,`Version ${a.published_version}, the one its chats talk to:`,a.published)})}};function t2(e){let t=e.indexOf(":"),n=t>0?e.slice(0,t):"",s=e.slice(t+1);if(!kw.includes(n)||s==="")throw h(`--tool is source:name \u2014 ${kw.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 o=s.slice(0,a);if(s=s.slice(a+1),!ec.test(o)||s==="")throw h(`--tool backend:<machine>/<name> names one of the environment's machines and its tool, not ${JSON.stringify(e)}`);return{source:"backend",name:s,machine:o}}async function n2(e){let t={},n=e.flags.from;if(n!==void 0){let a=await _w(e,n,n),o=fl(a)&&fl(a.definition)&&typeof a.name=="string"?a.definition:a;if(!fl(o))throw h(`${n} is an agent's definition: a JSON object { instructions, model, tools, \u2026 }`);t=o}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(t2));let s=e.flags["output-schema"];if(s!==void 0){let a=await _w(e,s,s);if(!fl(a)||a.type!=="object")throw h(`${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 h("an agent the environment keeps names no backend: a backend's agent is its code's (ai.agent)");return t}async function s2(e,t,n){try{let s=await m(e,t,"GET",`/ai/agents/${A(n)}`);return s.source==="platform"&&s.draft&&s.revision!==void 0?{draft:s.draft,revision:s.revision}:void 0}catch(s){if(s instanceof G&&s.status===404)return;throw s}}async function Tw(e,t,n,s,a){try{return await m(e,t,"PUT",`/ai/agents/${A(n)}${cs({revision:a})}`,s)}catch(o){throw Cw(e,o,n,"give the secret's value with it in the definition (env.<KEY>.value)")}}function Cw(e,t,n,s){if(!(t instanceof G))return t;let a=(e.io.env.PALBASE_TOKEN??"")!=="";switch(t.code){case"person_required":return new b(t.code,`${n}'s own secrets: ${t.message}`,{hint:`${a?"sign in as yourself: unset PALBASE_TOKEN, then palbase login":"ask an owner or an admin of the organization to do it, signed in as themselves"} \u2014 or ${s}`});case"secret_unusable":return new b(t.code,`${n}'s own secrets: ${t.message}`,{hint:`a value that is no secret (a region, a scheme) is { "value": "\u2026", "secret": false } in the definition's env; one the agent may read as it is { "value": "\u2026", "open": true, "acknowledge_open": true }`});case"secret_guessable":return new b(t.code,`${n}'s own secrets: ${t.message}`,{hint:`use a random key \u2014 or keep it sealed anyway: "acknowledge_guessable": true beside its value in the definition's env; a value that is no secret: "secret": false`});case"open_not_acknowledged":return new b(t.code,`${n}'s own secrets: ${t.message}`,{hint:`say you read it: "acknowledge_open": true beside it in the definition's env`});default:return t}}async function tc(e,t,n,s){return m(e,t,"POST",`/ai/agents/${A(n)}/publish`,s!==void 0?{revision:s}:{})}var a2={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=xn(e,"an agent"),n=qt(e.flags.revision,"revision"),s=await n2(e);if(Object.keys(s).length===0)throw h("the agent is empty","pass --from <file.json>, or --instructions, --model, --tool\u2026");let a=await f(e),o=e.flags.from===void 0?await s2(e,a,t):void 0,i={...o?.draft,...s},r=e.flags.publish===!0;await k(e,a,`save the draft of the agent ${t}${r?" and publish it":""}`);let l=await Tw(e,a,t,i,n??o?.revision),p=r?await tc(e,a,t,l.revision):l;e.out.result(p,()=>{e.out.line(`Saved the draft of ${t} (revision ${l.revision}).`),r?e.out.line(`Published ${t} as version ${p.published_version}: its chats talk to it from their next turn.`):e.out.line(`${Zd(p)[0].toUpperCase()}${Zd(p).slice(1)}: palbase ai:agents:publish ${t} makes its chats talk to it.`)})}},o2={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=xn(e,"an agent"),n=qt(e.flags.revision,"revision"),s=await f(e);await k(e,s,`publish the draft of the agent ${t}`);let a=await tc(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.`))}},i2={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=xn(e,"an agent"),n=Number(e.args[1]);if(!Number.isSafeInteger(n)||n<1)throw h(`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 f(e);await k(e,s,`make version ${n} of the agent ${t} the one its chats talk to (a draft not published is dropped)`);let a;try{a=await m(e,s,"POST",`/ai/agents/${A(t)}/rollback`,{version:n})}catch(o){throw Cw(e,o,t,`save a draft that says them with their values (palbase ai:agents:create ${t} --from <file.json>) and publish it`)}e.out.result(a,()=>e.out.line(`${t}'s chats talk to version ${a.published_version} again; its draft is that version.`))}},r2={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=xn(e,"an agent"),n=qt(e.flags.limit,"limit"),s=await f(e),a=await m(e,s,"GET",`/ai/agents/${A(t)}/versions${cs({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:o=>`${o.version}${o.version===a.published_version?" (published)":""}`},{header:"published",value:o=>o.published_at},{header:"by",value:o=>o.published_by},{header:"model",value:o=>o.definition.model??"-"},{header:"description",value:o=>o.definition.description??""}]),a.next_cursor&&e.out.line(`More: palbase ai:agents:versions ${t} --cursor ${a.next_cursor}`)})}},l2={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 h("the description says the agent in words: 1 to 4000 characters");let n=e.flags.name;if(n!==void 0&&!ec.test(n))throw h(`${JSON.stringify(n)} is not an agent's name: lowercase letters, digits, _ and -, a letter first, at most 64`);let s=await f(e),a=await m(e,s,"POST","/ai/agent-drafts",{description:t,...n!==void 0?{name:n}:{}}),o=e.flags.publish===!0;if(e.flags.save!==!0&&!o){e.out.result(a,()=>{oo(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 k(e,s,`save the draft of the agent ${a.name}${o?" and publish it":""}`);let i=await Tw(e,s,a.name,a.definition,void 0),r=o?await tc(e,s,a.name,i.revision):i;e.out.result({...a,agent:r},()=>{oo(e,`${a.name}:`,a.definition),e.out.line(),e.out.line(o?`Saved and published ${a.name} as version ${r.published_version}.`:`Saved the draft of ${a.name} (revision ${i.revision}): palbase ai:agents:publish ${a.name} makes its chats talk to it.`)})}},p2={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=xn(e,"an agent"),n=await f(e);await k(e,n,`forget the agent ${t} and its versions`),await m(e,n,"DELETE",`/ai/agents/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`Forgot ${t} and its versions.`))}},d2={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 f(e),{tools:n}=await m(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).")})}},c2={name:"ai:chats:list",summary:"the environment's chats, newest first \u2014 every one, a member's, or only active ones",usage:"[--member <user id>] [--status active|all] [--limit <n>] [--cursor <cursor>]",flags:{member:{type:"string",value:"user id",description:"only the chats this user is in"},status:{type:"string",value:"active|all",description:"active returns only chats with a running or waiting turn"},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=qt(e.flags.limit,"limit"),n=e.flags.status;if(n!==void 0&&n!=="active"&&n!=="all")throw h("--status is active or all");let s=await f(e),a=await m(e,s,"GET",`/ai/chats${cs({member:e.flags.member,status:n,limit:t,cursor:e.flags.cursor})}`);e.out.result(a,()=>{a.chats.length===0&&e.out.line("No chat."),e.out.table(a.chats,[{header:"id",value:o=>o.id},{header:"agent",value:o=>`${o.agent}${o.agent_version?`@${o.agent_version}`:""}`},{header:"title",value:o=>o.title},{header:"members",value:o=>String(o.members.length)},{header:"started",value:o=>o.created_at}]),a.next_cursor&&e.out.line(`More: palbase ai:chats:list --cursor ${a.next_cursor}`)})}},u2=/^chat_[0-9a-f]{32}$/;function _l(e){let t=e.args[0];if(!u2.test(t))throw h(`${JSON.stringify(t)} is not a chat's id (chat_ and 32 hex digits)`,"palbase ai:chats:list");return t}var m2={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=_l(e),n=qt(e.flags.limit,"limit")??50,s=await f(e),a=await m(e,s,"GET",`/ai/chats/${A(t)}`),o=await m(e,s,"GET",`/ai/chats/${A(t)}/messages${cs({limit:n})}`),i=[...o.messages].reverse(),r=await g2(e,s,t,new Set(i.flatMap(d=>d.response_id?[d.response_id]:[]))),l=new Map;i.forEach((d,u)=>d.response_id&&l.set(d.response_id,u));let p=new Map;if(e.flags.cost===!0)for(let d of new Set(i.flatMap(u=>u.response_id?[u.response_id]:[])))p.set(d,await m(e,s,"GET",`/ai/chats/${A(t)}/turns/${A(d)}/cost`));e.out.result({chat:a,messages:i,answers:Object.fromEntries(r),...e.flags.cost===!0?{costs:Object.fromEntries(p)}:{}},()=>{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(d=>`${d.name||d.user_id}${d.owner?" (owner)":""}`).join(", ")}`),e.out.line(),i.length===0&&e.out.line("Nothing written yet."),i.forEach((d,u)=>{if(e.out.line(`${d.created_at} ${d.author===null?"server":d.author_name||d.author}: ${d.text}${d.status==="failed"?` [failed: ${d.error??""}]`:""}`),!d.response_id||l.get(d.response_id)!==u)return;let g=r.get(d.response_id);g&&e.out.line(` ${a.agent}: ${g.replace(/\s*\n\s*/g," ")}`);let y=p.get(d.response_id);y&&e.out.line(` turn ${y.response_id}: ${wl(y.usd)}${y.unpriced?" at least":""}, ${y.input_tokens} in / ${y.output_tokens} out${y.final?"":" (still settling)"}`)}),o.next_cursor&&e.out.line(`(older messages are not shown: --limit ${Math.min(n*2,100)})`)})}};async function g2(e,t,n,s){let a=[],o;for(let r=0;r<20&&s.size>0;r++){let l=await m(e,t,"GET",`/ai/chats/${A(n)}/parts${cs({limit:1e3,cursor:o})}`);if(a.unshift(l.parts),!l.next_cursor)break;o=l.next_cursor}let i=new Map;for(let r of a.flat()){let l=r.data.response_id,p=r.data.offset;if(typeof l!="string"||!s.has(l)||typeof p!="number")continue;let d=(i.get(l)??Buffer.alloc(0)).subarray(0,p);i.set(l,r.type==="text"&&typeof r.data.text=="string"?Buffer.concat([d,Buffer.from(r.data.text)]):r.type==="reset"?d:i.get(l)??d)}return new Map([...i].map(([r,l])=>[r,l.toString("utf8").trim()]))}var h2={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=_l(e),n=await f(e);await k(e,n,`delete the chat ${t}`),await m(e,n,"DELETE",`/ai/chats/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`Deleted the chat ${t}.`))}},y2=/^[a-z][a-z0-9_-]{0,63}(@[1-9][0-9]{0,8})?$/,ds=/^[A-Za-z0-9_.:-]{1,160}$/,f2=/^[a-z0-9][a-z0-9_-]{0,62}$/,b2={name:"ai:chats:create",summary:"start a chat with one of the environment's agents \u2014 optionally on a runner pool and bound to a standalone workspace",usage:"--agent <name> [--pool <pool>] [--workspace <ws_id>] [--title <title>]",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.","--workspace binds an encrypted standalone workspace (palbase workspaces:list, ws_\u2026) to the chat."],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 session runs on, by id or name"},workspace:{type:"string",value:"ws_id",description:"standalone workspace id (ws_\u2026) bound to the chat"},title:{type:"string",value:"title",description:"the chat's title"}},scope:"environment",async run(e){let t=e.flags.agent;if(t===void 0)throw h("--agent names the chat's agent","palbase ai:agents:list");if(!y2.test(t))throw h(`${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&&!ds.test(n))throw h(`${JSON.stringify(n)} is not a runner pool's id or name`,"palbase ai:pools:list");let s=e.flags.workspace;if(s!==void 0&&s.trim()==="")throw h("--workspace is a standalone workspace id (ws_\u2026)","palbase workspaces:list");let a={agent:t};e.flags.title!==void 0&&(a.title=e.flags.title),n!==void 0&&(a.pool=n),s!==void 0&&(a.workspace_id=s);let o=await f(e);await k(e,o,`start a chat with the agent ${t}${n!==void 0?` on the pool ${n}`:""}`);let i=await m(e,o,"POST","/ai/chats",a);e.out.result(i,()=>{e.out.line(`Started the chat ${i.id} with ${i.agent}${i.pool?` on the pool ${i.pool}`:""}${s?` bound to workspace ${s}`:""}.`)})}},w2=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/u,v2="128 bytes at most, no control, format (bidi, zero-width) or line-separator character",k2=e=>Buffer.byteLength(e)<=128&&!w2.test(e);function _2(e){if(e==="cloud"||e==="serverless")return{kind:e};if(e.startsWith("pool:")){let t=e.slice(5);if(!ds.test(t))throw h(`--to ${JSON.stringify(e)}: pool id or name after pool:`);return{kind:"pool",pool_id:t}}if(e.startsWith("machine:")||e.startsWith("mac:")){let t=e.slice(e.indexOf(":")+1);if(!ds.test(t))throw h(`--to ${JSON.stringify(e)}: machine id after machine:`);return{kind:"machine",machine_id:t}}throw h(`--to must be cloud, serverless, pool:<id|name>, or machine:<machine_id> (got ${JSON.stringify(e)})`)}var S2={name:"ai:chats:handoff",summary:"teleport a chat session to another compute target and/or local ACP CLI harness",usage:"<chat id> --to <cloud|serverless|pool:<pool>|machine:<id>> [--harness claude-code|codex|gemini-cli] [--when idle|after_turn|now] [--grace <seconds>] [--model <model>] [--effort <effort>]",details:["Moves the chat session atomically (advancing target_generation so stale writes from the prior target are rejected with 409 superseded).","Leave --harness out to run on the Palbase single engine; pass --harness claude-code, codex, or gemini-cli to execute through a locally installed ACP CLI on an enrolled machine."],args:{min:1,max:1},flags:{to:{type:"string",value:"target",description:"cloud, serverless, pool:<pool>, or machine:<machine_id>"},harness:{type:"string",value:"name",description:"ACP CLI harness: claude-code, codex, or gemini-cli"},when:{type:"string",value:"idle|after_turn|now",description:"when to cut over (default idle)"},grace:{type:"string",value:"seconds",description:"grace window (1\u201360s) when --when now parks a running turn"},model:{type:"string",value:"model",description:"optional default model override on the new target"},effort:{type:"string",value:"effort",description:"optional default reasoning effort override"},"idempotency-key":{type:"string",value:"key",description:"idempotency key so retries never double-teleport"}},scope:"environment",async run(e){let t=_l(e),n=e.flags.to;if(!n)throw h("--to is required: cloud, serverless, pool:<pool>, or machine:<machine_id>");let s=_2(n),a=e.flags.harness;if(a!==void 0&&a!=="claude-code"&&a!=="codex"&&a!=="gemini-cli")throw h("--harness must be claude-code, codex, or gemini-cli");let o=e.flags.when;if(o!==void 0&&o!=="idle"&&o!=="after_turn"&&o!=="now")throw h("--when must be idle, after_turn, or now");let i=qt(e.flags.grace,"grace");if(i!==void 0&&i>60)throw h("--grace is 1 to 60 seconds");let r=a!==void 0?{kind:"acp",harness:a}:{kind:"palbase"};typeof e.flags.model=="string"&&e.flags.model!==""&&(r.model=e.flags.model),typeof e.flags.effort=="string"&&e.flags.effort!==""&&(r.effort=e.flags.effort);let l={to:{compute:s,executor:r},...o!==void 0?{when:o}:{},...i!==void 0?{grace_seconds:i}:{},...typeof e.flags["idempotency-key"]=="string"?{idempotency_key:e.flags["idempotency-key"]}:{}},p=await f(e);await k(e,p,`hand off the chat ${t} to ${n}${a?` (${a})`:""}`);let d=await m(e,p,"POST",`/ai/chats/${A(t)}/handoff`,l);e.out.result(d,()=>{let u=d.target.executor.kind==="acp"?`acp:${d.target.executor.harness??""}`:"palbase",g=d.target.compute.machine_id?`${d.target.compute.kind}:${d.target.compute.machine_id}`:d.target.compute.pool_id?`${d.target.compute.kind}:${d.target.compute.pool_id}`:d.target.compute.kind;e.out.line(`Handed off ${d.chat_id} to ${g} (${u}) \u2014 generation ${d.target_generation}, workspace seq ${d.workspace_seq}, action ${d.active_run_action}.`)})}},$2={name:"ai:chats:execution",summary:"show a chat's current execution target, target generation, machine online status, harnesses, and auto-failover state",usage:"<chat id>",args:{min:1,max:1},scope:"environment",async run(e){let t=_l(e),n=await f(e),s=await m(e,n,"GET",`/ai/chats/${A(t)}/execution`);e.out.result(s,()=>{let a=s.target.executor.kind==="acp"?`acp:${s.target.executor.harness??""}`:"palbase";e.out.line(`${s.chat_id} generation ${s.target_generation}`),e.out.line(`compute ${s.target.compute.kind}${s.target.compute.machine_id?` (${s.target.compute.machine_id})`:s.target.compute.pool_id?` (${s.target.compute.pool_id})`:""}`),e.out.line(`executor ${a}${s.target.executor.model?` model ${s.target.executor.model}`:""}`),s.workspace_id&&e.out.line(`workspace ${s.workspace_id} (seq ${s.workspace_seq})`),s.machine_status&&e.out.line(`machine ${s.machine_name??s.target.compute.machine_id??"-"} (${s.machine_status})${s.failover_at?`, failover at ${s.failover_at}`:""}`),s.auto_failover&&e.out.line(`failover after ${s.auto_failover.after_offline_seconds}s offline -> ${s.auto_failover.to.compute.kind}/${s.auto_failover.to.executor.kind}`),s.pending_handoff&&e.out.line(`pending -> ${s.pending_handoff.to.compute.kind}/${s.pending_handoff.to.executor.kind} (${s.pending_handoff.reason})`)})}},A2={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 f(e),{endpoints:n}=await m(e,t,"GET","/ai/endpoints"),s=n.map(({signing_secret:a,...o})=>o);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}])})}},P2={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=xn(e,"an endpoint"),n=await f(e);await k(e,n,`forget the endpoint ${t}`),await m(e,n,"DELETE",`/ai/endpoints/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`Forgot the endpoint ${t}.`))}};function fi(e,t=0){let n=e.args[t];if(!f2.test(n))throw h(`${JSON.stringify(n)} is not a runtime environment's name: lowercase letters, digits, _ and -, at most 63`);return n}var R2={name:"ai:environments:list",summary:"list the project's runtime environments (ephemeral or always_on)",scope:"environment",async run(e){let t=await f(e),{environments:n}=await m(e,t,"GET","/ai/environments");e.out.result({environments:n},()=>{n.length===0&&e.out.line("No runtime environment."),e.out.table(n,[{header:"name",value:s=>s.name},{header:"mode",value:s=>s.mode},{header:"isolation",value:s=>s.isolation},{header:"runtime",value:s=>s.runtime.vm_profile??s.runtime.image??"dockerfile"},{header:"egress",value:s=>s.network.egress??"default"},{header:"palbase db",value:s=>s.network.allow_palbase_db?"yes":"no"}])})}},j2={name:"ai:environments:get",summary:"inspect one runtime environment by name",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=fi(e),n=await f(e),s=await m(e,n,"GET",`/ai/environments/${A(t)}`);e.out.result(s,()=>{e.out.line(`${s.name} mode ${s.mode} isolation ${s.isolation}`),e.out.line(`runtime ${s.runtime.vm_profile?`vm:${s.runtime.vm_profile}`:s.runtime.image??"dockerfile"}`),e.out.line(`resources cpu=${s.resources.cpu??"-"} mem=${s.resources.memory_mb??"-"}MB disk=${s.resources.disk_mb??"-"}MB idle=${s.resources.idle_timeout_seconds??0}s`),e.out.line(`scaling min_warm=${s.scaling.min_warm??0} max=${s.scaling.max_instances??"-"}`),e.out.line(`network egress=${s.network.egress??"default"} allow_palbase_db=${s.network.allow_palbase_db?"true":"false"}`)})}},E2={name:"ai:environments:put",summary:"create or update a runtime environment (ephemeral or always_on)",usage:"<name> [--mode ephemeral|always_on] [--isolation strict|relaxed] [--image <image>] [--vm-profile macos-xcode|linux-vm] [--cpu <n>] [--memory-mb <n>] [--disk-mb <n>] [--idle-timeout <seconds>] [--min-warm <n>] [--max-instances <n>] [--egress default|restricted|none] [--allow-palbase-db] [--allow-host <host>]\u2026 [--setup <cmd>]\u2026",args:{min:1,max:1},flags:{mode:{type:"string",value:"ephemeral|always_on",description:"lifecycle mode (always_on never auto-parks)"},isolation:{type:"string",value:"strict|relaxed",description:"minimum sandbox isolation posture"},image:{type:"string",value:"image",description:"base OCI container image"},"vm-profile":{type:"string",value:"macos-xcode|linux-vm",description:"Virtualization.framework VM profile"},cpu:{type:"string",value:"n",description:"vCPU count"},"memory-mb":{type:"string",value:"mb",description:"memory limit in MiB"},"disk-mb":{type:"string",value:"mb",description:"encrypted workspace disk budget in MiB"},"idle-timeout":{type:"string",value:"seconds",description:"idle timeout before parking (0 for always_on)"},"min-warm":{type:"string",value:"n",description:"minimum pre-warmed instances"},"max-instances":{type:"string",value:"n",description:"maximum concurrent instances"},egress:{type:"string",value:"default|restricted|none",description:"outbound network egress policy"},"allow-palbase-db":{type:"boolean",description:"allow TLS/SSLRequest connectivity to project Palbase Postgres DBs"},"allow-host":{type:"string",multiple:!0,value:"host",description:"allowlisted hostname when egress is restricted"},setup:{type:"string",multiple:!0,value:"cmd",description:"setup command executed when baking/initializing"}},scope:"environment",async run(e){let t=fi(e),n=e.flags.mode;if(n!==void 0&&n!=="ephemeral"&&n!=="always_on")throw h("--mode must be ephemeral or always_on");let s=e.flags.isolation;if(s!==void 0&&s!=="strict"&&s!=="relaxed")throw h("--isolation must be strict or relaxed");let a=e.flags["vm-profile"];if(a!==void 0&&a!=="macos-xcode"&&a!=="linux-vm")throw h("--vm-profile must be macos-xcode or linux-vm");let o=e.flags.egress;if(o!==void 0&&o!=="default"&&o!=="restricted"&&o!=="none")throw h("--egress must be default, restricted, or none");let i={};n!==void 0&&(i.mode=n),s!==void 0&&(i.isolation=s);let r={};e.flags.image!==void 0&&(r.image=e.flags.image),a!==void 0&&(r.vm_profile=a);let l=Me(e.flags.setup);l&&l.length>0&&(r.setup=l),Object.keys(r).length>0&&(i.runtime=r);let p={},d=qt(e.flags.cpu,"cpu");d!==void 0&&(p.cpu=d);let u=qt(e.flags["memory-mb"],"memory-mb");u!==void 0&&(p.memory_mb=u);let g=qt(e.flags["disk-mb"],"disk-mb");g!==void 0&&(p.disk_mb=g);let y=we(e.flags["idle-timeout"],"idle-timeout");y!==void 0&&(p.idle_timeout_seconds=y),Object.keys(p).length>0&&(i.resources=p);let w={},v=we(e.flags["min-warm"],"min-warm");v!==void 0&&(w.min_warm=v);let R=qt(e.flags["max-instances"],"max-instances");R!==void 0&&(w.max_instances=R),Object.keys(w).length>0&&(i.scaling=w);let P={};o!==void 0&&(P.egress=o),e.flags["allow-palbase-db"]===!0&&(P.allow_palbase_db=!0);let E=Me(e.flags["allow-host"]);E&&E.length>0&&(P.allow_hosts=E),Object.keys(P).length>0&&(i.network=P);let T=await f(e);await k(e,T,`save the runtime environment ${t}`);let C=await m(e,T,"PUT",`/ai/environments/${A(t)}`,i);e.out.result(C,()=>e.out.line(`Saved runtime environment ${C.name} (${C.mode}, ${C.isolation}).`))}},T2={name:"ai:environments:delete",summary:"delete a runtime environment and its build records",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=fi(e),n=await f(e);await k(e,n,`delete the runtime environment ${t}`),await m(e,n,"DELETE",`/ai/environments/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`Deleted runtime environment ${t}.`))}},C2={name:"ai:environments:build",summary:"queue an immutable pre-bake build for a runtime environment",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=fi(e),n=await f(e);await k(e,n,`queue a build for runtime environment ${t}`);let s=await m(e,n,"POST",`/ai/environments/${A(t)}/builds`);e.out.result(s,()=>e.out.line(`Queued build ${s.build_id} for ${s.environment_name} (${s.status}).`))}},O2={name:"ai:environments:build:get",summary:"read the status of a runtime environment build",usage:"<name> <build_id>",args:{min:2,max:2},scope:"environment",async run(e){let t=fi(e,0),n=e.args[1];if(!ds.test(n))throw h(`${JSON.stringify(n)} is not a build id`);let s=await f(e),a=await m(e,s,"GET",`/ai/environments/${A(t)}/builds/${A(n)}`);e.out.result(a,()=>{e.out.line(`${a.build_id} ${a.environment_name} status=${a.status}`),a.image_digest&&e.out.line(`digest ${a.image_digest}`),a.error_message&&e.out.line(`error ${a.error_message}`)})}};function Sl(e){let t=e.args[0];if(!ds.test(t))throw h(`${JSON.stringify(t)} is not a runner pool's id or name`,"palbase ai:pools:list");return t}function $l(e){let t=e.args[0];if(!ds.test(t))throw h(`${JSON.stringify(t)} is not a machine's id`,"palbase ai:pools:state <pool> lists its machines");return t}function x2(e){if(!(e instanceof G))return e;switch(e.code){case"pool_not_empty":return new b(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 b(e.code,e.message,{hint:"palbase ai:machines:cordon <id> first"});case"machine_busy":return new b(e.code,e.message,{hint:"delete it once ai:pools:state <pool> says it holds none (used 0)"});case"pool_exists":return new b(e.code,e.message,{hint:"palbase ai:pools:list"});default:return e}}async function ya(e,t,n,s,a){try{return await m(e,t,n,s,a)}catch(o){throw x2(o)}}var L2={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 palbase-agent 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=xn(e,"a pool"),n=e.flags.os,s=e.flags.arch;if(n!=="linux"&&n!=="macos")throw h("--os is the pool's machines' operating system: linux or macos");if(s!=="amd64"&&s!=="arm64")throw h("--arch is the pool's machines' architecture: amd64 or arm64");let a=await f(e);await k(e,a,`make the runner pool ${t} (${n}/${s})`);let o=await ya(e,a,"POST","/ai/pools",{name:t,os:n,arch:s});e.out.result(o,()=>{e.out.line(`Made the pool ${o.name} (${o.id}), ${o.os}/${o.arch}.`),e.out.line(`Enrol a machine: palbase ai:pools:keys:create ${o.name}`)})}},I2={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 f(e),{pools:n}=await m(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)}])})}},N2={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=Sl(e),n=await f(e);await k(e,n,`delete the runner pool ${t}`),await ya(e,n,"DELETE",`/ai/pools/${A(t)}`),e.out.result({deleted:t},()=>e.out.line(`Deleted the pool ${t}.`))}},M2={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=Sl(e),n=await f(e),s=await m(e,n,"GET",`/ai/pools/${A(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??"-"}])})}},D2={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: palbase-agent 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=Sl(e),n=e.flags.label;if(n!==void 0&&!k2(n))throw h(`--label is ${v2}`);let s=await f(e);await k(e,s,`mint a key a machine enrols into the pool ${t} with`);let a=await ya(e,s,"POST",`/ai/pools/${A(t)}/keys`,n!==void 0?{label:n}:{});if(typeof a.key!="string"||a.key==="")throw new b("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 o=a.enroll_url??a.enroll?.url??"<enroll_url>",i=`${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: palbase-agent enroll --url ${o} --key-file <file> --capacity <n>${i}`),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}`)})}},z2={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=Sl(e),n=await f(e),{keys:s}=await m(e,n,"GET",`/ai/pools/${A(t)}/keys`),a=s.map(({key:o,...i})=>i);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:o=>o.id},{header:"label",value:o=>o.label??""},{header:"minted",value:o=>o.created_at??"-"},{header:"expires",value:o=>o.expires_at??"-"},{header:"last used",value:o=>o.last_used_at??"-"},{header:"revoked",value:o=>o.revoked_at??"-"}])})}},q2={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(!ds.test(t))throw h(`${JSON.stringify(t)} is not a key's id`,"palbase ai:pools:keys:list <pool>");let n=await f(e);await k(e,n,`revoke the enrolment key ${t}`),await ya(e,n,"POST",`/ai/pool-keys/${A(t)}/revoke`),e.out.result({revoked:t},()=>e.out.line(`Revoked ${t}: no machine enrols with it any more.`))}},G2={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=$l(e),n=await f(e);await k(e,n,`cordon the machine ${t}`),await ya(e,n,"POST",`/ai/machines/${A(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}`))}},K2={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=$l(e),n=await f(e);await k(e,n,`let the machine ${t} take sessions again`),await ya(e,n,"POST",`/ai/machines/${A(t)}/resume`),e.out.result({resumed:t},()=>e.out.line(`${t} takes sessions again.`))}},U2={name:"ai:machines:delete",summary:"delete a cordoned machine that holds no session from its runner pool: its palbase-agent is refused from then",usage:"<machine id>",args:{min:1,max:1},scope:"environment",async run(e){let t=$l(e),n=await f(e);await k(e,n,`delete the machine ${t} from its pool`),await ya(e,n,"DELETE",`/ai/machines/${A(t)}`),e.out.result({deleted:t},()=>e.out.line(`Deleted ${t}: its palbase-agent is refused from now.`))}},W2={name:"ai:machines:harnesses",summary:"list locally installed ACP CLI harnesses (claude-code, codex, gemini-cli) reported by palbase-agent on a machine",usage:"<machine id> [--pool <pool>]",args:{min:1,max:1},flags:{pool:{type:"string",value:"pool",description:"the machine's runner pool (optional; searches all pools when omitted)"}},scope:"environment",async run(e){let t=$l(e),n=e.flags.pool;if(n!==void 0&&!ds.test(n))throw h(`${JSON.stringify(n)} is not a runner pool's id or name`,"palbase ai:pools:list");let s=await f(e),a,o=n??"";if(n!==void 0){let r=await m(e,s,"GET",`/ai/pools/${A(n)}/state`);a=r.machines.find(l=>l.id===t),o=r.pool.name}else{let{pools:r}=await m(e,s,"GET","/ai/pools");for(let l of r){let p=await m(e,s,"GET",`/ai/pools/${A(l.id)}/state`),d=p.machines.find(u=>u.id===t);if(d){a=d,o=p.pool.name;break}}}if(!a)throw new b("machine_not_found",`no machine ${t} in the environment's runner pools`,{hint:"palbase ai:pools:list"});let i=a.harnesses??[];e.out.result({machine_id:a.id,pool:o,state:a.state,harnesses:i},()=>{if(e.out.line(`${a.id}${a.label?` (${a.label})`:""} pool ${o} ${a.state}`),i.length===0){e.out.line("No ACP CLI harnesses reported by palbase-agent yet.");return}e.out.table(i,[{header:"harness",value:r=>r.name},{header:"status",value:r=>r.status},{header:"cli",value:r=>r.cli_version??"-"},{header:"acp",value:r=>r.acp_version??"-"}])})}},F2=/^[A-Z][A-Z0-9_]{0,127}$/,$w=32768;function nc(e){let t=e.args[0];if(!F2.test(t)||t.startsWith("PALAI_"))throw h(`${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 B2=["header","query","body"],yi="an exact DNS name (api.stripe.com) or *. and one (*.stripe.com: one label more) \u2014 no IP address, port, single-label name or public suffix, and no wildcard over palbase.studio",J2=/^(\*\.)?[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/,Ow=e=>e.length<=253&&J2.test(e);function H2(e){let t=Me(e);if(t!==void 0){if(t.length===1&&t[0]==="none")return[];if(t.length===0)throw h(`--host is a host the secret may go to: ${yi}; --host none takes them all away`);return t.forEach((n,s)=>{if(!Ow(n))throw h(`--host number ${s+1} is no host name: ${yi}; --host none, alone, takes them all away`)}),t}}function V2(e){let t=Me(e);if(t!==void 0){if(t.length===0||t.some(n=>!B2.includes(n)))throw h("--inject is where in a request to one of its hosts the secret may be put: header, query or body (repeat it for several)");return t}}var X2="an open secret is read by the agent as it is: anyone who can drive the environment's agents \u2014 an app's user where the environment lets them (ai:settings:set --open-secrets-for-app-users), a prompt the agent reads \u2014 can get its value",Y2="a variable that is no secret is read by the agent as it is: anyone who can drive the environment's agents \u2014 an app's user where the environment lets them, a prompt the agent reads \u2014 can get its value",xw="looks like a value a person chose (fewer than 16 characters, or one kind of character only): the proxy hides a sealed value an allowed host echoes back, which lets an agent confirm a guess there";async function Aw(e,t,n="open"){let s=n==="open"?`${t} would be open: ${X2}`:`${t} is a secret and would be no secret: ${Y2}`,a=n==="open"?"--open --acknowledge-open":"--value-stdin --not-secret --acknowledge-open < value.txt";if(!e.interactive)throw new b("open_not_acknowledged",s,{hint:`say you read it: palbase ai:env:set ${t} ${a} (-y does not say it)`});e.out.warn(s);let o=(await e.io.prompt(n==="open"?`Make ${t} open? [y/N] `:`Make ${t} no secret? [y/N] `)).trim().toLowerCase();if(o!=="y"&&o!=="yes")throw new b("cancelled","nothing was changed")}async function Z2(e,t){e.out.warn(`${t}'s value ${xw}`);let n=(await e.io.prompt(`Keep ${t} sealed anyway? [y/N] `)).trim().toLowerCase();if(n!=="y"&&n!=="yes")throw new b("cancelled","nothing was changed",{hint:`a random key is never one: palbase ai:env:set ${t} --value-stdin < key.txt`})}async function Q2(e,t,n){let{variables:s}=await m(e,t,"GET","/ai/env");return s.some(a=>a.key===n&&a.secret)}function Qd(e){let t=e.hosts??[];return e.secret?e.open?"an open secret: the agent reads it as it is":t.length===0?"a sealed secret with no host yet":`a sealed secret for ${t.join(", ")}, put in ${(e.inject??[]).join(", ")}`:"no secret"}function Pw(e){let t=[];return e.hosts!==void 0&&t.push(e.hosts.length===0?"no host":`its hosts ${e.hosts.join(", ")}`),e.inject!==void 0&&t.push(`put in ${e.inject.join(", ")}`),e.open===!0&&t.push("open: the agent reads it as it is"),t.join("; ")}function eO(e,t,n,s){if(!(e instanceof G))return e;switch(e.code){case"open_not_acknowledged":return new b(e.code,e.message,{hint:`say you read it: palbase ai:env:set ${t} ${s?"--value-stdin --not-secret --acknowledge-open < value.txt":"--open --acknowledge-open"}`});case"secret_unusable":return new b(e.code,`${t} cannot be kept sealed: ${e.message}`,{hint:n?`a sealed secret's value is 8 bytes or more on one line. A value that is no secret (a region, a scheme): palbase ai:env:set ${t} --value-stdin --not-secret < value.txt; one the agent may read as it is: --open --acknowledge-open`:`sealed, it needs a value of 8 bytes or more on one line: palbase ai:env:set ${t} --value-stdin --host <host> < value.txt`});case"secret_guessable":return new b(e.code,`${t}'s value ${xw}`,{hint:`use a random key \u2014 or keep it sealed anyway: palbase ai:env:set ${t}${n?" --value-stdin":""} --acknowledge-guessable \u2026${n?" < value.txt":""} (or your yes at a terminal; -y does not say it); an open secret: --open --acknowledge-open`})}return n?e:e.code==="value_required"?new b(e.code,`${t} would be sealed: a sealed secret is set with its value, which the platform judges \u2014 never one it keeps`,{hint:`give it again: palbase ai:env:set ${t} --value-stdin --host <host> \u2026 < value.txt`}):e.code==="person_required"||e.code==="token_out_of_scope"?ro(e,`change what ${t} says of itself without its value`,`say it with its value: palbase ai:env:set ${t} --value-stdin \u2026 < value.txt`):e.status===404?new b(e.code,`${t} is not set: what a secret says of itself is changed without its value only for one set before`,{hint:`set it with its value: palbase ai:env:set ${t} --value-stdin \u2026 < value.txt`}):e.code==="not_a_secret"?new b(e.code,`${t} is no secret: a variable the agent reads as it is has no hosts, no inject and no class`,{hint:`make it a secret with its value: palbase ai:env:set ${t} --value-stdin --host <host> < value.txt`}):e}var tO={name:"ai:env:set",summary:"set a variable every session of the environment's agents has, and say where a secret may go: its value piped in or typed unseen, never shown or put on the command line",usage:"<KEY> [--value-stdin] [--not-secret [--acknowledge-open]] [--host <host>]\u2026 [--inject header|query|body]\u2026 [--open --acknowledge-open] [--acknowledge-guessable] < 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: it is given to the agent as it is, with no hosts, never open; its value is masked and never shown either way. A secret made none is said with --acknowledge-open, or your yes at the terminal once the warning is shown; a new variable needs neither.",`A secret is sealed (the default) or open. A sealed one says the hosts a request may carry it to (--host, 32 at most: ${yi}) and where in such a request it may be put (--inject: header, the default; query; body \u2014 never over plain http). Nothing of how a value is delivered changes until the proxy beside the machines swaps a sealed secret in only on a request to one of its hosts: one with no host yet is delivered as it is.`,"A sealed value is 8 bytes or more on one line (secret_unusable): a short one that is no secret \u2014 a region, a scheme \u2014 is set with --not-secret. One the platform finds a person may have chosen (fewer than 16 characters, or one kind of character only: secret_guessable) is kept sealed with --acknowledge-guessable, or with your yes at the terminal once the platform has said so; -y does not say it.","--host names all its hosts, those it had replaced \u2014 --host none takes them all away, and a sealed secret is made of an open one; ai:env:hosts:allow adds one.","--open: the agent reads it as it is, with no hosts and no inject \u2014 so anyone who can drive the environment's agents can get its value. Said with --acknowledge-open, or with your yes at the terminal once the warning is shown; -y does not say it.","--host, --inject or --open without --value-stdin changes what a variable set before says of itself and keeps its value (what is not given stays as it is): a person's change alone \u2014 an owner or an admin of the organization signed in as themselves (palbase login), never a key or a token (PALBASE_TOKEN), which say them with the value."],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:"it is no secret (its value is never shown either way)"},host:{type:"string",multiple:!0,value:"host",description:"a host a request may carry the secret to (repeat for several; none: no host)"},inject:{type:"string",multiple:!0,value:"header|query|body",description:"where in a request to one of its hosts it may be put (repeat for several)"},open:{type:"boolean",description:"the agent reads it as it is: no hosts, no inject"},"acknowledge-open":{type:"boolean",description:"say you read that anyone who can drive the agents can get an open secret's value (or a secret made none's)"},"acknowledge-guessable":{type:"boolean",description:"keep a value a person may have chosen sealed: say you read that an agent can confirm a guess at an allowed host"}},scope:"environment",async run(e){let t=nc(e),n=H2(e.flags.host),s=V2(e.flags.inject),a=e.flags.open===!0,o=e.flags["not-secret"]===!0,i=e.flags["acknowledge-open"]===!0,r=e.flags["acknowledge-guessable"]===!0;if(i&&!a&&!o)throw h("--acknowledge-open goes with --open, or with --not-secret: it says you read what the agent reading it as it is means");if(a&&(n!==void 0||s!==void 0))throw h("an open secret is read by the agent as it is: it has no hosts and no inject \u2014 --open, or --host and --inject for a sealed one");let l=n!==void 0||s!==void 0||a;if(o&&l)throw h("a variable that is no secret (--not-secret) is given to the agent as it is: it has no hosts, no inject, and is never open");if(r&&(a||o))throw h("--acknowledge-guessable is a sealed value's: an open secret's value and one that is no secret's are the agent's to read, and the platform judges neither");let p=e.flags["value-stdin"]===!0||!l;if(p&&e.flags["value-stdin"]!==!0&&!e.interactive)throw h(`${t}'s value is read from stdin`,`pipe it in: palbase ai:env:set ${t} --value-stdin < value.txt`);p||io(e,`change what ${t} says of itself without its value`,`say it with its value: palbase ai:env:set ${t} --value-stdin \u2026 < value.txt`),a&&!i&&await Aw(e,t);let d=await f(e),u=o&&(i||await Q2(e,d,t)&&(await Aw(e,t,"plain"),!0)),g={};if(p){let v=await lt(e,`${t}'s value`);if(Buffer.byteLength(v)>$w||v.includes("\0"))throw h(`${t}'s value is 1 to ${$w} bytes, no NUL`);g.value=v}o&&(g.secret=!1),n!==void 0&&(g.hosts=n),s!==void 0&&(g.inject=s),(a||u)&&(g.acknowledge_open=!0),a&&(g.open=!0),r&&(g.acknowledge_guessable=!0),await k(e,d,p?`set the variable ${t} for every session of the environment's agents${l?`: ${Pw(g)}`:""}`:`change what ${t} says of itself, its value kept: ${Pw(g)}`);let y=async()=>{try{return await m(e,d,"PUT",`/ai/env/${A(t)}`,g)}catch(v){if(v instanceof G&&v.code==="secret_guessable"&&e.interactive&&g.acknowledge_guessable!==!0)return await Z2(e,t),g.acknowledge_guessable=!0,y();throw eO(v,t,p,o)}},w=await y();e.out.result(w,()=>e.out.line(p?`Set ${w.key} (${Qd(w)}): every session begun from now has it. Its value is kept sealed, never shown.`:`${w.key} is ${Qd(w)} now; its value is as it was.`))}},nO={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=nc(e),n=await f(e);await k(e,n,`remove the variable ${t}`),await m(e,n,"DELETE",`/ai/env/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`Removed ${t}: sessions begun from now no longer have it.`))}},sO={name:"ai:env:list",summary:"the variables every session of the environment's agents has: their names, whether each is a secret \u2014 sealed, with the hosts it may go to and where it is put, or open \u2014 and when each was set: never a value",scope:"environment",async run(e){let t=await f(e),{variables:n}=await m(e,t,"GET","/ai/env"),s=a=>a.secret&&!a.open;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:a=>a.key},{header:"secret",value:a=>a.secret?a.open?"open":"sealed":"no"},{header:"hosts",value:a=>s(a)?(a.hosts??[]).length===0?"none yet":a.hosts.join(", "):"-"},{header:"inject",value:a=>s(a)?(a.inject??[]).join(", "):"-"},{header:"value",value:()=>"set"},{header:"updated",value:a=>a.updated_at}])})}},aO=/^shr_[A-Za-z0-9]{1,156}$/,oO=/^sha_[A-Za-z0-9]{1,156}$/,kl="allow a host for a secret";function iO(e,t,n){if(!(e instanceof G))return e;switch(e.code){case"not_a_sealed_secret":return new b(e.code,`${t} is no sealed secret: only a sealed secret has hosts \u2014 it is no secret, or an open one the agent reads as it is`,{hint:`palbase ai:env:list says which: an open one is sealed with its hosts (palbase ai:env:set ${t} --host ${n}); one that is no secret is set again as a secret (palbase ai:env:set ${t} --value-stdin --host ${n} < value.txt)`});case"too_many_hosts":return new b(e.code,`${t} is allowed for 32 hosts at most`,{hint:`name those it keeps: palbase ai:env:set ${t} --host <host> --host <host>\u2026 (palbase ai:env:list shows them)`});case"person_required":case"token_out_of_scope":return ro(e,kl);default:return e.status===404?new b(e.code,`${t} is not set`,{hint:"palbase ai:env:list"}):e}}function rO(e,t){if(!(e instanceof G))return e;switch(e.code){case"not_a_sealed_secret":return new b(e.code,`the secret the ask ${t} names is no sealed secret now: only a sealed secret has hosts \u2014 it is no secret, or an open one the agent reads as it is`,{hint:"palbase ai:env:list says which"});case"too_many_hosts":return new b(e.code,"its variable is allowed for 32 hosts at most",{hint:"name those it keeps: palbase ai:env:set <KEY> --host <host> --host <host>\u2026 (palbase ai:env:list shows them)"});case"too_many_allowances":return new b(e.code,"the environment's allowances for its agents' own secrets hold 500 hosts at most",{hint:"take one away first: palbase ai:env:hosts:allowances, then palbase ai:env:hosts:allowances:remove <allowance id>"});case"already_allowed":return new b(e.code,`the ask ${t} was allowed already: a host taken away from its secret since is asked again by its next request, and allowed from that ask`,{hint:"palbase ai:env:hosts:requests"});case"person_required":case"token_out_of_scope":return ro(e,kl);default:return e.status===404?new b(e.code,`the ask ${t} cannot be allowed: ${e.message} \u2014 no such ask, or the variable it names is no longer set`,{hint:"palbase ai:env:hosts:requests, palbase ai:env:list"}):e}}var lO={name:"ai:env:hosts:allow",summary:"allow an ask \u2014 its host for its secret, a project's variable's or an agent's own \u2014 or let a variable's sealed secret go to one more host: only a host you know the secret belongs to",usage:"<request id> | <KEY> <host>",details:["An agent can be led to send a secret anywhere: allow only a host you know the secret belongs to. palbase ai:env:hosts:requests lists the hosts the secrets were sent to that they are not allowed for, each by its request id.","<request id> (shr_\u2026) allows any ask: its host goes on the variable's hosts (one of the environment's), or on the environment's allowances (an agent's own secret: palbase ai:env:hosts:allowances), and the asks it now allows are marked allowed.",`<KEY> <host> lets one of the environment's variables go to a host no ask named. A host is ${yi}; a variable has 32 at most \u2014 ai:env:set <KEY> --host \u2026 names them all.`,"A person's alone: an owner or an admin of the organization signed in as themselves (palbase login), never a key or a token (PALBASE_TOKEN) \u2014 refused before anything is sent."],args:{min:1,max:2},scope:"environment",async run(e){if(e.args.length===1){let o=e.args[0];if(!aO.test(o))throw h(`${JSON.stringify(o.slice(0,40))} is not an ask's id (shr_\u2026): an ask is allowed by its id, a variable's host as <KEY> <host>`,"palbase ai:env:hosts:requests");io(e,kl);let i=await f(e),r=await mO(e,i,o);if(!r)throw new b("not_found",`no ask ${o} to allow: an ask is allowed from what it says, and none of that id is listed`,{hint:"palbase ai:env:hosts:requests --status asked|dismissed"});if(r.status==="allowed")throw new b("already_allowed",`the ask ${o} was allowed already: a host taken away from its secret since is asked again by its next request, and allowed from that ask`,{hint:"palbase ai:env:hosts:requests"});let l=uO(r);if("refused"in l)throw new b("ask_not_allowable",`the ask ${o} is not allowed from here: ${l.refused}`,{hint:"look at it in Studio (AI \u203A Secrets) \u2014 dismiss it if you do not know why a secret was sent there (palbase ai:env:hosts:dismiss <request id>)"});let p=l.domain!==r.host?` \u2014 a name under ${l.domain}, whoever holds ${l.domain} runs it`:"",d=r.origin==="chat"&&r.agent?`; it covers every chat that defines an agent named ${r.agent}, not one chat alone`:"",u=`allow the ask ${o}: ${r.key} may go to ${r.host}${p}${d}`;await k(e,i,u);let g;try{g=await m(e,i,"POST",`/ai/env/host-requests/${A(o)}/allow`)}catch(y){throw rO(y,o)}e.out.result(g,()=>e.out.line(g.agent===null?`Allowed ${I(g.host)} for ${I(g.key)}: one of its hosts now (palbase ai:env:list).`:`Allowed ${I(g.host)} for ${I(sc(g.origin,g.agent))}'s ${I(g.key)}: on the environment's allowances (palbase ai:env:hosts:allowances).`));return}let t=nc(e),n=e.args[1];if(!Ow(n))throw h(`the host is no host name: ${yi}`);io(e,kl);let s=await f(e);await k(e,s,`let ${t} go to ${n}`);let a;try{a=await m(e,s,"POST",`/ai/env/${A(t)}/hosts`,{host:n})}catch(o){throw iO(o,t,n)}e.out.result(a,()=>e.out.line(`Allowed ${n} for ${a.key}: ${Qd(a)}.`))}},pO=["asked","allowed","dismissed"];function sc(e,t){return e==="chat"?`chat-defined agent ${t}`:e==="backend"?`backend agent ${t}`:`agent ${t}`}var dO=/^[A-Z][A-Z0-9_]{0,127}$/,cO=/^[a-z][a-z0-9_-]{0,63}$/,bl=e=>I(JSON.stringify(e)??String(e));function uO(e){let t=[];(typeof e.key!="string"||!dO.test(e.key)||e.key.startsWith("PALAI_"))&&t.push(`its key ${bl(e.key)} is no variable's name`),e.agent!=null&&(typeof e.agent!="string"||!cO.test(e.agent))&&t.push(`its agent ${bl(e.agent)} is no agent's name`);let n=typeof e.host=="string"?yl(e.host):void 0;return n===void 0?t.push(`its host ${bl(e.host)} is no host a secret is allowed for`):e.domain!=null&&e.domain!==""&&e.domain!==n&&t.push(`the domain it names, ${bl(e.domain)}, is not ${n}, the one its host is under`),t.length>0||n===void 0?{refused:t.join("; ")}:{domain:n}}async function mO(e,t,n){for(let s of["asked","dismissed","allowed"]){let{requests:a}=await m(e,t,"GET",`/ai/env/host-requests${cs({status:s})}`),o=a.find(i=>i.request_id===n);if(o)return o}}var gO={name:"ai:env:hosts:requests",summary:"the hosts the environment's sealed secrets were sent to that they are not allowed for \u2014 each secret and host once, how many times, newest first",usage:"[--status asked|allowed|dismissed]",details:["The placeholder went as it is, and the organization's owners are emailed at most once a day for each (3 a day for one secret, 10 an environment a day). Nobody has checked who runs a host listed here: each is shown with the registrable domain it is under \u2014 api.stripe.com.evil.io is evil.io's \u2014, which an Allow hands the secret to.","Allow one only if you know the host is the secret's: palbase ai:env:hosts:allow <request id> \u2014 a project's variable's and an agent's own secret's alike (the agent's goes on the environment's allowances); or dismiss it: palbase ai:env:hosts:dismiss <request id>.","An environment keeps 500 asked, 50 of them a secret and 100 an agent's own secrets: an ask past one forgets an asked one alone \u2014 the secret's own oldest, else the oldest of the secret that holds the most, the one asked last among equals \u2014, never a dismissed or an allowed one (500 of each are kept)."],flags:{status:{type:"string",value:"asked|allowed|dismissed",description:"the asks of that status (default asked)"}},scope:"environment",async run(e){let t=e.flags.status;if(t!==void 0&&!pO.includes(t))throw h("--status is asked (the default), allowed or dismissed");let n=await f(e),{requests:s}=await m(e,n,"GET",`/ai/env/host-requests${cs({status:t})}`),a=(t??"asked")==="asked";e.out.result({requests:s},()=>{if(s.length===0){e.out.line(a?"No host asked for: no sealed secret was sent where it is not allowed.":`No ask ${t}.`);return}e.out.table(s,[{header:"request id",value:o=>o.request_id},{header:"key",value:o=>o.key},{header:"of",value:o=>o.agent===null?"the environment":sc(o.origin,o.agent)},{header:"domain",value:o=>yl(o.host)??"?"},{header:"host",value:o=>o.host},{header:"asks",value:o=>String(o.asks)},{header:"last asked",value:o=>o.last_asked_at},...a?[]:[{header:t,value:o=>o.decided_at??"-"}]]),a&&(e.out.line(),e.out.line("Allow one only if you know the host is the secret's \u2014 an agent can be led to send a secret anywhere: palbase ai:env:hosts:allow <request id>. Dismiss one: palbase ai:env:hosts:dismiss <request id>."),s.some(o=>o.agent!==null)&&e.out.line("An agent's own secret is allowed the same way: its host goes on the environment's allowances (palbase ai:env:hosts:allowances) \u2014 or name it in the agent's definition: env.<KEY>.hosts."))})}},hO={name:"ai:env:hosts:dismiss",summary:"dismiss an ask: its owners are never told of it again (it is still counted)",usage:"<request id>",details:["One allowed is not undone here: its host is the secret's \u2014 ai:env:set <KEY> --host \u2026 names those a variable keeps (--host none: none); an agent's is taken away from the allowances (ai:env:hosts:allowances:remove).","A person's alone: an owner or an admin of the organization signed in as themselves, never a key or a token (PALBASE_TOKEN)."],args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0];if(!ds.test(t))throw h(`${JSON.stringify(t)} is not an ask's id (shr_\u2026)`,"palbase ai:env:hosts:requests");io(e,"dismiss an ask for a secret");let n=await f(e);await k(e,n,`dismiss the ask ${t}`);let s;try{s=await m(e,n,"POST",`/ai/env/host-requests/${A(t)}/dismiss`)}catch(a){throw a instanceof G&&a.code==="already_allowed"?new b(a.code,`the ask ${t} was allowed: its host is the secret's`,{hint:"take it away: a variable's by naming the hosts it keeps (palbase ai:env:set <KEY> --host <host>\u2026, --host none: none); an agent's from the allowances (palbase ai:env:hosts:allowances:remove <allowance id>)"}):a instanceof G&&a.status===404?new b(a.code,`no ask ${t}`,{hint:"palbase ai:env:hosts:requests"}):ro(a,"dismiss an ask for a secret")}e.out.result(s,()=>e.out.line(`Dismissed: ${I(s.key)} sent to ${I(s.host)} is not told again.`))}},yO={name:"ai:env:hosts:allowances",summary:"the hosts the environment's agents' own secrets are allowed beside their definitions': each an owner's Allow of an ask, newest first",details:["An agent's own secret (its definition's env) goes to the hosts its definition names and to those allowed here (palbase ai:env:hosts:allow <request id>). Take one away: palbase ai:env:hosts:allowances:remove <allowance id>.","An environment keeps 500. A new value keeps them; one goes with its key \u2014 a kept agent's once neither its draft nor its version published has it, a chat's own definition's with the last chat that has it, a backend's agent's after 30 days with no turn."],scope:"environment",async run(e){let t=await f(e),{allowances:n}=await m(e,t,"GET","/ai/env/allowances");e.out.result({allowances:n},()=>{if(n.length===0){e.out.line("No allowance: an agent's own secret goes only to the hosts its definition names.");return}e.out.table(n,[{header:"allowance id",value:s=>s.allowance_id},{header:"agent",value:s=>sc(s.origin,s.agent)},{header:"key",value:s=>s.key},{header:"domain",value:s=>yl(s.host)??"?"},{header:"host",value:s=>s.host},{header:"allowed",value:s=>s.allowed_at},{header:"by",value:s=>s.allowed_by}]),e.out.line(),e.out.line("Take one away: palbase ai:env:hosts:allowances:remove <allowance id>.")})}},fO={name:"ai:env:hosts:allowances:remove",summary:"take an allowance away: the agent's secret no longer goes to its host, and a request carrying it there is asked again",usage:"<allowance id>",details:["A person's alone: an owner or an admin of the organization signed in as themselves, never a key or a token (PALBASE_TOKEN)."],args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0];if(!oO.test(t))throw h(`${JSON.stringify(t.slice(0,40))} is not an allowance's id (sha_\u2026)`,"palbase ai:env:hosts:allowances");let n="take an agent's secret's allowance away";io(e,n);let s=await f(e);await k(e,s,`take the allowance ${t} away: its agent's secret no longer goes to its host`);try{await m(e,s,"DELETE",`/ai/env/allowances/${A(t)}`)}catch(a){throw a instanceof G&&a.status===404?new b(a.code,`no allowance ${t}`,{hint:"palbase ai:env:hosts:allowances"}):ro(a,n)}e.out.result({removed:t},()=>e.out.line(`Took ${t} away: a request carrying its secret to its host is asked again.`))}},bO={name:"ai:templates:list",summary:"list the project\u2019s guardrailed client AI templates",args:{min:0,max:0},scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/ai/templates");e.out.result(n.templates,()=>{if(n.templates.length===0){e.out.line("No AI templates yet.");return}e.out.table(n.templates,[{header:"name",value:s=>s.name},{header:"published",value:s=>s.published_version?`v${s.published_version}`:"draft"},{header:"modality",value:s=>s.published?.modality??s.draft?.modality??"-"},{header:"model",value:s=>s.published?.model??s.draft?.model??"-"}])})}},wO={name:"ai:templates:publish",summary:"publish a guardrailed client AI template version so mobile/web apps can call it",usage:"<name> [--version <n>]",args:{min:1,max:1},flags:{version:{type:"string",value:"n",description:"specific version number to publish (defaults to latest draft)"}},scope:"environment",async run(e){let t=xn(e,"a template"),n=qt(e.flags.version,"version"),s=await f(e);await k(e,s,`publish template ${t}`);let a=n!==void 0?{version:n}:{},o=await m(e,s,"POST",`/ai/templates/${A(t)}/publish`,a);e.out.result(o,()=>e.out.line(`Published template ${o.name} as v${o.published_version??"?"}.`))}},vO={name:"ai:templates:rollback",summary:"roll a guardrailed client AI template back to a prior version",usage:"<name> <version>",args:{min:2,max:2},scope:"environment",async run(e){let t=xn(e,"a template"),n=Number(e.args[1]);if(!Number.isInteger(n)||n<1)throw h("version must be a positive integer",`palbase ai:templates:rollback ${t} 1`);let s=await f(e);await k(e,s,`roll template ${t} back to v${n}`);let a=await m(e,s,"POST",`/ai/templates/${A(t)}/rollback`,{version:n});e.out.result(a,()=>e.out.line(`Rolled template ${a.name} back to v${a.published_version??n}.`))}},kO={name:"ai:templates:remove",summary:"delete a guardrailed client AI template and all of its versions",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=xn(e,"a template"),n=await f(e);await k(e,n,`delete template ${t} and all of its versions`),await m(e,n,"DELETE",`/ai/templates/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`Removed template ${t}.`))}},Lw=[qC,UC,GC,WC,FC,BC,VC,XC,ZC,e2,a2,o2,i2,r2,l2,p2,bO,wO,vO,kO,d2,c2,m2,b2,$2,S2,h2,A2,P2,R2,j2,E2,T2,C2,O2,L2,I2,N2,M2,D2,z2,q2,G2,K2,U2,W2,tO,nO,sO,lO,gO,hO,yO,fO];var _O={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 h("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 h("--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((o,i)=>{i>0&&e.out.line(),e.out.line(`${i+1}. ${o.title===o.heading?o.title:`${o.title} \u203A ${o.heading}`}`),e.out.line(` ${o.url}`),e.out.line(),e.out.line(o.text)})})}},Iw=[_O];var Nw=3e4,ac=3,SO=80;async function $O(e,t){let n=[],s;try{s=(await m(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 o of s.slice(0,ac)){n.push(`machine ${o.name}: ${o.state}, size ${o.size}, version ${o.running_version===o.version?o.version:`${o.running_version} \u2192 ${o.version}`}`);let i;try{i=(await m(e,t,"GET",`/machines/${Q("a machine's name",o.name)}/builds?limit=3`)).builds}catch{n.push(" builds: not readable with this sign-in or token");continue}for(let l of i)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(`
|
|
11095
|
+
`))e.out.line(` ${s}`)}var e2={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=xn(e,"an agent"),n=qt(e.flags.version,"version");if(n!==void 0&&e.flags.draft===!0)throw h("--draft or --version, not both");let s=await f(e);if(n!==void 0){let o=await QC(e,s,t,n);e.out.result(o,()=>oo(e,`${t} version ${o.version}, published ${o.published_at} by ${o.published_by}:`,o.definition));return}let a=await m(e,s,"GET",`/ai/agents/${A(t)}`);if(e.flags.draft===!0&&a.source==="code")throw new b("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}: ${Zd(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"?oo(e,`Its last turn${a.defined_at?` (${a.defined_at})`:""} was defined as:`,a.definition):e.flags.draft===!0||a.published===void 0?oo(e,`The draft (revision ${a.revision}):`,a.draft):oo(e,`Version ${a.published_version}, the one its chats talk to:`,a.published)})}};function t2(e){let t=e.indexOf(":"),n=t>0?e.slice(0,t):"",s=e.slice(t+1);if(!kw.includes(n)||s==="")throw h(`--tool is source:name \u2014 ${kw.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 o=s.slice(0,a);if(s=s.slice(a+1),!ec.test(o)||s==="")throw h(`--tool backend:<machine>/<name> names one of the environment's machines and its tool, not ${JSON.stringify(e)}`);return{source:"backend",name:s,machine:o}}async function n2(e){let t={},n=e.flags.from;if(n!==void 0){let a=await _w(e,n,n),o=fl(a)&&fl(a.definition)&&typeof a.name=="string"?a.definition:a;if(!fl(o))throw h(`${n} is an agent's definition: a JSON object { instructions, model, tools, \u2026 }`);t=o}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(t2));let s=e.flags["output-schema"];if(s!==void 0){let a=await _w(e,s,s);if(!fl(a)||a.type!=="object")throw h(`${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 h("an agent the environment keeps names no backend: a backend's agent is its code's (ai.agent)");return t}async function s2(e,t,n){try{let s=await m(e,t,"GET",`/ai/agents/${A(n)}`);return s.source==="platform"&&s.draft&&s.revision!==void 0?{draft:s.draft,revision:s.revision}:void 0}catch(s){if(s instanceof G&&s.status===404)return;throw s}}async function Tw(e,t,n,s,a){try{return await m(e,t,"PUT",`/ai/agents/${A(n)}${cs({revision:a})}`,s)}catch(o){throw Cw(e,o,n,"give the secret's value with it in the definition (env.<KEY>.value)")}}function Cw(e,t,n,s){if(!(t instanceof G))return t;let a=(e.io.env.PALBASE_TOKEN??"")!=="";switch(t.code){case"person_required":return new b(t.code,`${n}'s own secrets: ${t.message}`,{hint:`${a?"sign in as yourself: unset PALBASE_TOKEN, then palbase login":"ask an owner or an admin of the organization to do it, signed in as themselves"} \u2014 or ${s}`});case"secret_unusable":return new b(t.code,`${n}'s own secrets: ${t.message}`,{hint:`a value that is no secret (a region, a scheme) is { "value": "\u2026", "secret": false } in the definition's env; one the agent may read as it is { "value": "\u2026", "open": true, "acknowledge_open": true }`});case"secret_guessable":return new b(t.code,`${n}'s own secrets: ${t.message}`,{hint:`use a random key \u2014 or keep it sealed anyway: "acknowledge_guessable": true beside its value in the definition's env; a value that is no secret: "secret": false`});case"open_not_acknowledged":return new b(t.code,`${n}'s own secrets: ${t.message}`,{hint:`say you read it: "acknowledge_open": true beside it in the definition's env`});default:return t}}async function tc(e,t,n,s){return m(e,t,"POST",`/ai/agents/${A(n)}/publish`,s!==void 0?{revision:s}:{})}var a2={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=xn(e,"an agent"),n=qt(e.flags.revision,"revision"),s=await n2(e);if(Object.keys(s).length===0)throw h("the agent is empty","pass --from <file.json>, or --instructions, --model, --tool\u2026");let a=await f(e),o=e.flags.from===void 0?await s2(e,a,t):void 0,i={...o?.draft,...s},r=e.flags.publish===!0;await k(e,a,`save the draft of the agent ${t}${r?" and publish it":""}`);let l=await Tw(e,a,t,i,n??o?.revision),p=r?await tc(e,a,t,l.revision):l;e.out.result(p,()=>{e.out.line(`Saved the draft of ${t} (revision ${l.revision}).`),r?e.out.line(`Published ${t} as version ${p.published_version}: its chats talk to it from their next turn.`):e.out.line(`${Zd(p)[0].toUpperCase()}${Zd(p).slice(1)}: palbase ai:agents:publish ${t} makes its chats talk to it.`)})}},o2={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=xn(e,"an agent"),n=qt(e.flags.revision,"revision"),s=await f(e);await k(e,s,`publish the draft of the agent ${t}`);let a=await tc(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.`))}},i2={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=xn(e,"an agent"),n=Number(e.args[1]);if(!Number.isSafeInteger(n)||n<1)throw h(`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 f(e);await k(e,s,`make version ${n} of the agent ${t} the one its chats talk to (a draft not published is dropped)`);let a;try{a=await m(e,s,"POST",`/ai/agents/${A(t)}/rollback`,{version:n})}catch(o){throw Cw(e,o,t,`save a draft that says them with their values (palbase ai:agents:create ${t} --from <file.json>) and publish it`)}e.out.result(a,()=>e.out.line(`${t}'s chats talk to version ${a.published_version} again; its draft is that version.`))}},r2={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=xn(e,"an agent"),n=qt(e.flags.limit,"limit"),s=await f(e),a=await m(e,s,"GET",`/ai/agents/${A(t)}/versions${cs({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:o=>`${o.version}${o.version===a.published_version?" (published)":""}`},{header:"published",value:o=>o.published_at},{header:"by",value:o=>o.published_by},{header:"model",value:o=>o.definition.model??"-"},{header:"description",value:o=>o.definition.description??""}]),a.next_cursor&&e.out.line(`More: palbase ai:agents:versions ${t} --cursor ${a.next_cursor}`)})}},l2={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 h("the description says the agent in words: 1 to 4000 characters");let n=e.flags.name;if(n!==void 0&&!ec.test(n))throw h(`${JSON.stringify(n)} is not an agent's name: lowercase letters, digits, _ and -, a letter first, at most 64`);let s=await f(e),a=await m(e,s,"POST","/ai/agent-drafts",{description:t,...n!==void 0?{name:n}:{}}),o=e.flags.publish===!0;if(e.flags.save!==!0&&!o){e.out.result(a,()=>{oo(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 k(e,s,`save the draft of the agent ${a.name}${o?" and publish it":""}`);let i=await Tw(e,s,a.name,a.definition,void 0),r=o?await tc(e,s,a.name,i.revision):i;e.out.result({...a,agent:r},()=>{oo(e,`${a.name}:`,a.definition),e.out.line(),e.out.line(o?`Saved and published ${a.name} as version ${r.published_version}.`:`Saved the draft of ${a.name} (revision ${i.revision}): palbase ai:agents:publish ${a.name} makes its chats talk to it.`)})}},p2={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=xn(e,"an agent"),n=await f(e);await k(e,n,`forget the agent ${t} and its versions`),await m(e,n,"DELETE",`/ai/agents/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`Forgot ${t} and its versions.`))}},d2={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 f(e),{tools:n}=await m(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).")})}},c2={name:"ai:chats:list",summary:"the environment's chats, newest first \u2014 every one, a member's, or only active ones",usage:"[--member <user id>] [--status active|all] [--limit <n>] [--cursor <cursor>]",flags:{member:{type:"string",value:"user id",description:"only the chats this user is in"},status:{type:"string",value:"active|all",description:"active returns only chats with a running or waiting turn"},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=qt(e.flags.limit,"limit"),n=e.flags.status;if(n!==void 0&&n!=="active"&&n!=="all")throw h("--status is active or all");let s=await f(e),a=await m(e,s,"GET",`/ai/chats${cs({member:e.flags.member,status:n,limit:t,cursor:e.flags.cursor})}`);e.out.result(a,()=>{a.chats.length===0&&e.out.line("No chat."),e.out.table(a.chats,[{header:"id",value:o=>o.id},{header:"agent",value:o=>`${o.agent}${o.agent_version?`@${o.agent_version}`:""}`},{header:"title",value:o=>o.title},{header:"members",value:o=>String(o.members.length)},{header:"started",value:o=>o.created_at}]),a.next_cursor&&e.out.line(`More: palbase ai:chats:list --cursor ${a.next_cursor}`)})}},u2=/^chat_[0-9a-f]{32}$/;function _l(e){let t=e.args[0];if(!u2.test(t))throw h(`${JSON.stringify(t)} is not a chat's id (chat_ and 32 hex digits)`,"palbase ai:chats:list");return t}var m2={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=_l(e),n=qt(e.flags.limit,"limit")??50,s=await f(e),a=await m(e,s,"GET",`/ai/chats/${A(t)}`),o=await m(e,s,"GET",`/ai/chats/${A(t)}/messages${cs({limit:n})}`),i=[...o.messages].reverse(),r=await g2(e,s,t,new Set(i.flatMap(d=>d.response_id?[d.response_id]:[]))),l=new Map;i.forEach((d,u)=>d.response_id&&l.set(d.response_id,u));let p=new Map;if(e.flags.cost===!0)for(let d of new Set(i.flatMap(u=>u.response_id?[u.response_id]:[])))p.set(d,await m(e,s,"GET",`/ai/chats/${A(t)}/turns/${A(d)}/cost`));e.out.result({chat:a,messages:i,answers:Object.fromEntries(r),...e.flags.cost===!0?{costs:Object.fromEntries(p)}:{}},()=>{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(d=>`${d.name||d.user_id}${d.owner?" (owner)":""}`).join(", ")}`),e.out.line(),i.length===0&&e.out.line("Nothing written yet."),i.forEach((d,u)=>{if(e.out.line(`${d.created_at} ${d.author===null?"server":d.author_name||d.author}: ${d.text}${d.status==="failed"?` [failed: ${d.error??""}]`:""}`),!d.response_id||l.get(d.response_id)!==u)return;let g=r.get(d.response_id);g&&e.out.line(` ${a.agent}: ${g.replace(/\s*\n\s*/g," ")}`);let y=p.get(d.response_id);y&&e.out.line(` turn ${y.response_id}: ${wl(y.usd)}${y.unpriced?" at least":""}, ${y.input_tokens} in / ${y.output_tokens} out${y.final?"":" (still settling)"}`)}),o.next_cursor&&e.out.line(`(older messages are not shown: --limit ${Math.min(n*2,100)})`)})}};async function g2(e,t,n,s){let a=[],o;for(let r=0;r<20&&s.size>0;r++){let l=await m(e,t,"GET",`/ai/chats/${A(n)}/parts${cs({limit:1e3,cursor:o})}`);if(a.unshift(l.parts),!l.next_cursor)break;o=l.next_cursor}let i=new Map;for(let r of a.flat()){let l=r.data.response_id,p=r.data.offset;if(typeof l!="string"||!s.has(l)||typeof p!="number")continue;let d=(i.get(l)??Buffer.alloc(0)).subarray(0,p);i.set(l,r.type==="text"&&typeof r.data.text=="string"?Buffer.concat([d,Buffer.from(r.data.text)]):r.type==="reset"?d:i.get(l)??d)}return new Map([...i].map(([r,l])=>[r,l.toString("utf8").trim()]))}var h2={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=_l(e),n=await f(e);await k(e,n,`delete the chat ${t}`),await m(e,n,"DELETE",`/ai/chats/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`Deleted the chat ${t}.`))}},y2=/^[a-z][a-z0-9_-]{0,63}(@[1-9][0-9]{0,8})?$/,ds=/^[A-Za-z0-9_.:-]{1,160}$/,f2=/^[a-z0-9][a-z0-9_-]{0,62}$/,b2={name:"ai:chats:create",summary:"start a chat with one of the environment's agents \u2014 optionally on a runner pool and bound to a standalone workspace",usage:"--agent <name> [--pool <pool>] [--workspace <ws_id>] [--title <title>]",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.","--workspace binds an encrypted standalone workspace (palbase workspaces:list, ws_\u2026) to the chat."],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 session runs on, by id or name"},workspace:{type:"string",value:"ws_id",description:"standalone workspace id (ws_\u2026) bound to the chat"},title:{type:"string",value:"title",description:"the chat's title"}},scope:"environment",async run(e){let t=e.flags.agent;if(t===void 0)throw h("--agent names the chat's agent","palbase ai:agents:list");if(!y2.test(t))throw h(`${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&&!ds.test(n))throw h(`${JSON.stringify(n)} is not a runner pool's id or name`,"palbase ai:pools:list");let s=e.flags.workspace;if(s!==void 0&&s.trim()==="")throw h("--workspace is a standalone workspace id (ws_\u2026)","palbase workspaces:list");let a={agent:t};e.flags.title!==void 0&&(a.title=e.flags.title),n!==void 0&&(a.pool=n),s!==void 0&&(a.workspace_id=s);let o=await f(e);await k(e,o,`start a chat with the agent ${t}${n!==void 0?` on the pool ${n}`:""}`);let i=await m(e,o,"POST","/ai/chats",a);e.out.result(i,()=>{e.out.line(`Started the chat ${i.id} with ${i.agent}${i.pool?` on the pool ${i.pool}`:""}${s?` bound to workspace ${s}`:""}.`)})}},w2=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/u,v2="128 bytes at most, no control, format (bidi, zero-width) or line-separator character",k2=e=>Buffer.byteLength(e)<=128&&!w2.test(e);function _2(e){if(e==="cloud"||e==="serverless")return{kind:e};if(e.startsWith("pool:")){let t=e.slice(5);if(!ds.test(t))throw h(`--to ${JSON.stringify(e)}: pool id or name after pool:`);return{kind:"pool",pool_id:t}}if(e.startsWith("machine:")||e.startsWith("mac:")){let t=e.slice(e.indexOf(":")+1);if(!ds.test(t))throw h(`--to ${JSON.stringify(e)}: machine id after machine:`);return{kind:"machine",machine_id:t}}throw h(`--to must be cloud, serverless, pool:<id|name>, or machine:<machine_id> (got ${JSON.stringify(e)})`)}var S2={name:"ai:chats:handoff",summary:"teleport a chat session to another compute target and/or local ACP CLI harness",usage:"<chat id> --to <cloud|serverless|pool:<pool>|machine:<id>> [--harness claude-code|codex|gemini-cli] [--when idle|after_turn|now] [--grace <seconds>] [--model <model>] [--effort <effort>]",details:["Moves the chat session atomically (advancing target_generation so stale writes from the prior target are rejected with 409 superseded).","Leave --harness out to run on the Palbase single engine; pass --harness claude-code, codex, or gemini-cli to execute through a locally installed ACP CLI on an enrolled machine."],args:{min:1,max:1},flags:{to:{type:"string",value:"target",description:"cloud, serverless, pool:<pool>, or machine:<machine_id>"},harness:{type:"string",value:"name",description:"ACP CLI harness: claude-code, codex, or gemini-cli"},when:{type:"string",value:"idle|after_turn|now",description:"when to cut over (default idle)"},grace:{type:"string",value:"seconds",description:"grace window (1\u201360s) when --when now parks a running turn"},model:{type:"string",value:"model",description:"optional default model override on the new target"},effort:{type:"string",value:"effort",description:"optional default reasoning effort override"},"idempotency-key":{type:"string",value:"key",description:"idempotency key so retries never double-teleport"}},scope:"environment",async run(e){let t=_l(e),n=e.flags.to;if(!n)throw h("--to is required: cloud, serverless, pool:<pool>, or machine:<machine_id>");let s=_2(n),a=e.flags.harness;if(a!==void 0&&a!=="claude-code"&&a!=="codex"&&a!=="gemini-cli")throw h("--harness must be claude-code, codex, or gemini-cli");let o=e.flags.when;if(o!==void 0&&o!=="idle"&&o!=="after_turn"&&o!=="now")throw h("--when must be idle, after_turn, or now");let i=qt(e.flags.grace,"grace");if(i!==void 0&&i>60)throw h("--grace is 1 to 60 seconds");let r=a!==void 0?{kind:"acp",harness:a}:{kind:"palbase"};typeof e.flags.model=="string"&&e.flags.model!==""&&(r.model=e.flags.model),typeof e.flags.effort=="string"&&e.flags.effort!==""&&(r.effort=e.flags.effort);let l={to:{compute:s,executor:r},...o!==void 0?{when:o}:{},...i!==void 0?{grace_seconds:i}:{},...typeof e.flags["idempotency-key"]=="string"?{idempotency_key:e.flags["idempotency-key"]}:{}},p=await f(e);await k(e,p,`hand off the chat ${t} to ${n}${a?` (${a})`:""}`);let d=await m(e,p,"POST",`/ai/chats/${A(t)}/handoff`,l);e.out.result(d,()=>{let u=d.target.executor.kind==="acp"?`acp:${d.target.executor.harness??""}`:"palbase",g=d.target.compute.machine_id?`${d.target.compute.kind}:${d.target.compute.machine_id}`:d.target.compute.pool_id?`${d.target.compute.kind}:${d.target.compute.pool_id}`:d.target.compute.kind;e.out.line(`Handed off ${d.chat_id} to ${g} (${u}) \u2014 generation ${d.target_generation}, workspace seq ${d.workspace_seq}, action ${d.active_run_action}.`)})}},$2={name:"ai:chats:execution",summary:"show a chat's current execution target, target generation, machine online status, harnesses, and auto-failover state",usage:"<chat id>",args:{min:1,max:1},scope:"environment",async run(e){let t=_l(e),n=await f(e),s=await m(e,n,"GET",`/ai/chats/${A(t)}/execution`);e.out.result(s,()=>{let a=s.target.executor.kind==="acp"?`acp:${s.target.executor.harness??""}`:"palbase";e.out.line(`${s.chat_id} generation ${s.target_generation}`),e.out.line(`compute ${s.target.compute.kind}${s.target.compute.machine_id?` (${s.target.compute.machine_id})`:s.target.compute.pool_id?` (${s.target.compute.pool_id})`:""}`),e.out.line(`executor ${a}${s.target.executor.model?` model ${s.target.executor.model}`:""}`),s.workspace_id&&e.out.line(`workspace ${s.workspace_id} (seq ${s.workspace_seq})`),s.machine_status&&e.out.line(`machine ${s.machine_name??s.target.compute.machine_id??"-"} (${s.machine_status})${s.failover_at?`, failover at ${s.failover_at}`:""}`),s.auto_failover&&e.out.line(`failover after ${s.auto_failover.after_offline_seconds}s offline -> ${s.auto_failover.to.compute.kind}/${s.auto_failover.to.executor.kind}`),s.pending_handoff&&e.out.line(`pending -> ${s.pending_handoff.to.compute.kind}/${s.pending_handoff.to.executor.kind} (${s.pending_handoff.reason})`)})}},A2={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 f(e),{endpoints:n}=await m(e,t,"GET","/ai/endpoints"),s=n.map(({signing_secret:a,...o})=>o);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}])})}},P2={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=xn(e,"an endpoint"),n=await f(e);await k(e,n,`forget the endpoint ${t}`),await m(e,n,"DELETE",`/ai/endpoints/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`Forgot the endpoint ${t}.`))}};function fi(e,t=0){let n=e.args[t];if(!f2.test(n))throw h(`${JSON.stringify(n)} is not a runtime environment's name: lowercase letters, digits, _ and -, at most 63`);return n}var R2={name:"ai:environments:list",summary:"list the project's runtime environments (ephemeral or always_on)",scope:"environment",async run(e){let t=await f(e),{environments:n}=await m(e,t,"GET","/ai/environments");e.out.result({environments:n},()=>{n.length===0&&e.out.line("No runtime environment."),e.out.table(n,[{header:"name",value:s=>s.name},{header:"mode",value:s=>s.mode},{header:"isolation",value:s=>s.isolation},{header:"runtime",value:s=>s.runtime.vm_profile??s.runtime.image??"dockerfile"},{header:"egress",value:s=>s.network.egress??"default"},{header:"palbase db",value:s=>s.network.allow_palbase_db?"yes":"no"}])})}},j2={name:"ai:environments:get",summary:"inspect one runtime environment by name",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=fi(e),n=await f(e),s=await m(e,n,"GET",`/ai/environments/${A(t)}`);e.out.result(s,()=>{e.out.line(`${s.name} mode ${s.mode} isolation ${s.isolation}`),e.out.line(`runtime ${s.runtime.vm_profile?`vm:${s.runtime.vm_profile}`:s.runtime.image??"dockerfile"}`),e.out.line(`resources cpu=${s.resources.cpu??"-"} mem=${s.resources.memory_mb??"-"}MB disk=${s.resources.disk_mb??"-"}MB idle=${s.resources.idle_timeout_seconds??0}s`),e.out.line(`scaling min_warm=${s.scaling.min_warm??0} max=${s.scaling.max_instances??"-"}`),e.out.line(`network egress=${s.network.egress??"default"} allow_palbase_db=${s.network.allow_palbase_db?"true":"false"}`)})}},E2={name:"ai:environments:put",summary:"create or update a runtime environment (ephemeral or always_on)",usage:"<name> [--mode ephemeral|always_on] [--isolation strict|relaxed] [--image <image>] [--vm-profile macos-xcode|linux-vm] [--cpu <n>] [--memory-mb <n>] [--disk-mb <n>] [--idle-timeout <seconds>] [--min-warm <n>] [--max-instances <n>] [--egress default|restricted|none] [--allow-palbase-db] [--allow-host <host>]\u2026 [--setup <cmd>]\u2026",args:{min:1,max:1},flags:{mode:{type:"string",value:"ephemeral|always_on",description:"lifecycle mode (always_on never auto-parks)"},isolation:{type:"string",value:"strict|relaxed",description:"minimum sandbox isolation posture"},image:{type:"string",value:"image",description:"base OCI container image"},"vm-profile":{type:"string",value:"macos-xcode|linux-vm",description:"VM profile for isolated macOS or Linux sandboxes"},cpu:{type:"string",value:"n",description:"vCPU count"},"memory-mb":{type:"string",value:"mb",description:"memory limit in MiB"},"disk-mb":{type:"string",value:"mb",description:"encrypted workspace disk budget in MiB"},"idle-timeout":{type:"string",value:"seconds",description:"idle timeout before parking (0 for always_on)"},"min-warm":{type:"string",value:"n",description:"minimum pre-warmed instances"},"max-instances":{type:"string",value:"n",description:"maximum concurrent instances"},egress:{type:"string",value:"default|restricted|none",description:"outbound network egress policy"},"allow-palbase-db":{type:"boolean",description:"allow TLS/SSLRequest connectivity to project Palbase Postgres DBs"},"allow-host":{type:"string",multiple:!0,value:"host",description:"allowlisted hostname when egress is restricted"},setup:{type:"string",multiple:!0,value:"cmd",description:"setup command executed when baking/initializing"}},scope:"environment",async run(e){let t=fi(e),n=e.flags.mode;if(n!==void 0&&n!=="ephemeral"&&n!=="always_on")throw h("--mode must be ephemeral or always_on");let s=e.flags.isolation;if(s!==void 0&&s!=="strict"&&s!=="relaxed")throw h("--isolation must be strict or relaxed");let a=e.flags["vm-profile"];if(a!==void 0&&a!=="macos-xcode"&&a!=="linux-vm")throw h("--vm-profile must be macos-xcode or linux-vm");let o=e.flags.egress;if(o!==void 0&&o!=="default"&&o!=="restricted"&&o!=="none")throw h("--egress must be default, restricted, or none");let i={};n!==void 0&&(i.mode=n),s!==void 0&&(i.isolation=s);let r={};e.flags.image!==void 0&&(r.image=e.flags.image),a!==void 0&&(r.vm_profile=a);let l=Me(e.flags.setup);l&&l.length>0&&(r.setup=l),Object.keys(r).length>0&&(i.runtime=r);let p={},d=qt(e.flags.cpu,"cpu");d!==void 0&&(p.cpu=d);let u=qt(e.flags["memory-mb"],"memory-mb");u!==void 0&&(p.memory_mb=u);let g=qt(e.flags["disk-mb"],"disk-mb");g!==void 0&&(p.disk_mb=g);let y=we(e.flags["idle-timeout"],"idle-timeout");y!==void 0&&(p.idle_timeout_seconds=y),Object.keys(p).length>0&&(i.resources=p);let w={},v=we(e.flags["min-warm"],"min-warm");v!==void 0&&(w.min_warm=v);let R=qt(e.flags["max-instances"],"max-instances");R!==void 0&&(w.max_instances=R),Object.keys(w).length>0&&(i.scaling=w);let P={};o!==void 0&&(P.egress=o),e.flags["allow-palbase-db"]===!0&&(P.allow_palbase_db=!0);let E=Me(e.flags["allow-host"]);E&&E.length>0&&(P.allow_hosts=E),Object.keys(P).length>0&&(i.network=P);let T=await f(e);await k(e,T,`save the runtime environment ${t}`);let C=await m(e,T,"PUT",`/ai/environments/${A(t)}`,i);e.out.result(C,()=>e.out.line(`Saved runtime environment ${C.name} (${C.mode}, ${C.isolation}).`))}},T2={name:"ai:environments:delete",summary:"delete a runtime environment and its build records",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=fi(e),n=await f(e);await k(e,n,`delete the runtime environment ${t}`),await m(e,n,"DELETE",`/ai/environments/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`Deleted runtime environment ${t}.`))}},C2={name:"ai:environments:build",summary:"queue an immutable pre-bake build for a runtime environment",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=fi(e),n=await f(e);await k(e,n,`queue a build for runtime environment ${t}`);let s=await m(e,n,"POST",`/ai/environments/${A(t)}/builds`);e.out.result(s,()=>e.out.line(`Queued build ${s.build_id} for ${s.environment_name} (${s.status}).`))}},O2={name:"ai:environments:build:get",summary:"read the status of a runtime environment build",usage:"<name> <build_id>",args:{min:2,max:2},scope:"environment",async run(e){let t=fi(e,0),n=e.args[1];if(!ds.test(n))throw h(`${JSON.stringify(n)} is not a build id`);let s=await f(e),a=await m(e,s,"GET",`/ai/environments/${A(t)}/builds/${A(n)}`);e.out.result(a,()=>{e.out.line(`${a.build_id} ${a.environment_name} status=${a.status}`),a.image_digest&&e.out.line(`digest ${a.image_digest}`),a.error_message&&e.out.line(`error ${a.error_message}`)})}};function Sl(e){let t=e.args[0];if(!ds.test(t))throw h(`${JSON.stringify(t)} is not a runner pool's id or name`,"palbase ai:pools:list");return t}function $l(e){let t=e.args[0];if(!ds.test(t))throw h(`${JSON.stringify(t)} is not a machine's id`,"palbase ai:pools:state <pool> lists its machines");return t}function x2(e){if(!(e instanceof G))return e;switch(e.code){case"pool_not_empty":return new b(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 b(e.code,e.message,{hint:"palbase ai:machines:cordon <id> first"});case"machine_busy":return new b(e.code,e.message,{hint:"delete it once ai:pools:state <pool> says it holds none (used 0)"});case"pool_exists":return new b(e.code,e.message,{hint:"palbase ai:pools:list"});default:return e}}async function ya(e,t,n,s,a){try{return await m(e,t,n,s,a)}catch(o){throw x2(o)}}var L2={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 palbase-agent 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=xn(e,"a pool"),n=e.flags.os,s=e.flags.arch;if(n!=="linux"&&n!=="macos")throw h("--os is the pool's machines' operating system: linux or macos");if(s!=="amd64"&&s!=="arm64")throw h("--arch is the pool's machines' architecture: amd64 or arm64");let a=await f(e);await k(e,a,`make the runner pool ${t} (${n}/${s})`);let o=await ya(e,a,"POST","/ai/pools",{name:t,os:n,arch:s});e.out.result(o,()=>{e.out.line(`Made the pool ${o.name} (${o.id}), ${o.os}/${o.arch}.`),e.out.line(`Enrol a machine: palbase ai:pools:keys:create ${o.name}`)})}},I2={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 f(e),{pools:n}=await m(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)}])})}},N2={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=Sl(e),n=await f(e);await k(e,n,`delete the runner pool ${t}`),await ya(e,n,"DELETE",`/ai/pools/${A(t)}`),e.out.result({deleted:t},()=>e.out.line(`Deleted the pool ${t}.`))}},M2={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=Sl(e),n=await f(e),s=await m(e,n,"GET",`/ai/pools/${A(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??"-"}])})}},D2={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: palbase-agent 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=Sl(e),n=e.flags.label;if(n!==void 0&&!k2(n))throw h(`--label is ${v2}`);let s=await f(e);await k(e,s,`mint a key a machine enrols into the pool ${t} with`);let a=await ya(e,s,"POST",`/ai/pools/${A(t)}/keys`,n!==void 0?{label:n}:{});if(typeof a.key!="string"||a.key==="")throw new b("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 o=a.enroll_url??a.enroll?.url??"<enroll_url>",i=`${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: palbase-agent enroll --url ${o} --key-file <file> --capacity <n>${i}`),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}`)})}},z2={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=Sl(e),n=await f(e),{keys:s}=await m(e,n,"GET",`/ai/pools/${A(t)}/keys`),a=s.map(({key:o,...i})=>i);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:o=>o.id},{header:"label",value:o=>o.label??""},{header:"minted",value:o=>o.created_at??"-"},{header:"expires",value:o=>o.expires_at??"-"},{header:"last used",value:o=>o.last_used_at??"-"},{header:"revoked",value:o=>o.revoked_at??"-"}])})}},q2={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(!ds.test(t))throw h(`${JSON.stringify(t)} is not a key's id`,"palbase ai:pools:keys:list <pool>");let n=await f(e);await k(e,n,`revoke the enrolment key ${t}`),await ya(e,n,"POST",`/ai/pool-keys/${A(t)}/revoke`),e.out.result({revoked:t},()=>e.out.line(`Revoked ${t}: no machine enrols with it any more.`))}},G2={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=$l(e),n=await f(e);await k(e,n,`cordon the machine ${t}`),await ya(e,n,"POST",`/ai/machines/${A(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}`))}},K2={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=$l(e),n=await f(e);await k(e,n,`let the machine ${t} take sessions again`),await ya(e,n,"POST",`/ai/machines/${A(t)}/resume`),e.out.result({resumed:t},()=>e.out.line(`${t} takes sessions again.`))}},U2={name:"ai:machines:delete",summary:"delete a cordoned machine that holds no session from its runner pool: its palbase-agent is refused from then",usage:"<machine id>",args:{min:1,max:1},scope:"environment",async run(e){let t=$l(e),n=await f(e);await k(e,n,`delete the machine ${t} from its pool`),await ya(e,n,"DELETE",`/ai/machines/${A(t)}`),e.out.result({deleted:t},()=>e.out.line(`Deleted ${t}: its palbase-agent is refused from now.`))}},W2={name:"ai:machines:harnesses",summary:"list locally installed ACP CLI harnesses (claude-code, codex, gemini-cli) reported by palbase-agent on a machine",usage:"<machine id> [--pool <pool>]",args:{min:1,max:1},flags:{pool:{type:"string",value:"pool",description:"the machine's runner pool (optional; searches all pools when omitted)"}},scope:"environment",async run(e){let t=$l(e),n=e.flags.pool;if(n!==void 0&&!ds.test(n))throw h(`${JSON.stringify(n)} is not a runner pool's id or name`,"palbase ai:pools:list");let s=await f(e),a,o=n??"";if(n!==void 0){let r=await m(e,s,"GET",`/ai/pools/${A(n)}/state`);a=r.machines.find(l=>l.id===t),o=r.pool.name}else{let{pools:r}=await m(e,s,"GET","/ai/pools");for(let l of r){let p=await m(e,s,"GET",`/ai/pools/${A(l.id)}/state`),d=p.machines.find(u=>u.id===t);if(d){a=d,o=p.pool.name;break}}}if(!a)throw new b("machine_not_found",`no machine ${t} in the environment's runner pools`,{hint:"palbase ai:pools:list"});let i=a.harnesses??[];e.out.result({machine_id:a.id,pool:o,state:a.state,harnesses:i},()=>{if(e.out.line(`${a.id}${a.label?` (${a.label})`:""} pool ${o} ${a.state}`),i.length===0){e.out.line("No ACP CLI harnesses reported by palbase-agent yet.");return}e.out.table(i,[{header:"harness",value:r=>r.name},{header:"status",value:r=>r.status},{header:"cli",value:r=>r.cli_version??"-"},{header:"acp",value:r=>r.acp_version??"-"}])})}},F2=/^[A-Z][A-Z0-9_]{0,127}$/,$w=32768;function nc(e){let t=e.args[0];if(!F2.test(t)||t.startsWith("PALAI_"))throw h(`${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 B2=["header","query","body"],yi="an exact DNS name (api.stripe.com) or *. and one (*.stripe.com: one label more) \u2014 no IP address, port, single-label name or public suffix, and no wildcard over palbase.studio",J2=/^(\*\.)?[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/,Ow=e=>e.length<=253&&J2.test(e);function H2(e){let t=Me(e);if(t!==void 0){if(t.length===1&&t[0]==="none")return[];if(t.length===0)throw h(`--host is a host the secret may go to: ${yi}; --host none takes them all away`);return t.forEach((n,s)=>{if(!Ow(n))throw h(`--host number ${s+1} is no host name: ${yi}; --host none, alone, takes them all away`)}),t}}function V2(e){let t=Me(e);if(t!==void 0){if(t.length===0||t.some(n=>!B2.includes(n)))throw h("--inject is where in a request to one of its hosts the secret may be put: header, query or body (repeat it for several)");return t}}var X2="an open secret is read by the agent as it is: anyone who can drive the environment's agents \u2014 an app's user where the environment lets them (ai:settings:set --open-secrets-for-app-users), a prompt the agent reads \u2014 can get its value",Y2="a variable that is no secret is read by the agent as it is: anyone who can drive the environment's agents \u2014 an app's user where the environment lets them, a prompt the agent reads \u2014 can get its value",xw="looks like a value a person chose (fewer than 16 characters, or one kind of character only): the proxy hides a sealed value an allowed host echoes back, which lets an agent confirm a guess there";async function Aw(e,t,n="open"){let s=n==="open"?`${t} would be open: ${X2}`:`${t} is a secret and would be no secret: ${Y2}`,a=n==="open"?"--open --acknowledge-open":"--value-stdin --not-secret --acknowledge-open < value.txt";if(!e.interactive)throw new b("open_not_acknowledged",s,{hint:`say you read it: palbase ai:env:set ${t} ${a} (-y does not say it)`});e.out.warn(s);let o=(await e.io.prompt(n==="open"?`Make ${t} open? [y/N] `:`Make ${t} no secret? [y/N] `)).trim().toLowerCase();if(o!=="y"&&o!=="yes")throw new b("cancelled","nothing was changed")}async function Z2(e,t){e.out.warn(`${t}'s value ${xw}`);let n=(await e.io.prompt(`Keep ${t} sealed anyway? [y/N] `)).trim().toLowerCase();if(n!=="y"&&n!=="yes")throw new b("cancelled","nothing was changed",{hint:`a random key is never one: palbase ai:env:set ${t} --value-stdin < key.txt`})}async function Q2(e,t,n){let{variables:s}=await m(e,t,"GET","/ai/env");return s.some(a=>a.key===n&&a.secret)}function Qd(e){let t=e.hosts??[];return e.secret?e.open?"an open secret: the agent reads it as it is":t.length===0?"a sealed secret with no host yet":`a sealed secret for ${t.join(", ")}, put in ${(e.inject??[]).join(", ")}`:"no secret"}function Pw(e){let t=[];return e.hosts!==void 0&&t.push(e.hosts.length===0?"no host":`its hosts ${e.hosts.join(", ")}`),e.inject!==void 0&&t.push(`put in ${e.inject.join(", ")}`),e.open===!0&&t.push("open: the agent reads it as it is"),t.join("; ")}function eO(e,t,n,s){if(!(e instanceof G))return e;switch(e.code){case"open_not_acknowledged":return new b(e.code,e.message,{hint:`say you read it: palbase ai:env:set ${t} ${s?"--value-stdin --not-secret --acknowledge-open < value.txt":"--open --acknowledge-open"}`});case"secret_unusable":return new b(e.code,`${t} cannot be kept sealed: ${e.message}`,{hint:n?`a sealed secret's value is 8 bytes or more on one line. A value that is no secret (a region, a scheme): palbase ai:env:set ${t} --value-stdin --not-secret < value.txt; one the agent may read as it is: --open --acknowledge-open`:`sealed, it needs a value of 8 bytes or more on one line: palbase ai:env:set ${t} --value-stdin --host <host> < value.txt`});case"secret_guessable":return new b(e.code,`${t}'s value ${xw}`,{hint:`use a random key \u2014 or keep it sealed anyway: palbase ai:env:set ${t}${n?" --value-stdin":""} --acknowledge-guessable \u2026${n?" < value.txt":""} (or your yes at a terminal; -y does not say it); an open secret: --open --acknowledge-open`})}return n?e:e.code==="value_required"?new b(e.code,`${t} would be sealed: a sealed secret is set with its value, which the platform judges \u2014 never one it keeps`,{hint:`give it again: palbase ai:env:set ${t} --value-stdin --host <host> \u2026 < value.txt`}):e.code==="person_required"||e.code==="token_out_of_scope"?ro(e,`change what ${t} says of itself without its value`,`say it with its value: palbase ai:env:set ${t} --value-stdin \u2026 < value.txt`):e.status===404?new b(e.code,`${t} is not set: what a secret says of itself is changed without its value only for one set before`,{hint:`set it with its value: palbase ai:env:set ${t} --value-stdin \u2026 < value.txt`}):e.code==="not_a_secret"?new b(e.code,`${t} is no secret: a variable the agent reads as it is has no hosts, no inject and no class`,{hint:`make it a secret with its value: palbase ai:env:set ${t} --value-stdin --host <host> < value.txt`}):e}var tO={name:"ai:env:set",summary:"set a variable every session of the environment's agents has, and say where a secret may go: its value piped in or typed unseen, never shown or put on the command line",usage:"<KEY> [--value-stdin] [--not-secret [--acknowledge-open]] [--host <host>]\u2026 [--inject header|query|body]\u2026 [--open --acknowledge-open] [--acknowledge-guessable] < 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: it is given to the agent as it is, with no hosts, never open; its value is masked and never shown either way. A secret made none is said with --acknowledge-open, or your yes at the terminal once the warning is shown; a new variable needs neither.",`A secret is sealed (the default) or open. A sealed one says the hosts a request may carry it to (--host, 32 at most: ${yi}) and where in such a request it may be put (--inject: header, the default; query; body \u2014 never over plain http). Nothing of how a value is delivered changes until the proxy beside the machines swaps a sealed secret in only on a request to one of its hosts: one with no host yet is delivered as it is.`,"A sealed value is 8 bytes or more on one line (secret_unusable): a short one that is no secret \u2014 a region, a scheme \u2014 is set with --not-secret. One the platform finds a person may have chosen (fewer than 16 characters, or one kind of character only: secret_guessable) is kept sealed with --acknowledge-guessable, or with your yes at the terminal once the platform has said so; -y does not say it.","--host names all its hosts, those it had replaced \u2014 --host none takes them all away, and a sealed secret is made of an open one; ai:env:hosts:allow adds one.","--open: the agent reads it as it is, with no hosts and no inject \u2014 so anyone who can drive the environment's agents can get its value. Said with --acknowledge-open, or with your yes at the terminal once the warning is shown; -y does not say it.","--host, --inject or --open without --value-stdin changes what a variable set before says of itself and keeps its value (what is not given stays as it is): a person's change alone \u2014 an owner or an admin of the organization signed in as themselves (palbase login), never a key or a token (PALBASE_TOKEN), which say them with the value."],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:"it is no secret (its value is never shown either way)"},host:{type:"string",multiple:!0,value:"host",description:"a host a request may carry the secret to (repeat for several; none: no host)"},inject:{type:"string",multiple:!0,value:"header|query|body",description:"where in a request to one of its hosts it may be put (repeat for several)"},open:{type:"boolean",description:"the agent reads it as it is: no hosts, no inject"},"acknowledge-open":{type:"boolean",description:"say you read that anyone who can drive the agents can get an open secret's value (or a secret made none's)"},"acknowledge-guessable":{type:"boolean",description:"keep a value a person may have chosen sealed: say you read that an agent can confirm a guess at an allowed host"}},scope:"environment",async run(e){let t=nc(e),n=H2(e.flags.host),s=V2(e.flags.inject),a=e.flags.open===!0,o=e.flags["not-secret"]===!0,i=e.flags["acknowledge-open"]===!0,r=e.flags["acknowledge-guessable"]===!0;if(i&&!a&&!o)throw h("--acknowledge-open goes with --open, or with --not-secret: it says you read what the agent reading it as it is means");if(a&&(n!==void 0||s!==void 0))throw h("an open secret is read by the agent as it is: it has no hosts and no inject \u2014 --open, or --host and --inject for a sealed one");let l=n!==void 0||s!==void 0||a;if(o&&l)throw h("a variable that is no secret (--not-secret) is given to the agent as it is: it has no hosts, no inject, and is never open");if(r&&(a||o))throw h("--acknowledge-guessable is a sealed value's: an open secret's value and one that is no secret's are the agent's to read, and the platform judges neither");let p=e.flags["value-stdin"]===!0||!l;if(p&&e.flags["value-stdin"]!==!0&&!e.interactive)throw h(`${t}'s value is read from stdin`,`pipe it in: palbase ai:env:set ${t} --value-stdin < value.txt`);p||io(e,`change what ${t} says of itself without its value`,`say it with its value: palbase ai:env:set ${t} --value-stdin \u2026 < value.txt`),a&&!i&&await Aw(e,t);let d=await f(e),u=o&&(i||await Q2(e,d,t)&&(await Aw(e,t,"plain"),!0)),g={};if(p){let v=await lt(e,`${t}'s value`);if(Buffer.byteLength(v)>$w||v.includes("\0"))throw h(`${t}'s value is 1 to ${$w} bytes, no NUL`);g.value=v}o&&(g.secret=!1),n!==void 0&&(g.hosts=n),s!==void 0&&(g.inject=s),(a||u)&&(g.acknowledge_open=!0),a&&(g.open=!0),r&&(g.acknowledge_guessable=!0),await k(e,d,p?`set the variable ${t} for every session of the environment's agents${l?`: ${Pw(g)}`:""}`:`change what ${t} says of itself, its value kept: ${Pw(g)}`);let y=async()=>{try{return await m(e,d,"PUT",`/ai/env/${A(t)}`,g)}catch(v){if(v instanceof G&&v.code==="secret_guessable"&&e.interactive&&g.acknowledge_guessable!==!0)return await Z2(e,t),g.acknowledge_guessable=!0,y();throw eO(v,t,p,o)}},w=await y();e.out.result(w,()=>e.out.line(p?`Set ${w.key} (${Qd(w)}): every session begun from now has it. Its value is kept sealed, never shown.`:`${w.key} is ${Qd(w)} now; its value is as it was.`))}},nO={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=nc(e),n=await f(e);await k(e,n,`remove the variable ${t}`),await m(e,n,"DELETE",`/ai/env/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`Removed ${t}: sessions begun from now no longer have it.`))}},sO={name:"ai:env:list",summary:"the variables every session of the environment's agents has: their names, whether each is a secret \u2014 sealed, with the hosts it may go to and where it is put, or open \u2014 and when each was set: never a value",scope:"environment",async run(e){let t=await f(e),{variables:n}=await m(e,t,"GET","/ai/env"),s=a=>a.secret&&!a.open;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:a=>a.key},{header:"secret",value:a=>a.secret?a.open?"open":"sealed":"no"},{header:"hosts",value:a=>s(a)?(a.hosts??[]).length===0?"none yet":a.hosts.join(", "):"-"},{header:"inject",value:a=>s(a)?(a.inject??[]).join(", "):"-"},{header:"value",value:()=>"set"},{header:"updated",value:a=>a.updated_at}])})}},aO=/^shr_[A-Za-z0-9]{1,156}$/,oO=/^sha_[A-Za-z0-9]{1,156}$/,kl="allow a host for a secret";function iO(e,t,n){if(!(e instanceof G))return e;switch(e.code){case"not_a_sealed_secret":return new b(e.code,`${t} is no sealed secret: only a sealed secret has hosts \u2014 it is no secret, or an open one the agent reads as it is`,{hint:`palbase ai:env:list says which: an open one is sealed with its hosts (palbase ai:env:set ${t} --host ${n}); one that is no secret is set again as a secret (palbase ai:env:set ${t} --value-stdin --host ${n} < value.txt)`});case"too_many_hosts":return new b(e.code,`${t} is allowed for 32 hosts at most`,{hint:`name those it keeps: palbase ai:env:set ${t} --host <host> --host <host>\u2026 (palbase ai:env:list shows them)`});case"person_required":case"token_out_of_scope":return ro(e,kl);default:return e.status===404?new b(e.code,`${t} is not set`,{hint:"palbase ai:env:list"}):e}}function rO(e,t){if(!(e instanceof G))return e;switch(e.code){case"not_a_sealed_secret":return new b(e.code,`the secret the ask ${t} names is no sealed secret now: only a sealed secret has hosts \u2014 it is no secret, or an open one the agent reads as it is`,{hint:"palbase ai:env:list says which"});case"too_many_hosts":return new b(e.code,"its variable is allowed for 32 hosts at most",{hint:"name those it keeps: palbase ai:env:set <KEY> --host <host> --host <host>\u2026 (palbase ai:env:list shows them)"});case"too_many_allowances":return new b(e.code,"the environment's allowances for its agents' own secrets hold 500 hosts at most",{hint:"take one away first: palbase ai:env:hosts:allowances, then palbase ai:env:hosts:allowances:remove <allowance id>"});case"already_allowed":return new b(e.code,`the ask ${t} was allowed already: a host taken away from its secret since is asked again by its next request, and allowed from that ask`,{hint:"palbase ai:env:hosts:requests"});case"person_required":case"token_out_of_scope":return ro(e,kl);default:return e.status===404?new b(e.code,`the ask ${t} cannot be allowed: ${e.message} \u2014 no such ask, or the variable it names is no longer set`,{hint:"palbase ai:env:hosts:requests, palbase ai:env:list"}):e}}var lO={name:"ai:env:hosts:allow",summary:"allow an ask \u2014 its host for its secret, a project's variable's or an agent's own \u2014 or let a variable's sealed secret go to one more host: only a host you know the secret belongs to",usage:"<request id> | <KEY> <host>",details:["An agent can be led to send a secret anywhere: allow only a host you know the secret belongs to. palbase ai:env:hosts:requests lists the hosts the secrets were sent to that they are not allowed for, each by its request id.","<request id> (shr_\u2026) allows any ask: its host goes on the variable's hosts (one of the environment's), or on the environment's allowances (an agent's own secret: palbase ai:env:hosts:allowances), and the asks it now allows are marked allowed.",`<KEY> <host> lets one of the environment's variables go to a host no ask named. A host is ${yi}; a variable has 32 at most \u2014 ai:env:set <KEY> --host \u2026 names them all.`,"A person's alone: an owner or an admin of the organization signed in as themselves (palbase login), never a key or a token (PALBASE_TOKEN) \u2014 refused before anything is sent."],args:{min:1,max:2},scope:"environment",async run(e){if(e.args.length===1){let o=e.args[0];if(!aO.test(o))throw h(`${JSON.stringify(o.slice(0,40))} is not an ask's id (shr_\u2026): an ask is allowed by its id, a variable's host as <KEY> <host>`,"palbase ai:env:hosts:requests");io(e,kl);let i=await f(e),r=await mO(e,i,o);if(!r)throw new b("not_found",`no ask ${o} to allow: an ask is allowed from what it says, and none of that id is listed`,{hint:"palbase ai:env:hosts:requests --status asked|dismissed"});if(r.status==="allowed")throw new b("already_allowed",`the ask ${o} was allowed already: a host taken away from its secret since is asked again by its next request, and allowed from that ask`,{hint:"palbase ai:env:hosts:requests"});let l=uO(r);if("refused"in l)throw new b("ask_not_allowable",`the ask ${o} is not allowed from here: ${l.refused}`,{hint:"look at it in Studio (AI \u203A Secrets) \u2014 dismiss it if you do not know why a secret was sent there (palbase ai:env:hosts:dismiss <request id>)"});let p=l.domain!==r.host?` \u2014 a name under ${l.domain}, whoever holds ${l.domain} runs it`:"",d=r.origin==="chat"&&r.agent?`; it covers every chat that defines an agent named ${r.agent}, not one chat alone`:"",u=`allow the ask ${o}: ${r.key} may go to ${r.host}${p}${d}`;await k(e,i,u);let g;try{g=await m(e,i,"POST",`/ai/env/host-requests/${A(o)}/allow`)}catch(y){throw rO(y,o)}e.out.result(g,()=>e.out.line(g.agent===null?`Allowed ${I(g.host)} for ${I(g.key)}: one of its hosts now (palbase ai:env:list).`:`Allowed ${I(g.host)} for ${I(sc(g.origin,g.agent))}'s ${I(g.key)}: on the environment's allowances (palbase ai:env:hosts:allowances).`));return}let t=nc(e),n=e.args[1];if(!Ow(n))throw h(`the host is no host name: ${yi}`);io(e,kl);let s=await f(e);await k(e,s,`let ${t} go to ${n}`);let a;try{a=await m(e,s,"POST",`/ai/env/${A(t)}/hosts`,{host:n})}catch(o){throw iO(o,t,n)}e.out.result(a,()=>e.out.line(`Allowed ${n} for ${a.key}: ${Qd(a)}.`))}},pO=["asked","allowed","dismissed"];function sc(e,t){return e==="chat"?`chat-defined agent ${t}`:e==="backend"?`backend agent ${t}`:`agent ${t}`}var dO=/^[A-Z][A-Z0-9_]{0,127}$/,cO=/^[a-z][a-z0-9_-]{0,63}$/,bl=e=>I(JSON.stringify(e)??String(e));function uO(e){let t=[];(typeof e.key!="string"||!dO.test(e.key)||e.key.startsWith("PALAI_"))&&t.push(`its key ${bl(e.key)} is no variable's name`),e.agent!=null&&(typeof e.agent!="string"||!cO.test(e.agent))&&t.push(`its agent ${bl(e.agent)} is no agent's name`);let n=typeof e.host=="string"?yl(e.host):void 0;return n===void 0?t.push(`its host ${bl(e.host)} is no host a secret is allowed for`):e.domain!=null&&e.domain!==""&&e.domain!==n&&t.push(`the domain it names, ${bl(e.domain)}, is not ${n}, the one its host is under`),t.length>0||n===void 0?{refused:t.join("; ")}:{domain:n}}async function mO(e,t,n){for(let s of["asked","dismissed","allowed"]){let{requests:a}=await m(e,t,"GET",`/ai/env/host-requests${cs({status:s})}`),o=a.find(i=>i.request_id===n);if(o)return o}}var gO={name:"ai:env:hosts:requests",summary:"the hosts the environment's sealed secrets were sent to that they are not allowed for \u2014 each secret and host once, how many times, newest first",usage:"[--status asked|allowed|dismissed]",details:["The placeholder went as it is, and the organization's owners are emailed at most once a day for each (3 a day for one secret, 10 an environment a day). Nobody has checked who runs a host listed here: each is shown with the registrable domain it is under \u2014 api.stripe.com.evil.io is evil.io's \u2014, which an Allow hands the secret to.","Allow one only if you know the host is the secret's: palbase ai:env:hosts:allow <request id> \u2014 a project's variable's and an agent's own secret's alike (the agent's goes on the environment's allowances); or dismiss it: palbase ai:env:hosts:dismiss <request id>.","An environment keeps 500 asked, 50 of them a secret and 100 an agent's own secrets: an ask past one forgets an asked one alone \u2014 the secret's own oldest, else the oldest of the secret that holds the most, the one asked last among equals \u2014, never a dismissed or an allowed one (500 of each are kept)."],flags:{status:{type:"string",value:"asked|allowed|dismissed",description:"the asks of that status (default asked)"}},scope:"environment",async run(e){let t=e.flags.status;if(t!==void 0&&!pO.includes(t))throw h("--status is asked (the default), allowed or dismissed");let n=await f(e),{requests:s}=await m(e,n,"GET",`/ai/env/host-requests${cs({status:t})}`),a=(t??"asked")==="asked";e.out.result({requests:s},()=>{if(s.length===0){e.out.line(a?"No host asked for: no sealed secret was sent where it is not allowed.":`No ask ${t}.`);return}e.out.table(s,[{header:"request id",value:o=>o.request_id},{header:"key",value:o=>o.key},{header:"of",value:o=>o.agent===null?"the environment":sc(o.origin,o.agent)},{header:"domain",value:o=>yl(o.host)??"?"},{header:"host",value:o=>o.host},{header:"asks",value:o=>String(o.asks)},{header:"last asked",value:o=>o.last_asked_at},...a?[]:[{header:t,value:o=>o.decided_at??"-"}]]),a&&(e.out.line(),e.out.line("Allow one only if you know the host is the secret's \u2014 an agent can be led to send a secret anywhere: palbase ai:env:hosts:allow <request id>. Dismiss one: palbase ai:env:hosts:dismiss <request id>."),s.some(o=>o.agent!==null)&&e.out.line("An agent's own secret is allowed the same way: its host goes on the environment's allowances (palbase ai:env:hosts:allowances) \u2014 or name it in the agent's definition: env.<KEY>.hosts."))})}},hO={name:"ai:env:hosts:dismiss",summary:"dismiss an ask: its owners are never told of it again (it is still counted)",usage:"<request id>",details:["One allowed is not undone here: its host is the secret's \u2014 ai:env:set <KEY> --host \u2026 names those a variable keeps (--host none: none); an agent's is taken away from the allowances (ai:env:hosts:allowances:remove).","A person's alone: an owner or an admin of the organization signed in as themselves, never a key or a token (PALBASE_TOKEN)."],args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0];if(!ds.test(t))throw h(`${JSON.stringify(t)} is not an ask's id (shr_\u2026)`,"palbase ai:env:hosts:requests");io(e,"dismiss an ask for a secret");let n=await f(e);await k(e,n,`dismiss the ask ${t}`);let s;try{s=await m(e,n,"POST",`/ai/env/host-requests/${A(t)}/dismiss`)}catch(a){throw a instanceof G&&a.code==="already_allowed"?new b(a.code,`the ask ${t} was allowed: its host is the secret's`,{hint:"take it away: a variable's by naming the hosts it keeps (palbase ai:env:set <KEY> --host <host>\u2026, --host none: none); an agent's from the allowances (palbase ai:env:hosts:allowances:remove <allowance id>)"}):a instanceof G&&a.status===404?new b(a.code,`no ask ${t}`,{hint:"palbase ai:env:hosts:requests"}):ro(a,"dismiss an ask for a secret")}e.out.result(s,()=>e.out.line(`Dismissed: ${I(s.key)} sent to ${I(s.host)} is not told again.`))}},yO={name:"ai:env:hosts:allowances",summary:"the hosts the environment's agents' own secrets are allowed beside their definitions': each an owner's Allow of an ask, newest first",details:["An agent's own secret (its definition's env) goes to the hosts its definition names and to those allowed here (palbase ai:env:hosts:allow <request id>). Take one away: palbase ai:env:hosts:allowances:remove <allowance id>.","An environment keeps 500. A new value keeps them; one goes with its key \u2014 a kept agent's once neither its draft nor its version published has it, a chat's own definition's with the last chat that has it, a backend's agent's after 30 days with no turn."],scope:"environment",async run(e){let t=await f(e),{allowances:n}=await m(e,t,"GET","/ai/env/allowances");e.out.result({allowances:n},()=>{if(n.length===0){e.out.line("No allowance: an agent's own secret goes only to the hosts its definition names.");return}e.out.table(n,[{header:"allowance id",value:s=>s.allowance_id},{header:"agent",value:s=>sc(s.origin,s.agent)},{header:"key",value:s=>s.key},{header:"domain",value:s=>yl(s.host)??"?"},{header:"host",value:s=>s.host},{header:"allowed",value:s=>s.allowed_at},{header:"by",value:s=>s.allowed_by}]),e.out.line(),e.out.line("Take one away: palbase ai:env:hosts:allowances:remove <allowance id>.")})}},fO={name:"ai:env:hosts:allowances:remove",summary:"take an allowance away: the agent's secret no longer goes to its host, and a request carrying it there is asked again",usage:"<allowance id>",details:["A person's alone: an owner or an admin of the organization signed in as themselves, never a key or a token (PALBASE_TOKEN)."],args:{min:1,max:1},scope:"environment",async run(e){let t=e.args[0];if(!oO.test(t))throw h(`${JSON.stringify(t.slice(0,40))} is not an allowance's id (sha_\u2026)`,"palbase ai:env:hosts:allowances");let n="take an agent's secret's allowance away";io(e,n);let s=await f(e);await k(e,s,`take the allowance ${t} away: its agent's secret no longer goes to its host`);try{await m(e,s,"DELETE",`/ai/env/allowances/${A(t)}`)}catch(a){throw a instanceof G&&a.status===404?new b(a.code,`no allowance ${t}`,{hint:"palbase ai:env:hosts:allowances"}):ro(a,n)}e.out.result({removed:t},()=>e.out.line(`Took ${t} away: a request carrying its secret to its host is asked again.`))}},bO={name:"ai:templates:list",summary:"list the project\u2019s guardrailed client AI templates",args:{min:0,max:0},scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/ai/templates");e.out.result(n.templates,()=>{if(n.templates.length===0){e.out.line("No AI templates yet.");return}e.out.table(n.templates,[{header:"name",value:s=>s.name},{header:"published",value:s=>s.published_version?`v${s.published_version}`:"draft"},{header:"modality",value:s=>s.published?.modality??s.draft?.modality??"-"},{header:"model",value:s=>s.published?.model??s.draft?.model??"-"}])})}},wO={name:"ai:templates:publish",summary:"publish a guardrailed client AI template version so mobile/web apps can call it",usage:"<name> [--version <n>]",args:{min:1,max:1},flags:{version:{type:"string",value:"n",description:"specific version number to publish (defaults to latest draft)"}},scope:"environment",async run(e){let t=xn(e,"a template"),n=qt(e.flags.version,"version"),s=await f(e);await k(e,s,`publish template ${t}`);let a=n!==void 0?{version:n}:{},o=await m(e,s,"POST",`/ai/templates/${A(t)}/publish`,a);e.out.result(o,()=>e.out.line(`Published template ${o.name} as v${o.published_version??"?"}.`))}},vO={name:"ai:templates:rollback",summary:"roll a guardrailed client AI template back to a prior version",usage:"<name> <version>",args:{min:2,max:2},scope:"environment",async run(e){let t=xn(e,"a template"),n=Number(e.args[1]);if(!Number.isInteger(n)||n<1)throw h("version must be a positive integer",`palbase ai:templates:rollback ${t} 1`);let s=await f(e);await k(e,s,`roll template ${t} back to v${n}`);let a=await m(e,s,"POST",`/ai/templates/${A(t)}/rollback`,{version:n});e.out.result(a,()=>e.out.line(`Rolled template ${a.name} back to v${a.published_version??n}.`))}},kO={name:"ai:templates:remove",summary:"delete a guardrailed client AI template and all of its versions",usage:"<name>",args:{min:1,max:1},scope:"environment",async run(e){let t=xn(e,"a template"),n=await f(e);await k(e,n,`delete template ${t} and all of its versions`),await m(e,n,"DELETE",`/ai/templates/${A(t)}`),e.out.result({removed:t},()=>e.out.line(`Removed template ${t}.`))}},Lw=[qC,UC,GC,WC,FC,BC,VC,XC,ZC,e2,a2,o2,i2,r2,l2,p2,bO,wO,vO,kO,d2,c2,m2,b2,$2,S2,h2,A2,P2,R2,j2,E2,T2,C2,O2,L2,I2,N2,M2,D2,z2,q2,G2,K2,U2,W2,tO,nO,sO,lO,gO,hO,yO,fO];var _O={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 h("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 h("--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((o,i)=>{i>0&&e.out.line(),e.out.line(`${i+1}. ${o.title===o.heading?o.title:`${o.title} \u203A ${o.heading}`}`),e.out.line(` ${o.url}`),e.out.line(),e.out.line(o.text)})})}},Iw=[_O];var Nw=3e4,ac=3,SO=80;async function $O(e,t){let n=[],s;try{s=(await m(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 o of s.slice(0,ac)){n.push(`machine ${o.name}: ${o.state}, size ${o.size}, version ${o.running_version===o.version?o.version:`${o.running_version} \u2192 ${o.version}`}`);let i;try{i=(await m(e,t,"GET",`/machines/${Q("a machine's name",o.name)}/builds?limit=3`)).builds}catch{n.push(" builds: not readable with this sign-in or token");continue}for(let l of i)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(`
|
|
11096
11096
|
`)[0].slice(0,80)}"`);let r=i.find(l=>l.state==="failed");if(r)try{let l=await m(e,t,"GET",`/machines/${Q("a machine's name",o.name)}/builds/${Q("a build's id",r.id)}/log`),p=typeof l=="string"?l:JSON.stringify(l);n.push(` the end of build ${r.id}'s log:`,...p.trimEnd().split(`
|
|
11097
11097
|
`).slice(-SO).map(d=>` ${d}`))}catch{n.push(` build ${r.id}'s log: not readable with this sign-in or token`)}}s.length>ac&&n.push(`(${s.length-ac} more machines not shown)`);let a=n.join(`
|
|
11098
11098
|
`);return a.length>Nw?`${a.slice(0,Nw)}
|
|
@@ -11119,7 +11119,7 @@ ${t}}`}var us=e=>["",e.toUpperCase(),"-".repeat(e.length)],UO=[{title:"One packa
|
|
|
11119
11119
|
`)}
|
|
11120
11120
|
`}var Rl={$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","macos"],type:"string"},maxItems:4,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 /iap/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 _t=`${ue}/paywalls`,uo=`${_t}/paywall.schema.json`,Is="paywall-assets",pc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Cl=e=>`"${e}"`;function mo(e,t,n){let s=e.args[t];if(s===void 0||s.trim()==="")throw h(`${n} is required`);return s}async function ms(e,t){return(await m(e,t,"GET","/iap/paywalls")).paywalls}function Ol(e,t){if(pc.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 b("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 wa(e,t,n){let s=await ms(e,t),a=Ol(s,n);if(!a)throw new b("paywall_not_found",`no paywall ${JSON.stringify(n)}`,{hint:s.length>0?`the project's: ${s.map(o=>o.name).join(", ")}`:"the project has none yet: palbase iap:paywalls:put <name> --file <file> --revision 0 makes one"});return a}function bi(e){let t=e.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60);return t===""?"paywall":t}function Kt(e,t,n,s,a=`${_t}/<name>${s}`){let o=XO(e.io.cwd,sv(e.io.cwd,n)).split(YO).join("/");if(!o.startsWith(`${ue}/`)||o.split("/").includes(".."))throw h(`--${t} ${n}: the file goes under ${ue}/, as the CLI writes nothing else in the checkout`,`--${t} ${a}`);if(!o.endsWith(s))throw h(`--${t} ${n}: the file's name ends in ${s}`);return o}async function El(e,t,n){let s=await Be(e.io.cwd,t);await BO(VO(s),{recursive:!0}),await Be(e.io.cwd,t),await HO(s,n)}var av=`${JSON.stringify(Rl,null,2)}
|
|
11121
11121
|
`;async function Tl(e,t,n){await El(e,uo,av);let s=ev.relative(ev.dirname(t),uo);await El(e,t,`${JSON.stringify({$schema:s.startsWith(".")?s:`./${s}`,...n},null,2)}
|
|
11122
|
-
`)}async function xl(e,t){let n=Ne(await ze(e,t,"the paywall"),"the paywall");if(typeof n!="object"||n===null||Array.isArray(n))throw h("a paywall is a JSON object: { schema, name, default_locale, theme, root, \u2026 }");if("draft"in n&&"draft_revision"in n)throw h('the file is a whole paywall (its draft, its revision, its problems): give its "draft" alone, as iap:paywalls:get --out writes it');if("definition"in n&&!("root"in n))throw h('the file is a definition inside something else: give the "definition" alone, as iap:paywalls:get --out writes it');let{$schema:s,...a}=n;return a}function Ll(e,t){for(let n of t)e.out.note(` ${n.path}: ${n.code} \u2014 ${n.message}${n.warning?" (warning)":""}`)}var ov=e=>e.filter(t=>!t.warning).length;function iv(e){if(!(!(e instanceof G)||e.code!=="invalid_paywall"))return(e.body??{}).problems??[]}function rv(e,t,n){let s=iv(t);throw s!==void 0?(s.length>0&&(e.out.note(`The paywall breaks ${ov(s)} rule(s):`),Ll(e,s)),new b("invalid_paywall",`${n}: ${t.message}`,{hint:"fix each problem in the file (palbase iap:paywalls:validate --file <file> checks it without saving)"})):t}function lv(e,t,n){return new b("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 iap:paywalls:get ${JSON.stringify(e)}), make the edit on it, and save it with that revision`})}async function ZO(e,t){let n=new Map,s=(r,l)=>{if(r===void 0)return;let p=n.get(r)??[];p.includes(l)||p.push(l),n.set(r,p)},{placements:a}=await m(e,t,"GET","/iap/placements");for(let r of a)s(r.paywall_id,r.key);let o=a.filter(r=>r.rule_count>0);return(await Promise.all(o.map(r=>m(e,t,"GET",`/iap/placements/${A(r.key)}/rules`)))).forEach((r,l)=>{for(let p of r.rules)s(p.target.paywall_id,`${o[l].key} (rule)`)}),n}var QO={name:"iap: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: iap:paywalls:get writes one to a file, iap:paywalls:put saves the edit as its draft, iap: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 iap:paywalls:guide"],scope:"environment",async run(e){let t=await f(e),[n,s]=await Promise.all([ms(e,t),ZO(e,t)]),a=n.map(o=>({...o,placements:s.get(o.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 iap:paywalls:put <name> --file ${_t}/<name>.json --revision 0`);return}e.out.table(a,[{header:"name",value:o=>o.name},{header:"id",value:o=>o.id},{header:"draft",value:o=>`revision ${o.draft_revision}`},{header:"published",value:o=>o.published_version===0?"never":`version ${o.published_version}, ${Z(o.published_at)}`},{header:"shown at",value:o=>o.placements.length===0?"\u2014":o.placements.join(", ")}])})}},e1={name:"iap: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 <${_t}/name.json>] [--version <n>]`,details:[`The file is the definition alone, as iap:paywalls:put takes it, under ${_t}/. Its first line names its JSON Schema, written beside it (${uo}), so an editor checks the file as it is edited.`,"The revision printed is the one an edit is saved on: iap:paywalls:put --revision."],args:{min:1,max:1},flags:{out:{type:"string",value:"file",description:`where under ${ue}/ (default: ${_t}/<name>.json)`},version:{type:"string",value:"n",description:"a published version instead of the draft"}},scope:"environment",async run(e){let t=await f(e),n=we(e.flags.version,"version");if(n===0)throw h("--version is 1 or more: the versions published");let s=await wa(e,t,mo(e,0,"the paywall's name or id")),a=e.flags.out!==void 0?Kt(e,"out",e.flags.out,".json"):`${_t}/${bi(s.name)}${n===void 0?"":`.v${n}`}.json`;if(n!==void 0){let i;try{i=await m(e,t,"GET",`/iap/paywalls/${A(s.id)}/versions/${n}`)}catch(r){throw r instanceof G&&r.status===404?new b("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)`}`):r}if(!i.definition)throw new b("unexpected_answer",`the module answered version ${n} of ${s.name} without its definition`);await Tl(e,a,i.definition),e.out.result({file:a,paywall_id:s.id,name:s.name,version:i.version,published_at:i.published_at,draft_revision:s.draft_revision},()=>{e.out.line(`Wrote version ${i.version} of ${s.name} (published ${Z(i.published_at)}) to ${a}.`),e.out.line(`Saved as the draft, it goes on the draft's revision: palbase iap:paywalls:put ${JSON.stringify(s.name)} --file ${a} --revision ${s.draft_revision}`)});return}let o=await m(e,t,"GET",`/iap/paywalls/${A(s.id)}`);await Tl(e,a,o.draft),e.out.result({file:a,paywall_id:o.id,name:o.name,revision:o.draft_revision,published_version:o.published_version,problems:o.problems},()=>{e.out.line(`Wrote draft revision ${o.draft_revision} of ${o.name} to ${a}${o.published_version===0?" (never published)":` (version ${o.published_version} is published)`}.`),o.problems.length>0&&(e.out.note("The module says of the draft:"),Ll(e,o.problems)),e.out.line(`Save an edit of it: palbase iap:paywalls:put ${JSON.stringify(o.name)} --file ${a} --revision ${o.draft_revision}`)})}},t1={name:"iap: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 f(e),n=await xl(e,e.flags.file),s;try{s={valid:!0,problems:(await m(e,t,"POST","/iap/paywalls/validate",n,D())).problems??[]}}catch(a){let o=iv(a);if(o===void 0)throw a;s={valid:!1,problems:o}}return e.out.result(s,()=>{s.problems.length>0&&Ll(e,s.problems);let a=s.problems.filter(o=>o.warning).length;e.out.line(s.valid?`The paywall can be published${a>0?`, with ${a} warning(s)`:""}.`:`The paywall breaks ${ov(s.problems)} rule(s): it cannot be saved as it is.`)}),s.valid?void 0:1}};async function pv(e,t,n,s){try{let a=await Pt(e,t,"POST",`/iap/paywalls/${A(n.id)}/publish`,void 0,{"if-match":Cl(s),...D()});return{version:a.body,fresh:a.status===201}}catch(a){if(a instanceof G&&a.status===412)throw lv(n.name,s,"published");rv(e,a,`${n.name} was not published`)}}function dv(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 n1={name:"iap: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 iap:paywalls:publish). A new paywall takes the name its definition gives.","How a definition is written: palbase iap:paywalls:guide"],args:{min:1,max:1},flags:{file:{type:"string",value:"paywall.json",description:"the definition, as iap:paywalls:get wrote it ('-' or none: stdin)"},revision:{type:"string",value:"n",description:"the draft revision it was edited from, as iap: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 f(e),n=mo(e,0,"the paywall's name or id"),s=we(e.flags.revision,"revision");if(s===void 0)throw h("--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 xl(e,e.flags.file),o=Ol(await ms(e,t),n),i=e.flags.publish===!0?" and publish it":"",r;try{if(o){if(s===0)throw new b("paywall_exists",`${o.name} is there already, at draft revision ${o.draft_revision}: an edit of it is saved on the revision it was read at`,{hint:`palbase iap:paywalls:get ${JSON.stringify(o.name)} writes it and prints the revision`});await k(e,t,`save the draft of ${o.name} over revision ${s}${i}`),r=await m(e,t,"PUT",`/iap/paywalls/${A(o.id)}/draft`,{definition:a},{"if-match":Cl(s),...D()})}else{if(pc.test(n))throw new b("paywall_not_found",`no paywall ${n}`);if(s!==0)throw new b("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 h(`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 iap:paywalls:put ${JSON.stringify(a.name??"")} \u2026`);await k(e,t,`make the paywall ${a.name}${i}`),r=await m(e,t,"POST","/iap/paywalls",{definition:a},D())}}catch(p){if(p instanceof G&&p.status===412)throw lv(o?.name??n,s,"saved");if(p instanceof G&&p.code==="too_many_paywalls")throw new b("too_many_paywalls","the project has 100 paywalls, the most it holds: nothing was made",{hint:"delete one no placement shows: palbase iap:paywalls:delete <name>"});rv(e,p,"the paywall was not saved")}let l=e.flags.publish===!0?await pv(e,t,r,r.draft_revision):void 0;e.out.result({...r,...l?{published:l.version,published_new:l.fresh}:{}},()=>{e.out.line(`${o?"Saved":"Made"} ${r.name}: its draft is at revision ${r.draft_revision}.`),r.problems.length>0&&(e.out.note("The module says of the draft:"),Ll(e,r.problems)),l?dv(e,r.name,l):e.out.line(`The apps draw it once it is published: palbase iap:paywalls:publish ${JSON.stringify(r.name)}`)})}},s1={name:"iap: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 f(e),n=await wa(e,t,mo(e,0,"the paywall's name or id")),s=we(e.flags.revision,"revision")??n.draft_revision;await k(e,t,`publish draft revision ${s} of ${n.name}`);let a=await pv(e,t,n,s);e.out.result({...a.version,published_new:a.fresh},()=>dv(e,n.name,a))}},a1={name:"iap: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 f(e),n=await wa(e,t,mo(e,0,"the paywall's name or id"));await k(e,t,`delete the paywall ${n.name}: its draft and every version of it`);try{await m(e,t,"DELETE",`/iap/paywalls/${A(n.id)}`,void 0,D())}catch(s){throw s instanceof G&&s.code==="paywall_in_use"?new b("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 iap: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}.`))}},o1={name:"iap: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 <${uo}>]`,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 iap:paywalls:validate asks it.",'iap: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 ${ue}/ (default: ${uo}); --json prints it instead`}},scope:"none",async run(e){if(e.global.json){e.out.result(Rl,()=>{});return}let t=e.flags.out!==void 0?Kt(e,"out",e.flags.out,".json"):uo;await El(e,t,av),e.out.line(`Wrote the paywall definition's JSON Schema to ${t}.`)}},i1={name:"iap: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 <${_t}/GUIDE.txt>]`,details:["It is made from the definition's JSON Schema the CLI carries (iap: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 ${ue}/ instead of printing it`}},scope:"none",async run(e){let t=Qw(Rl),n=e.flags.out;if(n===void 0){e.out.result({guide:t},()=>e.io.stdout(t));return}let s=Kt(e,"out",n,".txt");await El(e,s,t),e.out.result({file:s},()=>e.out.line(`Wrote the guide to ${s}.`))}},tv=["image","video","font","html"];function lc(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 go(e,t){return(await m(e,t,"GET","/iap/paywalls/assets")).assets??[]}var nv={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 iap 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 iap:paywalls:assets:delete <id>)"};async function dc(e,t){let n;try{n=await m(e,t,"GET",`/storage/buckets/${Is}`)}catch(s){if(!(s instanceof G)||s.status!==404)throw s}if(!n?.public){if(n)throw new b("asset_bucket_private",`the project's ${Is} 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 ${Is} --public`});await m(e,t,"PUT",`/storage/buckets/${Is}`,{public:!0,file_size_limit:null,allowed_mime_types:[],variants:[]}),e.out.note(`Made the public bucket ${Is}: paywall assets are kept in the project's own storage.`)}}function r1(e){let t=jl(e).normalize("NFKD").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(-80).replace(/^\.+$/,"")||"file";return`paywalls/${FO()}/${t}`}async function cc(e,t,n,s){let a=r1(n);await Jd(e,t,n,Is,a);try{return await m(e,t,"POST","/iap/paywalls/assets",{path:a,...s?{kind:s}:{}},D())}catch(o){throw await m(e,t,"DELETE",`/storage/buckets/${Is}/objects/${ml(a)}`).catch(()=>{}),o instanceof G&&o.code!==void 0&&o.code in nv?new b(o.code,`${jl(n)} was not registered: ${nv[o.code]}`):o}}var l1={name:"iap: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 f(e),n=await go(e,t);e.out.result({assets:n},()=>{if(n.length===0){e.out.line("No paywall asset yet."),e.out.line("Upload one: palbase iap: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=>lc(s.bytes)},{header:"file",value:s=>s.path.split("/").pop()??s.path},{header:"registered",value:s=>Z(s.created_at)}])})}},p1={name:"iap: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 ${Is} (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 f(e),n=sv(e.io.cwd,mo(e,0,"the file")),s=e.flags.kind;if(s!==void 0&&!tv.includes(s))throw h(`--kind is one of ${tv.join(", ")}`);let a;try{let i=await JO(n);if(!i.isFile())throw new Error("it is not a file");a=i.size}catch(i){throw new b("unreadable_file",`${e.args[0]} could not be read: ${i instanceof Error?i.message:String(i)}`)}if(a===0)throw new b("empty_file",`${e.args[0]} is empty`);await k(e,t,`upload ${jl(n)} (${lc(a)}) as a paywall asset`),await dc(e,t);let o=await cc(e,t,n,s);e.out.result(o,()=>{e.out.line(`Registered ${jl(n)} as ${o.ref} (${o.kind}, ${lc(o.bytes)}).`),e.out.line(`A definition names it "${o.ref}" where it takes ${o.kind==="html"?"an HTML block":o.kind==="image"?"an image":`a ${o.kind}`}.`)})}},d1={name:"iap: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 f(e),n=mo(e,0,"the asset's id").replace(/^asset:/,"").toLowerCase();if(!pc.test(n))throw h(`${e.args[0]} is not an asset: asset:<id>, as iap:paywalls:assets lists them`);let s=(await go(e,t)).find(o=>o.id===n);if(!s)throw new b("asset_not_found",`the project has no asset ${n}`,{hint:"palbase iap:paywalls:assets lists them"});await k(e,t,`delete the paywall asset ${s.ref} (${s.path.split("/").pop()})`);try{await m(e,t,"DELETE",`/iap/paywalls/assets/${A(n)}`,void 0,D())}catch(o){throw o instanceof G&&o.code==="asset_in_use"?new b("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"}):o}let a=!0;await m(e,t,"DELETE",`/storage/buckets/${A(s.bucket)}/objects/${ml(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}`)})}},cv=[QO,e1,t1,n1,s1,a1,o1,i1,l1,p1,d1];var hv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,v1=/^AuthKey_([A-Z0-9]{10})\.p8$/,k1=8192,yv=["testflight","play_internal","development"],fv=["testflight","development"],uc=100,bv=5,_1=5,Ev=300,S1=5,Il=900,$1=["iphone_6_9","iphone_6_5","ipad_13"],wv=/^[0-9a-f]{64}$/i,A1=10*1024*1024,vv=3,P1={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg"},gs=`${ue}/store/listing.json`,Ds={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 ho(e){return e.package_id?`package ${e.package_id}`:`app ${e.app_id??"?"}`}var hc=e=>e.charAt(0).toUpperCase()+e.slice(1);function Z(e){return e?e.slice(0,19).replace("T"," "):"\u2014"}function ve(e,t,n){let s=e.args[t];if(s===void 0||s.trim()==="")throw h(`${n} is required`);return s}function mn(e,t,n,s){let a=Qt(e.cloud,t.env_ref),o;try{o=new URL(n).origin}catch{throw new b("unexpected_address",`${s} is not a URL: nothing was sent`)}if(o!==a)throw new b("unexpected_address",`${s} names ${o}, not the environment's address ${a}: nothing was sent`);return a}async function vi(e,t,n,s){let a;try{a=await e.io.fetch(t,{...n,redirect:"manual"})}catch(l){throw new b("network_error",`${s}: ${t} could not be reached: ${l instanceof Error?l.message:String(l)}`)}let o=await a.text(),i;if(o!=="")try{i=JSON.parse(o)}catch{i=o}if(a.status>=200&&a.status<300)return i;let r=i??{};throw new G({op:s,status:a.status,code:typeof r.error=="string"?r.error:`http_${a.status}`,message:dr(i,a.status),requestId:typeof r.request_id=="string"?r.request_id:a.headers.get("x-request-id")??void 0,retryAfter:R1(a.headers.get("retry-after"),r.retry_after,e.io.now()),body:i})}function R1(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 yc(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 ${Z(t.checked_at)})`:""}`),t.capabilities&&e.out.line(`reaches: ${t.capabilities.length>0?t.capabilities.join(", "):"nothing"}`),t.connected_at&&e.out.line(`connected ${Z(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 fc(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 ${Z(t.checked_at)})`:""}`),t.connected_at&&e.out.line(`signed in ${Z(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 j1={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 f(e),n=await m(e,t,"GET","/stores/apple"),s=await m(e,t,"GET","/stores/apple/session").catch(a=>{if(!(a instanceof G&&a.status===404))throw a});e.out.result(s===void 0?n:{...n,apple_id_session:s},()=>{yc(e,n),s!==void 0&&(e.out.line(""),fc(e,s))})}};async function E1(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 Lp(Un(e.seal_key),n,new TextEncoder().encode(t)),o=new Uint8Array(s.length+a.length);return o.set(s),o.set(a,s.length),Vo(o)}async function T1(e,t,n){if(e.flags["key-file"]!==void 0)throw h("--apple-id or --key-file, not both");if(e.flags["print-link"]===!0){await k(e,t,"make a link that signs an Apple ID in");let d=await m(e,t,"POST","/stores/apple/session/grants",void 0,D());mn(e,t,d.connect_url,"the sign-in link"),e.out.result({connect_url:d.connect_url,expires_at:d.expires_at},()=>{e.out.line(d.connect_url),e.out.note(`Open it in a browser and sign in there; it works once, until ${Z(d.expires_at)}.`)});return}if(!e.io.interactive)throw h("signing an Apple ID in asks for Apple's code at the terminal","or --print-link for a link a browser opens");await k(e,t,`sign the Apple ID ${n} in`);let s=await lt(e,`the password of ${n}`),a=await m(e,t,"POST","/stores/apple/session/grants",void 0,D()),o=mn(e,t,a.connect_url,"the sign-in link"),i=await E1(a,s),r=(d,u)=>vi(e,`${o}/stores/connect/apple-id${d}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({grant:a.grant,...u})},"signing the Apple ID in"),l=await r("",{apple_id:n,password_sealed:i});for(;l.step==="code";){let d=l.method==="phone"?`to ${l.destination??"your phone"}`:"to your trusted devices",u=(await e.io.prompt(`Apple sent a code ${d}. Code: `)).replace(/\s/g,"");try{l=await r("/code",{code:u})}catch(g){if(g instanceof G&&g.code==="apple_code_refused"){e.out.note("Apple did not accept this code.");continue}throw g}}if(l.step==="team"){let d=l.teams??[],u=e.flags.team,g=u===void 0?void 0:d.find(y=>y.id===u||y.name===u);if(u!==void 0&&g===void 0)throw new b("unknown_team",`${n} is not in the team ${u}: ${d.map(y=>y.name).join(", ")}`);for(;g===void 0;){d.forEach((w,v)=>e.out.note(` ${v+1}. ${w.name}`));let y=Number((await e.io.prompt(`${n} is in ${d.length} teams. The one this environment's apps are in [1-${d.length}]: `)).trim());g=d[y-1]}l=await r("/team",{team:g.id})}let p=l.session??{connected:!1};e.out.result(p,()=>{e.out.line(`Signed ${n} in to ${ee(t)}.`),fc(e,p)})}var C1={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 f(e),n=e.flags["apple-id"];if(n!==void 0){if(n.trim()==="")throw h("--apple-id is the Apple ID: an email address");await T1(e,t,n.trim());return}if(e.flags["print-link"]===!0){if(e.flags["key-file"]!==void 0)throw h("--print-link or --key-file, not both");await k(e,t,"make a link that connects an Apple account");let g=await m(e,t,"POST","/stores/apple/grants",void 0,D());mn(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 ${Z(g.expires_at)}.`)});return}let s=e.flags["key-file"],a=e.flags["issuer-id"];if(s===void 0)throw h("--key-file names the .p8 file","or --print-link for a link a browser opens");if(a===void 0||a.trim()==="")throw h("--issuer-id is the account's issuer id (App Store Connect \u2192 Users and Access \u2192 Integrations)");let o=h1(s),i=e.flags["key-id"]??v1.exec(o)?.[1];if(i===void 0)throw h(`--key-id is needed: ${o} is not named AuthKey_<KEYID>.p8`);let r;try{let g=hs(e.io.cwd,s);if((await gc(g)).size>k1)throw new b("not_a_key",`${s} is larger than a .p8 key`);r=await u1(g,"utf8")}catch(g){throw g instanceof b?g:new b("unreadable_file",`${s} could not be read: ${g instanceof Error?g.message:String(g)}`)}if(!r.includes("-----BEGIN PRIVATE KEY-----"))throw new b("not_a_key",`${s} is not a .p8 key (no "BEGIN PRIVATE KEY")`);await k(e,t,`connect the Apple account of issuer ${a} with key ${i}`);let l=await m(e,t,"POST","/stores/apple/grants",void 0,D()),p=mn(e,t,l.connect_url,"the connect link"),d={grant:l.grant,issuer_id:a.trim(),key_id:i,private_key:r,file_name:o},u=await vi(e,`${p}/stores/connect`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(d)},"connecting the Apple key");e.out.result(u,()=>{e.out.line(`Connected key ${i} to ${ee(t)}.`),yc(e,u)})}},O1={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 f(e);if(e.flags["apple-id"]===!0){let s=await m(e,t,"POST","/stores/apple/session/check",void 0,D());e.out.result(s,()=>fc(e,s));return}let n=await m(e,t,"POST","/stores/apple/check",void 0,D());e.out.result(n,()=>yc(e,n))}},x1={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 f(e);if(e.flags["apple-id"]===!0){let n=await m(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 k(e,t,`sign the Apple ID out${s}`),await m(e,t,"DELETE","/stores/apple/session",void 0,D()),e.out.result({disconnected:!0},()=>e.out.line(`Signed the Apple ID out of ${ee(t)}, at Apple too.`));return}await k(e,t,"disconnect the Apple account (a key Palbase made is revoked at Apple)"),await m(e,t,"DELETE","/stores/apple",void 0,D()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected the Apple account from ${ee(t)}.`))}},va={asc:"App Store Connect API key",apns:"APNs keys (one for production, one for the sandbox)",iap:"In-App Purchase key"},L1=2,I1=60;function bc(e,t){let n=t.kind==="apns"?`APNs key (${t.environment??"?"})`:va[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 Tv(e,t,n){let s=r=>n.some(l=>l.kind===r&&l.state==="waiting"),a=await m(e,t,"GET","/stores/apple"),o=await m(e,t,"GET","/notify/providers"),i=await m(e,t,"GET","/iap/apple");return{asc:!a.connected,apns:!o.providers.some(r=>r.channel==="push"&&r.provider==="apns")&&!s("apns"),iap:!i.connected&&!s("iap")}}var N1={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 f(e),n=await m(e,t,"GET","/stores/apple/keys"),s=await Tv(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(o=>bc(e,o)));let a=Object.keys(va).filter(o=>s[o]);if(a.length===0){e.out.line("The environment lacks no key.");return}e.out.line(`The environment lacks: ${a.map(o=>va[o]).join("; ")}.`),e.out.line("Make them at Apple: palbase stores:apple:keys:make")})}},M1={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); iap 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 f(e),n=await m(e,t,"GET","/stores/apple/keys"),s=await Tv(e,t,n.keys),a=Object.keys(va).filter(d=>e.flags[d]===!0),o=a.length>0?a:Object.keys(va);for(let d of o.filter(u=>!s[u]))e.out.note(`The environment has its ${va[d]}: it is kept.`);let i=o.filter(d=>s[d]);if(i.length===0){e.out.result({keys:[]},()=>e.out.line("The environment lacks none of these keys: nothing to make."));return}await k(e,t,`make at Apple and connect: ${i.map(d=>va[d]).join("; ")}`);let r=[];for(let d of i){let u={kind:d};d==="iap"&&typeof e.flags.bundle=="string"&&(u.bundle=e.flags.bundle);let g=await m(e,t,"POST","/stores/apple/keys",u,D());r.push(...g.keys)}let l=e.io.now()+I1*1e3,p=r;for(;p.some(d=>d.state==="waiting")&&e.io.now()<l;){await e.io.sleep(L1*1e3);let d=await m(e,t,"GET","/stores/apple/keys");p=r.map(u=>d.keys.find(g=>g.key_id===u.key_id)??u)}e.out.result({keys:p},()=>{e.out.line(`Made at Apple for ${ee(t)}:`),p.forEach(d=>bc(e,d)),p.some(d=>d.state==="waiting")&&e.out.note("A module has not taken its key yet: palbase stores:apple:keys says when it has.")})}},D1={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=ve(e,0,"the key id"),n=await f(e);await k(e,n,`revoke the key ${t} at Apple`);let s=await m(e,n,"DELETE",`/stores/apple/keys/${A(t)}`,void 0,D());e.out.result(s,()=>{e.out.line(`Revoked ${t} at Apple.`),bc(e,s)})}};async function Cv(e,t,n){let s=(await rt(e.studio)).filter(o=>o.project_id===t.project_id),a=s.find(o=>o.slug===n||o.ref===n);if(!a)throw new b("no_such_environment",`${t.project_name} has no environment ${JSON.stringify(n)}`,{hint:`its environments: ${s.map(o=>o.slug).join(", ")}`});if(a.ref===t.env_ref)throw h("the environment uses its own session: name another environment of the project");return a}var z1={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=ve(e,0,"the environment to share with"),n=await f(e),s=await Cv(e,n,t);await k(e,n,`share its Apple ID session with ${s.name} (${s.slug})`);let a=await m(e,n,"PUT",`/stores/apple/session/shares/${A(s.ref)}`,void 0,D());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.`)})}},q1={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=ve(e,0,"the environment to take it back from"),n=await f(e),s=await Cv(e,n,t);await k(e,n,`take its Apple ID session back from ${s.name} (${s.slug})`),await m(e,n,"DELETE",`/stores/apple/session/shares/${A(s.ref)}`,void 0,D()),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 wc(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 ${Z(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 ${Z(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.action&&e.out.line(`To do: ${t.action}`)}var G1={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 f(e),n=await m(e,t,"GET","/stores/google");e.out.result(n,()=>wc(e,n))}},K1={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 f(e);await k(e,t,"connect Google Play (Palbase makes a service account for it)");let n=await m(e,t,"POST","/stores/google",void 0,D());e.out.result(n,()=>wc(e,n))}},U1={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 f(e),n=await m(e,t,"POST","/stores/google/check",void 0,D());e.out.result(n,()=>wc(e,n))}},W1={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 f(e);await k(e,t,"disconnect Google Play (its service account is deleted)"),await m(e,t,"DELETE","/stores/google",void 0,D()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected Google Play from ${ee(t)}.`))}};function F1(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 B1={name:"stores:apps",summary:"the environment's apps linked to their store",scope:"environment",async run(e){let t=await f(e),n=await m(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":""}])})}},J1={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 f(e),n=ve(e,0,"the app's id"),s=e.flags.name!==void 0?{name:e.flags.name}:{};await k(e,t,`link the app ${n} to its store`);let a=await m(e,t,"POST",`/stores/apps/${A(n)}/link`,s,D());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}).`),F1(e,a)})}},H1={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 f(e),n=ve(e,0,"the app's id"),s=await m(e,t,"GET",`/stores/apps/${A(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=>Z(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>`)})}},V1={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 f(e),n=ve(e,0,"the app's id"),s=e.args[1];if(s!=="crash"&&s!=="screenshot")throw h("the kind is crash or screenshot");let a=ve(e,2,"the feedback's id"),o=await m(e,t,"GET",`/stores/apps/${A(n)}/feedback/${s}/${A(a)}`);e.out.result(o,()=>{e.out.line(`${hc(o.kind)} ${I(o.id)}, sent ${Z(o.created_at)}${o.email?` by ${I(o.email)}`:""}`);let i=[o.device_model,o.os_version?`iOS ${o.os_version}`:void 0,o.locale].filter(Boolean).join(", ");i&&e.out.line(`from: ${I(i)}`),o.asc_build_id&&e.out.line(`build: ${I(o.asc_build_id)} (App Store Connect's id)`),o.comment&&e.out.line(`comment: ${I(o.comment)}`);for(let r of o.screenshots??[])e.out.line(`screenshot ${r.width}x${r.height}, until ${Z(r.expires_at)}: ${I(r.url)}`);o.kind==="crash"&&(o.crash_log?(e.out.line(o.crash_log_cut?"crash log (cut at 32 KiB):":"crash log:"),e.out.line(o.crash_log)):e.out.line("Apple has no log of this crash."))})}};function kv(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: ${I(n.error)}`),n.url&&e.out.line(`reports to: ${I(n.url)}`),n.event_types.length>0&&e.out.line(`tells: ${n.event_types.join(", ")}`),n.installed_at&&e.out.line(`made ${Z(n.installed_at)}${n.asc_webhook_id?` (App Store Connect's ${I(n.asc_webhook_id)})`:""}`),e.out.line(n.last_delivery_at?`last delivery: ${I(n.last_delivery_type??"?")}, ${Z(n.last_delivery_at)}`:"last delivery: none yet"),n.pinged_at&&e.out.line(`last ping: ${Z(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 _v=30,Sv=2,X1={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 f(e),n=ve(e,0,"the app's id"),s=`/stores/apps/${A(n)}/webhook`,a;if(e.flags.make?(await k(e,t,`make the App Store Connect webhook of ${n} again`),a=await m(e,t,"POST",s,{})):a=await m(e,t,"GET",s),e.flags.ping){let o=a.last_delivery_at;await m(e,t,"POST",`${s}/ping`,{});for(let r=0;r<_v&&(await e.io.sleep(Sv*1e3),a=await m(e,t,"GET",s),!(a.pinged_at&&a.last_delivery_at&&a.last_delivery_at!==o));r+=Sv);let i=!!(a.last_delivery_at&&a.last_delivery_at!==o);e.out.result({...a,ping_arrived:i},()=>{kv(e,n,a),e.out.line(i?"The ping arrived.":`Apple did not deliver the ping within ${_v} s: look again with palbase stores:webhook ${n}`)});return}e.out.result(a,()=>kv(e,n,a))}},wi=e=>e==null?"\u2014":`${(e*100).toFixed(2)}%`,Y1={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"},Z1={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 f(e),n=ve(e,0,"the app's id"),s=await m(e,t,"GET",`/stores/apps/${A(n)}/vitals`);e.out.result(s,()=>{if(e.out.line(`${s.platform==="android"?"Google Play":"App Store"} health of ${n}, read ${Z(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:o=>Z(o.created_at)},{header:"id",value:o=>o.id},{header:"comment",value:o=>o.comment??""}])),a.testflight_builds.length>0&&(e.out.line("TestFlight builds, as Apple counts them:"),e.out.table(a.testflight_builds,[{header:"build",value:o=>`${o.version} (${o.build_number})${o.expired?", expired":""}`},{header:"days",value:o=>o.from?`${o.from} \u2013 ${o.to??o.from}`:"\u2014"},{header:"installs",value:o=>String(o.installs)},{header:"sessions",value:o=>String(o.sessions)},{header:"crashes",value:o=>String(o.crashes)},{header:"feedback",value:o=>String(o.feedback)},{header:"invites",value:o=>String(o.invites)}])),e.out.line(Y1[a.crash_counts]??a.crash_counts),a.crash_days.length>0&&e.out.table(a.crash_days,[{header:"day",value:o=>o.date},{header:"version",value:o=>o.version},{header:"crashes",value:o=>String(o.crashes)},{header:"devices",value:o=>String(o.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:o=>o.category},{header:"metric",value:o=>o.identifier},{header:"version",value:o=>o.version},{header:"value",value:o=>`${o.value}${o.unit?` ${o.unit}`:""}`},{header:"devices",value:o=>o.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:o=>String(o.version_code)},{header:"crashes",value:o=>wi(o.crash_rate)},{header:"crashes in use",value:o=>wi(o.user_perceived_crash_rate)},{header:"ANRs",value:o=>wi(o.anr_rate)},{header:"ANRs in use",value:o=>wi(o.user_perceived_anr_rate)},{header:"users",value:o=>String(o.users)}]),a.issues.length>0&&e.out.table(a.issues,[{header:"error",value:o=>o.type},{header:"cause",value:o=>o.cause},{header:"where",value:o=>o.location},{header:"reports",value:o=>String(o.reports)},{header:"users",value:o=>String(o.users)}]);for(let o of a.anomalies)e.out.line(`Play flagged ${I(o.metric)}${o.version_code?` of version code ${o.version_code}`:""}${o.value!==null?`: ${wi(o.value)}`:""}${o.from?` (${o.from}${o.to?` \u2013 ${o.to}`:""})`:""}`)}})}};function Q1(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 ${Z(t.uploaded_at)}`:"waiting for its build"}`),t.size!==null&&e.out.line(`${t.format?`.${t.format}`:"build"}: ${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 ${Z(t.created_at)} by ${t.created_by} (command ${t.command_id})`);for(let n of t.deliveries)e.out.line(`${n.channel}: ${Ov(n)}`)}function Ov(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.signed_devices!==void 0&&t.push(`signed for ${e.signed_devices} phone${e.signed_devices===1?"":"s"}`),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 ex={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 f(e),n=we(e.flags.limit,"limit")??20;if(n<1||n>200)throw h("--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 m(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:o=>o.id},{header:"app",value:o=>o.app_id},{header:"build",value:o=>String(o.build_number)},{header:"version",value:o=>o.version??""},{header:"status",value:o=>o.status},{header:"testflight",value:o=>o.deliveries.find(i=>i.channel==="testflight")?.status??""},{header:"development",value:o=>o.deliveries.find(i=>i.channel==="development")?.status??""},{header:"made",value:o=>Z(o.created_at)}]),a.next_cursor&&e.out.note(`More than ${n}: raise --limit to see older ones.`)})}},tx={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 f(e),n=await m(e,t,"GET",`/stores/packages/${A(ve(e,0,"the package's id"))}`);e.out.result(n,()=>Q1(e,n))}},nx={name:"stores:packages:create",summary:"make a package of an app: its build number, and the URL and token its build 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 (an iOS app's CFBundleVersion, an Android app's versionCode), 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 f(e),n=ve(e,0,"the app's id"),s=e.flags["command-id"];if(s===void 0||s.trim()==="")throw h("--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 r=Ne(await ze(e,e.flags["entitlements-file"],"the entitlements"),"the entitlements"),l=p=>typeof p=="object"&&p!==null&&!Array.isArray(p);if(!l(r)||!Object.values(r).every(l))throw h("the entitlements are an object of bundle id \u2192 its entitlements object");a.entitlements=r}await k(e,t,`make a package of ${n}`);let o=await Pt(e,t,"POST",`/stores/apps/${A(n)}/packages`,a,D()),i=o.body;e.out.result(i,()=>{if(e.out.line(`Package ${i.id} of ${i.app_id}: build number ${i.build_number}${o.status===200?" (made before by this command id)":""}.`),i.status==="uploaded"){e.out.line("Its build has arrived already.");return}e.out.line(`Build it with build number ${i.build_number} (CFBundleVersion; an Android app's versionCode), then upload it:`),i.upload&&(e.out.line(` palbase stores:packages:upload ${i.id} --file <app.ipa> --token ${i.upload.token}`),e.out.line(`url: ${i.upload.url}`),e.out.line(`token: ${i.upload.token} (shown this once; it works until ${Z(i.upload.expires_at)})`))})}},sx={name:"stores:packages:upload",summary:"hand a package its build: the .ipa, .aab or .apk goes straight to the environment's address with the upload token",usage:"<package id> --file <app.ipa|app.aab|app.apk> --token <upload token>",details:["An Android app's App Bundle (.aab) goes to Play; its APK is installed directly on testers' phones (stores:deliver --channel development), signed with the app's upload key whatever it came signed with. The file is told by what it holds, not by its name.","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|app.apk",description:"the unsigned .ipa, the Android App Bundle (unsigned, or signed with the app's upload key) or the Android APK the build machine made"},token:{type:"string",value:"upload token",description:"the package's upload token"}},scope:"environment",async run(e){let t=await f(e),n=ve(e,0,"the package's id"),s=e.flags.file;if(s===void 0)throw h("--file names the .ipa, .aab or .apk");let a=e.flags.token??e.io.env.PALBASE_UPLOAD_TOKEN;if(a===void 0||a.trim()==="")throw h("--token is the package's upload token (stores:packages:create printed it)","or PALBASE_UPLOAD_TOKEN");let o=hs(e.io.cwd,s),i;try{let d=await gc(o);if(!d.isFile())throw new Error("not a file");i=d.size}catch(d){throw new b("unreadable_file",`${s} could not be read: ${d instanceof Error?d.message:String(d)}`)}await k(e,t,`upload ${s} (${i} bytes) as the build of package ${n}`);let r=`${Qt(e.cloud,t.env_ref)}/stores/packages/${A(n)}/artifact`,l;try{l=await Pv(o)}catch(d){throw new b("unreadable_file",`${s} could not be read: ${d instanceof Error?d.message:String(d)}`)}let p=`${s} \u2192 package ${n}`;for(let d=1;;d++)try{let u=await vi(e,r,{method:"PUT",headers:{"palbase-upload-token":a,"content-type":"application/octet-stream","content-length":String(l.size),accept:"application/json"},body:l},p);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(u.format==="apk"?`Install it on testers' phones: palbase stores:deliver ${u.id} --channel development --groups <group>, or palbase stores:invite ${u.id} <email>`:`Send it to testers: palbase stores:deliver ${u.id}`)});return}catch(u){if(!(u instanceof G))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??_1,1);if(!g||d>=bv||y>Ev)throw u;e.out.note(`${p}: ${u.message}; trying again in ${y} s (${d+1} of ${bv})`),await e.io.sleep(y*1e3)}}},ax={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 f(e),n=ve(e,0,"the app's id"),s=await m(e,t,"GET",`/stores/apps/${A(n)}/upload-key`),a=e.flags.out;if(a!==void 0){let o=await Rv(hs(e.io.cwd,a),Ms.O_WRONLY|Ms.O_CREAT|Ms.O_TRUNC|Ms.O_NOFOLLOW);try{await o.writeFile(s.certificate)}finally{await o.close()}}e.out.result(s,()=>{e.out.line(`upload key of ${n}: SHA-256 ${s.fingerprint} (made ${Z(s.created_at)})`),a!==void 0&&e.out.line(`certificate written to ${a}`)})}},ox={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 f(e),n=ve(e,0,"the package's id"),s=e.flags.out;if(s===void 0)throw h("--out names the file to write");let a=e.flags.channel??"play_internal";if(a!=="play_internal")throw h("--channel is play_internal");let o=await m(e,t,"POST",`/stores/packages/${A(n)}/deliveries/${A(a)}/bundle-link`,void 0,D());mn(e,t,o.url,"the download link");let i;try{i=await e.io.fetch(o.url,{method:"GET",redirect:"manual"})}catch(g){throw new b("network_error",`the signed bundle could not be downloaded: ${g instanceof Error?g.message:String(g)}`)}if(i.status!==200||!i.body){let g=await i.text(),y=g;try{y=JSON.parse(g)}catch{}throw new b("download_failed",`the signed bundle: ${dr(y,i.status)}`)}let r=hs(e.io.cwd,s),l=await Rv(r,Ms.O_WRONLY|Ms.O_CREAT|Ms.O_TRUNC|Ms.O_NOFOLLOW),p=0,d=b1.fromWeb(i.body).on("data",g=>{p+=g.length}),u=Number(i.headers.get("content-length")??NaN);try{if(await w1(d,l.createWriteStream()),Number.isFinite(u)&&p!==u)throw new Error(`${p} of its ${u} bytes arrived`)}catch(g){throw await m1(r,{force:!0}),new b("download_failed",`the signed bundle did not arrive whole: ${g instanceof Error?g.message:String(g)}; ask again`)}e.out.result({file:s,bytes:p},()=>{e.out.line(`Wrote ${s} (${p} 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 ix(e,t,n,s){if(s.every(i=>hv.test(i)))return s;let a=await m(e,t,"GET",`/stores/packages/${A(n)}`),o=(await m(e,t,"GET",`/stores/apps/${A(a.app_id)}/groups`)).groups;return s.map(i=>{if(hv.test(i))return i;let r=o.filter(p=>p.name===i),l=r.length>0?r:o.filter(p=>p.name.toLowerCase()===i.toLowerCase());if(l.length!==1)throw new b(l.length===0?"no_such_group":"ambiguous_group",`${a.app_id} has ${l.length===0?"no group":"more than one group"} named ${JSON.stringify(i)}`,{hint:`palbase stores:groups ${a.app_id} lists them`});return l[0].id})}async function rx(e,t,n){let s=await m(e,t,"GET",`/stores/packages/${A(n)}`);return s.format==="apk"?"development":(await m(e,t,"GET","/stores/apps")).apps.find(o=>o.app_id===s.app_id)?.platform==="android"?"play_internal":"testflight"}var lx={name:"stores:deliver",summary:"send a package to a channel's testers: signed, handed to Apple or Play \u2014 or installed on their own phones directly",usage:"<package id> [--channel testflight|play_internal|development] [--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.","--channel development installs it directly, with no TestFlight: each person of the development groups named is mailed a link, their iPhone registers itself, and the package is signed for their phones \u2014 again, with no new build, when another phone comes. Sent again, it invites who joined the groups since. palbase stores:invitations <package id> shows where each person is.","An Android app's APK goes to development alone (its default), its bundle to Play alone: the APK is signed with the app's upload key and is ready for everyone invited at once \u2014 an Android phone registers nowhere.","palbase stores:deliveries <package id> follows it."],args:{min:1,max:1},flags:{channel:{type:"string",value:"channel",description:"where it goes: testflight, play_internal (default: the app's platform's), or development (direct install; an APK's default)"},groups:{type:"string",multiple:!0,value:"group,\u2026",description:"the groups it goes to, by id or name: the channel's own kind (TestFlight groups, or development groups)"},"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 f(e),n=ve(e,0,"the package's id"),s=e.flags.channel??await rx(e,t,n);if(!yv.includes(s))throw h(`--channel is one of ${yv.join(", ")}`);let a=e.flags["what-to-test"];if(e.flags.locale!==void 0&&a===void 0)throw h("--locale is the --what-to-test note's");let o={channel:s},i=Me(e.flags.groups);i&&i.length>0&&(o.groups=await ix(e,t,n,i)),a!==void 0&&(o.what_to_test={text:a,...e.flags.locale!==void 0?{locale:e.flags.locale}:{}}),await k(e,t,`send package ${n} to ${s}${o.groups?` (${o.groups.length} group${o.groups.length===1?"":"s"})`:""}`);let r=await m(e,t,"POST",`/stores/packages/${A(n)}/deliveries`,o,D());e.out.result(r,()=>{e.out.line(`Package ${n} \u2192 ${r.channel}: ${Ov(r)}.`),r.status!=="ready"&&r.status!=="failed"&&e.out.line(`Follow it: palbase stores:deliveries ${n}`)})}},px={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 f(e),n=ve(e,0,"the package's id"),s=await m(e,t,"GET",`/stores/packages/${A(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}`:""}`:a.signed_devices!==void 0?`${a.signed_devices} phone${a.signed_devices===1?"":"s"}`:"")},{header:"groups",value:a=>String(a.groups.length)},{header:"updated",value:a=>Z(a.updated_at)},{header:"error",value:a=>a.error_code?`${a.error_code}${a.error?`: ${a.error}`:""}`:""}])})}};function dx(e){return e.devices.length===0?"":e.devices.map(t=>`${t.product??"phone"} \u2026${t.udid.slice(-6)} ${t.signed?"signed":t.status}`).join(", ")}function xv(e){return e.mail==="failed"&&e.mail_error?`failed: ${e.mail_error}`:e.mail}var cx={name:"stores:invitations",summary:"the people invited to install a package directly: how far each got, their mail, their phones",usage:"<package id>",details:["invited \u2192 opened (the link) \u2192 enrolled (a phone of theirs registered) \u2192 downloaded (a phone took the build to install it); or revoked, or expired.","A phone is signed once the package's build installs on it; registering, processing (Apple holds a new device up to 72 hours) or refused before that. Links are not listed: palbase stores:invite <package id> <email> answers a person's."],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=ve(e,0,"the package's id"),s=await m(e,t,"GET",`/stores/packages/${A(n)}/invitations`);e.out.result(s,()=>{s.invitations.length===0?e.out.line(`Nobody is invited to package ${n}: palbase stores:deliver ${n} --channel development --groups <group>, or palbase stores:invite ${n} <email>`):e.out.table(s.invitations,[{header:"invitation",value:a=>a.id},{header:"email",value:a=>a.email},{header:"status",value:a=>a.status},{header:"mail",value:xv},{header:"phones",value:dx},{header:"expires",value:a=>Z(a.expires_at)}])})}},ux={name:"stores:invite",summary:"invite one person to install a package directly: mails their link, and prints it",usage:"<package id> <email> [--no-mail] [--locale <language>]",details:["A person invited already keeps their link \u2014 mailed again unless --no-mail \u2014; an expired or revoked invitation is made again, with a new link. The package gets its development delivery when it had none.","The link works for 14 days. A person registers two new iPhones at most in 30 days, through whatever links they hold; a phone already theirs registers again freely. With an environment token the link works no longer than the token."],args:{min:2,max:2},flags:{"no-mail":{type:"boolean",description:"only print the link: nothing is mailed"},locale:{type:"string",value:"language",description:"the mail's and the page's language (en, tr; default: the project's)"}},scope:"environment",async run(e){let t=await f(e),n=ve(e,0,"the package's id"),s=e.args[1]??"";if(!/^[^\s@]+@[^\s@]+$/.test(s))throw h("the person's email address is the second argument");let a=e.flags["no-mail"]!==!0,o={email:s,...a?{}:{mail:!1},...e.flags.locale!==void 0?{locale:e.flags.locale}:{}};await k(e,t,`invite ${s} to install package ${n}${a?" (a mail goes to them)":""}`);let i=await m(e,t,"POST",`/stores/packages/${A(n)}/invitations`,o,D());e.out.result(i,()=>{e.out.line(`${i.email} is ${i.status} (${xv(i)}); the link works until ${Z(i.expires_at)}:`),e.out.line(i.url)})}},mx={name:"stores:invitations:revoke",summary:"revoke an invitation: its link, its build and its registration stop working",usage:"<invitation id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=ve(e,0,"the invitation's id");await k(e,t,`revoke the invitation ${n}`),await m(e,t,"DELETE",`/stores/invitations/${A(n)}`,void 0,D()),e.out.result({id:n,revoked:!0},()=>e.out.line(`Revoked the invitation ${n}.`))}},gx={name:"stores:devices",summary:"the phones registered for the project's development builds, and where each stands at Apple",usage:"",details:["registering (to be registered at Apple when a build is signed for it), enabled, processing (Apple holds a new membership's 11th to 100th device out of builds for 24 to 72 hours) or refused, in Apple's words.","An Apple account registers 100 iPhones a membership year, and a removed one keeps its place until the year ends."],scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/stores/devices");e.out.result(n,()=>{n.devices.length===0?e.out.line("No phone is registered: a person invited to a package registers theirs from the link (palbase stores:invite)."):e.out.table(n.devices,[{header:"udid",value:s=>s.udid},{header:"model",value:s=>s.product??""},{header:"status",value:s=>s.status==="refused"?`refused${s.limit?" (yearly limit)":""}${s.refusal?`: ${s.refusal}`:""}`:s.status},{header:"people",value:s=>s.people.join(", ")},{header:"registered",value:s=>Z(s.created_at)}])})}},hx={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 f(e),n=ve(e,0,"the package's id"),s=e.flags.text;if(s===void 0||s.trim()==="")throw h("--text is the note testers read");if(s.length>4e3)throw h(`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 k(e,t,`change what testers read with package ${n}${a.locale?` (${a.locale})`:""}`);let o=await m(e,t,"PUT",`/stores/packages/${A(n)}/what-to-test`,a,D());e.out.result(o,()=>e.out.line(`Testers of package ${n} read${a.locale?` (${a.locale})`:""}: ${o.what_to_test??s}`))}};function Lv(e,t){let n=(e.args[t]??"").trim();if(n===""||n.length>40||/[\r\n]/.test(n))throw h("a group's name is 1 to 40 characters on one line");return n}var yx={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 f(e),n=ve(e,0,"the app's id"),s=await m(e,t,"GET",`/stores/apps/${A(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:"kind",value:a=>a.kind??"testflight"},{header:"testers",value:a=>String(a.testers)},{header:"updated",value:a=>Z(a.updated_at)}])})}},fx={name:"stores:groups:create",summary:"make a group of testers for an app: a TestFlight group, or a development group for direct install",usage:"<app id> <name> [--kind testflight|development]",details:["A TestFlight group (an iOS app's default) is an internal and an external group at Apple, whose people Apple mails TestFlight's invitations.","A development group (an Android app's default) is Palbase's own list of the people a package is installed for directly (stores:deliver --channel development): nothing at Apple, no TestFlight invitation."],args:{min:2,max:2},flags:{kind:{type:"string",value:"kind",description:"testflight or development (default: testflight for an iOS app, development for an Android app)"}},scope:"environment",async run(e){let t=await f(e),n=ve(e,0,"the app's id"),s=Lv(e,1),a=e.flags.kind;if(a!==void 0&&!fv.includes(a))throw h(`--kind is one of ${fv.join(", ")}`);await k(e,t,`make the ${a?`${a} `:""}group ${JSON.stringify(s)} of ${n}`);let o={name:s,...a?{kind:a}:{}},i=await m(e,t,"POST",`/stores/apps/${A(n)}/groups`,o,D());e.out.result(i,()=>e.out.line(`Made ${i.name} (${i.id}), a ${i.kind} group.`))}},bx={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 f(e),n=ve(e,0,"the group's id"),s=Lv(e,1);await k(e,t,`rename the group ${n} to ${JSON.stringify(s)}`);let a=await m(e,t,"PATCH",`/stores/groups/${A(n)}`,{name:s},D());e.out.result(a,()=>e.out.line(`${a.id} is ${a.name}.`))}},wx={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 f(e),n=ve(e,0,"the group's id");await k(e,t,`delete the group ${n}`),await m(e,t,"DELETE",`/stores/groups/${A(n)}`,void 0,D()),e.out.result({id:n,deleted:!0},()=>e.out.line(`Deleted the group ${n}.`))}},vx={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 f(e),n=ve(e,0,"the group's id"),s=await m(e,t,"GET",`/stores/groups/${A(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=>Z(a.added_at)}])})}};function kx(e){let t=e.trim();if(t.startsWith("[")){let n=Ne(t,"the testers");if(!Array.isArray(n)||!n.every(s=>typeof s=="object"&&s!==null&&typeof s.email=="string"))throw h('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,o]=n.split(",").map(i=>i.trim());return{email:s,...a?{first_name:a}:{},...o?{last_name:o}:{}}})}var _x={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. ${uc} 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 f(e),n=ve(e,0,"the group's id"),s=Me(e.flags.emails);if(s===void 0==(e.flags.file===void 0))throw h("the testers are named by --emails or --file, one of the two");let a=s?s.map(p=>({email:p})):kx(await ze(e,e.flags.file,"the testers"));for(let p of a)if(!/^[^@\s]+@[^@\s]+$/.test(p.email))throw h(`${JSON.stringify(p.email)} is not an email address`);if(a.length>uc)throw h(`a group holds ${uc} testers at most (${a.length} were named)`);let o=(await m(e,t,"GET",`/stores/groups/${A(n)}/testers`)).testers,i=new Set(a.map(p=>p.email.toLowerCase())),r=o.filter(p=>!i.has(p.email.toLowerCase())).map(p=>p.email);await k(e,t,`set the testers of ${n} to ${a.length}${r.length>0?`; ${r.length} leave: ${r.join(", ")}`:""}`);let l=await m(e,t,"PUT",`/stores/groups/${A(n)}/testers`,{testers:a},D());e.out.result({...l,left:r},()=>{e.out.line(`${n} holds ${l.testers.length} tester${l.testers.length===1?"":"s"}${r.length>0?`; ${r.join(", ")} left it`:""}.`)})}},Sx={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 f(e),n=ve(e,0,"the group's id"),s=ve(e,1,"the package's id");await k(e,t,`give package ${s} to the group ${n}`),await m(e,t,"POST",`/stores/groups/${A(n)}/builds`,{package_id:s},D()),e.out.result({group_id:n,package_id:s},()=>e.out.line(`Gave package ${s} to ${n}.`))}},$x={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 Ln(e){return e===""?"(not set)":e}var Ax={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 f(e),n=ve(e,0,"the app's id"),s=e.flags.locale!==void 0?`?${new URLSearchParams({locale:e.flags.locale})}`:"",a=await m(e,t,"GET",`/stores/apps/${A(n)}/testflight/review-info${s}`);e.out.result(a,()=>{let o=a.locales.filter(d=>d!==a.locale);e.out.line(`Test information of ${n} in ${a.locale}${o.length>0?` (also in ${o.join(", ")})`:""}:`);let i=[`${a.contact_first_name} ${a.contact_last_name}`.trim(),a.contact_phone,a.contact_email].filter(d=>d!=="").join(", "),r=a.demo_account_required?`required: ${Ln(a.demo_account_name)}, password ${a.demo_account_password_set?"set":"not set"}`:"not required",l=[["what to test",Ln(a.description)],["feedback email",Ln(a.feedback_email)],["review contact",Ln(i)],["demo account",r],["notes",Ln(a.notes)]],p=Math.max(...l.map(([d])=>d.length));for(let[d,u]of l)e.out.line(` ${d.padEnd(p)} ${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).`)})}},Px={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 f(e),n=ve(e,0,"the app's id"),s={};for(let[o,i]of Object.entries($x))e.flags[o]!==void 0&&(s[i]=e.flags[o]);if(e.flags["demo-password-stdin"]===!0&&(s.demo_account_password=await lt(e,"the demo account's password")),Object.keys(s).length===0)throw h("nothing to write: name at least one field","palbase help stores:review-info:set");await k(e,t,`write ${Object.keys(s).join(", ")} of ${n}'s Beta App Review information`);let a=await m(e,t,"PUT",`/stores/apps/${A(n)}/testflight/review-info`,s,D());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 vc(e,t){let n=P1[y1(t).toLowerCase()];if(n===void 0)throw h(`${e}: a screenshot is a .png or .jpg file`);let s;try{let a=await gc(t);if(!a.isFile())throw new Error("not a file");s=a.size}catch(a){throw new b("unreadable_file",`${e} could not be read: ${a instanceof Error?a.message:String(a)}`)}if(s===0||s>A1)throw h(`${e}: a screenshot is 1 byte to 10 MB, and it is ${s} bytes`);return{file:e,path:t,contentType:n}}async function Rx(e,t,n){let s=hs(e.io.cwd,ue),a=hs(t,n),o=mv(s,a);if(o===""||o===".."||o.startsWith(`..${gv}`)||f1(o))throw h(`${n}: a screenshot the page names by its file is under ${ue}/, and ${mv(e.io.cwd,a)||a} is not`,`move it under ${ue}/, or name it by the SHA-256 palbase stores:screenshots:upload printed`);let i,r;try{[r,i]=await Promise.all([uv(s),uv(a)])}catch(l){throw new b("unreadable_file",`${n} could not be read: ${l instanceof Error?l.message:String(l)}`)}if(!i.startsWith(r+gv))throw new b("outside_palbase",`${n} is a link out of ${ue}/: palbase reads only what is under it`);return vc(n,i)}async function kc(e,t,n,s,a="page"){let o;try{o=await Pv(s.path,{type:s.contentType})}catch(i){throw new b("unreadable_file",`${s.file} could not be read: ${i instanceof Error?i.message:String(i)}`)}for(let i=1;;i++)try{let r=`/stores/apps/${A(n)}/screenshots${a==="review"?"?for=review":""}`;return await m(e,t,"PUT",r,new Hs(o,s.contentType))}catch(r){if(!(r instanceof G)||r.status!==503||r.code!=="stores_busy")throw r;let l=Math.max(r.retryAfter??60,1);if(i>=vv||l>Ev)throw r;e.out.note(`${s.file}: ${r.message}; trying again in ${l} s (${i+1} of ${vv})`),await e.io.sleep(l*1e3)}}var Ns=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function jx(e){let t=Ns(e)&&"draft"in e&&"revision"in e?e.draft:e;if(!Ns(t)||!Ns(t.locales))throw h('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 ${gs} writes it`);for(let[n,s]of Object.entries(t.locales)){if(!Ns(s))throw h(`locales.${n} is an object: { "name": \u2026, \u2026 }`);if(s.screenshots!==void 0){if(!Ns(s.screenshots))throw h(`locales.${n}.screenshots is an object of display \u2192 its screenshots (${$1.join(", ")})`);for(let[a,o]of Object.entries(s.screenshots))if(!Array.isArray(o)||!o.every(i=>typeof i=="string"&&i.trim()!==""))throw h(`locales.${n}.screenshots.${a} is a list of screenshots, each a SHA-256 or a file under ${ue}/`)}}return t}function Ex(e,t){let n=structuredClone(e);for(let s of Object.values(n.locales))for(let[a,o]of Object.entries(s.screenshots??{}))s.screenshots[a]=o.map(t);return n}var Xn=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`;function Iv(e,t,n,s,a){if(t instanceof G){if(t.code==="listing_moved")throw new b("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 o=t.message.split("; ").filter(i=>i!=="");e.out.note(`The page has ${Xn(o.length,"problem")}:`);for(let i of o)e.out.note(` ${i}`);throw new b("listing_invalid",`${s}: the page breaks ${Xn(o.length,"rule")} of the App Store's`,{hint:"fix each in the file, and save it again"})}if(t.code==="listing_empty")throw new b("listing_empty",`${n} has no draft App Store page yet: ${s}`,{hint:`write one: palbase stores:listing:get ${n} --out ${gs}, edit it, then palbase stores:listing:put ${n} --file ${gs} --revision 0`});if(t.code==="no_editable_version")throw new b("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 Tx={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 <${gs}>]`,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 f(e),n=ve(e,0,"the app's id"),s=e.flags.out,a=s!==void 0?Kt(e,"out",s,".json",gs):void 0,o=await m(e,t,"GET",`/stores/apps/${A(n)}/listing`);if(a!==void 0){let i=await Be(e.io.cwd,a);await c1(jv(i),{recursive:!0}),await Be(e.io.cwd,a),await g1(i,`${JSON.stringify(o.draft,null,2)}
|
|
11122
|
+
`)}async function xl(e,t){let n=Ne(await ze(e,t,"the paywall"),"the paywall");if(typeof n!="object"||n===null||Array.isArray(n))throw h("a paywall is a JSON object: { schema, name, default_locale, theme, root, \u2026 }");if("draft"in n&&"draft_revision"in n)throw h('the file is a whole paywall (its draft, its revision, its problems): give its "draft" alone, as iap:paywalls:get --out writes it');if("definition"in n&&!("root"in n))throw h('the file is a definition inside something else: give the "definition" alone, as iap:paywalls:get --out writes it');let{$schema:s,...a}=n;return a}function Ll(e,t){for(let n of t)e.out.note(` ${n.path}: ${n.code} \u2014 ${n.message}${n.warning?" (warning)":""}`)}var ov=e=>e.filter(t=>!t.warning).length;function iv(e){if(!(!(e instanceof G)||e.code!=="invalid_paywall"))return(e.body??{}).problems??[]}function rv(e,t,n){let s=iv(t);throw s!==void 0?(s.length>0&&(e.out.note(`The paywall breaks ${ov(s)} rule(s):`),Ll(e,s)),new b("invalid_paywall",`${n}: ${t.message}`,{hint:"fix each problem in the file (palbase iap:paywalls:validate --file <file> checks it without saving)"})):t}function lv(e,t,n){return new b("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 iap:paywalls:get ${JSON.stringify(e)}), make the edit on it, and save it with that revision`})}async function ZO(e,t){let n=new Map,s=(r,l)=>{if(r===void 0)return;let p=n.get(r)??[];p.includes(l)||p.push(l),n.set(r,p)},{placements:a}=await m(e,t,"GET","/iap/placements");for(let r of a)s(r.paywall_id,r.key);let o=a.filter(r=>r.rule_count>0);return(await Promise.all(o.map(r=>m(e,t,"GET",`/iap/placements/${A(r.key)}/rules`)))).forEach((r,l)=>{for(let p of r.rules)s(p.target.paywall_id,`${o[l].key} (rule)`)}),n}var QO={name:"iap: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: iap:paywalls:get writes one to a file, iap:paywalls:put saves the edit as its draft, iap: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 iap:paywalls:guide"],scope:"environment",async run(e){let t=await f(e),[n,s]=await Promise.all([ms(e,t),ZO(e,t)]),a=n.map(o=>({...o,placements:s.get(o.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 iap:paywalls:put <name> --file ${_t}/<name>.json --revision 0`);return}e.out.table(a,[{header:"name",value:o=>o.name},{header:"id",value:o=>o.id},{header:"draft",value:o=>`revision ${o.draft_revision}`},{header:"published",value:o=>o.published_version===0?"never":`version ${o.published_version}, ${Z(o.published_at)}`},{header:"shown at",value:o=>o.placements.length===0?"\u2014":o.placements.join(", ")}])})}},e1={name:"iap: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 <${_t}/name.json>] [--version <n>]`,details:[`The file is the definition alone, as iap:paywalls:put takes it, under ${_t}/. Its first line names its JSON Schema, written beside it (${uo}), so an editor checks the file as it is edited.`,"The revision printed is the one an edit is saved on: iap:paywalls:put --revision."],args:{min:1,max:1},flags:{out:{type:"string",value:"file",description:`where under ${ue}/ (default: ${_t}/<name>.json)`},version:{type:"string",value:"n",description:"a published version instead of the draft"}},scope:"environment",async run(e){let t=await f(e),n=we(e.flags.version,"version");if(n===0)throw h("--version is 1 or more: the versions published");let s=await wa(e,t,mo(e,0,"the paywall's name or id")),a=e.flags.out!==void 0?Kt(e,"out",e.flags.out,".json"):`${_t}/${bi(s.name)}${n===void 0?"":`.v${n}`}.json`;if(n!==void 0){let i;try{i=await m(e,t,"GET",`/iap/paywalls/${A(s.id)}/versions/${n}`)}catch(r){throw r instanceof G&&r.status===404?new b("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)`}`):r}if(!i.definition)throw new b("unexpected_answer",`the module answered version ${n} of ${s.name} without its definition`);await Tl(e,a,i.definition),e.out.result({file:a,paywall_id:s.id,name:s.name,version:i.version,published_at:i.published_at,draft_revision:s.draft_revision},()=>{e.out.line(`Wrote version ${i.version} of ${s.name} (published ${Z(i.published_at)}) to ${a}.`),e.out.line(`Saved as the draft, it goes on the draft's revision: palbase iap:paywalls:put ${JSON.stringify(s.name)} --file ${a} --revision ${s.draft_revision}`)});return}let o=await m(e,t,"GET",`/iap/paywalls/${A(s.id)}`);await Tl(e,a,o.draft),e.out.result({file:a,paywall_id:o.id,name:o.name,revision:o.draft_revision,published_version:o.published_version,problems:o.problems},()=>{e.out.line(`Wrote draft revision ${o.draft_revision} of ${o.name} to ${a}${o.published_version===0?" (never published)":` (version ${o.published_version} is published)`}.`),o.problems.length>0&&(e.out.note("The module says of the draft:"),Ll(e,o.problems)),e.out.line(`Save an edit of it: palbase iap:paywalls:put ${JSON.stringify(o.name)} --file ${a} --revision ${o.draft_revision}`)})}},t1={name:"iap: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 f(e),n=await xl(e,e.flags.file),s;try{s={valid:!0,problems:(await m(e,t,"POST","/iap/paywalls/validate",n,D())).problems??[]}}catch(a){let o=iv(a);if(o===void 0)throw a;s={valid:!1,problems:o}}return e.out.result(s,()=>{s.problems.length>0&&Ll(e,s.problems);let a=s.problems.filter(o=>o.warning).length;e.out.line(s.valid?`The paywall can be published${a>0?`, with ${a} warning(s)`:""}.`:`The paywall breaks ${ov(s.problems)} rule(s): it cannot be saved as it is.`)}),s.valid?void 0:1}};async function pv(e,t,n,s){try{let a=await Pt(e,t,"POST",`/iap/paywalls/${A(n.id)}/publish`,void 0,{"if-match":Cl(s),...D()});return{version:a.body,fresh:a.status===201}}catch(a){if(a instanceof G&&a.status===412)throw lv(n.name,s,"published");rv(e,a,`${n.name} was not published`)}}function dv(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 n1={name:"iap: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 iap:paywalls:publish). A new paywall takes the name its definition gives.","How a definition is written: palbase iap:paywalls:guide"],args:{min:1,max:1},flags:{file:{type:"string",value:"paywall.json",description:"the definition, as iap:paywalls:get wrote it ('-' or none: stdin)"},revision:{type:"string",value:"n",description:"the draft revision it was edited from, as iap: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 f(e),n=mo(e,0,"the paywall's name or id"),s=we(e.flags.revision,"revision");if(s===void 0)throw h("--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 xl(e,e.flags.file),o=Ol(await ms(e,t),n),i=e.flags.publish===!0?" and publish it":"",r;try{if(o){if(s===0)throw new b("paywall_exists",`${o.name} is there already, at draft revision ${o.draft_revision}: an edit of it is saved on the revision it was read at`,{hint:`palbase iap:paywalls:get ${JSON.stringify(o.name)} writes it and prints the revision`});await k(e,t,`save the draft of ${o.name} over revision ${s}${i}`),r=await m(e,t,"PUT",`/iap/paywalls/${A(o.id)}/draft`,{definition:a},{"if-match":Cl(s),...D()})}else{if(pc.test(n))throw new b("paywall_not_found",`no paywall ${n}`);if(s!==0)throw new b("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 h(`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 iap:paywalls:put ${JSON.stringify(a.name??"")} \u2026`);await k(e,t,`make the paywall ${a.name}${i}`),r=await m(e,t,"POST","/iap/paywalls",{definition:a},D())}}catch(p){if(p instanceof G&&p.status===412)throw lv(o?.name??n,s,"saved");if(p instanceof G&&p.code==="too_many_paywalls")throw new b("too_many_paywalls","the project has 100 paywalls, the most it holds: nothing was made",{hint:"delete one no placement shows: palbase iap:paywalls:delete <name>"});rv(e,p,"the paywall was not saved")}let l=e.flags.publish===!0?await pv(e,t,r,r.draft_revision):void 0;e.out.result({...r,...l?{published:l.version,published_new:l.fresh}:{}},()=>{e.out.line(`${o?"Saved":"Made"} ${r.name}: its draft is at revision ${r.draft_revision}.`),r.problems.length>0&&(e.out.note("The module says of the draft:"),Ll(e,r.problems)),l?dv(e,r.name,l):e.out.line(`The apps draw it once it is published: palbase iap:paywalls:publish ${JSON.stringify(r.name)}`)})}},s1={name:"iap: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 f(e),n=await wa(e,t,mo(e,0,"the paywall's name or id")),s=we(e.flags.revision,"revision")??n.draft_revision;await k(e,t,`publish draft revision ${s} of ${n.name}`);let a=await pv(e,t,n,s);e.out.result({...a.version,published_new:a.fresh},()=>dv(e,n.name,a))}},a1={name:"iap: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 f(e),n=await wa(e,t,mo(e,0,"the paywall's name or id"));await k(e,t,`delete the paywall ${n.name}: its draft and every version of it`);try{await m(e,t,"DELETE",`/iap/paywalls/${A(n.id)}`,void 0,D())}catch(s){throw s instanceof G&&s.code==="paywall_in_use"?new b("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 iap: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}.`))}},o1={name:"iap: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 <${uo}>]`,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 iap:paywalls:validate asks it.",'iap: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 ${ue}/ (default: ${uo}); --json prints it instead`}},scope:"none",async run(e){if(e.global.json){e.out.result(Rl,()=>{});return}let t=e.flags.out!==void 0?Kt(e,"out",e.flags.out,".json"):uo;await El(e,t,av),e.out.line(`Wrote the paywall definition's JSON Schema to ${t}.`)}},i1={name:"iap: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 <${_t}/GUIDE.txt>]`,details:["It is made from the definition's JSON Schema the CLI carries (iap: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 ${ue}/ instead of printing it`}},scope:"none",async run(e){let t=Qw(Rl),n=e.flags.out;if(n===void 0){e.out.result({guide:t},()=>e.io.stdout(t));return}let s=Kt(e,"out",n,".txt");await El(e,s,t),e.out.result({file:s},()=>e.out.line(`Wrote the guide to ${s}.`))}},tv=["image","video","font","html"];function lc(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 go(e,t){return(await m(e,t,"GET","/iap/paywalls/assets")).assets??[]}var nv={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 iap 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 iap:paywalls:assets:delete <id>)"};async function dc(e,t){let n;try{n=await m(e,t,"GET",`/storage/buckets/${Is}`)}catch(s){if(!(s instanceof G)||s.status!==404)throw s}if(!n?.public){if(n)throw new b("asset_bucket_private",`the project's ${Is} 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 ${Is} --public`});await m(e,t,"PUT",`/storage/buckets/${Is}`,{public:!0,file_size_limit:null,allowed_mime_types:[],variants:[]}),e.out.note(`Made the public bucket ${Is}: paywall assets are kept in the project's own storage.`)}}function r1(e){let t=jl(e).normalize("NFKD").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(-80).replace(/^\.+$/,"")||"file";return`paywalls/${FO()}/${t}`}async function cc(e,t,n,s){let a=r1(n);await Jd(e,t,n,Is,a);try{return await m(e,t,"POST","/iap/paywalls/assets",{path:a,...s?{kind:s}:{}},D())}catch(o){throw await m(e,t,"DELETE",`/storage/buckets/${Is}/objects/${ml(a)}`).catch(()=>{}),o instanceof G&&o.code!==void 0&&o.code in nv?new b(o.code,`${jl(n)} was not registered: ${nv[o.code]}`):o}}var l1={name:"iap: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 f(e),n=await go(e,t);e.out.result({assets:n},()=>{if(n.length===0){e.out.line("No paywall asset yet."),e.out.line("Upload one: palbase iap: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=>lc(s.bytes)},{header:"file",value:s=>s.path.split("/").pop()??s.path},{header:"registered",value:s=>Z(s.created_at)}])})}},p1={name:"iap: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 ${Is} (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 f(e),n=sv(e.io.cwd,mo(e,0,"the file")),s=e.flags.kind;if(s!==void 0&&!tv.includes(s))throw h(`--kind is one of ${tv.join(", ")}`);let a;try{let i=await JO(n);if(!i.isFile())throw new Error("it is not a file");a=i.size}catch(i){throw new b("unreadable_file",`${e.args[0]} could not be read: ${i instanceof Error?i.message:String(i)}`)}if(a===0)throw new b("empty_file",`${e.args[0]} is empty`);await k(e,t,`upload ${jl(n)} (${lc(a)}) as a paywall asset`),await dc(e,t);let o=await cc(e,t,n,s);e.out.result(o,()=>{e.out.line(`Registered ${jl(n)} as ${o.ref} (${o.kind}, ${lc(o.bytes)}).`),e.out.line(`A definition names it "${o.ref}" where it takes ${o.kind==="html"?"an HTML block":o.kind==="image"?"an image":`a ${o.kind}`}.`)})}},d1={name:"iap: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 f(e),n=mo(e,0,"the asset's id").replace(/^asset:/,"").toLowerCase();if(!pc.test(n))throw h(`${e.args[0]} is not an asset: asset:<id>, as iap:paywalls:assets lists them`);let s=(await go(e,t)).find(o=>o.id===n);if(!s)throw new b("asset_not_found",`the project has no asset ${n}`,{hint:"palbase iap:paywalls:assets lists them"});await k(e,t,`delete the paywall asset ${s.ref} (${s.path.split("/").pop()})`);try{await m(e,t,"DELETE",`/iap/paywalls/assets/${A(n)}`,void 0,D())}catch(o){throw o instanceof G&&o.code==="asset_in_use"?new b("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"}):o}let a=!0;await m(e,t,"DELETE",`/storage/buckets/${A(s.bucket)}/objects/${ml(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}`)})}},cv=[QO,e1,t1,n1,s1,a1,o1,i1,l1,p1,d1];var hv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,v1=/^AuthKey_([A-Z0-9]{10})\.p8$/,k1=8192,yv=["testflight","play_internal","development"],fv=["testflight","development"],uc=100,bv=5,_1=5,Ev=300,S1=5,Il=900,$1=["iphone_6_9","iphone_6_5","ipad_13"],wv=/^[0-9a-f]{64}$/i,A1=10*1024*1024,vv=3,P1={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg"},gs=`${ue}/store/listing.json`,Ds={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 ho(e){return e.package_id?`package ${e.package_id}`:`app ${e.app_id??"?"}`}var hc=e=>e.charAt(0).toUpperCase()+e.slice(1);function Z(e){return e?e.slice(0,19).replace("T"," "):"\u2014"}function ve(e,t,n){let s=e.args[t];if(s===void 0||s.trim()==="")throw h(`${n} is required`);return s}function mn(e,t,n,s){let a=Qt(e.cloud,t.env_ref),o;try{o=new URL(n).origin}catch{throw new b("unexpected_address",`${s} is not a URL: nothing was sent`)}if(o!==a)throw new b("unexpected_address",`${s} names ${o}, not the environment's address ${a}: nothing was sent`);return a}async function vi(e,t,n,s){let a;try{a=await e.io.fetch(t,{...n,redirect:"manual"})}catch(l){throw new b("network_error",`${s}: ${t} could not be reached: ${l instanceof Error?l.message:String(l)}`)}let o=await a.text(),i;if(o!=="")try{i=JSON.parse(o)}catch{i=o}if(a.status>=200&&a.status<300)return i;let r=i??{};throw new G({op:s,status:a.status,code:typeof r.error=="string"?r.error:`http_${a.status}`,message:dr(i,a.status),requestId:typeof r.request_id=="string"?r.request_id:a.headers.get("x-request-id")??void 0,retryAfter:R1(a.headers.get("retry-after"),r.retry_after,e.io.now()),body:i})}function R1(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 yc(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 ${Z(t.checked_at)})`:""}`),t.capabilities&&e.out.line(`reaches: ${t.capabilities.length>0?t.capabilities.join(", "):"nothing"}`),t.connected_at&&e.out.line(`connected ${Z(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 fc(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 ${Z(t.checked_at)})`:""}`),t.connected_at&&e.out.line(`signed in ${Z(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 j1={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 f(e),n=await m(e,t,"GET","/stores/apple"),s=await m(e,t,"GET","/stores/apple/session").catch(a=>{if(!(a instanceof G&&a.status===404))throw a});e.out.result(s===void 0?n:{...n,apple_id_session:s},()=>{yc(e,n),s!==void 0&&(e.out.line(""),fc(e,s))})}};async function E1(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 Lp(Un(e.seal_key),n,new TextEncoder().encode(t)),o=new Uint8Array(s.length+a.length);return o.set(s),o.set(a,s.length),Vo(o)}async function T1(e,t,n){if(e.flags["key-file"]!==void 0)throw h("--apple-id or --key-file, not both");if(e.flags["print-link"]===!0){await k(e,t,"make a link that signs an Apple ID in");let d=await m(e,t,"POST","/stores/apple/session/grants",void 0,D());mn(e,t,d.connect_url,"the sign-in link"),e.out.result({connect_url:d.connect_url,expires_at:d.expires_at},()=>{e.out.line(d.connect_url),e.out.note(`Open it in a browser and sign in there; it works once, until ${Z(d.expires_at)}.`)});return}if(!e.io.interactive)throw h("signing an Apple ID in asks for Apple's code at the terminal","or --print-link for a link a browser opens");await k(e,t,`sign the Apple ID ${n} in`);let s=await lt(e,`the password of ${n}`),a=await m(e,t,"POST","/stores/apple/session/grants",void 0,D()),o=mn(e,t,a.connect_url,"the sign-in link"),i=await E1(a,s),r=(d,u)=>vi(e,`${o}/stores/connect/apple-id${d}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({grant:a.grant,...u})},"signing the Apple ID in"),l=await r("",{apple_id:n,password_sealed:i});for(;l.step==="code";){let d=l.method==="phone"?`to ${l.destination??"your phone"}`:"to your trusted devices",u=(await e.io.prompt(`Apple sent a code ${d}. Code: `)).replace(/\s/g,"");try{l=await r("/code",{code:u})}catch(g){if(g instanceof G&&g.code==="apple_code_refused"){e.out.note("Apple did not accept this code.");continue}throw g}}if(l.step==="team"){let d=l.teams??[],u=e.flags.team,g=u===void 0?void 0:d.find(y=>y.id===u||y.name===u);if(u!==void 0&&g===void 0)throw new b("unknown_team",`${n} is not in the team ${u}: ${d.map(y=>y.name).join(", ")}`);for(;g===void 0;){d.forEach((w,v)=>e.out.note(` ${v+1}. ${w.name}`));let y=Number((await e.io.prompt(`${n} is in ${d.length} teams. The one this environment's apps are in [1-${d.length}]: `)).trim());g=d[y-1]}l=await r("/team",{team:g.id})}let p=l.session??{connected:!1};e.out.result(p,()=>{e.out.line(`Signed ${n} in to ${ee(t)}.`),fc(e,p)})}var C1={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 f(e),n=e.flags["apple-id"];if(n!==void 0){if(n.trim()==="")throw h("--apple-id is the Apple ID: an email address");await T1(e,t,n.trim());return}if(e.flags["print-link"]===!0){if(e.flags["key-file"]!==void 0)throw h("--print-link or --key-file, not both");await k(e,t,"make a link that connects an Apple account");let g=await m(e,t,"POST","/stores/apple/grants",void 0,D());mn(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 ${Z(g.expires_at)}.`)});return}let s=e.flags["key-file"],a=e.flags["issuer-id"];if(s===void 0)throw h("--key-file names the .p8 file","or --print-link for a link a browser opens");if(a===void 0||a.trim()==="")throw h("--issuer-id is the account's issuer id (App Store Connect \u2192 Users and Access \u2192 Integrations)");let o=h1(s),i=e.flags["key-id"]??v1.exec(o)?.[1];if(i===void 0)throw h(`--key-id is needed: ${o} is not named AuthKey_<KEYID>.p8`);let r;try{let g=hs(e.io.cwd,s);if((await gc(g)).size>k1)throw new b("not_a_key",`${s} is larger than a .p8 key`);r=await u1(g,"utf8")}catch(g){throw g instanceof b?g:new b("unreadable_file",`${s} could not be read: ${g instanceof Error?g.message:String(g)}`)}if(!r.includes("-----BEGIN PRIVATE KEY-----"))throw new b("not_a_key",`${s} is not a .p8 key (no "BEGIN PRIVATE KEY")`);await k(e,t,`connect the Apple account of issuer ${a} with key ${i}`);let l=await m(e,t,"POST","/stores/apple/grants",void 0,D()),p=mn(e,t,l.connect_url,"the connect link"),d={grant:l.grant,issuer_id:a.trim(),key_id:i,private_key:r,file_name:o},u=await vi(e,`${p}/stores/connect`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(d)},"connecting the Apple key");e.out.result(u,()=>{e.out.line(`Connected key ${i} to ${ee(t)}.`),yc(e,u)})}},O1={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 f(e);if(e.flags["apple-id"]===!0){let s=await m(e,t,"POST","/stores/apple/session/check",void 0,D());e.out.result(s,()=>fc(e,s));return}let n=await m(e,t,"POST","/stores/apple/check",void 0,D());e.out.result(n,()=>yc(e,n))}},x1={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 f(e);if(e.flags["apple-id"]===!0){let n=await m(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 k(e,t,`sign the Apple ID out${s}`),await m(e,t,"DELETE","/stores/apple/session",void 0,D()),e.out.result({disconnected:!0},()=>e.out.line(`Signed the Apple ID out of ${ee(t)}, at Apple too.`));return}await k(e,t,"disconnect the Apple account (a key Palbase made is revoked at Apple)"),await m(e,t,"DELETE","/stores/apple",void 0,D()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected the Apple account from ${ee(t)}.`))}},va={asc:"App Store Connect API key",apns:"APNs keys (one for production, one for the sandbox)",iap:"In-App Purchase key"},L1=2,I1=60;function bc(e,t){let n=t.kind==="apns"?`APNs key (${t.environment??"?"})`:va[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 Tv(e,t,n){let s=r=>n.some(l=>l.kind===r&&l.state==="waiting"),a=await m(e,t,"GET","/stores/apple"),o=await m(e,t,"GET","/notify/providers"),i=await m(e,t,"GET","/iap/apple");return{asc:!a.connected,apns:!o.providers.some(r=>r.channel==="push"&&r.provider==="apns")&&!s("apns"),iap:!i.connected&&!s("iap")}}var N1={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 f(e),n=await m(e,t,"GET","/stores/apple/keys"),s=await Tv(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(o=>bc(e,o)));let a=Object.keys(va).filter(o=>s[o]);if(a.length===0){e.out.line("The environment lacks no key.");return}e.out.line(`The environment lacks: ${a.map(o=>va[o]).join("; ")}.`),e.out.line("Make them at Apple: palbase stores:apple:keys:make")})}},M1={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); iap 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 f(e),n=await m(e,t,"GET","/stores/apple/keys"),s=await Tv(e,t,n.keys),a=Object.keys(va).filter(d=>e.flags[d]===!0),o=a.length>0?a:Object.keys(va);for(let d of o.filter(u=>!s[u]))e.out.note(`The environment has its ${va[d]}: it is kept.`);let i=o.filter(d=>s[d]);if(i.length===0){e.out.result({keys:[]},()=>e.out.line("The environment lacks none of these keys: nothing to make."));return}await k(e,t,`make at Apple and connect: ${i.map(d=>va[d]).join("; ")}`);let r=[];for(let d of i){let u={kind:d};d==="iap"&&typeof e.flags.bundle=="string"&&(u.bundle=e.flags.bundle);let g=await m(e,t,"POST","/stores/apple/keys",u,D());r.push(...g.keys)}let l=e.io.now()+I1*1e3,p=r;for(;p.some(d=>d.state==="waiting")&&e.io.now()<l;){await e.io.sleep(L1*1e3);let d=await m(e,t,"GET","/stores/apple/keys");p=r.map(u=>d.keys.find(g=>g.key_id===u.key_id)??u)}e.out.result({keys:p},()=>{e.out.line(`Made at Apple for ${ee(t)}:`),p.forEach(d=>bc(e,d)),p.some(d=>d.state==="waiting")&&e.out.note("A module has not taken its key yet: palbase stores:apple:keys says when it has.")})}},D1={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=ve(e,0,"the key id"),n=await f(e);await k(e,n,`revoke the key ${t} at Apple`);let s=await m(e,n,"DELETE",`/stores/apple/keys/${A(t)}`,void 0,D());e.out.result(s,()=>{e.out.line(`Revoked ${t} at Apple.`),bc(e,s)})}};async function Cv(e,t,n){let s=(await rt(e.studio)).filter(o=>o.project_id===t.project_id),a=s.find(o=>o.slug===n||o.ref===n);if(!a)throw new b("no_such_environment",`${t.project_name} has no environment ${JSON.stringify(n)}`,{hint:`its environments: ${s.map(o=>o.slug).join(", ")}`});if(a.ref===t.env_ref)throw h("the environment uses its own session: name another environment of the project");return a}var z1={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=ve(e,0,"the environment to share with"),n=await f(e),s=await Cv(e,n,t);await k(e,n,`share its Apple ID session with ${s.name} (${s.slug})`);let a=await m(e,n,"PUT",`/stores/apple/session/shares/${A(s.ref)}`,void 0,D());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.`)})}},q1={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=ve(e,0,"the environment to take it back from"),n=await f(e),s=await Cv(e,n,t);await k(e,n,`take its Apple ID session back from ${s.name} (${s.slug})`),await m(e,n,"DELETE",`/stores/apple/session/shares/${A(s.ref)}`,void 0,D()),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 wc(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 ${Z(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 ${Z(t.connected_at)}${t.connected_by?` by ${t.connected_by}`:""}`),t.action&&e.out.line(`To do: ${t.action}`)}var G1={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 f(e),n=await m(e,t,"GET","/stores/google");e.out.result(n,()=>wc(e,n))}},K1={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 manages a dedicated service account for your environment.","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 f(e);await k(e,t,"connect Google Play (Palbase makes a service account for it)");let n=await m(e,t,"POST","/stores/google",void 0,D());e.out.result(n,()=>wc(e,n))}},U1={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 f(e),n=await m(e,t,"POST","/stores/google/check",void 0,D());e.out.result(n,()=>wc(e,n))}},W1={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 f(e);await k(e,t,"disconnect Google Play (its service account is deleted)"),await m(e,t,"DELETE","/stores/google",void 0,D()),e.out.result({disconnected:!0},()=>e.out.line(`Disconnected Google Play from ${ee(t)}.`))}};function F1(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 B1={name:"stores:apps",summary:"the environment's apps linked to their store",scope:"environment",async run(e){let t=await f(e),n=await m(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":""}])})}},J1={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 f(e),n=ve(e,0,"the app's id"),s=e.flags.name!==void 0?{name:e.flags.name}:{};await k(e,t,`link the app ${n} to its store`);let a=await m(e,t,"POST",`/stores/apps/${A(n)}/link`,s,D());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}).`),F1(e,a)})}},H1={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 f(e),n=ve(e,0,"the app's id"),s=await m(e,t,"GET",`/stores/apps/${A(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=>Z(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>`)})}},V1={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 f(e),n=ve(e,0,"the app's id"),s=e.args[1];if(s!=="crash"&&s!=="screenshot")throw h("the kind is crash or screenshot");let a=ve(e,2,"the feedback's id"),o=await m(e,t,"GET",`/stores/apps/${A(n)}/feedback/${s}/${A(a)}`);e.out.result(o,()=>{e.out.line(`${hc(o.kind)} ${I(o.id)}, sent ${Z(o.created_at)}${o.email?` by ${I(o.email)}`:""}`);let i=[o.device_model,o.os_version?`iOS ${o.os_version}`:void 0,o.locale].filter(Boolean).join(", ");i&&e.out.line(`from: ${I(i)}`),o.asc_build_id&&e.out.line(`build: ${I(o.asc_build_id)} (App Store Connect's id)`),o.comment&&e.out.line(`comment: ${I(o.comment)}`);for(let r of o.screenshots??[])e.out.line(`screenshot ${r.width}x${r.height}, until ${Z(r.expires_at)}: ${I(r.url)}`);o.kind==="crash"&&(o.crash_log?(e.out.line(o.crash_log_cut?"crash log (cut at 32 KiB):":"crash log:"),e.out.line(o.crash_log)):e.out.line("Apple has no log of this crash."))})}};function kv(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: ${I(n.error)}`),n.url&&e.out.line(`reports to: ${I(n.url)}`),n.event_types.length>0&&e.out.line(`tells: ${n.event_types.join(", ")}`),n.installed_at&&e.out.line(`made ${Z(n.installed_at)}${n.asc_webhook_id?` (App Store Connect's ${I(n.asc_webhook_id)})`:""}`),e.out.line(n.last_delivery_at?`last delivery: ${I(n.last_delivery_type??"?")}, ${Z(n.last_delivery_at)}`:"last delivery: none yet"),n.pinged_at&&e.out.line(`last ping: ${Z(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 _v=30,Sv=2,X1={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 f(e),n=ve(e,0,"the app's id"),s=`/stores/apps/${A(n)}/webhook`,a;if(e.flags.make?(await k(e,t,`make the App Store Connect webhook of ${n} again`),a=await m(e,t,"POST",s,{})):a=await m(e,t,"GET",s),e.flags.ping){let o=a.last_delivery_at;await m(e,t,"POST",`${s}/ping`,{});for(let r=0;r<_v&&(await e.io.sleep(Sv*1e3),a=await m(e,t,"GET",s),!(a.pinged_at&&a.last_delivery_at&&a.last_delivery_at!==o));r+=Sv);let i=!!(a.last_delivery_at&&a.last_delivery_at!==o);e.out.result({...a,ping_arrived:i},()=>{kv(e,n,a),e.out.line(i?"The ping arrived.":`Apple did not deliver the ping within ${_v} s: look again with palbase stores:webhook ${n}`)});return}e.out.result(a,()=>kv(e,n,a))}},wi=e=>e==null?"\u2014":`${(e*100).toFixed(2)}%`,Y1={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"},Z1={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 f(e),n=ve(e,0,"the app's id"),s=await m(e,t,"GET",`/stores/apps/${A(n)}/vitals`);e.out.result(s,()=>{if(e.out.line(`${s.platform==="android"?"Google Play":"App Store"} health of ${n}, read ${Z(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:o=>Z(o.created_at)},{header:"id",value:o=>o.id},{header:"comment",value:o=>o.comment??""}])),a.testflight_builds.length>0&&(e.out.line("TestFlight builds, as Apple counts them:"),e.out.table(a.testflight_builds,[{header:"build",value:o=>`${o.version} (${o.build_number})${o.expired?", expired":""}`},{header:"days",value:o=>o.from?`${o.from} \u2013 ${o.to??o.from}`:"\u2014"},{header:"installs",value:o=>String(o.installs)},{header:"sessions",value:o=>String(o.sessions)},{header:"crashes",value:o=>String(o.crashes)},{header:"feedback",value:o=>String(o.feedback)},{header:"invites",value:o=>String(o.invites)}])),e.out.line(Y1[a.crash_counts]??a.crash_counts),a.crash_days.length>0&&e.out.table(a.crash_days,[{header:"day",value:o=>o.date},{header:"version",value:o=>o.version},{header:"crashes",value:o=>String(o.crashes)},{header:"devices",value:o=>String(o.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:o=>o.category},{header:"metric",value:o=>o.identifier},{header:"version",value:o=>o.version},{header:"value",value:o=>`${o.value}${o.unit?` ${o.unit}`:""}`},{header:"devices",value:o=>o.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:o=>String(o.version_code)},{header:"crashes",value:o=>wi(o.crash_rate)},{header:"crashes in use",value:o=>wi(o.user_perceived_crash_rate)},{header:"ANRs",value:o=>wi(o.anr_rate)},{header:"ANRs in use",value:o=>wi(o.user_perceived_anr_rate)},{header:"users",value:o=>String(o.users)}]),a.issues.length>0&&e.out.table(a.issues,[{header:"error",value:o=>o.type},{header:"cause",value:o=>o.cause},{header:"where",value:o=>o.location},{header:"reports",value:o=>String(o.reports)},{header:"users",value:o=>String(o.users)}]);for(let o of a.anomalies)e.out.line(`Play flagged ${I(o.metric)}${o.version_code?` of version code ${o.version_code}`:""}${o.value!==null?`: ${wi(o.value)}`:""}${o.from?` (${o.from}${o.to?` \u2013 ${o.to}`:""})`:""}`)}})}};function Q1(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 ${Z(t.uploaded_at)}`:"waiting for its build"}`),t.size!==null&&e.out.line(`${t.format?`.${t.format}`:"build"}: ${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 ${Z(t.created_at)} by ${t.created_by} (command ${t.command_id})`);for(let n of t.deliveries)e.out.line(`${n.channel}: ${Ov(n)}`)}function Ov(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.signed_devices!==void 0&&t.push(`signed for ${e.signed_devices} phone${e.signed_devices===1?"":"s"}`),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 ex={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 f(e),n=we(e.flags.limit,"limit")??20;if(n<1||n>200)throw h("--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 m(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:o=>o.id},{header:"app",value:o=>o.app_id},{header:"build",value:o=>String(o.build_number)},{header:"version",value:o=>o.version??""},{header:"status",value:o=>o.status},{header:"testflight",value:o=>o.deliveries.find(i=>i.channel==="testflight")?.status??""},{header:"development",value:o=>o.deliveries.find(i=>i.channel==="development")?.status??""},{header:"made",value:o=>Z(o.created_at)}]),a.next_cursor&&e.out.note(`More than ${n}: raise --limit to see older ones.`)})}},tx={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 f(e),n=await m(e,t,"GET",`/stores/packages/${A(ve(e,0,"the package's id"))}`);e.out.result(n,()=>Q1(e,n))}},nx={name:"stores:packages:create",summary:"make a package of an app: its build number, and the URL and token its build 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 (an iOS app's CFBundleVersion, an Android app's versionCode), 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 f(e),n=ve(e,0,"the app's id"),s=e.flags["command-id"];if(s===void 0||s.trim()==="")throw h("--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 r=Ne(await ze(e,e.flags["entitlements-file"],"the entitlements"),"the entitlements"),l=p=>typeof p=="object"&&p!==null&&!Array.isArray(p);if(!l(r)||!Object.values(r).every(l))throw h("the entitlements are an object of bundle id \u2192 its entitlements object");a.entitlements=r}await k(e,t,`make a package of ${n}`);let o=await Pt(e,t,"POST",`/stores/apps/${A(n)}/packages`,a,D()),i=o.body;e.out.result(i,()=>{if(e.out.line(`Package ${i.id} of ${i.app_id}: build number ${i.build_number}${o.status===200?" (made before by this command id)":""}.`),i.status==="uploaded"){e.out.line("Its build has arrived already.");return}e.out.line(`Build it with build number ${i.build_number} (CFBundleVersion; an Android app's versionCode), then upload it:`),i.upload&&(e.out.line(` palbase stores:packages:upload ${i.id} --file <app.ipa> --token ${i.upload.token}`),e.out.line(`url: ${i.upload.url}`),e.out.line(`token: ${i.upload.token} (shown this once; it works until ${Z(i.upload.expires_at)})`))})}},sx={name:"stores:packages:upload",summary:"hand a package its build: the .ipa, .aab or .apk goes straight to the environment's address with the upload token",usage:"<package id> --file <app.ipa|app.aab|app.apk> --token <upload token>",details:["An Android app's App Bundle (.aab) goes to Play; its APK is installed directly on testers' phones (stores:deliver --channel development), signed with the app's upload key whatever it came signed with. The file is told by what it holds, not by its name.","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|app.apk",description:"the unsigned .ipa, the Android App Bundle (unsigned, or signed with the app's upload key) or the Android APK the build machine made"},token:{type:"string",value:"upload token",description:"the package's upload token"}},scope:"environment",async run(e){let t=await f(e),n=ve(e,0,"the package's id"),s=e.flags.file;if(s===void 0)throw h("--file names the .ipa, .aab or .apk");let a=e.flags.token??e.io.env.PALBASE_UPLOAD_TOKEN;if(a===void 0||a.trim()==="")throw h("--token is the package's upload token (stores:packages:create printed it)","or PALBASE_UPLOAD_TOKEN");let o=hs(e.io.cwd,s),i;try{let d=await gc(o);if(!d.isFile())throw new Error("not a file");i=d.size}catch(d){throw new b("unreadable_file",`${s} could not be read: ${d instanceof Error?d.message:String(d)}`)}await k(e,t,`upload ${s} (${i} bytes) as the build of package ${n}`);let r=`${Qt(e.cloud,t.env_ref)}/stores/packages/${A(n)}/artifact`,l;try{l=await Pv(o)}catch(d){throw new b("unreadable_file",`${s} could not be read: ${d instanceof Error?d.message:String(d)}`)}let p=`${s} \u2192 package ${n}`;for(let d=1;;d++)try{let u=await vi(e,r,{method:"PUT",headers:{"palbase-upload-token":a,"content-type":"application/octet-stream","content-length":String(l.size),accept:"application/json"},body:l},p);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(u.format==="apk"?`Install it on testers' phones: palbase stores:deliver ${u.id} --channel development --groups <group>, or palbase stores:invite ${u.id} <email>`:`Send it to testers: palbase stores:deliver ${u.id}`)});return}catch(u){if(!(u instanceof G))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??_1,1);if(!g||d>=bv||y>Ev)throw u;e.out.note(`${p}: ${u.message}; trying again in ${y} s (${d+1} of ${bv})`),await e.io.sleep(y*1e3)}}},ax={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 f(e),n=ve(e,0,"the app's id"),s=await m(e,t,"GET",`/stores/apps/${A(n)}/upload-key`),a=e.flags.out;if(a!==void 0){let o=await Rv(hs(e.io.cwd,a),Ms.O_WRONLY|Ms.O_CREAT|Ms.O_TRUNC|Ms.O_NOFOLLOW);try{await o.writeFile(s.certificate)}finally{await o.close()}}e.out.result(s,()=>{e.out.line(`upload key of ${n}: SHA-256 ${s.fingerprint} (made ${Z(s.created_at)})`),a!==void 0&&e.out.line(`certificate written to ${a}`)})}},ox={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 f(e),n=ve(e,0,"the package's id"),s=e.flags.out;if(s===void 0)throw h("--out names the file to write");let a=e.flags.channel??"play_internal";if(a!=="play_internal")throw h("--channel is play_internal");let o=await m(e,t,"POST",`/stores/packages/${A(n)}/deliveries/${A(a)}/bundle-link`,void 0,D());mn(e,t,o.url,"the download link");let i;try{i=await e.io.fetch(o.url,{method:"GET",redirect:"manual"})}catch(g){throw new b("network_error",`the signed bundle could not be downloaded: ${g instanceof Error?g.message:String(g)}`)}if(i.status!==200||!i.body){let g=await i.text(),y=g;try{y=JSON.parse(g)}catch{}throw new b("download_failed",`the signed bundle: ${dr(y,i.status)}`)}let r=hs(e.io.cwd,s),l=await Rv(r,Ms.O_WRONLY|Ms.O_CREAT|Ms.O_TRUNC|Ms.O_NOFOLLOW),p=0,d=b1.fromWeb(i.body).on("data",g=>{p+=g.length}),u=Number(i.headers.get("content-length")??NaN);try{if(await w1(d,l.createWriteStream()),Number.isFinite(u)&&p!==u)throw new Error(`${p} of its ${u} bytes arrived`)}catch(g){throw await m1(r,{force:!0}),new b("download_failed",`the signed bundle did not arrive whole: ${g instanceof Error?g.message:String(g)}; ask again`)}e.out.result({file:s,bytes:p},()=>{e.out.line(`Wrote ${s} (${p} 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 ix(e,t,n,s){if(s.every(i=>hv.test(i)))return s;let a=await m(e,t,"GET",`/stores/packages/${A(n)}`),o=(await m(e,t,"GET",`/stores/apps/${A(a.app_id)}/groups`)).groups;return s.map(i=>{if(hv.test(i))return i;let r=o.filter(p=>p.name===i),l=r.length>0?r:o.filter(p=>p.name.toLowerCase()===i.toLowerCase());if(l.length!==1)throw new b(l.length===0?"no_such_group":"ambiguous_group",`${a.app_id} has ${l.length===0?"no group":"more than one group"} named ${JSON.stringify(i)}`,{hint:`palbase stores:groups ${a.app_id} lists them`});return l[0].id})}async function rx(e,t,n){let s=await m(e,t,"GET",`/stores/packages/${A(n)}`);return s.format==="apk"?"development":(await m(e,t,"GET","/stores/apps")).apps.find(o=>o.app_id===s.app_id)?.platform==="android"?"play_internal":"testflight"}var lx={name:"stores:deliver",summary:"send a package to a channel's testers: signed, handed to Apple or Play \u2014 or installed on their own phones directly",usage:"<package id> [--channel testflight|play_internal|development] [--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.","--channel development installs it directly, with no TestFlight: each person of the development groups named is mailed a link, their iPhone registers itself, and the package is signed for their phones \u2014 again, with no new build, when another phone comes. Sent again, it invites who joined the groups since. palbase stores:invitations <package id> shows where each person is.","An Android app's APK goes to development alone (its default), its bundle to Play alone: the APK is signed with the app's upload key and is ready for everyone invited at once \u2014 an Android phone registers nowhere.","palbase stores:deliveries <package id> follows it."],args:{min:1,max:1},flags:{channel:{type:"string",value:"channel",description:"where it goes: testflight, play_internal (default: the app's platform's), or development (direct install; an APK's default)"},groups:{type:"string",multiple:!0,value:"group,\u2026",description:"the groups it goes to, by id or name: the channel's own kind (TestFlight groups, or development groups)"},"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 f(e),n=ve(e,0,"the package's id"),s=e.flags.channel??await rx(e,t,n);if(!yv.includes(s))throw h(`--channel is one of ${yv.join(", ")}`);let a=e.flags["what-to-test"];if(e.flags.locale!==void 0&&a===void 0)throw h("--locale is the --what-to-test note's");let o={channel:s},i=Me(e.flags.groups);i&&i.length>0&&(o.groups=await ix(e,t,n,i)),a!==void 0&&(o.what_to_test={text:a,...e.flags.locale!==void 0?{locale:e.flags.locale}:{}}),await k(e,t,`send package ${n} to ${s}${o.groups?` (${o.groups.length} group${o.groups.length===1?"":"s"})`:""}`);let r=await m(e,t,"POST",`/stores/packages/${A(n)}/deliveries`,o,D());e.out.result(r,()=>{e.out.line(`Package ${n} \u2192 ${r.channel}: ${Ov(r)}.`),r.status!=="ready"&&r.status!=="failed"&&e.out.line(`Follow it: palbase stores:deliveries ${n}`)})}},px={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 f(e),n=ve(e,0,"the package's id"),s=await m(e,t,"GET",`/stores/packages/${A(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}`:""}`:a.signed_devices!==void 0?`${a.signed_devices} phone${a.signed_devices===1?"":"s"}`:"")},{header:"groups",value:a=>String(a.groups.length)},{header:"updated",value:a=>Z(a.updated_at)},{header:"error",value:a=>a.error_code?`${a.error_code}${a.error?`: ${a.error}`:""}`:""}])})}};function dx(e){return e.devices.length===0?"":e.devices.map(t=>`${t.product??"phone"} \u2026${t.udid.slice(-6)} ${t.signed?"signed":t.status}`).join(", ")}function xv(e){return e.mail==="failed"&&e.mail_error?`failed: ${e.mail_error}`:e.mail}var cx={name:"stores:invitations",summary:"the people invited to install a package directly: how far each got, their mail, their phones",usage:"<package id>",details:["invited \u2192 opened (the link) \u2192 enrolled (a phone of theirs registered) \u2192 downloaded (a phone took the build to install it); or revoked, or expired.","A phone is signed once the package's build installs on it; registering, processing (Apple holds a new device up to 72 hours) or refused before that. Links are not listed: palbase stores:invite <package id> <email> answers a person's."],args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=ve(e,0,"the package's id"),s=await m(e,t,"GET",`/stores/packages/${A(n)}/invitations`);e.out.result(s,()=>{s.invitations.length===0?e.out.line(`Nobody is invited to package ${n}: palbase stores:deliver ${n} --channel development --groups <group>, or palbase stores:invite ${n} <email>`):e.out.table(s.invitations,[{header:"invitation",value:a=>a.id},{header:"email",value:a=>a.email},{header:"status",value:a=>a.status},{header:"mail",value:xv},{header:"phones",value:dx},{header:"expires",value:a=>Z(a.expires_at)}])})}},ux={name:"stores:invite",summary:"invite one person to install a package directly: mails their link, and prints it",usage:"<package id> <email> [--no-mail] [--locale <language>]",details:["A person invited already keeps their link \u2014 mailed again unless --no-mail \u2014; an expired or revoked invitation is made again, with a new link. The package gets its development delivery when it had none.","The link works for 14 days. A person registers two new iPhones at most in 30 days, through whatever links they hold; a phone already theirs registers again freely. With an environment token the link works no longer than the token."],args:{min:2,max:2},flags:{"no-mail":{type:"boolean",description:"only print the link: nothing is mailed"},locale:{type:"string",value:"language",description:"the mail's and the page's language (en, tr; default: the project's)"}},scope:"environment",async run(e){let t=await f(e),n=ve(e,0,"the package's id"),s=e.args[1]??"";if(!/^[^\s@]+@[^\s@]+$/.test(s))throw h("the person's email address is the second argument");let a=e.flags["no-mail"]!==!0,o={email:s,...a?{}:{mail:!1},...e.flags.locale!==void 0?{locale:e.flags.locale}:{}};await k(e,t,`invite ${s} to install package ${n}${a?" (a mail goes to them)":""}`);let i=await m(e,t,"POST",`/stores/packages/${A(n)}/invitations`,o,D());e.out.result(i,()=>{e.out.line(`${i.email} is ${i.status} (${xv(i)}); the link works until ${Z(i.expires_at)}:`),e.out.line(i.url)})}},mx={name:"stores:invitations:revoke",summary:"revoke an invitation: its link, its build and its registration stop working",usage:"<invitation id>",args:{min:1,max:1},scope:"environment",async run(e){let t=await f(e),n=ve(e,0,"the invitation's id");await k(e,t,`revoke the invitation ${n}`),await m(e,t,"DELETE",`/stores/invitations/${A(n)}`,void 0,D()),e.out.result({id:n,revoked:!0},()=>e.out.line(`Revoked the invitation ${n}.`))}},gx={name:"stores:devices",summary:"the phones registered for the project's development builds, and where each stands at Apple",usage:"",details:["registering (to be registered at Apple when a build is signed for it), enabled, processing (Apple holds a new membership's 11th to 100th device out of builds for 24 to 72 hours) or refused, in Apple's words.","An Apple account registers 100 iPhones a membership year, and a removed one keeps its place until the year ends."],scope:"environment",async run(e){let t=await f(e),n=await m(e,t,"GET","/stores/devices");e.out.result(n,()=>{n.devices.length===0?e.out.line("No phone is registered: a person invited to a package registers theirs from the link (palbase stores:invite)."):e.out.table(n.devices,[{header:"udid",value:s=>s.udid},{header:"model",value:s=>s.product??""},{header:"status",value:s=>s.status==="refused"?`refused${s.limit?" (yearly limit)":""}${s.refusal?`: ${s.refusal}`:""}`:s.status},{header:"people",value:s=>s.people.join(", ")},{header:"registered",value:s=>Z(s.created_at)}])})}},hx={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 f(e),n=ve(e,0,"the package's id"),s=e.flags.text;if(s===void 0||s.trim()==="")throw h("--text is the note testers read");if(s.length>4e3)throw h(`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 k(e,t,`change what testers read with package ${n}${a.locale?` (${a.locale})`:""}`);let o=await m(e,t,"PUT",`/stores/packages/${A(n)}/what-to-test`,a,D());e.out.result(o,()=>e.out.line(`Testers of package ${n} read${a.locale?` (${a.locale})`:""}: ${o.what_to_test??s}`))}};function Lv(e,t){let n=(e.args[t]??"").trim();if(n===""||n.length>40||/[\r\n]/.test(n))throw h("a group's name is 1 to 40 characters on one line");return n}var yx={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 f(e),n=ve(e,0,"the app's id"),s=await m(e,t,"GET",`/stores/apps/${A(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:"kind",value:a=>a.kind??"testflight"},{header:"testers",value:a=>String(a.testers)},{header:"updated",value:a=>Z(a.updated_at)}])})}},fx={name:"stores:groups:create",summary:"make a group of testers for an app: a TestFlight group, or a development group for direct install",usage:"<app id> <name> [--kind testflight|development]",details:["A TestFlight group (an iOS app's default) is an internal and an external group at Apple, whose people Apple mails TestFlight's invitations.","A development group (an Android app's default) is Palbase's own list of the people a package is installed for directly (stores:deliver --channel development): nothing at Apple, no TestFlight invitation."],args:{min:2,max:2},flags:{kind:{type:"string",value:"kind",description:"testflight or development (default: testflight for an iOS app, development for an Android app)"}},scope:"environment",async run(e){let t=await f(e),n=ve(e,0,"the app's id"),s=Lv(e,1),a=e.flags.kind;if(a!==void 0&&!fv.includes(a))throw h(`--kind is one of ${fv.join(", ")}`);await k(e,t,`make the ${a?`${a} `:""}group ${JSON.stringify(s)} of ${n}`);let o={name:s,...a?{kind:a}:{}},i=await m(e,t,"POST",`/stores/apps/${A(n)}/groups`,o,D());e.out.result(i,()=>e.out.line(`Made ${i.name} (${i.id}), a ${i.kind} group.`))}},bx={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 f(e),n=ve(e,0,"the group's id"),s=Lv(e,1);await k(e,t,`rename the group ${n} to ${JSON.stringify(s)}`);let a=await m(e,t,"PATCH",`/stores/groups/${A(n)}`,{name:s},D());e.out.result(a,()=>e.out.line(`${a.id} is ${a.name}.`))}},wx={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 f(e),n=ve(e,0,"the group's id");await k(e,t,`delete the group ${n}`),await m(e,t,"DELETE",`/stores/groups/${A(n)}`,void 0,D()),e.out.result({id:n,deleted:!0},()=>e.out.line(`Deleted the group ${n}.`))}},vx={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 f(e),n=ve(e,0,"the group's id"),s=await m(e,t,"GET",`/stores/groups/${A(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=>Z(a.added_at)}])})}};function kx(e){let t=e.trim();if(t.startsWith("[")){let n=Ne(t,"the testers");if(!Array.isArray(n)||!n.every(s=>typeof s=="object"&&s!==null&&typeof s.email=="string"))throw h('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,o]=n.split(",").map(i=>i.trim());return{email:s,...a?{first_name:a}:{},...o?{last_name:o}:{}}})}var _x={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. ${uc} 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 f(e),n=ve(e,0,"the group's id"),s=Me(e.flags.emails);if(s===void 0==(e.flags.file===void 0))throw h("the testers are named by --emails or --file, one of the two");let a=s?s.map(p=>({email:p})):kx(await ze(e,e.flags.file,"the testers"));for(let p of a)if(!/^[^@\s]+@[^@\s]+$/.test(p.email))throw h(`${JSON.stringify(p.email)} is not an email address`);if(a.length>uc)throw h(`a group holds ${uc} testers at most (${a.length} were named)`);let o=(await m(e,t,"GET",`/stores/groups/${A(n)}/testers`)).testers,i=new Set(a.map(p=>p.email.toLowerCase())),r=o.filter(p=>!i.has(p.email.toLowerCase())).map(p=>p.email);await k(e,t,`set the testers of ${n} to ${a.length}${r.length>0?`; ${r.length} leave: ${r.join(", ")}`:""}`);let l=await m(e,t,"PUT",`/stores/groups/${A(n)}/testers`,{testers:a},D());e.out.result({...l,left:r},()=>{e.out.line(`${n} holds ${l.testers.length} tester${l.testers.length===1?"":"s"}${r.length>0?`; ${r.join(", ")} left it`:""}.`)})}},Sx={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 f(e),n=ve(e,0,"the group's id"),s=ve(e,1,"the package's id");await k(e,t,`give package ${s} to the group ${n}`),await m(e,t,"POST",`/stores/groups/${A(n)}/builds`,{package_id:s},D()),e.out.result({group_id:n,package_id:s},()=>e.out.line(`Gave package ${s} to ${n}.`))}},$x={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 Ln(e){return e===""?"(not set)":e}var Ax={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 f(e),n=ve(e,0,"the app's id"),s=e.flags.locale!==void 0?`?${new URLSearchParams({locale:e.flags.locale})}`:"",a=await m(e,t,"GET",`/stores/apps/${A(n)}/testflight/review-info${s}`);e.out.result(a,()=>{let o=a.locales.filter(d=>d!==a.locale);e.out.line(`Test information of ${n} in ${a.locale}${o.length>0?` (also in ${o.join(", ")})`:""}:`);let i=[`${a.contact_first_name} ${a.contact_last_name}`.trim(),a.contact_phone,a.contact_email].filter(d=>d!=="").join(", "),r=a.demo_account_required?`required: ${Ln(a.demo_account_name)}, password ${a.demo_account_password_set?"set":"not set"}`:"not required",l=[["what to test",Ln(a.description)],["feedback email",Ln(a.feedback_email)],["review contact",Ln(i)],["demo account",r],["notes",Ln(a.notes)]],p=Math.max(...l.map(([d])=>d.length));for(let[d,u]of l)e.out.line(` ${d.padEnd(p)} ${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).`)})}},Px={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 f(e),n=ve(e,0,"the app's id"),s={};for(let[o,i]of Object.entries($x))e.flags[o]!==void 0&&(s[i]=e.flags[o]);if(e.flags["demo-password-stdin"]===!0&&(s.demo_account_password=await lt(e,"the demo account's password")),Object.keys(s).length===0)throw h("nothing to write: name at least one field","palbase help stores:review-info:set");await k(e,t,`write ${Object.keys(s).join(", ")} of ${n}'s Beta App Review information`);let a=await m(e,t,"PUT",`/stores/apps/${A(n)}/testflight/review-info`,s,D());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 vc(e,t){let n=P1[y1(t).toLowerCase()];if(n===void 0)throw h(`${e}: a screenshot is a .png or .jpg file`);let s;try{let a=await gc(t);if(!a.isFile())throw new Error("not a file");s=a.size}catch(a){throw new b("unreadable_file",`${e} could not be read: ${a instanceof Error?a.message:String(a)}`)}if(s===0||s>A1)throw h(`${e}: a screenshot is 1 byte to 10 MB, and it is ${s} bytes`);return{file:e,path:t,contentType:n}}async function Rx(e,t,n){let s=hs(e.io.cwd,ue),a=hs(t,n),o=mv(s,a);if(o===""||o===".."||o.startsWith(`..${gv}`)||f1(o))throw h(`${n}: a screenshot the page names by its file is under ${ue}/, and ${mv(e.io.cwd,a)||a} is not`,`move it under ${ue}/, or name it by the SHA-256 palbase stores:screenshots:upload printed`);let i,r;try{[r,i]=await Promise.all([uv(s),uv(a)])}catch(l){throw new b("unreadable_file",`${n} could not be read: ${l instanceof Error?l.message:String(l)}`)}if(!i.startsWith(r+gv))throw new b("outside_palbase",`${n} is a link out of ${ue}/: palbase reads only what is under it`);return vc(n,i)}async function kc(e,t,n,s,a="page"){let o;try{o=await Pv(s.path,{type:s.contentType})}catch(i){throw new b("unreadable_file",`${s.file} could not be read: ${i instanceof Error?i.message:String(i)}`)}for(let i=1;;i++)try{let r=`/stores/apps/${A(n)}/screenshots${a==="review"?"?for=review":""}`;return await m(e,t,"PUT",r,new Hs(o,s.contentType))}catch(r){if(!(r instanceof G)||r.status!==503||r.code!=="stores_busy")throw r;let l=Math.max(r.retryAfter??60,1);if(i>=vv||l>Ev)throw r;e.out.note(`${s.file}: ${r.message}; trying again in ${l} s (${i+1} of ${vv})`),await e.io.sleep(l*1e3)}}var Ns=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function jx(e){let t=Ns(e)&&"draft"in e&&"revision"in e?e.draft:e;if(!Ns(t)||!Ns(t.locales))throw h('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 ${gs} writes it`);for(let[n,s]of Object.entries(t.locales)){if(!Ns(s))throw h(`locales.${n} is an object: { "name": \u2026, \u2026 }`);if(s.screenshots!==void 0){if(!Ns(s.screenshots))throw h(`locales.${n}.screenshots is an object of display \u2192 its screenshots (${$1.join(", ")})`);for(let[a,o]of Object.entries(s.screenshots))if(!Array.isArray(o)||!o.every(i=>typeof i=="string"&&i.trim()!==""))throw h(`locales.${n}.screenshots.${a} is a list of screenshots, each a SHA-256 or a file under ${ue}/`)}}return t}function Ex(e,t){let n=structuredClone(e);for(let s of Object.values(n.locales))for(let[a,o]of Object.entries(s.screenshots??{}))s.screenshots[a]=o.map(t);return n}var Xn=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`;function Iv(e,t,n,s,a){if(t instanceof G){if(t.code==="listing_moved")throw new b("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 o=t.message.split("; ").filter(i=>i!=="");e.out.note(`The page has ${Xn(o.length,"problem")}:`);for(let i of o)e.out.note(` ${i}`);throw new b("listing_invalid",`${s}: the page breaks ${Xn(o.length,"rule")} of the App Store's`,{hint:"fix each in the file, and save it again"})}if(t.code==="listing_empty")throw new b("listing_empty",`${n} has no draft App Store page yet: ${s}`,{hint:`write one: palbase stores:listing:get ${n} --out ${gs}, edit it, then palbase stores:listing:put ${n} --file ${gs} --revision 0`});if(t.code==="no_editable_version")throw new b("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 Tx={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 <${gs}>]`,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 f(e),n=ve(e,0,"the app's id"),s=e.flags.out,a=s!==void 0?Kt(e,"out",s,".json",gs):void 0,o=await m(e,t,"GET",`/stores/apps/${A(n)}/listing`);if(a!==void 0){let i=await Be(e.io.cwd,a);await c1(jv(i),{recursive:!0}),await Be(e.io.cwd,a),await g1(i,`${JSON.stringify(o.draft,null,2)}
|
|
11123
11123
|
`),e.out.result({file:a,app_id:o.app_id,revision:o.revision},()=>{e.out.line(`Wrote revision ${o.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 ${o.revision}`)});return}e.out.result(o,()=>{if(o.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 ${gs}, then palbase stores:listing:put ${n} --file ${gs} --revision 0`);return}e.out.line(`${n}'s draft App Store page, revision ${o.revision}${o.updated_at?` (saved ${Z(o.updated_at)}${o.updated_by?` by ${o.updated_by}`:""})`:""}:`);for(let i of JSON.stringify(o.draft,null,2).split(`
|
|
11124
11124
|
`))e.out.line(i);e.out.line(`Edit it in a file: palbase stores:listing:get ${n} --out ${gs}`)})}},Cx={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 <${gs}> --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 f(e),n=ve(e,0,"the app's id"),s=we(e.flags.revision,"revision");if(s===void 0)throw h("--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,o=jx(Ne(await ze(e,a,"the page"),"the page")),i=a!==void 0&&a!=="-"?jv(hs(e.io.cwd,a)):e.io.cwd,r=new Map,l=new Map;for(let y of Object.values(o.locales))for(let w of Object.values(y.screenshots??{}).flat()){if(wv.test(w)||l.has(w))continue;let v=await Rx(e,i,w);l.set(w,v.path),r.has(v.path)||r.set(v.path,v)}await k(e,t,`save ${n}'s draft App Store page over revision ${s}${r.size>0?`, uploading ${Xn(r.size,"screenshot")} first`:""}`);let p=new Map,d=[];for(let y of r.values()){let w=await kc(e,t,n,y);p.set(y.path,w.sha256),d.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=Ex(o,y=>wv.test(y)?y.toLowerCase():p.get(l.get(y))),g;try{g=await m(e,t,"PUT",`/stores/apps/${A(n)}/listing`,{revision:s,draft:u},D())}catch(y){Iv(e,y,n,"nothing was saved",s)}e.out.result({...g,uploaded:d},()=>{let y=Object.keys(g.draft.locales),w=Object.values(g.draft.locales).flatMap(v=>Object.values(v.screenshots??{}).flat()).length;e.out.line(`Saved revision ${g.revision} of ${n}'s draft App Store page: ${Xn(y.length,"language")}${y.length>0?` (${y.join(", ")})`:""}, ${Xn(w,"screenshot")}.`),e.out.line(`Nothing is at Apple yet: palbase stores:listing:plan ${n} says what it changes there.`)})}},Ox={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 f(e),n=ve(e,0,"the app's id"),s=[];for(let o of e.args.slice(1))s.push(await vc(o,hs(e.io.cwd,o)));await k(e,t,`upload ${Xn(s.length,"screenshot")} for ${n}'s App Store page`);let a=[];for(let o of s)a.push({file:o.file,...await kc(e,t,n,o)});e.out.result({screenshots:a},()=>{e.out.table(a,[{header:"file",value:o=>o.file},{header:"sha256",value:o=>o.sha256},{header:"size",value:o=>`${o.width}x${o.height}`},{header:"fits",value:o=>o.displays.length>0?o.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>`)})}},xx={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 iap: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 f(e),n=ve(e,0,"the app's id"),s=await vc(e.args[1],hs(e.io.cwd,e.args[1]));await k(e,t,`upload ${s.file} as a review screenshot for ${n}`);let a=await kc(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 iap:catalog:plan`)})}},Lx={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 f(e),n=ve(e,0,"the app's id");await k(e,t,`plan writing ${n}'s App Store page`);let s;try{s=await m(e,t,"POST",`/stores/apps/${A(n)}/listing/plan`,void 0,D())}catch(a){Iv(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,o)=>e.out.line(` ${o+1}. ${a.says}`)),_c(e,s.action,{summary:!1})})}},Ix={USES_THIRD_PARTY_CONTENT:"it shows, contains or reaches third-party content",DOES_NOT_USE_THIRD_PARTY_CONTENT:"no third-party content"},Nx={manual:"manual: a person releases it once approved",after_approval:"as soon as it is approved"},Mx=["paused","active","complete"];function Nv(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",Ln(s.copyright)]),a.push(["release",s.release==="scheduled"?`scheduled: not before ${Z(s.release_at)}`:Nx[s.release]??Ln(s.release)]));let o=n.phased;a.push(["phased",o?`over seven days \u2014 ${o.state}${o.state!=="INACTIVE"?`, day ${o.day} of 7`:""}${o.paused_days>0?`, paused ${Xn(o.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",Ix[n.content_rights]??Ln(n.content_rights)]);let i=n.review,r=[`${i.contact_first_name} ${i.contact_last_name}`.trim(),i.contact_phone,i.contact_email].filter(p=>p!=="").join(", ");a.push(["review contact",Ln(r)]),a.push(["demo account",i.demo_account_required?`required: ${Ln(i.demo_account_name)}, password ${i.has_demo_password?"set":"not set"}`:"not required"]),a.push(["review notes",Ln(i.notes)]),n.watched&&a.push(["watched",`${n.watched.version_string} ${n.watched.state} since ${Z(n.watched.state_at)} (read ${Z(n.watched.checked_at)})`]);let l=Math.max(...a.map(([p])=>p.length));for(let[p,d]of a)e.out.line(` ${p.padEnd(l)} ${d}`);if(n.missing.length>0){e.out.line("App Review would refuse it for:");for(let p of n.missing)e.out.line(` - ${p}`)}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 Dx={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 f(e),n=ve(e,0,"the app's id"),s=await m(e,t,"GET",`/stores/apps/${A(n)}/version`);e.out.result(s,()=>Nv(e,n,s))}},$v={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 zx(e){let t=Ns(e)&&Ns(e.review)&&"app_id"in e?e.review:e;if(!Ns(t))throw h('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,o]of Object.entries(s)){if(a==="demo_account_password")throw h("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 i=$v[a];if(i===void 0)throw h(`the review file's ${a} is not one of App Review's details: ${Object.keys($v).join(", ")}`);if(typeof o!==i)throw h(`the review file's ${a} is ${i==="string"?"text":"true or false"}`)}return s}function Av(e,t){if(e.flags[t]===!0&&e.flags[`no-${t}`]===!0)throw h(`--${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 qx={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 f(e),n=ve(e,0,"the app's id"),s={},a=[],o=e.flags.version;if(o!==void 0){if(!/^\d+(\.\d+){0,2}$/.test(o)||o.length>18)throw h(`--version ${o}: one to three numbers with dots (1.2.3)`);s.version_string=o,a.push(`version ${o}`)}let i=we(e.flags.build,"build");if(i!==void 0){if(i<1)throw h("--build is a TestFlight build's number");s.build_number=i,a.push(`build ${i}`)}let r=e.flags.copyright;if(r!==void 0){if(r.trim()===""||r.length>200)throw h("--copyright is 1 to 200 characters (2026 Your Company)");s.copyright=r,a.push("copyright")}let l=e.flags.release,p=e.flags["release-at"];if(l!==void 0&&!["manual","after_approval","scheduled"].includes(l))throw h("--release is manual, after_approval or scheduled");if(p!==void 0){if(l!==void 0&&l!=="scheduled")throw h(`--release-at is a scheduled release's: not ${l}`);let P=Date.parse(p);if(!Number.isFinite(P))throw h(`--release-at ${p}: a time, RFC 3339 (2026-11-02T09:00:00Z)`);if(P<=e.io.now())throw h(`--release-at ${p}: a scheduled release's time is in the future`);s.release="scheduled",s.release_at=new Date(P).toISOString()}else{if(l==="scheduled")throw h("--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 d=Av(e,"phased");d!==void 0&&(s.phased=d,a.push(d?"phased release":"release to everyone at once"));let u=Av(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 h("--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 h("--app-privacy is published or unpublished");s.app_privacy=y,a.push(`App Privacy ${y}`)}let w=e.flags["review-file"],v=e.flags["demo-password-stdin"]===!0;if(v&&w==="-")throw h("stdin carries the demo password or the review file, not both","--review-file <review.json> --demo-password-stdin < password.txt");if(w!==void 0||v){let P=w!==void 0?zx(Ne(await ze(e,w,"the review details"),"the review details")):{},E=v?await lt(e,"the demo account's password"):void 0;if(E!==void 0&&E.length>256)throw h("the demo account's password is 256 characters at most");let{has_demo_password:T,...C}=(await m(e,t,"GET",`/stores/apps/${A(n)}/version`)).review;s.review={...C,...P,...E!==void 0?{demo_account_password:E}:{}},w!==void 0&&a.push("App Review's details"),E!==void 0&&a.push("the demo account's password")}if(a.length===0)throw h("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 k(e,t,`prepare ${n}'s App Store version: ${a.join(", ")}`);let R;try{R=await m(e,t,"PUT",`/stores/apps/${A(n)}/version`,s)}catch(P){throw P instanceof G&&P.code==="no_editable_version"?new b("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`}):P}e.out.result(R,()=>{e.out.line(`Prepared ${n}'s App Store version.`),Nv(e,n,R)})}};function Nl(e,t,n,s,a={},o){return{name:e,summary:s,usage:"<app id>",args:{min:1,max:1},scope:"environment",...a,async run(i){let r=await f(i),l=ve(i,0,"the app's id"),p=o?.(i);await k(i,r,`plan ${Ds[t]} of app ${l}`);let d;try{d=await m(i,r,"POST",`/stores/apps/${A(l)}/version/${n}`,p,D())}catch(u){if(u instanceof G&&u.code==="version_incomplete"){let g=u.message.slice(u.message.indexOf(": ")+2).split("; ").filter(y=>y!=="");i.out.note("App Review would refuse the version for:");for(let y of g)i.out.note(` - ${y}`);throw new b("version_incomplete",`nothing was planned: the version lacks ${Xn(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 G&&u.code==="no_editable_version"?new b("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}i.out.result(d,()=>_c(i,d))}}}var Gx=Nl("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 h("--with names 1 to 50 product ids, comma-separated");return{in_app_purchases:n}}),Kx=Nl("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"),Ux=Nl("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"),Wx=Nl("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(!Mx.includes(t))throw h(`a phased release is paused, active (resumed) or complete (everyone gets it now), not ${JSON.stringify(t)}`);return{state:t}});function _c(e,t,n={}){e.out.line(`Planned ${Ds[t.kind]??t.kind} of ${ho(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 ${Z(t.expires_at)}:`),e.out.line(` palbase stores:actions:confirm ${t.id} --hash ${t.hash}`)}function Sc(e,t,n,s,a={},o){return{name:e,summary:s,usage:"<package id>",args:{min:1,max:1},scope:"environment",...a,async run(i){let r=await f(i),l=ve(i,0,"the package's id"),p=o?.(i);await k(i,r,`plan ${Ds[t]} of package ${l}`);let d=await m(i,r,"POST",`/stores/packages/${A(l)}/${n}`,p,D());i.out.result(d,()=>_c(i,d))}}}var Fx=Sc("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"),Bx=Sc("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=Gn(e.flags["uses-non-exempt-encryption"],"uses-non-exempt-encryption");if(t===void 0)throw h("--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}}),Jx=Sc("stores:expire","expire_build","expire","plan expiring a package's build in TestFlight (testers can no longer install it); it runs when confirmed"),Hx={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 f(e),n=e.flags.status;if(n!==void 0&&!["planned","done","declined","failed"].includes(n))throw h("--status is planned, done, declined or failed");let s=we(e.flags.limit,"limit")??30;if(s<1||s>200)throw h("--limit is a whole number from 1 to 200");let a=new URLSearchParams({limit:String(s),...n?{status:n}:{}}),o=await m(e,t,"GET",`/stores/actions?${a}`);e.out.result(o,()=>{o.actions.length===0?e.out.line(n?`No ${n} action.`:"No action yet."):e.out.table(o.actions,[{header:"action",value:i=>i.id},{header:"kind",value:i=>i.kind},{header:"package / app",value:i=>i.package_id??i.app_id??""},{header:"status",value:i=>i.status},{header:"planned",value:i=>Z(i.created_at)},{header:"what",value:i=>i.summary}]),o.next_cursor&&e.out.note(`More than ${s}: raise --limit to see older ones.`)})}},Vx={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, ${Il/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 f(e),n=ve(e,0,"the action's id"),s=e.flags.hash;if(s===void 0||s.trim()==="")throw h("--hash is the plan's hash, as stores:actions or the plan printed it: a confirmation names the plan it saw");let a=await m(e,t,"GET",`/stores/actions/${A(n)}`);if(a.status!=="planned")throw new b("action_not_planned",`the action ${n} is ${a.status}: only a planned one is confirmed`);await k(e,t,`run ${Ds[a.kind]??a.kind} of ${ho(a)}: ${a.summary}`,"It is done at Apple and cannot be undone");let o=await m(e,t,"POST",`/stores/actions/${A(n)}/confirm`,{hash:s},D());return o.status==="running"&&(o=await Yx(e,t,o)),e.out.result(o,()=>Xx(e,o)),o.status==="failed"?1:0}};function Xx(e,t){e.out.line(`${hc(Ds[t.kind]??t.kind)} of ${ho(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(`${Xn(n.steps_done,"step")} written at App Store Connect.`):e.out.line(`${Xn(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 Yx(e,t,n){e.out.note(`${hc(Ds[n.kind]??n.kind)} of ${ho(n)} is under way at App Store Connect; waiting for it to end (${Il/60} minutes at most \u2014 stopping the wait does not stop it).`);let s=e.io.now()+Il*1e3,a=n;for(;a.status==="running";){if(e.io.now()>=s)throw new b("action_running",`${Ds[n.kind]??n.kind} of ${ho(n)} is still running after ${Il/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(S1*1e3),a=await m(e,t,"GET",`/stores/actions/${A(n.id)}`)}return a}var Zx={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 f(e),n=ve(e,0,"the action's id");await k(e,t,`decline the action ${n}`);let s=await m(e,t,"POST",`/stores/actions/${A(n)}/decline`,void 0,D());e.out.result(s,()=>e.out.line(`Declined ${Ds[s.kind]??s.kind} of ${ho(s)}.`))}},mc={"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"},Mv=e=>Object.entries(mc).find(([,t])=>t===e)?.[0]??e,Qx=100;function eL(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=>Mv(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 Dv(e,t,n){let s=(await m(e,t,"GET","/stores/apple/sandbox-testers")).testers,a=[];for(let o of n){let i=s.find(r=>r.id===o||r.email.toLowerCase()===o.toLowerCase());if(!i)throw new b("no_such_tester",`the team has no sandbox tester ${o}`,{hint:`its testers: ${s.map(r=>r.email).join(", ")||"none \u2014 App Store Connect \u203A Users and Access \u203A Sandbox makes one"}`});a.some(r=>r.id===i.id)||a.push(i)}return a}var tL={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 f(e),n=await m(e,t,"GET","/stores/apple/sandbox-testers");e.out.result(n,()=>eL(e,n))}},nL={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 f(e),n={},s=e.flags.renewal;if(s!==void 0){let l=mc[s.trim().toLowerCase()];if(l===void 0)throw h(`--renewal ${s}: a monthly subscription renews every ${Object.keys(mc).join(", ")}`);n.subscription_renewal_rate=l}let a=e.flags.interrupt;if(a!==void 0){if(a!=="on"&&a!=="off")throw h("--interrupt is on or off");n.interrupt_purchases=a==="on"}let o=e.flags.storefront?.trim().toUpperCase();if(o!==void 0){if(!lo.has(o))throw h(`--storefront ${e.flags.storefront}: not an App Store storefront`,"three letters, its country's ISO 3166-1 code: USA, DEU, TUR \u2026");n.territory=o}if(Object.keys(n).length===0)throw h("nothing to change: --renewal, --interrupt or --storefront");let[i]=await Dv(e,t,[e.args[0]]);await k(e,t,`change the sandbox tester ${i.email}`);let r=await m(e,t,"PATCH",`/stores/apple/sandbox-testers/${A(i.id)}`,n,D());e.out.result(r,()=>{e.out.line(`${r.email}: monthly subscriptions renew every ${Mv(r.subscription_renewal_rate)}, purchases ${r.interrupt_purchases?"interrupted":"not interrupted"}, storefront ${r.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.")})}},sL={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:Qx},scope:"environment",async run(e){let t=await f(e),n=await Dv(e,t,e.args);await k(e,t,`clear what ${n.map(s=>s.email).join(", ")} bought in the sandbox`),await m(e,t,"POST","/stores/apple/sandbox-testers/clear-purchase-history",{tester_ids:n.map(s=>s.id)},D()),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 aL(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 ${Z(s.last_message_at)}`:""}${s.can_reply?"":" (takes no answer)"}`);for(let a of s.rejections)for(let o of a.reasons)e.out.line(` guideline ${o.section??"?"}: ${o.description??""}`);for(let a of s.messages){e.out.line(` ${a.from??"message"}${a.created_at?` ${Z(a.created_at)}`:""}:`);for(let o of a.body.split(`
|
|
11125
11125
|
`))e.out.line(` ${o}`)}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 oL={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 f(e),n=ve(e,0,"the app's id"),s=await m(e,t,"GET",`/stores/apps/${A(n)}/review`);e.out.result(s,()=>aL(e,n,s))}},iL={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 f(e),n=ve(e,0,"the app's id"),s=ve(e,1,"the thread's id"),a=(await ze(e,e.flags.file,"the answer")).trim(),o=e.flags.send===!0;await k(e,t,o?`send an answer to App Review on thread ${s}`:`write an answer to App Review on thread ${s}`);let i=await m(e,t,"PUT",`/stores/apps/${A(n)}/review/threads/${A(s)}/draft`,{body:a},D());if(!o){e.out.result(i,()=>e.out.line(`Wrote the answer as a draft (${i.id}); send it with --send, or from App Store Connect.`));return}let r=await m(e,t,"POST",`/stores/apps/${A(n)}/review/threads/${A(s)}/draft/send`,void 0,D());e.out.result(r,()=>e.out.line(`Sent the answer to App Review (message ${r.id}).`))}};function zv(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 rL={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 f(e),n=ve(e,0,"the app's id"),s=await m(e,t,"GET",`/stores/apps/${A(n)}/privacy`);e.out.result(s,()=>zv(e,s))}},lL={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 f(e),n=ve(e,0,"the app's id"),s=Ne(await ze(e,e.flags.file,"the App Privacy lines"),"the App Privacy lines"),a=Array.isArray(s)?s:s?.usages;if(!Array.isArray(a))throw h('the file is a list of lines, or {"usages": [...]}');await k(e,t,`write the App Privacy details of ${n} at Apple${e.flags.publish===!0?" and publish them":""}`);let o={usages:a,publish:e.flags.publish===!0},i=await m(e,t,"PUT",`/stores/apps/${A(n)}/privacy`,o,D());e.out.result(i,()=>zv(e,i))}},pL={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 f(e),n=ve(e,0,"the app's id"),s=e.flags.name;if(s===void 0||s.trim()==="")throw h("--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 k(e,t,`make the App Store Connect record "${a.name}" for ${n}`);let o=await m(e,t,"POST",`/stores/apps/${A(n)}/record`,a,D());e.out.result(o,()=>e.out.line(`Made the App Store Connect record ${o.asc_app_id??"?"} for ${o.bundle_id}, and linked ${o.name} to it.`))}},dL={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 f(e),n=ve(e,0,"the app's id");await k(e,t,`remove the App Store Connect record of ${n}`),await m(e,t,"DELETE",`/stores/apps/${A(n)}/record`,void 0,D()),e.out.result({removed:!0},()=>e.out.line(`Removed the App Store Connect record of ${n}; the app stays linked, with no record.`))}},qv=[j1,C1,O1,x1,N1,M1,D1,z1,q1,G1,K1,U1,W1,tL,nL,sL,B1,J1,pL,dL,ax,H1,V1,X1,Z1,ex,tx,nx,sx,ox,lx,px,cx,ux,mx,gx,hx,yx,fx,bx,wx,vx,_x,Sx,Ax,Px,Fx,Bx,Jx,Tx,Cx,Ox,xx,Lx,Dx,qx,Gx,Kx,Ux,Wx,oL,iL,rL,lL,Hx,Vx,Zx];import{createHash as TL}from"node:crypto";import{mkdir as CL,writeFile as OL}from"node:fs/promises";import{dirname as xL}from"node:path";import{spawn as cL}from"node:child_process";import{accessSync as uL,constants as mL,mkdtempSync as gL,readFileSync as hL,rmSync as yL}from"node:fs";import{tmpdir as fL}from"node:os";import{delimiter as bL,join as ka}from"node:path";import{pathToFileURL as wL}from"node:url";function Gv(e,t=process.platform){let n=i=>{try{return uL(i,mL.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 i of["/Applications",ka(e.HOME??"","Applications")])a.push(`${i}/Google Chrome.app/Contents/MacOS/Google Chrome`,`${i}/Chromium.app/Contents/MacOS/Chromium`,`${i}/Microsoft Edge.app/Contents/MacOS/Microsoft Edge`,`${i}/Brave Browser.app/Contents/MacOS/Brave Browser`);else if(t==="win32")for(let i of[e.PROGRAMFILES,e["PROGRAMFILES(X86)"],e.LOCALAPPDATA])i&&a.push(ka(i,"Google","Chrome","Application","chrome.exe"),ka(i,"Microsoft","Edge","Application","msedge.exe"),ka(i,"Chromium","Application","chrome.exe"));else for(let i of(e.PATH??"").split(bL).filter(Boolean))for(let r of["google-chrome","google-chrome-stable","chromium","chromium-browser","microsoft-edge","microsoft-edge-stable","brave-browser"])a.push(ka(i,r));let o=a.find(n);return o?{path:o}:{}}function Kv(e){return(e.PALBASE_BROWSER_ARGS??"").split(/\s+/).filter(Boolean)}var ki=class extends Error{noSandbox;constructor(t){let n=t.split(`
|