@zenku/cli-node 0.1.32 → 0.1.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/zenku-bundle.cjs +2 -2
package/package.json
CHANGED
package/zenku-bundle.cjs
CHANGED
|
@@ -124,7 +124,7 @@ ${t}`,f_=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),h_=Objec
|
|
|
124
124
|
`)}function Sv(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function L(e,t){if(t.length===0){E("No results.");return}let n=e.map(o=>o.length);for(let o of t)for(let a=0;a<o.length&&a<n.length;a++)n[a]=Math.max(n[a],o[a].length);let i=e.map((o,a)=>`\x1B[1m\x1B[34m${Sv(o,n[a])}\x1B[0m`).join(" ");process.stdout.write(i+`
|
|
125
125
|
`);let r=n.map(o=>`\x1B[90m${"\u2500".repeat(o)}\x1B[0m`).join(" ");process.stdout.write(r+`
|
|
126
126
|
`);for(let o of t){let a=o.slice(0,n.length).map((s,u)=>Sv(s,n[u])).join(" ");process.stdout.write(a+`
|
|
127
|
-
`)}}function kt(e){return Er||!pe()?null:kp(e).start()}function dt(e){e&&e.stop()}async function we(e,t){pe()||y("%s is required (use %s)",e,t?.flagHint??"the appropriate flag");let n=await Xg({message:e,placeholder:t?.placeholder});return Nt(n)?(E("cancelled"),null):n}async function Ov(e,t){pe()||y("%s is required (use %s)",e,t?.flagHint??"the appropriate flag");let n=await Qg({message:e});return Nt(n)?(E("cancelled"),null):n}async function Lt(e,t,n){pe()||y("%s is required (use %s)",e,n?.flagHint??"the appropriate flag");let i=await tv({message:e,options:t});return Nt(i)?(E("cancelled"),null):i}async function Cp(e,t){pe()||y("%s requires confirmation (use %s)",e,t?.flagHint??"the appropriate flag");let n=await ev({message:e});return Nt(n)?(E("cancelled"),null):n}var Ip="",Sp="";function zv(e){Ip=e}function Pv(e){Sp=e}function Ge(e){return Ip||(process.env.ZENKU_TENANT_ID?process.env.ZENKU_TENANT_ID:e.tenantId)}function Je(e){return Sp||(process.env.ZENKU_ACCOUNT_ID?process.env.ZENKU_ACCOUNT_ID:e.accountId)}async function Qo(e,t,n){try{let i=`user='${n}'`,r=await fetch(`${e}/api/collections/account_members/records?filter=${encodeURIComponent(i)}&expand=account&perPage=100`,{headers:{Authorization:t}});if(!r.ok)return"";let o=await r.json();if(o.items.length===0)return"";if(o.items.length===1)return o.items[0].account;if(!pe())return"";let a=o.items.map(u=>({value:u.account,label:u.expand?.account?.name??u.account}));return await Lt("Choose account",a,{flagHint:"`zenku context set --account <id>`"})??""}catch{return""}}var Gp=require("node:fs");var Av=T.object({accountId:T.string().
|
|
127
|
+
`)}}function kt(e){return Er||!pe()?null:kp(e).start()}function dt(e){e&&e.stop()}async function we(e,t){pe()||y("%s is required (use %s)",e,t?.flagHint??"the appropriate flag");let n=await Xg({message:e,placeholder:t?.placeholder});return Nt(n)?(E("cancelled"),null):n}async function Ov(e,t){pe()||y("%s is required (use %s)",e,t?.flagHint??"the appropriate flag");let n=await Qg({message:e});return Nt(n)?(E("cancelled"),null):n}async function Lt(e,t,n){pe()||y("%s is required (use %s)",e,n?.flagHint??"the appropriate flag");let i=await tv({message:e,options:t});return Nt(i)?(E("cancelled"),null):i}async function Cp(e,t){pe()||y("%s requires confirmation (use %s)",e,t?.flagHint??"the appropriate flag");let n=await ev({message:e});return Nt(n)?(E("cancelled"),null):n}var Ip="",Sp="";function zv(e){Ip=e}function Pv(e){Sp=e}function Ge(e){return Ip||(process.env.ZENKU_TENANT_ID?process.env.ZENKU_TENANT_ID:e.tenantId)}function Je(e){return Sp||(process.env.ZENKU_ACCOUNT_ID?process.env.ZENKU_ACCOUNT_ID:e.accountId)}async function Qo(e,t,n){try{let i=`user='${n}'`,r=await fetch(`${e}/api/collections/account_members/records?filter=${encodeURIComponent(i)}&expand=account&perPage=100`,{headers:{Authorization:t}});if(!r.ok)return"";let o=await r.json();if(o.items.length===0)return"";if(o.items.length===1)return o.items[0].account;if(!pe())return"";let a=o.items.map(u=>({value:u.account,label:u.expand?.account?.name??u.account}));return await Lt("Choose account",a,{flagHint:"`zenku context set --account <id>`"})??""}catch{return""}}var Gp=require("node:fs");var Av=T.object({accountId:T.string().min(1,"accountId is required"),params:T.record(T.string(),T.unknown()),conversationId:T.string().optional(),metadata:T.record(T.string(),T.unknown()).optional()}),B_=Av.extend({callbackUrl:T.url().optional(),callbackSecret:T.string().optional()});var Z_=T.object({params:T.record(T.string(),T.unknown()),conversationId:T.string().optional(),callbackUrl:T.url().optional(),callbackSecret:T.string().optional(),metadata:T.record(T.string(),T.unknown()).optional()});var Fr=class Tv extends Error{code;status;data;constructor(t,n,i){super(n),this.name="AgentClientError",this.code=t,this.status=i?.status??0,this.data=i?.data}static async fromResponse(t){let n=L_(t.status),i=`HTTP ${t.status}`,r;try{let o=await t.text();try{r=JSON.parse(o),i=typeof r.error=="string"?r.error:`HTTP ${t.status}: ${o}`}catch{i=o||i}}catch{}return new Tv(n,i,{status:t.status,data:r})}};function L_(e){return e===400?"BAD_REQUEST":e===401?"UNAUTHORIZED":e===403?"FORBIDDEN":e===404?"NOT_FOUND":e>=500?"SERVER_ERROR":"UNKNOWN"}function Ep(e,t){let n=t.persisted,i=null;switch(e){case"message":i={type:"message",message:t};break;case"agent:metadata":i={type:"agent:metadata",cost:t.cost,durationMs:t.durationMs,numTurns:t.numTurns};break;case"agent:start":i={type:"agent:start",sandboxId:t.sandboxId};break;case"agent:exit":i={type:"agent:exit",exitCode:t.exitCode};break;case"interaction:approval_requested":i={type:"interaction:approval_requested",approval:t.approval};break;case"interaction:approval_resolved":i={type:"interaction:approval_resolved",interactionId:t.interactionId,decision:t.decision};break;case"interaction:a2ui_update":i={type:"interaction:a2ui_update",message:t.message,callbackToken:t.callbackToken};break;case"interaction:client_event":i={type:"interaction:client_event",payload:t.payload};break;case"session:status":i={type:"session:status",status:t.status};break;case"keepalive":i={type:"keepalive"};break;case"error":i={type:"error",message:t.message};break;default:return!e&&t.type?t:null}return i&&n!==void 0&&(i.persisted=n),i}async function*ea(e,t){let n=e.getReader(),i=new TextDecoder,r="",o="",a;try{for(;!t?.aborted;){let{done:s,value:u}=await n.read();if(s)break;r+=i.decode(u,{stream:!0});let c=r.split(`
|
|
128
128
|
`);r=c.pop()||"";for(let l of c)if(l.startsWith("event: "))o=l.slice(7).trim();else if(l.startsWith("id: "))a=l.slice(4).trim();else if(l.startsWith("data: ")){let d=l.slice(6);if(d==="[DONE]")continue;let f=M_({event:o,data:d,id:a});f&&(yield f),o="",a=void 0}else l.trim()===""&&(o="",a=void 0)}}finally{n.releaseLock()}}function M_(e){if(e.event==="keepalive")return{type:"keepalive"};if(!e.data)return null;try{let t=JSON.parse(e.data);return Ep(e.event,t)}catch{return null}}var jv=class{baseUrl;auth;_fetch;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.auth=e.auth,this._fetch=e.fetch??globalThis.fetch.bind(globalThis)}async*stream(e,t){let n=await this.post(this.endpoint("/stream"),this.buildBody(e),t);if(!n.body)throw new Fr("NO_RESPONSE_BODY","No response body for SSE stream",{status:n.status});yield*ea(n.body,t)}async async(e){let t={...this.buildBody(e)};return e.callbackUrl!==void 0&&(t.callbackUrl=e.callbackUrl),e.callbackSecret!==void 0&&(t.callbackSecret=e.callbackSecret),await(await this.post(this.endpoint("/async"),t)).json()}async sync(e){return await(await this.post(this.endpoint("/sync"),this.buildBody(e))).json()}async createConversation(e,t){let n=await this.post(this.endpoint("/conversations"),{conversationId:e,...t?.agentSlug!==void 0&&{agentSlug:t.agentSlug}});return{...await n.json(),isNew:n.status===201}}async sendMessage(e,t,n){return await(await this.post(this.endpoint(`/conversations/${e}/messages`),{prompt:t,...n})).json()}async*subscribe(e,t,n){let i=await this.buildHeaders();t?.lastEventId&&(i["Last-Event-ID"]=t.lastEventId),delete i["Content-Type"];let r=await this.request("GET",this.endpoint(`/conversations/${e}/events`),i,void 0,n);if(!r.body)throw new Fr("NO_RESPONSE_BODY","No response body for SSE subscription",{status:r.status});yield*ea(r.body,n)}async getConversation(e){return await(await this.get(this.endpoint(`/conversations/${e}`))).json()}async resolve(e,t){return await(await this.post(this.endpoint("/resolve"),{callbackToken:e,...t?.decision!==void 0&&{decision:t.decision},...t?.userInput!==void 0&&{userInput:t.userInput}})).json()}async getStatus(e){return await(await this.get(this.endpoint(`/status/${e}`))).json()}get routePrefix(){return this.auth.type==="jwt"?"/api/webhooks":"/api/public"}endpoint(e){return`${this.baseUrl}${this.routePrefix}${e}`}async buildHeaders(){let e={"Content-Type":"application/json"};if(this.auth.type==="jwt"){let t=await Promise.resolve(this.auth.getToken());e.Authorization=`Bearer ${t}`,e["X-Tenant-Id"]=this.auth.tenantId,e["X-Account-Id"]=this.auth.accountId}return e}buildBody(e){let t={params:{prompt:e.prompt,...e.repo!==void 0&&{repo:e.repo},...e.token!==void 0&&{token:e.token},...e.ref!==void 0&&{ref:e.ref},...e.agentSlug!==void 0&&{agentSlug:e.agentSlug}}};return e.conversationId!==void 0&&(t.conversationId=e.conversationId),e.metadata!==void 0&&(t.metadata=e.metadata),this.auth.type==="jwt"&&(t.accountId=this.auth.accountId),t}async request(e,t,n,i,r){let o;try{o=await this._fetch(t,{method:e,headers:n,body:i,signal:r})}catch(a){throw a instanceof DOMException&&a.name==="AbortError"?a:new Fr("NETWORK_ERROR",a instanceof Error?a.message:"Network request failed")}if(!o.ok)throw await Fr.fromResponse(o);return o}async post(e,t,n){let i=await this.buildHeaders();return this.request("POST",e,i,JSON.stringify(t),n)}async get(e,t){let n=await this.buildHeaders();return delete n["Content-Type"],this.request("GET",e,n,void 0,t)}};function Fp(e){return new jv(e)}var ke=class e extends Error{constructor(t){super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,e.prototype),t!==null&&typeof t=="object"&&(this.originalError=t.originalError,this.url=typeof t.url=="string"?t.url:"",this.status=typeof t.status=="number"?t.status:0,this.isAbort=!!t.isAbort||t.name==="AbortError"||t.message==="Aborted",t.response!==null&&typeof t.response=="object"?this.response=t.response:t.data!==null&&typeof t.data=="object"?this.response=t.data:this.response={}),this.originalError||t instanceof e||(this.originalError=t),this.name="ClientResponseError "+this.status,this.message=this.response?.message,this.message||(this.isAbort?this.message="The request was aborted (most likely autocancelled; you can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation).":this.originalError?.cause?.message?.includes("ECONNREFUSED ::1")?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong."),this.cause=this.originalError}get data(){return this.response}toJSON(){return{...this}}},ta=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function q_(e,t){let n={};if(typeof e!="string")return n;let i=Object.assign({},t||{}).decode||V_,r=0;for(;r<e.length;){let o=e.indexOf("=",r);if(o===-1)break;let a=e.indexOf(";",r);if(a===-1)a=e.length;else if(a<o){r=e.lastIndexOf(";",o-1)+1;continue}let s=e.slice(r,o).trim();if(n[s]===void 0){let u=e.slice(o+1,a).trim();u.charCodeAt(0)===34&&(u=u.slice(1,-1));try{n[s]=i(u)}catch{n[s]=u}}r=a+1}return n}function Uv(e,t,n){let i=Object.assign({},n||{}),r=i.encode||W_;if(!ta.test(e))throw new TypeError("argument name is invalid");let o=r(t);if(o&&!ta.test(o))throw new TypeError("argument val is invalid");let a=e+"="+o;if(i.maxAge!=null){let s=i.maxAge-0;if(isNaN(s)||!isFinite(s))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(s)}if(i.domain){if(!ta.test(i.domain))throw new TypeError("option domain is invalid");a+="; Domain="+i.domain}if(i.path){if(!ta.test(i.path))throw new TypeError("option path is invalid");a+="; Path="+i.path}if(i.expires){if(!(function(u){return Object.prototype.toString.call(u)==="[object Date]"||u instanceof Date})(i.expires)||isNaN(i.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+i.expires.toUTCString()}if(i.httpOnly&&(a+="; HttpOnly"),i.secure&&(a+="; Secure"),i.priority)switch(typeof i.priority=="string"?i.priority.toLowerCase():i.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(i.sameSite)switch(typeof i.sameSite=="string"?i.sameSite.toLowerCase():i.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}function V_(e){return e.indexOf("%")!==-1?decodeURIComponent(e):e}function W_(e){return encodeURIComponent(e)}var G_=typeof navigator<"u"&&navigator.product==="ReactNative"||typeof global<"u"&&global.HermesInternal,Lv;function Or(e){if(e)try{let t=decodeURIComponent(Lv(e.split(".")[1]).split("").map((function(n){return"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(t)||{}}catch{}return{}}function Mv(e,t=0){let n=Or(e);return!(Object.keys(n).length>0&&(!n.exp||n.exp-t>Date.now()/1e3))}Lv=typeof atob!="function"||G_?e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,i,r=0,o=0,a="";i=t.charAt(o++);~i&&(n=r%4?64*n+i:i,r++%4)?a+=String.fromCharCode(255&n>>(-2*r&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return a}:atob;var Nv="pb_auth",In=class{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get record(){return this.baseModel}get model(){return this.baseModel}get isValid(){return!Mv(this.token)}get isSuperuser(){let t=Or(this.token);return t.type=="auth"&&(this.record?.collectionName=="_superusers"||!this.record?.collectionName&&t.collectionId=="pbc_3142635823")}get isAdmin(){return console.warn("Please replace pb.authStore.isAdmin with pb.authStore.isSuperuser OR simply check the value of pb.authStore.record?.collectionName"),this.isSuperuser}get isAuthRecord(){return console.warn("Please replace pb.authStore.isAuthRecord with !pb.authStore.isSuperuser OR simply check the value of pb.authStore.record?.collectionName"),Or(this.token).type=="auth"&&!this.isSuperuser}save(t,n){this.baseToken=t||"",this.baseModel=n||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(t,n=Nv){let i=q_(t||"")[n]||"",r={};try{r=JSON.parse(i),(typeof r===null||typeof r!="object"||Array.isArray(r))&&(r={})}catch{}this.save(r.token||"",r.record||r.model||null)}exportToCookie(t,n=Nv){let i={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},r=Or(this.token);i.expires=r?.exp?new Date(1e3*r.exp):new Date("1970-01-01"),t=Object.assign({},i,t);let o={token:this.token,record:this.record?JSON.parse(JSON.stringify(this.record)):null},a=Uv(n,JSON.stringify(o),t),s=typeof Blob<"u"?new Blob([a]).size:a.length;if(o.record&&s>4096){o.record={id:o.record?.id,email:o.record?.email};let u=["collectionId","collectionName","verified"];for(let c in this.record)u.includes(c)&&(o.record[c]=this.record[c]);a=Uv(n,JSON.stringify(o),t)}return a}onChange(t,n=!1){return this._onChangeCallbacks.push(t),n&&t(this.token,this.record),()=>{for(let i=this._onChangeCallbacks.length-1;i>=0;i--)if(this._onChangeCallbacks[i]==t)return delete this._onChangeCallbacks[i],void this._onChangeCallbacks.splice(i,1)}}triggerChange(){for(let t of this._onChangeCallbacks)t&&t(this.token,this.record)}},zp=class extends In{constructor(t="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=t,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get record(){let t=this._storageGet(this.storageKey)||{};return t.record||t.model||null}get model(){return this.record}save(t,n){this._storageSet(this.storageKey,{token:t,record:n}),super.save(t,n)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(t){if(typeof window<"u"&&window?.localStorage){let n=window.localStorage.getItem(t)||"";try{return JSON.parse(n)}catch{return n}}return this.storageFallback[t]}_storageSet(t,n){if(typeof window<"u"&&window?.localStorage){let i=n;typeof n!="string"&&(i=JSON.stringify(n)),window.localStorage.setItem(t,i)}else this.storageFallback[t]=n}_storageRemove(t){typeof window<"u"&&window?.localStorage&&window.localStorage?.removeItem(t),delete this.storageFallback[t]}_bindStorageEvent(){typeof window<"u"&&window?.localStorage&&window.addEventListener&&window.addEventListener("storage",(t=>{if(t.key!=this.storageKey)return;let n=this._storageGet(this.storageKey)||{};super.save(n.token||"",n.record||n.model||null)}))}},Ke=class{constructor(t){this.client=t}},Pp=class extends Ke{async getAll(t){return t=Object.assign({method:"GET"},t),this.client.send("/api/settings",t)}async update(t,n){return n=Object.assign({method:"PATCH",body:t},n),this.client.send("/api/settings",n)}async testS3(t="storage",n){return n=Object.assign({method:"POST",body:{filesystem:t}},n),this.client.send("/api/settings/test/s3",n).then((()=>!0))}async testEmail(t,n,i,r){return r=Object.assign({method:"POST",body:{email:n,template:i,collection:t}},r),this.client.send("/api/settings/test/email",r).then((()=>!0))}async generateAppleClientSecret(t,n,i,r,o,a){return a=Object.assign({method:"POST",body:{clientId:t,teamId:n,keyId:i,privateKey:r,duration:o}},a),this.client.send("/api/settings/apple/generate-client-secret",a)}},J_=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function Vp(e){if(e){e.query=e.query||{};for(let t in e)J_.includes(t)||(e.query[t]=e[t],delete e[t])}}function Wp(e){let t=[];for(let n in e){let i=encodeURIComponent(n),r=Array.isArray(e[n])?e[n]:[e[n]];for(let o of r)o=K_(o),o!==null&&t.push(i+"="+o)}return t.join("&")}function K_(e){return e==null?null:e instanceof Date?encodeURIComponent(e.toISOString().replace("T"," ")):encodeURIComponent(typeof e=="object"?JSON.stringify(e):e)}var ra=class extends Ke{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentSubscriptions=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}async subscribe(t,n,i){if(!t)throw new Error("topic must be set.");let r=t;if(i){Vp(i=Object.assign({},i));let a="options="+encodeURIComponent(JSON.stringify({query:i.query,headers:i.headers}));r+=(r.includes("?")?"&":"?")+a}let o=function(a){let s=a,u;try{u=JSON.parse(s?.data)}catch{}n(u||{})};return this.subscriptions[r]||(this.subscriptions[r]=[]),this.subscriptions[r].push(o),this.isConnected?this.subscriptions[r].length===1?await this.submitSubscriptions():this.eventSource?.addEventListener(r,o):await this.connect(),async()=>this.unsubscribeByTopicAndListener(t,o)}async unsubscribe(t){let n=!1;if(t){let i=this.getSubscriptionsByTopic(t);for(let r in i)if(this.hasSubscriptionListeners(r)){for(let o of this.subscriptions[r])this.eventSource?.removeEventListener(r,o);delete this.subscriptions[r],n||(n=!0)}}else this.subscriptions={};this.hasSubscriptionListeners()?n&&await this.submitSubscriptions():this.disconnect()}async unsubscribeByPrefix(t){let n=!1;for(let i in this.subscriptions)if((i+"?").startsWith(t)){n=!0;for(let r of this.subscriptions[i])this.eventSource?.removeEventListener(i,r);delete this.subscriptions[i]}n&&(this.hasSubscriptionListeners()?await this.submitSubscriptions():this.disconnect())}async unsubscribeByTopicAndListener(t,n){let i=!1,r=this.getSubscriptionsByTopic(t);for(let o in r){if(!Array.isArray(this.subscriptions[o])||!this.subscriptions[o].length)continue;let a=!1;for(let s=this.subscriptions[o].length-1;s>=0;s--)this.subscriptions[o][s]===n&&(a=!0,delete this.subscriptions[o][s],this.subscriptions[o].splice(s,1),this.eventSource?.removeEventListener(o,n));a&&(this.subscriptions[o].length||delete this.subscriptions[o],i||this.hasSubscriptionListeners(o)||(i=!0))}this.hasSubscriptionListeners()?i&&await this.submitSubscriptions():this.disconnect()}hasSubscriptionListeners(t){if(this.subscriptions=this.subscriptions||{},t)return!!this.subscriptions[t]?.length;for(let n in this.subscriptions)if(this.subscriptions[n]?.length)return!0;return!1}async submitSubscriptions(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentSubscriptions=this.getNonEmptySubscriptionKeys(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentSubscriptions},requestKey:this.getSubscriptionsCancelKey()}).catch((t=>{if(!t?.isAbort)throw t}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getSubscriptionsByTopic(t){let n={};t=t.includes("?")?t:t+"?";for(let i in this.subscriptions)(i+"?").startsWith(t)&&(n[i]=this.subscriptions[i]);return n}getNonEmptySubscriptionKeys(){let t=[];for(let n in this.subscriptions)this.subscriptions[n].length&&t.push(n);return t}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let t in this.subscriptions)for(let n of this.subscriptions[t])this.eventSource.addEventListener(t,n)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let t in this.subscriptions)for(let n of this.subscriptions[t])this.eventSource.removeEventListener(t,n)}async connect(){if(!(this.reconnectAttempts>0))return new Promise(((t,n)=>{this.pendingConnects.push({resolve:t,reject:n}),this.pendingConnects.length>1||this.initConnect()}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildURL("/api/realtime")),this.eventSource.onerror=t=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(t=>{let n=t;this.clientId=n?.lastEventId,this.submitSubscriptions().then((async()=>{let i=3;for(;this.hasUnsentSubscriptions()&&i>0;)i--,await this.submitSubscriptions()})).then((()=>{for(let r of this.pendingConnects)r.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId);let i=this.getSubscriptionsByTopic("PB_CONNECT");for(let r in i)for(let o of i[r])o(t)})).catch((i=>{this.clientId="",this.connectErrorHandler(i)}))}))}hasUnsentSubscriptions(){let t=this.getNonEmptySubscriptionKeys();if(t.length!=this.lastSentSubscriptions.length)return!0;for(let n of t)if(!this.lastSentSubscriptions.includes(n))return!0;return!1}connectErrorHandler(t){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let i of this.pendingConnects)i.reject(new ke(t));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);let n=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),n)}disconnect(t=!1){if(this.clientId&&this.onDisconnect&&this.onDisconnect(Object.keys(this.subscriptions)),clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),this.eventSource?.close(),this.eventSource=null,this.clientId="",!t){this.reconnectAttempts=0;for(let n of this.pendingConnects)n.resolve();this.pendingConnects=[]}}},na=class extends Ke{decode(t){return t}async getFullList(t,n){if(typeof t=="number")return this._getFullList(t,n);let i=1e3;return(n=Object.assign({},t,n)).batch&&(i=n.batch,delete n.batch),this._getFullList(i,n)}async getList(t=1,n=30,i){return(i=Object.assign({method:"GET"},i)).query=Object.assign({page:t,perPage:n},i.query),this.client.send(this.baseCrudPath,i).then((r=>(r.items=r.items?.map((o=>this.decode(o)))||[],r)))}async getFirstListItem(t,n){return(n=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+t},n)).query=Object.assign({filter:t,skipTotal:1},n.query),this.getList(1,1,n).then((i=>{if(!i?.items?.length)throw new ke({status:404,response:{code:404,message:"The requested resource wasn't found.",data:{}}});return i.items[0]}))}async getOne(t,n){if(!t)throw new ke({url:this.client.buildURL(this.baseCrudPath+"/"),status:404,response:{code:404,message:"Missing required record id.",data:{}}});return n=Object.assign({method:"GET"},n),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(t),n).then((i=>this.decode(i)))}async create(t,n){return n=Object.assign({method:"POST",body:t},n),this.client.send(this.baseCrudPath,n).then((i=>this.decode(i)))}async update(t,n,i){return i=Object.assign({method:"PATCH",body:n},i),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(t),i).then((r=>this.decode(r)))}async delete(t,n){return n=Object.assign({method:"DELETE"},n),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(t),n).then((()=>!0))}_getFullList(t=1e3,n){(n=n||{}).query=Object.assign({skipTotal:1},n.query);let i=[],r=async o=>this.getList(o,t||1e3,n).then((a=>{let s=a.items;return i=i.concat(s),s.length==a.perPage?r(o+1):i}));return r(1)}};function Ct(e,t,n,i){let r=i!==void 0;return r||n!==void 0?r?(console.warn(e),t.body=Object.assign({},t.body,n),t.query=Object.assign({},t.query,i),t):Object.assign(t,n):t}function Op(e){e._resetAutoRefresh?.()}var Ap=class extends na{constructor(t,n){super(t),this.collectionIdOrName=n}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}get isSuperusers(){return this.collectionIdOrName=="_superusers"||this.collectionIdOrName=="_pbc_2773867675"}async subscribe(t,n,i){if(!t)throw new Error("Missing topic.");if(!n)throw new Error("Missing subscription callback.");return this.client.realtime.subscribe(this.collectionIdOrName+"/"+t,n,i)}async unsubscribe(t){return t?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+t):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}async getFullList(t,n){if(typeof t=="number")return super.getFullList(t,n);let i=Object.assign({},t,n);return super.getFullList(i)}async getList(t=1,n=30,i){return super.getList(t,n,i)}async getFirstListItem(t,n){return super.getFirstListItem(t,n)}async getOne(t,n){return super.getOne(t,n)}async create(t,n){return super.create(t,n)}async update(t,n,i){return super.update(t,n,i).then((r=>{if(this.client.authStore.record?.id===r?.id&&(this.client.authStore.record?.collectionId===this.collectionIdOrName||this.client.authStore.record?.collectionName===this.collectionIdOrName)){let o=Object.assign({},this.client.authStore.record.expand),a=Object.assign({},this.client.authStore.record,r);o&&(a.expand=Object.assign(o,r.expand)),this.client.authStore.save(this.client.authStore.token,a)}return r}))}async delete(t,n){return super.delete(t,n).then((i=>(!i||this.client.authStore.record?.id!==t||this.client.authStore.record?.collectionId!==this.collectionIdOrName&&this.client.authStore.record?.collectionName!==this.collectionIdOrName||this.client.authStore.clear(),i)))}authResponse(t){let n=this.decode(t?.record||{});return this.client.authStore.save(t?.token,n),Object.assign({},t,{token:t?.token||"",record:n})}async listAuthMethods(t){return t=Object.assign({method:"GET",fields:"mfa,otp,password,oauth2"},t),this.client.send(this.baseCollectionPath+"/auth-methods",t)}async authWithPassword(t,n,i){let r;i=Object.assign({method:"POST",body:{identity:t,password:n}},i),this.isSuperusers&&(r=i.autoRefreshThreshold,delete i.autoRefreshThreshold,i.autoRefresh||Op(this.client));let o=await this.client.send(this.baseCollectionPath+"/auth-with-password",i);return o=this.authResponse(o),r&&this.isSuperusers&&(function(s,u,c,l){Op(s);let d=s.beforeSend,p=s.authStore.record,f=s.authStore.onChange(((g,x)=>{(!g||x?.id!=p?.id||(x?.collectionId||p?.collectionId)&&x?.collectionId!=p?.collectionId)&&Op(s)}));s._resetAutoRefresh=function(){f(),s.beforeSend=d,delete s._resetAutoRefresh},s.beforeSend=async(g,x)=>{let S=s.authStore.token;if(x.query?.autoRefresh)return d?d(g,x):{url:g,sendOptions:x};let N=s.authStore.isValid;if(N&&Mv(s.authStore.token,u))try{await c()}catch{N=!1}N||await l();let H=x.headers||{};for(let O in H)if(O.toLowerCase()=="authorization"&&S==H[O]&&s.authStore.token){H[O]=s.authStore.token;break}return x.headers=H,d?d(g,x):{url:g,sendOptions:x}}})(this.client,r,(()=>this.authRefresh({autoRefresh:!0})),(()=>this.authWithPassword(t,n,Object.assign({autoRefresh:!0},i)))),o}async authWithOAuth2Code(t,n,i,r,o,a,s){let u={method:"POST",body:{provider:t,code:n,codeVerifier:i,redirectURL:r,createData:o}};return u=Ct("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectURL, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectURL, createData?, options?).",u,a,s),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",u).then((c=>this.authResponse(c)))}authWithOAuth2(...t){if(t.length>1||typeof t?.[0]=="string")return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code(t?.[0]||"",t?.[1]||"",t?.[2]||"",t?.[3]||"",t?.[4]||{},t?.[5]||{},t?.[6]||{});let n=t?.[0]||{},i=null;n.urlCallback||(i=Rv(void 0));let r=new ra(this.client);function o(){i?.close(),r.unsubscribe()}let a={},s=n.requestKey;return s&&(a.requestKey=s),this.listAuthMethods(a).then((u=>{let c=u.oauth2.providers.find((d=>d.name===n.provider));if(!c)throw new ke(new Error(`Missing or invalid provider "${n.provider}".`));let l=this.client.buildURL("/api/oauth2-redirect");return new Promise((async(d,p)=>{let f=s?this.client.cancelControllers?.[s]:void 0;f&&(f.signal.onabort=()=>{o(),p(new ke({isAbort:!0,message:"manually cancelled"}))}),r.onDisconnect=g=>{g.length&&p&&(o(),p(new ke(new Error("realtime connection interrupted"))))};try{await r.subscribe("@oauth2",(async N=>{let H=r.clientId;try{if(!N.state||H!==N.state)throw new Error("State parameters don't match.");if(N.error||!N.code)throw new Error("OAuth2 redirect error or missing code: "+N.error);let O=Object.assign({},n);delete O.provider,delete O.scopes,delete O.createData,delete O.urlCallback,f?.signal?.onabort&&(f.signal.onabort=null);let W=await this.authWithOAuth2Code(c.name,N.code,c.codeVerifier,l,n.createData,O);d(W)}catch(O){p(new ke(O))}o()}));let g={state:r.clientId};n.scopes?.length&&(g.scope=n.scopes.join(" "));let x=this._replaceQueryParams(c.authURL+l,g);await(n.urlCallback||function(N){i?i.location.href=N:i=Rv(N)})(x)}catch(g){f?.signal?.onabort&&(f.signal.onabort=null),o(),p(new ke(g))}}))})).catch((u=>{throw o(),u}))}async authRefresh(t,n){let i={method:"POST"};return i=Ct("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",i,t,n),this.client.send(this.baseCollectionPath+"/auth-refresh",i).then((r=>this.authResponse(r)))}async requestPasswordReset(t,n,i){let r={method:"POST",body:{email:t}};return r=Ct("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",r,n,i),this.client.send(this.baseCollectionPath+"/request-password-reset",r).then((()=>!0))}async confirmPasswordReset(t,n,i,r,o){let a={method:"POST",body:{token:t,password:n,passwordConfirm:i}};return a=Ct("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",a,r,o),this.client.send(this.baseCollectionPath+"/confirm-password-reset",a).then((()=>!0))}async requestVerification(t,n,i){let r={method:"POST",body:{email:t}};return r=Ct("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).",r,n,i),this.client.send(this.baseCollectionPath+"/request-verification",r).then((()=>!0))}async confirmVerification(t,n,i){let r={method:"POST",body:{token:t}};return r=Ct("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).",r,n,i),this.client.send(this.baseCollectionPath+"/confirm-verification",r).then((()=>{let o=Or(t),a=this.client.authStore.record;return a&&!a.verified&&a.id===o.id&&a.collectionId===o.collectionId&&(a.verified=!0,this.client.authStore.save(this.client.authStore.token,a)),!0}))}async requestEmailChange(t,n,i){let r={method:"POST",body:{newEmail:t}};return r=Ct("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).",r,n,i),this.client.send(this.baseCollectionPath+"/request-email-change",r).then((()=>!0))}async confirmEmailChange(t,n,i,r){let o={method:"POST",body:{token:t,password:n}};return o=Ct("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).",o,i,r),this.client.send(this.baseCollectionPath+"/confirm-email-change",o).then((()=>{let a=Or(t),s=this.client.authStore.record;return s&&s.id===a.id&&s.collectionId===a.collectionId&&this.client.authStore.clear(),!0}))}async listExternalAuths(t,n){return this.client.collection("_externalAuths").getFullList(Object.assign({},n,{filter:this.client.filter("recordRef = {:id}",{id:t})}))}async unlinkExternalAuth(t,n,i){let r=await this.client.collection("_externalAuths").getFirstListItem(this.client.filter("recordRef = {:recordId} && provider = {:provider}",{recordId:t,provider:n}));return this.client.collection("_externalAuths").delete(r.id,i).then((()=>!0))}async requestOTP(t,n){return n=Object.assign({method:"POST",body:{email:t}},n),this.client.send(this.baseCollectionPath+"/request-otp",n)}async authWithOTP(t,n,i){return i=Object.assign({method:"POST",body:{otpId:t,password:n}},i),this.client.send(this.baseCollectionPath+"/auth-with-otp",i).then((r=>this.authResponse(r)))}async impersonate(t,n,i){(i=Object.assign({method:"POST",body:{duration:n}},i)).headers=i.headers||{},i.headers.Authorization||(i.headers.Authorization=this.client.authStore.token);let r=new Sn(this.client.baseURL,new In,this.client.lang),o=await r.send(this.baseCollectionPath+"/impersonate/"+encodeURIComponent(t),i);return r.authStore.save(o?.token,this.decode(o?.record||{})),r}_replaceQueryParams(t,n={}){let i=t,r="";t.indexOf("?")>=0&&(i=t.substring(0,t.indexOf("?")),r=t.substring(t.indexOf("?")+1));let o={},a=r.split("&");for(let s of a){if(s=="")continue;let u=s.split("=");o[decodeURIComponent(u[0].replace(/\+/g," "))]=decodeURIComponent((u[1]||"").replace(/\+/g," "))}for(let s in n)n.hasOwnProperty(s)&&(n[s]==null?delete o[s]:o[s]=n[s]);r="";for(let s in o)o.hasOwnProperty(s)&&(r!=""&&(r+="&"),r+=encodeURIComponent(s.replace(/%20/g,"+"))+"="+encodeURIComponent(o[s].replace(/%20/g,"+")));return r!=""?i+"?"+r:i}};function Rv(e){if(typeof window>"u"||!window?.open)throw new ke(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,n=768,i=window.innerWidth,r=window.innerHeight;t=t>i?i:t,n=n>r?r:n;let o=i/2-t/2,a=r/2-n/2;return window.open(e,"popup_window","width="+t+",height="+n+",top="+a+",left="+o+",resizable,menubar=no")}var Tp=class extends na{get baseCrudPath(){return"/api/collections"}async import(t,n=!1,i){return i=Object.assign({method:"PUT",body:{collections:t,deleteMissing:n}},i),this.client.send(this.baseCrudPath+"/import",i).then((()=>!0))}async getScaffolds(t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/meta/scaffolds",t)}async truncate(t,n){return n=Object.assign({method:"DELETE"},n),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(t)+"/truncate",n).then((()=>!0))}},jp=class extends Ke{async getList(t=1,n=30,i){return(i=Object.assign({method:"GET"},i)).query=Object.assign({page:t,perPage:n},i.query),this.client.send("/api/logs",i)}async getOne(t,n){if(!t)throw new ke({url:this.client.buildURL("/api/logs/"),status:404,response:{code:404,message:"Missing required log id.",data:{}}});return n=Object.assign({method:"GET"},n),this.client.send("/api/logs/"+encodeURIComponent(t),n)}async getStats(t){return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/stats",t)}},Up=class extends Ke{async check(t){return t=Object.assign({method:"GET"},t),this.client.send("/api/health",t)}},Np=class extends Ke{getUrl(t,n,i={}){return console.warn("Please replace pb.files.getUrl() with pb.files.getURL()"),this.getURL(t,n,i)}getURL(t,n,i={}){if(!n||!t?.id||!t?.collectionId&&!t?.collectionName)return"";let r=[];r.push("api"),r.push("files"),r.push(encodeURIComponent(t.collectionId||t.collectionName)),r.push(encodeURIComponent(t.id)),r.push(encodeURIComponent(n));let o=this.client.buildURL(r.join("/"));i.download===!1&&delete i.download;let a=Wp(i);return a&&(o+=(o.includes("?")?"&":"?")+a),o}async getToken(t){return t=Object.assign({method:"POST"},t),this.client.send("/api/files/token",t).then((n=>n?.token||""))}},Rp=class extends Ke{async getFullList(t){return t=Object.assign({method:"GET"},t),this.client.send("/api/backups",t)}async create(t,n){return n=Object.assign({method:"POST",body:{name:t}},n),this.client.send("/api/backups",n).then((()=>!0))}async upload(t,n){return n=Object.assign({method:"POST",body:t},n),this.client.send("/api/backups/upload",n).then((()=>!0))}async delete(t,n){return n=Object.assign({method:"DELETE"},n),this.client.send(`/api/backups/${encodeURIComponent(t)}`,n).then((()=>!0))}async restore(t,n){return n=Object.assign({method:"POST"},n),this.client.send(`/api/backups/${encodeURIComponent(t)}/restore`,n).then((()=>!0))}getDownloadUrl(t,n){return console.warn("Please replace pb.backups.getDownloadUrl() with pb.backups.getDownloadURL()"),this.getDownloadURL(t,n)}getDownloadURL(t,n){return this.client.buildURL(`/api/backups/${encodeURIComponent(n)}?token=${encodeURIComponent(t)}`)}},Bp=class extends Ke{async getFullList(t){return t=Object.assign({method:"GET"},t),this.client.send("/api/crons",t)}async run(t,n){return n=Object.assign({method:"POST"},n),this.client.send(`/api/crons/${encodeURIComponent(t)}`,n).then((()=>!0))}};function Zp(e){return typeof Blob<"u"&&e instanceof Blob||typeof File<"u"&&e instanceof File||e!==null&&typeof e=="object"&&e.uri&&(typeof navigator<"u"&&navigator.product==="ReactNative"||typeof global<"u"&&global.HermesInternal)}function Lp(e){return e&&(e.constructor?.name==="FormData"||typeof FormData<"u"&&e instanceof FormData)}function Bv(e){for(let t in e){let n=Array.isArray(e[t])?e[t]:[e[t]];for(let i of n)if(Zp(i))return!0}return!1}var H_=/^[\-\.\d]+$/;function Zv(e){if(typeof e!="string")return e;if(e=="true")return!0;if(e=="false")return!1;if((e[0]==="-"||e[0]>="0"&&e[0]<="9")&&H_.test(e)){let t=+e;if(""+t===e)return t}return e}var Mp=class extends Ke{constructor(){super(...arguments),this.requests=[],this.subs={}}collection(t){return this.subs[t]||(this.subs[t]=new qp(this.requests,t)),this.subs[t]}async send(t){let n=new FormData,i=[];for(let r=0;r<this.requests.length;r++){let o=this.requests[r];if(i.push({method:o.method,url:o.url,headers:o.headers,body:o.json}),o.files)for(let a in o.files){let s=o.files[a]||[];for(let u of s)n.append("requests."+r+"."+a,u)}}return n.append("@jsonPayload",JSON.stringify({requests:i})),t=Object.assign({method:"POST",body:n},t),this.client.send("/api/batch",t)}},qp=class{constructor(t,n){this.requests=[],this.requests=t,this.collectionIdOrName=n}upsert(t,n){n=Object.assign({body:t||{}},n);let i={method:"PUT",url:"/api/collections/"+encodeURIComponent(this.collectionIdOrName)+"/records"};this.prepareRequest(i,n),this.requests.push(i)}create(t,n){n=Object.assign({body:t||{}},n);let i={method:"POST",url:"/api/collections/"+encodeURIComponent(this.collectionIdOrName)+"/records"};this.prepareRequest(i,n),this.requests.push(i)}update(t,n,i){i=Object.assign({body:n||{}},i);let r={method:"PATCH",url:"/api/collections/"+encodeURIComponent(this.collectionIdOrName)+"/records/"+encodeURIComponent(t)};this.prepareRequest(r,i),this.requests.push(r)}delete(t,n){n=Object.assign({},n);let i={method:"DELETE",url:"/api/collections/"+encodeURIComponent(this.collectionIdOrName)+"/records/"+encodeURIComponent(t)};this.prepareRequest(i,n),this.requests.push(i)}prepareRequest(t,n){if(Vp(n),t.headers=n.headers,t.json={},t.files={},n.query!==void 0){let r=Wp(n.query);r&&(t.url+=(t.url.includes("?")?"&":"?")+r)}let i=n.body;Lp(i)&&(i=(function(o){let a={};return o.forEach(((s,u)=>{if(u==="@jsonPayload"&&typeof s=="string")try{let c=JSON.parse(s);Object.assign(a,c)}catch(c){console.warn("@jsonPayload error:",c)}else a[u]!==void 0?(Array.isArray(a[u])||(a[u]=[a[u]]),a[u].push(Zv(s))):a[u]=Zv(s)})),a})(i));for(let r in i){let o=i[r];if(Zp(o))t.files[r]=t.files[r]||[],t.files[r].push(o);else if(Array.isArray(o)){let a=[],s=[];for(let u of o)Zp(u)?a.push(u):s.push(u);if(a.length>0&&a.length==o.length){t.files[r]=t.files[r]||[];for(let u of a)t.files[r].push(u)}else if(t.json[r]=s,a.length>0){let u=r;r.startsWith("+")||r.endsWith("+")||(u+="+"),t.files[u]=t.files[u]||[];for(let c of a)t.files[u].push(c)}}else t.json[r]=o}}},Sn=class{get baseUrl(){return this.baseURL}set baseUrl(t){this.baseURL=t}constructor(t="/",n,i="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseURL=t,this.lang=i,n?this.authStore=n:typeof window<"u"&&window.Deno?this.authStore=new In:this.authStore=new zp,this.collections=new Tp(this),this.files=new Np(this),this.logs=new jp(this),this.settings=new Pp(this),this.realtime=new ra(this),this.health=new Up(this),this.backups=new Rp(this),this.crons=new Bp(this)}get admins(){return this.collection("_superusers")}createBatch(){return new Mp(this)}collection(t){return this.recordServices[t]||(this.recordServices[t]=new Ap(this,t)),this.recordServices[t]}autoCancellation(t){return this.enableAutoCancellation=!!t,this}cancelRequest(t){return this.cancelControllers[t]&&(this.cancelControllers[t].abort(),delete this.cancelControllers[t]),this}cancelAllRequests(){for(let t in this.cancelControllers)this.cancelControllers[t].abort();return this.cancelControllers={},this}filter(t,n){if(!n)return t;for(let i in n){let r=n[i];switch(typeof r){case"boolean":case"number":r=""+r;break;case"string":r="'"+r.replace(/'/g,"\\'")+"'";break;default:r=r===null?"null":r instanceof Date?"'"+r.toISOString().replace("T"," ")+"'":"'"+JSON.stringify(r).replace(/'/g,"\\'")+"'"}t=t.replaceAll("{:"+i+"}",r)}return t}getFileUrl(t,n,i={}){return console.warn("Please replace pb.getFileUrl() with pb.files.getURL()"),this.files.getURL(t,n,i)}buildUrl(t){return console.warn("Please replace pb.buildUrl() with pb.buildURL()"),this.buildURL(t)}buildURL(t){let n=this.baseURL;return typeof window>"u"||!window.location||n.startsWith("https://")||n.startsWith("http://")||(n=window.location.origin?.endsWith("/")?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseURL.startsWith("/")||(n+=window.location.pathname||"/",n+=n.endsWith("/")?"":"/"),n+=this.baseURL),t&&(n+=n.endsWith("/")?"":"/",n+=t.startsWith("/")?t.substring(1):t),n}async send(t,n){n=this.initSendOptions(t,n);let i=this.buildURL(t);if(this.beforeSend){let r=Object.assign({},await this.beforeSend(i,n));r.url!==void 0||r.options!==void 0?(i=r.url||i,n=r.options||n):Object.keys(r).length&&(n=r,console?.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(n.query!==void 0){let r=Wp(n.query);r&&(i+=(i.includes("?")?"&":"?")+r),delete n.query}return this.getHeader(n.headers,"Content-Type")=="application/json"&&n.body&&typeof n.body!="string"&&(n.body=JSON.stringify(n.body)),(n.fetch||fetch)(i,n).then((async r=>{let o={};try{o=await r.json()}catch(a){if(n.signal?.aborted||a?.name=="AbortError"||a?.message=="Aborted")throw a}if(this.afterSend&&(o=await this.afterSend(r,o,n)),r.status>=400)throw new ke({url:r.url,status:r.status,data:o});return o})).catch((r=>{throw new ke(r)}))}initSendOptions(t,n){if((n=Object.assign({method:"GET"},n)).body=(function(r){if(typeof FormData>"u"||r===void 0||typeof r!="object"||r===null||Lp(r)||!Bv(r))return r;let o=new FormData;for(let a in r){let s=r[a];if(s!==void 0)if(typeof s!="object"||Bv({data:s})){let u=Array.isArray(s)?s:[s];for(let c of u)o.append(a,c)}else{let u={};u[a]=s,o.append("@jsonPayload",JSON.stringify(u))}}return o})(n.body),Vp(n),n.query=Object.assign({},n.params,n.query),n.requestKey===void 0&&(n.$autoCancel===!1||n.query.$autoCancel===!1?n.requestKey=null:(n.$cancelKey||n.query.$cancelKey)&&(n.requestKey=n.$cancelKey||n.query.$cancelKey)),delete n.$autoCancel,delete n.query.$autoCancel,delete n.$cancelKey,delete n.query.$cancelKey,this.getHeader(n.headers,"Content-Type")!==null||Lp(n.body)||(n.headers=Object.assign({},n.headers,{"Content-Type":"application/json"})),this.getHeader(n.headers,"Accept-Language")===null&&(n.headers=Object.assign({},n.headers,{"Accept-Language":this.lang})),this.authStore.token&&this.getHeader(n.headers,"Authorization")===null&&(n.headers=Object.assign({},n.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&n.requestKey!==null){let i=n.requestKey||(n.method||"GET")+t;delete n.requestKey,this.cancelRequest(i);let r=new AbortController;this.cancelControllers[i]=r,n.signal=r.signal}return n}getHeader(t,n){t=t||{},n=n.toLowerCase();for(let i in t)if(i.toLowerCase()==n)return t[i];return null}};function qv(e){let t=new Sn(e.baseUrl);return t.autoCancellation(!1),e.token&&t.authStore.save(e.token),(e.tenantId||e.accountId)&&(t.beforeSend=(n,i)=>{let r=i.headers;return e.tenantId&&(r["X-Tenant-Id"]=e.tenantId),e.accountId&&(r["X-Account-Id"]=e.accountId),{url:n,options:i}}),t}function M(e){return e instanceof Error?e.message:String(e)}async function k(e,t){let n=kt(e);try{let i=await t();return dt(n),i}catch(i){dt(n),y("%s",M(i))}}function v(e){Pe()?Fv(e.json()):e.human()}function Y_(e){let t={};return e.token&&(t.Authorization=`Bearer ${e.token}`),e.tenantId&&(t["X-Tenant-Id"]=e.tenantId),e.accountId&&(t["X-Account-Id"]=e.accountId),t}function Vv(e){if(!e.length)throw new Error("empty batch response");let t=e[0];if(t.error?.message)throw new Error(`tRPC error: ${t.error.message}`);if(!t.result?.data)throw new Error("unexpected response format");return t.result.data.json}var ia=class{baseUrl;headers;constructor(t){this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.headers=Y_(t)}async query(t,n){let r=encodeURIComponent(JSON.stringify({0:{json:n}})),o=`${this.baseUrl}/trpc/${t}?batch=1&input=${r}`,a=await fetch(o,{headers:this.headers});a.status>=400&&await this.throwHttpError(a);let s=await a.json();return Vv(s)}async mutate(t,n){let i={0:{json:n}},r=`${this.baseUrl}/trpc/${t}?batch=1`,o=await fetch(r,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i)});o.status>=400&&await this.throwHttpError(o);let a=await o.json();return Vv(a)}async throwHttpError(t){let n;try{let i=await t.json();Array.isArray(i)&&i[0]?.error?.message?n=i[0].error.message:n=JSON.stringify(i)}catch{n=await t.text()}throw new Error(`${t.status}: ${n}`)}};var Jp="";function Wv(e){Jp=e}function ue(){return Jp}function X_(e,t){let n=`${t}-pb`,i=e.services[n];return i||y('no PB URL for "%s" (expected services["%s"] in profile)',t,n),i}async function En(){let e=oe(Jp),{cfg:t,profile:n}=se(e),i=await zo(t,e,n);return{cfg:t,profile:n,token:i}}async function P(e){let{cfg:t,profile:n,token:i}=await En(),r=qv({baseUrl:X_(n,e),token:i,tenantId:Ge(n),accountId:Je(n)});return{cfg:t,profile:n,client:r}}async function K(e){let{profile:t,token:n}=await En(),i=t.services[e];return i||y("no %s API URL configured (run `zenku profile show` to check)",e),new ia({baseUrl:i,token:n,tenantId:Ge(t),accountId:Je(t)})}async function It(){let{cfg:e,profile:t,token:n}=await En(),i=t.services.agent;return i||y("no agent API URL configured (run `zenku profile show` to check)"),{client:Fp({baseUrl:i,auth:{type:"jwt",getToken:()=>n,tenantId:Ge(t),accountId:Je(t)}}),profile:t,cfg:e}}function Q(e){return e==null?"":String(e)}function pt(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function Ce(e){if(e==="-")try{return(0,Gp.readFileSync)(0,"utf-8")}catch{y("failed to read from stdin")}if(e.startsWith("@")){let t=e.slice(1);try{return(0,Gp.readFileSync)(t,"utf-8")}catch(n){y("failed to read file %s: %s",t,M(n))}}return e}async function Gv(e,t,n){let i=await Ov("Password",{flagHint:"--email with password prompt"});if(i===null)return null;if(!i)throw new Error("password is required");let r=kt("Authenticating...");try{return await Ig(e,t,n,i)}finally{dt(r)}}async function Jv(e,t,n){let i=kt("Requesting OTP..."),r="";try{r=await Sg(e,t,n)}finally{dt(i)}process.stdout.write(`OTP sent to ${n}
|
|
129
129
|
`);let o=await we("Enter OTP code",{flagHint:"--otp <email>"});if(o===null)return null;if(!o)throw new Error("OTP code is required");let a=kt("Verifying OTP...");try{return await Eg(e,t,r,o)}finally{dt(a)}}async function Kv(e,t,n){let i=kt("Fetching auth methods..."),r;try{r=await Bd(e,t)}finally{dt(i)}if(r.oauth2Providers.length===0)throw new Error("no OAuth2 providers configured");let o;if(n){if(o=r.oauth2Providers.find(a=>a.name===n),!o)throw new Error(`provider "${n}" not found`)}else if(r.oauth2Providers.length===1)o=r.oauth2Providers[0];else{let a=await Lt("Choose OAuth provider",r.oauth2Providers.map(s=>({value:s.name,label:s.displayName})),{flagHint:"--provider <name>"});if(a===null)return null;o=r.oauth2Providers.find(s=>s.name===a)}if(!o)throw new Error("provider not found");return Fg(e,t,o)}async function Q_(e,t){let n=[],i=kt("Fetching auth methods...");try{let a=await Bd(e,t);a.password&&n.push({label:"Password",kind:"password"}),a.otp&&n.push({label:"OTP (email code)",kind:"otp"}),a.oauth2Providers.length>0&&n.push({label:"OAuth2 (browser)",kind:"oauth"})}catch{n.push({label:"Password",kind:"password"})}finally{dt(i)}if(n.length===0)throw new Error("no auth methods available");if(n.length>1){let a=await Lt("Choose auth method",n.map(u=>({value:u.kind,label:u.label})),{flagHint:"--email, --otp, or --oauth"});if(a===null)return null;let s=n.findIndex(u=>u.kind===a);if(s>0){let u=n[s];n.splice(s,1),n.unshift(u)}}let r=n[0];if(!r)throw new Error("unknown auth method");if(r.kind==="oauth")return Kv(e,t,"");let o=await we("Email",{flagHint:"--email <email>"});if(o===null)return null;if(r.kind==="password")return Gv(e,t,o);if(r.kind==="otp")return Jv(e,t,o);throw new Error("unknown auth method")}function Hv(e){let t=new z("login").description("Authenticate with a PocketBase instance").option("--email <email>","login with email + password").option("--otp <email>","login with OTP (email code)").option("--oauth","login with OAuth2 browser flow").option("--provider <provider>","OAuth2 provider name (with --oauth)").action(async n=>{let i=oe(ue()),r,o;try{({cfg:r,profile:o}=se(i))}catch(a){y("%s",M(a))}try{let a;if(n.email?a=await Gv(Ve(o),o.collection,n.email):n.otp?a=await Jv(Ve(o),o.collection,n.otp):n.oauth?a=await Kv(Ve(o),o.collection,n.provider??""):a=await Q_(Ve(o),o.collection),!a)return;if(o.token=a.token,o.userId=a.userId,o.email=a.email,be(r,i,o),!o.accountId&&pe()){let s=Ve(o),u=await Qo(s,a.token,a.userId);u&&(o.accountId=u,be(r,i,o))}v({json:()=>({email:a.email,userId:a.userId}),human:()=>I("Logged in as %s",a.email)})}catch(a){y("%s",M(a))}});e.addCommand(t)}function Yv(e){let t=new z("logout").description("Clear authentication token").action(()=>{let n=oe(ue());try{let{cfg:i,profile:r}=se(n);r.token="",r.userId="",r.email="",be(i,n,r),I('Logged out from profile "%s"',n)}catch(i){y("%s",M(i))}});e.addCommand(t)}function Xv(e){let t=new z("whoami").description("Show current user and profile").action(()=>{let n=oe(ue()),i,r;try{({cfg:i,profile:r}=se(n))}catch(l){y("%s",M(l))}r.token||y("not logged in (run `zenku login`)");let o;try{o=zg(r.token)}catch(l){y("%s",`invalid token: ${M(l)}`)}let a=i.defaultProfile===n,s=o.getTime()-Date.now(),u=Ge(r),c=Je(r);v({json:()=>({profile:n,default:a,email:r.email,userId:r.userId,authPb:Ve(r),tenantId:u||null,accountId:c||null,expiresAt:o.toISOString(),expiresIn:Zd(Math.max(s,0))}),human:()=>{let l=a?" (default)":"";process.stdout.write(`Profile: ${n}${l}
|
|
130
130
|
`),process.stdout.write(`Email: ${r.email}
|
|
@@ -254,4 +254,4 @@ ${JSON.stringify(o.data,null,2)}
|
|
|
254
254
|
`),process.stdout.write(`Timezone: ${Q(o.timezone)}
|
|
255
255
|
`),process.stdout.write(`Next Run: ${qt(o.next)}
|
|
256
256
|
`)}})}),t.command("upsert").description("Create or update a scheduler").requiredOption("-q, --queue <name>","queue name").requiredOption("--id <id>","scheduler ID").requiredOption("--pattern <cron>","cron pattern").option("--timezone <tz>","timezone (e.g., America/New_York)").option("--data <json>","job data as JSON string").action(async n=>{let i={queue:n.queue,id:n.id,pattern:n.pattern};if(n.timezone&&(i.timezone=n.timezone),n.data)try{i.data=JSON.parse(n.data)}catch{y("invalid JSON for --data")}let r=await K("jobs"),o=await k("Upserting scheduler...",()=>r.mutate("schedulers.upsert",i));v({json:()=>o,human:()=>I("Scheduler upserted: %s",o.schedulerId)})}),t.command("remove").description("Remove a scheduler").requiredOption("-q, --queue <name>","queue name").argument("<id>","scheduler ID").action(async(n,i)=>{let r=await K("jobs");await k("Removing scheduler...",()=>r.mutate("schedulers.remove",{queue:i.queue,id:n})),v({json:()=>({success:!0,id:n,queue:i.queue}),human:()=>I("Scheduler %s removed",n)})}),e.addCommand(t),e.command("web").description("Open the Bull Board dashboard in the browser").option("--no-open","print the URL without opening the browser").action(async({open:n})=>{let i=oe(ue()),{profile:r}=se(i),o=r.services.jobs;o||y("no jobs API URL configured (run `zenku profile show` to check)");let a=`${o.replace(/\/+$/,"")}/dashboard`;if(n){let s=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,SD.exec)(`${s} "${a}"`)}v({json:()=>({url:a}),human:()=>E("Opening %s",a)})}),e}function ED(e){e.addCommand(Vx())}var le=require("node:fs"),Se=require("node:path"),Un=require("node:os");function um(e){return e||(process.env.CLAUDE_CONFIG_DIR?process.env.CLAUDE_CONFIG_DIR:(0,Se.join)((0,Un.homedir)(),".claude"))}function FD(e){return e||(process.env.ZENKU_MACHINE_ID?process.env.ZENKU_MACHINE_ID:(0,Un.hostname)())}function cm(e){let t=[],n;try{n=(0,le.readdirSync)(e,{withFileTypes:!0})}catch{return t}for(let i of n){let r=(0,Se.join)(e,i.name);i.isDirectory()?t.push(...cm(r)):i.isFile()&&i.name.endsWith(".jsonl")&&t.push(r)}return t}function it(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Wx(e,t){let n=(0,le.statSync)(e);return Date.now()-n.mtimeMs>=t*86400*1e3}function OD(e,t,n){let i=(0,Se.relative)(t,e);return`${n}/${i}`}function lm(e){return e.replace(/'/g,"\\'")}async function zD(e,t,n,i,r,o,a){let u=(0,le.statSync)(t).size,c=null;try{let p=await e.collection("session_files").getFirstListItem(`key='${lm(n)}'`);c={id:p.id,size:p.size}}catch{}if(c&&c.size===u)return{status:"skipped",key:n,size:u};if(a)return c?E("[DRY-RUN] Would update: %s (%s -> %s)",n,it(c.size),it(u)):E("[DRY-RUN] Would upload: %s (%s)",n,it(u)),{status:c?"updated":"uploaded",key:n,size:u};let l=(0,le.readFileSync)(t),d=new File([l],(0,Se.basename)(t),{type:"application/x-ndjson"});try{return c?(await e.collection("session_files").update(c.id,{size:u,file:d}),I("Updated: %s (%s -> %s)",n,it(c.size),it(u)),{status:"updated",key:n,size:u}):(await e.collection("session_files").create({key:n,machine_id:i,size:u,tenant_id:r,account_id:o,file:d}),I("Uploaded: %s (%s)",n,it(u)),{status:"uploaded",key:n,size:u})}catch(p){let f=p instanceof Error?p.message:String(p);return{status:"failed",key:n,size:u,error:f}}}function Gx(){let e=new z("sessions").description("Upload and manage Claude Code session transcripts");return e.command("sync").description("Scan local Claude Code sessions and upload new/changed files").option("--machine-id <id>","machine identifier for R2 key namespacing").option("--claude-dir <path>","Claude config directory").option("--dry-run","show what would be uploaded without uploading").option("--cleanup-days <days>","delete local files older than N days after successful upload").action(async t=>{let n=um(t.claudeDir),i=FD(t.machineId),r=t.dryRun??!1,o=t.cleanupDays?Number(t.cleanupDays):0;o&&(Number.isNaN(o)||o<1)&&y("--cleanup-days requires a positive integer");let a=(0,Se.join)(n,"projects"),s=cm(a);if(s.length===0){E("No session files found in %s",a);return}let{client:u,profile:c}=await P("library"),l=Ge(c),d=Je(c);o>0&&E("Cleanup mode: syncing files older than %s days",o),E("Scanning %s sessions in %s",s.length,a);let p=0,f=0,g=0,x=0,S=0,N=0;for(let H of s){if(o>0&&!Wx(H,o)){N++;continue}let O=OD(H,a,i),W=await zD(u,H,O,i,l,d,r);switch(W.status){case"uploaded":p++;break;case"updated":f++;break;case"skipped":g++;break;case"failed":E("Failed: %s \u2014 %s",O,W.error),x++;continue}if(o>0)if(r)E("[DRY-RUN] Would delete local: %s",H);else try{(0,le.unlinkSync)(H),S++}catch{E("Failed to delete local: %s",H)}}E(""),o>0?E("Summary: %s total, %s too new (<%sd), %s uploaded, %s updated, %s unchanged, %s deleted locally, %s failed",s.length,N,o,p,f,g,S,x):E("Summary: %s total, %s uploaded, %s updated, %s unchanged, %s failed",s.length,p,f,g,x)}),e.command("list").description("List Claude Code session files").option("--remote","list uploaded session files from PocketBase").option("--claude-dir <path>","Claude config directory").action(async t=>{if(t.remote){let{client:n}=await P("library"),i=await k("Fetching session files...",()=>n.collection("session_files").getList(1,200,{sort:"-created"}));v({json:()=>i.items,human:()=>{let r=i.items.map(o=>[o.id,o.key,o.machine_id,it(o.size),o.created]);L(["ID","KEY","MACHINE","SIZE","CREATED"],r)}})}else{let n=um(t.claudeDir),i=(0,Se.join)(n,"projects"),r=cm(i);v({json:()=>r.map(o=>{let a=(0,le.statSync)(o);return{path:o,size:a.size,modified:a.mtime}}),human:()=>{let o=r.map(a=>{let s=(0,le.statSync)(a);return[(0,Se.relative)(i,a),it(s.size),s.mtime.toISOString().slice(0,19)]});L(["PATH","SIZE","MODIFIED"],o),E(`
|
|
257
|
-
%s files, %s total`,r.length,it(r.reduce((a,s)=>a+(0,le.statSync)(s).size,0)))}})}}),e.command("upload").description("Upload a single session file").option("--hook","hook mode: read session path from stdin JSON").option("--machine-id <id>","machine identifier for R2 key namespacing").option("--claude-dir <path>","Claude config directory").argument("[file]","path to .jsonl file (when not using --hook)").action(async(t,n)=>{let i=um(n.claudeDir),r=FD(n.machineId),o=(0,Se.join)(i,"projects"),a;if(n.hook){let f;try{f=(0,le.readFileSync)(0,"utf-8")}catch{y("failed to read from stdin")}let g;try{g=JSON.parse(f)}catch{y("invalid JSON on stdin")}let x=g.transcript_path;x||y("no transcript_path in hook input"),a=x.replace(/^~/,(0,Un.homedir)())}else t?a=t:y("provide a file path or use --hook to read from stdin");try{(0,le.statSync)(a)}catch{y("file not found: %s",a)}let s=OD(a,o,r),{client:u,profile:c}=await P("library"),l=Ge(c),d=Je(c),p=await zD(u,a,s,r,l,d,!1);p.status==="failed"&&y("upload failed: %s",p.error),v({json:()=>p,human:()=>{p.status==="skipped"&&E("Skipped (unchanged): %s",s)}})}),e.command("download").description("Download session files from PocketBase").argument("[dir]","output directory",".").option("--key <key>","download a specific file by key").option("--machine-id <id>","download all files from a specific machine").action(async(t,n)=>{let{client:i}=await P("library"),r=[];n.key&&r.push(`key='${lm(n.key)}'`),n.machineId&&r.push(`machine_id='${lm(n.machineId)}'`);let o=r.length>0?r.join(" && "):"",a=await k("Fetching session files...",()=>i.collection("session_files").getFullList({sort:"key",filter:o}));if(a.length===0){E("No session files found");return}E("Downloading %s files to %s",a.length,t);let s=await i.files.getToken(),u=0,c=0;for(let l of a){let d=l.key,p=l.file,f=(0,Se.join)(t,d),g=i.files.getURL(l,p,{token:s});try{let x=await fetch(g);if(!x.ok){E("Failed: %s \u2014 HTTP %s",d,x.status),c++;continue}let S=Buffer.from(await x.arrayBuffer());(0,le.mkdirSync)((0,Se.dirname)(f),{recursive:!0}),(0,le.writeFileSync)(f,S),I("Downloaded: %s (%s)",d,it(S.length)),u++}catch(x){let S=x instanceof Error?x.message:String(x);E("Failed: %s \u2014 %s",d,S),c++}}E(""),E("Summary: %s total, %s downloaded, %s failed",a.length,u,c),v({json:()=>a.map(l=>({id:l.id,key:l.key,machine_id:l.machine_id,size:l.size})),human:()=>{}})}),e}function PD(e){e.addCommand(Gx())}var ga=require("node:child_process"),he=require("node:fs"),TD=require("node:os"),St=require("node:path");function AD(){return!0}var jD="https://registry.npmjs.org",Jx=15e3,UD="@zenku";function Kx(){let{platform:e,arch:t}=process,n=["darwin-arm64","darwin-x64","linux-arm64","linux-x64"],i=`${e}-${t}`;return n.includes(i)||y("Unsupported platform: %s",i),`cli-${i}`}async function Hx(e){let t=`${jD}/${UD}/${e}/latest`,n=new AbortController,i=setTimeout(()=>n.abort(),Jx);try{let r=await fetch(t,{signal:n.signal});if(!r.ok)throw new Error(`HTTP ${r.status}`);return(await r.json()).version}catch(r){throw r instanceof DOMException&&r.name==="AbortError"?new Error("request timed out"):r}finally{clearTimeout(i)}}function Yx(e,t){let n=`${e}-${t}.tgz`,i=`${jD}/${UD}/${e}/-/${n}`,r=(0,he.mkdtempSync)((0,St.join)((0,TD.tmpdir)(),"zenku-upgrade-"));try{(0,ga.execSync)(`curl -fsSL "${i}" -o "${(0,St.join)(r,n)}"`,{stdio:"pipe"}),(0,ga.execSync)(`tar xzf "${(0,St.join)(r,n)}" -C "${r}"`,{stdio:"pipe"});let o=(0,St.join)(r,"package","zenku"),a=process.execPath,s=(0,St.dirname)(a),u=(0,St.join)(s,`.zenku-upgrade-${process.pid}`),c=!1;try{(0,he.accessSync)(s,he.constants.W_OK)}catch{c=!0}if(c)(0,ga.execSync)(`sudo install -m 755 "${o}" "${a}"`,{stdio:"inherit"});else{(0,he.copyFileSync)(o,u),(0,he.chmodSync)(u,493);try{(0,he.renameSync)(u,a)}catch{try{(0,he.unlinkSync)(u)}catch{}throw new Error(`failed to replace binary at ${a}`)}}}finally{(0,he.rmSync)(r,{recursive:!0,force:!0})}}function ND(e){e.addCommand(new z("upgrade").description("Upgrade zenku to the latest version").action(async()=>{if(AD()){v({json:()=>({mode:"bundle",message:"Self-upgrade not available in bundle mode. Use: npm update -g @zenku/cli-node"}),human:()=>{E("Self-upgrade is not available in bundle mode."),E("Update via npm: npm update -g @zenku/cli-node")}});return}let t=dm(),n=Kx(),i=await k("Checking for updates...",()=>Hx(n));if(t===i){v({json:()=>({previous:t,latest:i,upgraded:!1}),human:()=>E("Already up to date (v%s).",t)});return}E("v%s \u2192 v%s",t,i),await k(`Downloading v${i}...`,async()=>{Yx(n,i)}),v({json:()=>({previous:t,latest:i,upgraded:!0}),human:()=>E("Upgraded zenku to v%s.",i)})}))}var Xx={};function dm(){return"0.1.
|
|
257
|
+
%s files, %s total`,r.length,it(r.reduce((a,s)=>a+(0,le.statSync)(s).size,0)))}})}}),e.command("upload").description("Upload a single session file").option("--hook","hook mode: read session path from stdin JSON").option("--machine-id <id>","machine identifier for R2 key namespacing").option("--claude-dir <path>","Claude config directory").argument("[file]","path to .jsonl file (when not using --hook)").action(async(t,n)=>{let i=um(n.claudeDir),r=FD(n.machineId),o=(0,Se.join)(i,"projects"),a;if(n.hook){let f;try{f=(0,le.readFileSync)(0,"utf-8")}catch{y("failed to read from stdin")}let g;try{g=JSON.parse(f)}catch{y("invalid JSON on stdin")}let x=g.transcript_path;x||y("no transcript_path in hook input"),a=x.replace(/^~/,(0,Un.homedir)())}else t?a=t:y("provide a file path or use --hook to read from stdin");try{(0,le.statSync)(a)}catch{y("file not found: %s",a)}let s=OD(a,o,r),{client:u,profile:c}=await P("library"),l=Ge(c),d=Je(c),p=await zD(u,a,s,r,l,d,!1);p.status==="failed"&&y("upload failed: %s",p.error),v({json:()=>p,human:()=>{p.status==="skipped"&&E("Skipped (unchanged): %s",s)}})}),e.command("download").description("Download session files from PocketBase").argument("[dir]","output directory",".").option("--key <key>","download a specific file by key").option("--machine-id <id>","download all files from a specific machine").action(async(t,n)=>{let{client:i}=await P("library"),r=[];n.key&&r.push(`key='${lm(n.key)}'`),n.machineId&&r.push(`machine_id='${lm(n.machineId)}'`);let o=r.length>0?r.join(" && "):"",a=await k("Fetching session files...",()=>i.collection("session_files").getFullList({sort:"key",filter:o}));if(a.length===0){E("No session files found");return}E("Downloading %s files to %s",a.length,t);let s=await i.files.getToken(),u=0,c=0;for(let l of a){let d=l.key,p=l.file,f=(0,Se.join)(t,d),g=i.files.getURL(l,p,{token:s});try{let x=await fetch(g);if(!x.ok){E("Failed: %s \u2014 HTTP %s",d,x.status),c++;continue}let S=Buffer.from(await x.arrayBuffer());(0,le.mkdirSync)((0,Se.dirname)(f),{recursive:!0}),(0,le.writeFileSync)(f,S),I("Downloaded: %s (%s)",d,it(S.length)),u++}catch(x){let S=x instanceof Error?x.message:String(x);E("Failed: %s \u2014 %s",d,S),c++}}E(""),E("Summary: %s total, %s downloaded, %s failed",a.length,u,c),v({json:()=>a.map(l=>({id:l.id,key:l.key,machine_id:l.machine_id,size:l.size})),human:()=>{}})}),e}function PD(e){e.addCommand(Gx())}var ga=require("node:child_process"),he=require("node:fs"),TD=require("node:os"),St=require("node:path");function AD(){return!0}var jD="https://registry.npmjs.org",Jx=15e3,UD="@zenku";function Kx(){let{platform:e,arch:t}=process,n=["darwin-arm64","darwin-x64","linux-arm64","linux-x64"],i=`${e}-${t}`;return n.includes(i)||y("Unsupported platform: %s",i),`cli-${i}`}async function Hx(e){let t=`${jD}/${UD}/${e}/latest`,n=new AbortController,i=setTimeout(()=>n.abort(),Jx);try{let r=await fetch(t,{signal:n.signal});if(!r.ok)throw new Error(`HTTP ${r.status}`);return(await r.json()).version}catch(r){throw r instanceof DOMException&&r.name==="AbortError"?new Error("request timed out"):r}finally{clearTimeout(i)}}function Yx(e,t){let n=`${e}-${t}.tgz`,i=`${jD}/${UD}/${e}/-/${n}`,r=(0,he.mkdtempSync)((0,St.join)((0,TD.tmpdir)(),"zenku-upgrade-"));try{(0,ga.execSync)(`curl -fsSL "${i}" -o "${(0,St.join)(r,n)}"`,{stdio:"pipe"}),(0,ga.execSync)(`tar xzf "${(0,St.join)(r,n)}" -C "${r}"`,{stdio:"pipe"});let o=(0,St.join)(r,"package","zenku"),a=process.execPath,s=(0,St.dirname)(a),u=(0,St.join)(s,`.zenku-upgrade-${process.pid}`),c=!1;try{(0,he.accessSync)(s,he.constants.W_OK)}catch{c=!0}if(c)(0,ga.execSync)(`sudo install -m 755 "${o}" "${a}"`,{stdio:"inherit"});else{(0,he.copyFileSync)(o,u),(0,he.chmodSync)(u,493);try{(0,he.renameSync)(u,a)}catch{try{(0,he.unlinkSync)(u)}catch{}throw new Error(`failed to replace binary at ${a}`)}}}finally{(0,he.rmSync)(r,{recursive:!0,force:!0})}}function ND(e){e.addCommand(new z("upgrade").description("Upgrade zenku to the latest version").action(async()=>{if(AD()){v({json:()=>({mode:"bundle",message:"Self-upgrade not available in bundle mode. Use: npm update -g @zenku/cli-node"}),human:()=>{E("Self-upgrade is not available in bundle mode."),E("Update via npm: npm update -g @zenku/cli-node")}});return}let t=dm(),n=Kx(),i=await k("Checking for updates...",()=>Hx(n));if(t===i){v({json:()=>({previous:t,latest:i,upgraded:!1}),human:()=>E("Already up to date (v%s).",t)});return}E("v%s \u2192 v%s",t,i),await k(`Downloading v${i}...`,async()=>{Yx(n,i)}),v({json:()=>({previous:t,latest:i,upgraded:!0}),human:()=>E("Upgraded zenku to v%s.",i)})}))}var Xx={};function dm(){return"0.1.33"}function ZD(){let e=new z;return e.name("zenku").description("Zenku CLI \u2014 manage PocketBase services from the terminal.").version(dm()).option("--profile <name>","config profile to use").option("--tenant <id>","override tenant ID for this command").option("--account <id>","override account ID for this command").option("--json","output as JSON").option("--interactive","force interactive mode").option("--non-interactive","force non-interactive mode").hook("preAction",t=>{let n=t.optsWithGlobals();Wv(n.profile??""),zv(n.tenant??""),Pv(n.account??""),Ev(!!n.json),n.interactive&&n.nonInteractive&&y("--interactive and --non-interactive cannot be used together"),n.interactive?Md("interactive"):n.nonInteractive&&Md("non-interactive")}),e.commandsGroup("Core Commands:"),oD(e),uD(e),lD(e),ID(e),e.commandsGroup("Platform Commands:"),rD(e),nD(e),ED(e),e.commandsGroup("Auth & Config:"),Hv(e),Yv(e),Xv(e),eD(e),e.commandsGroup("Other:"),PD(e),ND(e),e.addHelpCommand(new z("help").argument("[command]")),e}var Qx=ZD();Qx.parse();
|