@zenku/cli-node 0.1.18 → 0.1.20
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 +3 -3
package/package.json
CHANGED
package/zenku-bundle.cjs
CHANGED
|
@@ -124,8 +124,8 @@ ${t}`,K$=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),H$=Objec
|
|
|
124
124
|
`)}function gv(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function ee(e,t){if(t.length===0){Q("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${gv(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)=>gv(s,n[u])).join(" ");process.stdout.write(a+`
|
|
127
|
-
`)}}function bt(e){return kr||!se()?null:vp(e).start()}function ot(e){e&&e.stop()}async function $e(e,t){se()||$("%s is required (use %s)",e,t?.flagHint??"the appropriate flag");let n=await Rg({message:e,placeholder:t?.placeholder});return Tt(n)?(Q("cancelled"),null):n}async function yv(e,t){se()||$("%s is required (use %s)",e,t?.flagHint??"the appropriate flag");let n=await Zg({message:e});return Tt(n)?(Q("cancelled"),null):n}async function Bt(e,t,n){se()||$("%s is required (use %s)",e,n?.flagHint??"the appropriate flag");let i=await Mg({message:e,options:t});return Tt(i)?(Q("cancelled"),null):i}async function Dp(e,t){se()||$("%s requires confirmation (use %s)",e,t?.flagHint??"the appropriate flag");let n=await Lg({message:e});return Tt(n)?(Q("cancelled"),null):n}var yp="",bp="";function bv(e){yp=e}function $v(e){bp=e}function $t(e){return yp||(process.env.ZENKU_TENANT_ID?process.env.ZENKU_TENANT_ID:e.tenantId)}function _t(e){return bp||(process.env.ZENKU_ACCOUNT_ID?process.env.ZENKU_ACCOUNT_ID:e.accountId)}async function Go(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(!se())return"";let a=o.items.map(u=>({value:u.account,label:u.expand?.account?.name??u.account}));return await Bt("Choose account",a,{flagHint:"`zenku context set --account <id>`"})??""}catch{return""}}var Bp=require("node:fs");var Cr=class
|
|
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 m=__({event:o,data:d,id:a});m&&(yield m),o="",a=void 0}else l.trim()===""&&(o="",a=void 0)}}finally{n.releaseLock()}}function __(e){if(e.event==="keepalive")return{type:"keepalive"};if(!e.data)return null;try{let t=JSON.parse(e.data);return $p(e.event,t)}catch{return null}}var xv=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 Cr("NO_RESPONSE_BODY","No response body for SSE stream",{status:n.status});yield*Wo(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 Cr("NO_RESPONSE_BODY","No response body for SSE subscription",{status:r.status});yield*Wo(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 Cr("NETWORK_ERROR",a instanceof Error?a.message:"Network request failed")}if(!o.ok)throw await Cr.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 _p(e){return new xv(e)}var wv=E.object({accountId:E.string().min(1,"accountId is required"),params:E.record(E.string(),E.unknown()),conversationId:E.string().optional(),metadata:E.record(E.string(),E.unknown()).optional()}),x_=wv.extend({callbackUrl:E.url().optional(),callbackSecret:E.string().optional()});var w_=E.object({params:E.record(E.string(),E.unknown()),conversationId:E.string().optional(),callbackUrl:E.url().optional(),callbackSecret:E.string().optional(),metadata:E.record(E.string(),E.unknown()).optional()});var _e=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}}},Jo=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function k_(e,t){let n={};if(typeof e!="string")return n;let i=Object.assign({},t||{}).decode||C_,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 kv(e,t,n){let i=Object.assign({},n||{}),r=i.encode||I_;if(!Jo.test(e))throw new TypeError("argument name is invalid");let o=r(t);if(o&&!Jo.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(!Jo.test(i.domain))throw new TypeError("option domain is invalid");a+="; Domain="+i.domain}if(i.path){if(!Jo.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 C_(e){return e.indexOf("%")!==-1?decodeURIComponent(e):e}function I_(e){return encodeURIComponent(e)}var S_=typeof navigator<"u"&&navigator.product==="ReactNative"||typeof global<"u"&&global.HermesInternal,Fv;function Ir(e){if(e)try{let t=decodeURIComponent(Fv(e.split(".")[1]).split("").map((function(n){return"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(t)||{}}catch{}return{}}function Ov(e,t=0){let n=Ir(e);return!(Object.keys(n).length>0&&(!n.exp||n.exp-t>Date.now()/1e3))}Fv=typeof atob!="function"||S_?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 Cv="pb_auth",_n=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!Ov(this.token)}get isSuperuser(){let t=Ir(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"),Ir(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=Cv){let i=k_(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=Cv){let i={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},r=Ir(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=kv(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=kv(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)}},wp=class extends _n{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)}))}},Ve=class{constructor(t){this.client=t}},kp=class extends Ve{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)}},E_=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function Up(e){if(e){e.query=e.query||{};for(let t in e)E_.includes(t)||(e.query[t]=e[t],delete e[t])}}function Np(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=F_(o),o!==null&&t.push(i+"="+o)}return t.join("&")}function F_(e){return e==null?null:e instanceof Date?encodeURIComponent(e.toISOString().replace("T"," ")):encodeURIComponent(typeof e=="object"?JSON.stringify(e):e)}var Ko=class extends Ve{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){Up(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 _e(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=[]}}},Ho=class extends Ve{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 _e({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 _e({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 xt(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 xp(e){e._resetAutoRefresh?.()}var Cp=class extends Ho{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||xp(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){xp(s);let d=s.beforeSend,p=s.authStore.record,m=s.authStore.onChange(((b,w)=>{(!b||w?.id!=p?.id||(w?.collectionId||p?.collectionId)&&w?.collectionId!=p?.collectionId)&&xp(s)}));s._resetAutoRefresh=function(){m(),s.beforeSend=d,delete s._resetAutoRefresh},s.beforeSend=async(b,w)=>{let z=s.authStore.token;if(w.query?.autoRefresh)return d?d(b,w):{url:b,sendOptions:w};let U=s.authStore.isValid;if(U&&Ov(s.authStore.token,u))try{await c()}catch{U=!1}U||await l();let ne=w.headers||{};for(let P in ne)if(P.toLowerCase()=="authorization"&&z==ne[P]&&s.authStore.token){ne[P]=s.authStore.token;break}return w.headers=ne,d?d(b,w):{url:b,sendOptions:w}}})(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=xt("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=Iv(void 0));let r=new Ko(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 _e(new Error(`Missing or invalid provider "${n.provider}".`));let l=this.client.buildURL("/api/oauth2-redirect");return new Promise((async(d,p)=>{let m=s?this.client.cancelControllers?.[s]:void 0;m&&(m.signal.onabort=()=>{o(),p(new _e({isAbort:!0,message:"manually cancelled"}))}),r.onDisconnect=b=>{b.length&&p&&(o(),p(new _e(new Error("realtime connection interrupted"))))};try{await r.subscribe("@oauth2",(async U=>{let ne=r.clientId;try{if(!U.state||ne!==U.state)throw new Error("State parameters don't match.");if(U.error||!U.code)throw new Error("OAuth2 redirect error or missing code: "+U.error);let P=Object.assign({},n);delete P.provider,delete P.scopes,delete P.createData,delete P.urlCallback,m?.signal?.onabort&&(m.signal.onabort=null);let J=await this.authWithOAuth2Code(c.name,U.code,c.codeVerifier,l,n.createData,P);d(J)}catch(P){p(new _e(P))}o()}));let b={state:r.clientId};n.scopes?.length&&(b.scope=n.scopes.join(" "));let w=this._replaceQueryParams(c.authURL+l,b);await(n.urlCallback||function(U){i?i.location.href=U:i=Iv(U)})(w)}catch(b){m?.signal?.onabort&&(m.signal.onabort=null),o(),p(new _e(b))}}))})).catch((u=>{throw o(),u}))}async authRefresh(t,n){let i={method:"POST"};return i=xt("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=xt("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=xt("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=xt("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=xt("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=Ir(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=xt("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=xt("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=Ir(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 xn(this.client.baseURL,new _n,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 Iv(e){if(typeof window>"u"||!window?.open)throw new _e(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 Ip=class extends Ho{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))}},Sp=class extends Ve{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 _e({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)}},Ep=class extends Ve{async check(t){return t=Object.assign({method:"GET"},t),this.client.send("/api/health",t)}},Fp=class extends Ve{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=Np(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||""))}},Op=class extends Ve{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)}`)}},zp=class extends Ve{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 Pp(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 Ap(e){return e&&(e.constructor?.name==="FormData"||typeof FormData<"u"&&e instanceof FormData)}function Sv(e){for(let t in e){let n=Array.isArray(e[t])?e[t]:[e[t]];for(let i of n)if(Pp(i))return!0}return!1}var O_=/^[\-\.\d]+$/;function Ev(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")&&O_.test(e)){let t=+e;if(""+t===e)return t}return e}var Tp=class extends Ve{constructor(){super(...arguments),this.requests=[],this.subs={}}collection(t){return this.subs[t]||(this.subs[t]=new jp(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)}},jp=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(Up(n),t.headers=n.headers,t.json={},t.files={},n.query!==void 0){let r=Np(n.query);r&&(t.url+=(t.url.includes("?")?"&":"?")+r)}let i=n.body;Ap(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(Ev(s))):a[u]=Ev(s)})),a})(i));for(let r in i){let o=i[r];if(Pp(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)Pp(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}}},xn=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 _n:this.authStore=new wp,this.collections=new Ip(this),this.files=new Fp(this),this.logs=new Sp(this),this.settings=new kp(this),this.realtime=new Ko(this),this.health=new Ep(this),this.backups=new Op(this),this.crons=new zp(this)}get admins(){return this.collection("_superusers")}createBatch(){return new Tp(this)}collection(t){return this.recordServices[t]||(this.recordServices[t]=new Cp(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=Np(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 _e({url:r.url,status:r.status,data:o});return o})).catch((r=>{throw new _e(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||Ap(r)||!Sv(r))return r;let o=new FormData;for(let a in r){let s=r[a];if(s!==void 0)if(typeof s!="object"||Sv({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),Up(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||Ap(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 zv(e){let t=new xn(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 Z(e){return e instanceof Error?e.message:String(e)}async function C(e,t){let n=bt(e);try{let i=await t();return ot(n),i}catch(i){ot(n),$("%s",Z(i))}}function _(e){Fe()?Dv(e.json()):e.human()}function z_(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 Pv(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 Yo=class{baseUrl;headers;constructor(t){this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.headers=z_(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 Pv(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 Pv(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 Rp="";function Av(e){Rp=e}function ve(){return Rp}function P_(e,t){let n=`${t}-pb`,i=e.services[n];return i||$('no PB URL for "%s" (expected services["%s"] in profile)',t,n),i}async function Zp(){let e=ae(Rp),{cfg:t,profile:n}=le(e),i=await bg(t,e,n);return{cfg:t,profile:n,token:i}}async function j(e){let{cfg:t,profile:n,token:i}=await Zp(),r=zv({baseUrl:P_(n,e),token:i,tenantId:$t(n),accountId:_t(n)});return{cfg:t,profile:n,client:r}}async function xe(e){let{profile:t,token:n}=await Zp(),i=t.services[e];return i||$("no %s API URL configured (run `zenku profile show` to check)",e),new Yo({baseUrl:i,token:n,tenantId:$t(t),accountId:_t(t)})}async function wt(){let{cfg:e,profile:t,token:n}=await Zp(),i=t.services.agent;return i||$("no agent API URL configured (run `zenku profile show` to check)"),{client:_p({baseUrl:i,auth:{type:"jwt",getToken:()=>n,tenantId:$t(t),accountId:_t(t)}}),profile:t,cfg:e}}function at(e){return e==null?"":String(e)}function st(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function we(e){if(e==="-")try{return(0,Bp.readFileSync)(0,"utf-8")}catch{$("failed to read from stdin")}if(e.startsWith("@")){let t=e.slice(1);try{return(0,Bp.readFileSync)(t,"utf-8")}catch(n){$("failed to read file %s: %s",t,Z(n))}}return e}async function Tv(e,t,n){let i=await yv("Password",{flagHint:"--email with password prompt"});if(i===null)return null;if(!i)throw new Error("password is required");let r=bt("Authenticating...");try{return await mg(e,t,n,i)}finally{ot(r)}}async function jv(e,t,n){let i=bt("Requesting OTP..."),r="";try{r=await hg(e,t,n)}finally{ot(i)}process.stdout.write(`OTP sent to ${n}
|
|
127
|
+
`)}}function bt(e){return kr||!se()?null:vp(e).start()}function ot(e){e&&e.stop()}async function $e(e,t){se()||$("%s is required (use %s)",e,t?.flagHint??"the appropriate flag");let n=await Rg({message:e,placeholder:t?.placeholder});return Tt(n)?(Q("cancelled"),null):n}async function yv(e,t){se()||$("%s is required (use %s)",e,t?.flagHint??"the appropriate flag");let n=await Zg({message:e});return Tt(n)?(Q("cancelled"),null):n}async function Bt(e,t,n){se()||$("%s is required (use %s)",e,n?.flagHint??"the appropriate flag");let i=await Mg({message:e,options:t});return Tt(i)?(Q("cancelled"),null):i}async function Dp(e,t){se()||$("%s requires confirmation (use %s)",e,t?.flagHint??"the appropriate flag");let n=await Lg({message:e});return Tt(n)?(Q("cancelled"),null):n}var yp="",bp="";function bv(e){yp=e}function $v(e){bp=e}function $t(e){return yp||(process.env.ZENKU_TENANT_ID?process.env.ZENKU_TENANT_ID:e.tenantId)}function _t(e){return bp||(process.env.ZENKU_ACCOUNT_ID?process.env.ZENKU_ACCOUNT_ID:e.accountId)}async function Go(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(!se())return"";let a=o.items.map(u=>({value:u.account,label:u.expand?.account?.name??u.account}));return await Bt("Choose account",a,{flagHint:"`zenku context set --account <id>`"})??""}catch{return""}}var Bp=require("node:fs");var _v=E.object({accountId:E.string().min(1,"accountId is required"),params:E.record(E.string(),E.unknown()),conversationId:E.string().optional(),metadata:E.record(E.string(),E.unknown()).optional()}),$_=_v.extend({callbackUrl:E.url().optional(),callbackSecret:E.string().optional()});var __=E.object({params:E.record(E.string(),E.unknown()),conversationId:E.string().optional(),callbackUrl:E.url().optional(),callbackSecret:E.string().optional(),metadata:E.record(E.string(),E.unknown()).optional()});var Cr=class xv 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=x_(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 xv(n,i,{status:t.status,data:r})}};function x_(e){return e===400?"BAD_REQUEST":e===401?"UNAUTHORIZED":e===403?"FORBIDDEN":e===404?"NOT_FOUND":e>=500?"SERVER_ERROR":"UNKNOWN"}function $p(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",approvalId:t.approvalId,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*Wo(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
|
+
`);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 m=w_({event:o,data:d,id:a});m&&(yield m),o="",a=void 0}else l.trim()===""&&(o="",a=void 0)}}finally{n.releaseLock()}}function w_(e){if(e.event==="keepalive")return{type:"keepalive"};if(!e.data)return null;try{let t=JSON.parse(e.data);return $p(e.event,t)}catch{return null}}var wv=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 Cr("NO_RESPONSE_BODY","No response body for SSE stream",{status:n.status});yield*Wo(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 Cr("NO_RESPONSE_BODY","No response body for SSE subscription",{status:r.status});yield*Wo(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 Cr("NETWORK_ERROR",a instanceof Error?a.message:"Network request failed")}if(!o.ok)throw await Cr.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 _p(e){return new wv(e)}var _e=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}}},Jo=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function k_(e,t){let n={};if(typeof e!="string")return n;let i=Object.assign({},t||{}).decode||C_,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 kv(e,t,n){let i=Object.assign({},n||{}),r=i.encode||I_;if(!Jo.test(e))throw new TypeError("argument name is invalid");let o=r(t);if(o&&!Jo.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(!Jo.test(i.domain))throw new TypeError("option domain is invalid");a+="; Domain="+i.domain}if(i.path){if(!Jo.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 C_(e){return e.indexOf("%")!==-1?decodeURIComponent(e):e}function I_(e){return encodeURIComponent(e)}var S_=typeof navigator<"u"&&navigator.product==="ReactNative"||typeof global<"u"&&global.HermesInternal,Fv;function Ir(e){if(e)try{let t=decodeURIComponent(Fv(e.split(".")[1]).split("").map((function(n){return"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(t)||{}}catch{}return{}}function Ov(e,t=0){let n=Ir(e);return!(Object.keys(n).length>0&&(!n.exp||n.exp-t>Date.now()/1e3))}Fv=typeof atob!="function"||S_?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 Cv="pb_auth",_n=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!Ov(this.token)}get isSuperuser(){let t=Ir(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"),Ir(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=Cv){let i=k_(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=Cv){let i={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},r=Ir(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=kv(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=kv(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)}},wp=class extends _n{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)}))}},Ve=class{constructor(t){this.client=t}},kp=class extends Ve{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)}},E_=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function Up(e){if(e){e.query=e.query||{};for(let t in e)E_.includes(t)||(e.query[t]=e[t],delete e[t])}}function Np(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=F_(o),o!==null&&t.push(i+"="+o)}return t.join("&")}function F_(e){return e==null?null:e instanceof Date?encodeURIComponent(e.toISOString().replace("T"," ")):encodeURIComponent(typeof e=="object"?JSON.stringify(e):e)}var Ko=class extends Ve{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){Up(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 _e(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=[]}}},Ho=class extends Ve{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 _e({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 _e({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 xt(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 xp(e){e._resetAutoRefresh?.()}var Cp=class extends Ho{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||xp(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){xp(s);let d=s.beforeSend,p=s.authStore.record,m=s.authStore.onChange(((b,w)=>{(!b||w?.id!=p?.id||(w?.collectionId||p?.collectionId)&&w?.collectionId!=p?.collectionId)&&xp(s)}));s._resetAutoRefresh=function(){m(),s.beforeSend=d,delete s._resetAutoRefresh},s.beforeSend=async(b,w)=>{let z=s.authStore.token;if(w.query?.autoRefresh)return d?d(b,w):{url:b,sendOptions:w};let U=s.authStore.isValid;if(U&&Ov(s.authStore.token,u))try{await c()}catch{U=!1}U||await l();let ne=w.headers||{};for(let P in ne)if(P.toLowerCase()=="authorization"&&z==ne[P]&&s.authStore.token){ne[P]=s.authStore.token;break}return w.headers=ne,d?d(b,w):{url:b,sendOptions:w}}})(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=xt("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=Iv(void 0));let r=new Ko(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 _e(new Error(`Missing or invalid provider "${n.provider}".`));let l=this.client.buildURL("/api/oauth2-redirect");return new Promise((async(d,p)=>{let m=s?this.client.cancelControllers?.[s]:void 0;m&&(m.signal.onabort=()=>{o(),p(new _e({isAbort:!0,message:"manually cancelled"}))}),r.onDisconnect=b=>{b.length&&p&&(o(),p(new _e(new Error("realtime connection interrupted"))))};try{await r.subscribe("@oauth2",(async U=>{let ne=r.clientId;try{if(!U.state||ne!==U.state)throw new Error("State parameters don't match.");if(U.error||!U.code)throw new Error("OAuth2 redirect error or missing code: "+U.error);let P=Object.assign({},n);delete P.provider,delete P.scopes,delete P.createData,delete P.urlCallback,m?.signal?.onabort&&(m.signal.onabort=null);let J=await this.authWithOAuth2Code(c.name,U.code,c.codeVerifier,l,n.createData,P);d(J)}catch(P){p(new _e(P))}o()}));let b={state:r.clientId};n.scopes?.length&&(b.scope=n.scopes.join(" "));let w=this._replaceQueryParams(c.authURL+l,b);await(n.urlCallback||function(U){i?i.location.href=U:i=Iv(U)})(w)}catch(b){m?.signal?.onabort&&(m.signal.onabort=null),o(),p(new _e(b))}}))})).catch((u=>{throw o(),u}))}async authRefresh(t,n){let i={method:"POST"};return i=xt("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=xt("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=xt("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=xt("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=xt("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=Ir(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=xt("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=xt("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=Ir(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 xn(this.client.baseURL,new _n,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 Iv(e){if(typeof window>"u"||!window?.open)throw new _e(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 Ip=class extends Ho{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))}},Sp=class extends Ve{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 _e({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)}},Ep=class extends Ve{async check(t){return t=Object.assign({method:"GET"},t),this.client.send("/api/health",t)}},Fp=class extends Ve{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=Np(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||""))}},Op=class extends Ve{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)}`)}},zp=class extends Ve{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 Pp(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 Ap(e){return e&&(e.constructor?.name==="FormData"||typeof FormData<"u"&&e instanceof FormData)}function Sv(e){for(let t in e){let n=Array.isArray(e[t])?e[t]:[e[t]];for(let i of n)if(Pp(i))return!0}return!1}var O_=/^[\-\.\d]+$/;function Ev(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")&&O_.test(e)){let t=+e;if(""+t===e)return t}return e}var Tp=class extends Ve{constructor(){super(...arguments),this.requests=[],this.subs={}}collection(t){return this.subs[t]||(this.subs[t]=new jp(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)}},jp=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(Up(n),t.headers=n.headers,t.json={},t.files={},n.query!==void 0){let r=Np(n.query);r&&(t.url+=(t.url.includes("?")?"&":"?")+r)}let i=n.body;Ap(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(Ev(s))):a[u]=Ev(s)})),a})(i));for(let r in i){let o=i[r];if(Pp(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)Pp(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}}},xn=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 _n:this.authStore=new wp,this.collections=new Ip(this),this.files=new Fp(this),this.logs=new Sp(this),this.settings=new kp(this),this.realtime=new Ko(this),this.health=new Ep(this),this.backups=new Op(this),this.crons=new zp(this)}get admins(){return this.collection("_superusers")}createBatch(){return new Tp(this)}collection(t){return this.recordServices[t]||(this.recordServices[t]=new Cp(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=Np(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 _e({url:r.url,status:r.status,data:o});return o})).catch((r=>{throw new _e(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||Ap(r)||!Sv(r))return r;let o=new FormData;for(let a in r){let s=r[a];if(s!==void 0)if(typeof s!="object"||Sv({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),Up(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||Ap(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 zv(e){let t=new xn(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 Z(e){return e instanceof Error?e.message:String(e)}async function C(e,t){let n=bt(e);try{let i=await t();return ot(n),i}catch(i){ot(n),$("%s",Z(i))}}function _(e){Fe()?Dv(e.json()):e.human()}function z_(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 Pv(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 Yo=class{baseUrl;headers;constructor(t){this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.headers=z_(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 Pv(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 Pv(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 Rp="";function Av(e){Rp=e}function ve(){return Rp}function P_(e,t){let n=`${t}-pb`,i=e.services[n];return i||$('no PB URL for "%s" (expected services["%s"] in profile)',t,n),i}async function Zp(){let e=ae(Rp),{cfg:t,profile:n}=le(e),i=await bg(t,e,n);return{cfg:t,profile:n,token:i}}async function j(e){let{cfg:t,profile:n,token:i}=await Zp(),r=zv({baseUrl:P_(n,e),token:i,tenantId:$t(n),accountId:_t(n)});return{cfg:t,profile:n,client:r}}async function xe(e){let{profile:t,token:n}=await Zp(),i=t.services[e];return i||$("no %s API URL configured (run `zenku profile show` to check)",e),new Yo({baseUrl:i,token:n,tenantId:$t(t),accountId:_t(t)})}async function wt(){let{cfg:e,profile:t,token:n}=await Zp(),i=t.services.agent;return i||$("no agent API URL configured (run `zenku profile show` to check)"),{client:_p({baseUrl:i,auth:{type:"jwt",getToken:()=>n,tenantId:$t(t),accountId:_t(t)}}),profile:t,cfg:e}}function at(e){return e==null?"":String(e)}function st(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function we(e){if(e==="-")try{return(0,Bp.readFileSync)(0,"utf-8")}catch{$("failed to read from stdin")}if(e.startsWith("@")){let t=e.slice(1);try{return(0,Bp.readFileSync)(t,"utf-8")}catch(n){$("failed to read file %s: %s",t,Z(n))}}return e}async function Tv(e,t,n){let i=await yv("Password",{flagHint:"--email with password prompt"});if(i===null)return null;if(!i)throw new Error("password is required");let r=bt("Authenticating...");try{return await mg(e,t,n,i)}finally{ot(r)}}async function jv(e,t,n){let i=bt("Requesting OTP..."),r="";try{r=await hg(e,t,n)}finally{ot(i)}process.stdout.write(`OTP sent to ${n}
|
|
129
129
|
`);let o=await $e("Enter OTP code",{flagHint:"--otp <email>"});if(o===null)return null;if(!o)throw new Error("OTP code is required");let a=bt("Verifying OTP...");try{return await gg(e,t,r,o)}finally{ot(a)}}async function Uv(e,t,n){let i=bt("Fetching auth methods..."),r;try{r=await zd(e,t)}finally{ot(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 Bt("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 vg(e,t,o)}async function A_(e,t){let n=[],i=bt("Fetching auth methods...");try{let a=await zd(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{ot(i)}if(n.length===0)throw new Error("no auth methods available");if(n.length>1){let a=await Bt("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 Uv(e,t,"");let o=await $e("Email",{flagHint:"--email <email>"});if(o===null)return null;if(r.kind==="password")return Tv(e,t,o);if(r.kind==="otp")return jv(e,t,o);throw new Error("unknown auth method")}function Nv(e){let t=new T("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=ae(ve()),r,o;try{({cfg:r,profile:o}=le(i))}catch(a){$("%s",Z(a))}try{let a;if(n.email?a=await Tv(Le(o),o.collection,n.email):n.otp?a=await jv(Le(o),o.collection,n.otp):n.oauth?a=await Uv(Le(o),o.collection,n.provider??""):a=await A_(Le(o),o.collection),!a)return;if(o.token=a.token,o.userId=a.userId,o.email=a.email,ge(r,i,o),!o.accountId&&se()){let s=Le(o),u=await Go(s,a.token,a.userId);u&&(o.accountId=u,ge(r,i,o))}_({json:()=>({email:a.email,userId:a.userId}),human:()=>O("Logged in as %s",a.email)})}catch(a){$("%s",Z(a))}});e.addCommand(t)}function Bv(e){let t=new T("logout").description("Clear authentication token").action(()=>{let n=ae(ve());try{let{cfg:i,profile:r}=le(n);r.token="",r.userId="",r.email="",ge(i,n,r),O('Logged out from profile "%s"',n)}catch(i){$("%s",Z(i))}});e.addCommand(t)}function Rv(e){let t=new T("whoami").description("Show current user and profile").action(()=>{let n=ae(ve()),i,r;try{({cfg:i,profile:r}=le(n))}catch(l){$("%s",Z(l))}r.token||$("not logged in (run `zenku login`)");let o;try{o=yg(r.token)}catch(l){$("%s",`invalid token: ${Z(l)}`)}let a=i.defaultProfile===n,s=o.getTime()-Date.now(),u=$t(r),c=_t(r);_({json:()=>({profile:n,default:a,email:r.email,userId:r.userId,authPb:Le(r),tenantId:u||null,accountId:c||null,expiresAt:o.toISOString(),expiresIn:Pd(Math.max(s,0))}),human:()=>{let l=a?" (default)":"";process.stdout.write(`Profile: ${n}${l}
|
|
130
130
|
`),process.stdout.write(`Email: ${r.email}
|
|
131
131
|
`),process.stdout.write(`User ID: ${r.userId}
|
|
@@ -236,4 +236,4 @@ ${r.result.output}
|
|
|
236
236
|
`),process.stdout.write(`
|
|
237
237
|
Contents:
|
|
238
238
|
`);for(let o of i)process.stdout.write(` ${o}
|
|
239
|
-
`)}})}),e.command("install").description("Install a skill, agent, or persona into the current project").argument("<name>","skill, agent, or persona name").option("--force","overwrite existing installation").option("--global","install to home directory (~/) instead of project root").option(...sa).action(async(t,n)=>{let i=ia(n.target),{item:r,zipBytes:o,version:a}=await C("Fetching kit catalog...",async()=>{let c=await On(),l=ra(c,t);l||$('"%s" not found in agent-kit (run `zenku agent-kit list` to see available items)',t);let d=await na(l.name,l.type);return{item:l,zipBytes:d,version:c.version}}),s=oa(n.global),u=i.map(c=>aa(s,r.name,r.type,c));if(!n.force){let c=u.filter(l=>(0,W.existsSync)(l));c.length>0&&$('"%s" is already installed at %s (use --force to overwrite)',t,c.join(", "))}for(let c of u)r.type==="skill"?((0,W.existsSync)(c)&&(0,W.rmSync)(c,{recursive:!0}),dD(o,c)):pD(o,c);_({json:()=>({installed:r.name,type:r.type,version:a,targets:i,paths:u}),human:()=>{for(let c of u)O("Installed %s (%s) -> %s",r.name,r.type,c)}})}),e.command("uninstall").description("Remove an installed skill, agent, or persona").argument("<name>","skill, agent, or persona name").option("--global","uninstall from home directory (~/) instead of project root").option(...sa).action(async(t,n)=>{try{let i=ia(n.target),r=oa(n.global),o=[];for(let a of i){let s=aa(r,t,"skill",a),u=aa(r,t,"agent",a),c=(0,W.existsSync)((0,ue.join)(s,"SKILL.md")),l=(0,W.existsSync)(u);c&&((0,W.rmSync)(s,{recursive:!0}),o.push({target:a,type:"skill"})),l&&((0,W.rmSync)(u),o.push({target:a,type:"agent"}))}o.length===0&&$('"%s" is not installed (run `zenku agent-kit installed` to see installed items)',t),_({json:()=>({uninstalled:t,type:o[0].type,targets:[...new Set(o.map(a=>a.target))]}),human:()=>O("Uninstalled %s",t)})}catch(i){$("%s",Z(i))}}),e.command("installed").description("List installed skills and agents").option("--skills","show skills only").option("--agents","show agents only").option("--global","list installed items in home directory (~/) instead of project root").option(...sa).action(async t=>{try{let n=ia(t.target),i=oa(t.global),r=lD(i,n);if(t.skills&&(r=r.filter(o=>o.type==="skill")),t.agents&&(r=r.filter(o=>o.type==="agent")),r.length===0){_({json:()=>({items:[]}),human:()=>Q("No skills or agents installed.")});return}_({json:()=>({items:r}),human:()=>{ee(["NAME","TYPE","TARGETS"],r.map(o=>[o.name,o.type,o.targets.join(", ")]))}})}catch(n){$("%s",Z(n))}}),e.command("update").description("Update installed items to the latest kit version").argument("[name]","skill, agent, or persona name (omit with --all)").option("--all","update all installed items").option("--global","update items in home directory (~/) instead of project root").option(...sa).action(async(t,n)=>{!t&&!n.all&&$("provide <name> or use --all"),t&&n.all&&$("use either <name> or --all, not both");let i=ia(n.target),r=oa(n.global),o=await C("Checking for updates...",()=>On()),a;if(n.all){a=new Map;let u=lD(r,i),c=new Set(o.items.map(l=>l.name));for(let l of u)c.has(l.name)&&a.set(l.name,l.targets)}else a=new Map([[t,i]]);if(a.size===0){Q("No kit items installed to update.");return}let s=[];for(let[u,c]of a){let l=ra(o,u);if(!l){s.push({name:u,action:"not-found"});continue}let d=await C(`Updating ${u}...`,()=>na(l.name,l.type));for(let p of c){let m=aa(r,u,l.type,p);l.type==="skill"?((0,W.existsSync)(m)&&(0,W.rmSync)(m,{recursive:!0}),dD(d,m)):pD(d,m)}s.push({name:u,action:"updated",targets:c})}_({json:()=>({version:o.version,results:s}),human:()=>{for(let u of s)u.action==="updated"?O("%s: updated to v%s",u.name,o.version):Q("%s: not found in agent-kit (may have been removed)",u.name)}})}),e}function mD(e){e.addCommand(kx())}var ua=require("node:child_process"),de=require("node:fs"),gD=require("node:os"),kt=require("node:path");function hD(){return!0}var vD="https://registry.npmjs.org",Cx=15e3,DD="@zenku";function Ix(){let{platform:e,arch:t}=process,n=["darwin-arm64","darwin-x64","linux-arm64","linux-x64"],i=`${e}-${t}`;return n.includes(i)||$("Unsupported platform: %s",i),`cli-${i}`}async function Sx(e){let t=`${vD}/${DD}/${e}/latest`,n=new AbortController,i=setTimeout(()=>n.abort(),Cx);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 Ex(e,t){let n=`${e}-${t}.tgz`,i=`${vD}/${DD}/${e}/-/${n}`,r=(0,de.mkdtempSync)((0,kt.join)((0,gD.tmpdir)(),"zenku-upgrade-"));try{(0,ua.execSync)(`curl -fsSL "${i}" -o "${(0,kt.join)(r,n)}"`,{stdio:"pipe"}),(0,ua.execSync)(`tar xzf "${(0,kt.join)(r,n)}" -C "${r}"`,{stdio:"pipe"});let o=(0,kt.join)(r,"package","zenku"),a=process.execPath,s=(0,kt.dirname)(a),u=(0,kt.join)(s,`.zenku-upgrade-${process.pid}`),c=!1;try{(0,de.accessSync)(s,de.constants.W_OK)}catch{c=!0}if(c)(0,ua.execSync)(`sudo install -m 755 "${o}" "${a}"`,{stdio:"inherit"});else{(0,de.copyFileSync)(o,u),(0,de.chmodSync)(u,493);try{(0,de.renameSync)(u,a)}catch{try{(0,de.unlinkSync)(u)}catch{}throw new Error(`failed to replace binary at ${a}`)}}}finally{(0,de.rmSync)(r,{recursive:!0,force:!0})}}function yD(e){e.addCommand(new T("upgrade").description("Upgrade zenku to the latest version").action(async()=>{if(hD()){_({json:()=>({mode:"bundle",message:"Self-upgrade not available in bundle mode. Use: npm update -g @zenku/cli-node"}),human:()=>{Q("Self-upgrade is not available in bundle mode."),Q("Update via npm: npm update -g @zenku/cli-node")}});return}let t=Xp(),n=Ix(),i=await C("Checking for updates...",()=>Sx(n));if(t===i){_({json:()=>({previous:t,latest:i,upgraded:!1}),human:()=>Q("Already up to date (v%s).",t)});return}Q("v%s \u2192 v%s",t,i),await C(`Downloading v${i}...`,async()=>{Ex(n,i)}),_({json:()=>({previous:t,latest:i,upgraded:!0}),human:()=>Q("Upgraded zenku to v%s.",i)})}))}var Fx={};function Xp(){return"0.1.
|
|
239
|
+
`)}})}),e.command("install").description("Install a skill, agent, or persona into the current project").argument("<name>","skill, agent, or persona name").option("--force","overwrite existing installation").option("--global","install to home directory (~/) instead of project root").option(...sa).action(async(t,n)=>{let i=ia(n.target),{item:r,zipBytes:o,version:a}=await C("Fetching kit catalog...",async()=>{let c=await On(),l=ra(c,t);l||$('"%s" not found in agent-kit (run `zenku agent-kit list` to see available items)',t);let d=await na(l.name,l.type);return{item:l,zipBytes:d,version:c.version}}),s=oa(n.global),u=i.map(c=>aa(s,r.name,r.type,c));if(!n.force){let c=u.filter(l=>(0,W.existsSync)(l));c.length>0&&$('"%s" is already installed at %s (use --force to overwrite)',t,c.join(", "))}for(let c of u)r.type==="skill"?((0,W.existsSync)(c)&&(0,W.rmSync)(c,{recursive:!0}),dD(o,c)):pD(o,c);_({json:()=>({installed:r.name,type:r.type,version:a,targets:i,paths:u}),human:()=>{for(let c of u)O("Installed %s (%s) -> %s",r.name,r.type,c)}})}),e.command("uninstall").description("Remove an installed skill, agent, or persona").argument("<name>","skill, agent, or persona name").option("--global","uninstall from home directory (~/) instead of project root").option(...sa).action(async(t,n)=>{try{let i=ia(n.target),r=oa(n.global),o=[];for(let a of i){let s=aa(r,t,"skill",a),u=aa(r,t,"agent",a),c=(0,W.existsSync)((0,ue.join)(s,"SKILL.md")),l=(0,W.existsSync)(u);c&&((0,W.rmSync)(s,{recursive:!0}),o.push({target:a,type:"skill"})),l&&((0,W.rmSync)(u),o.push({target:a,type:"agent"}))}o.length===0&&$('"%s" is not installed (run `zenku agent-kit installed` to see installed items)',t),_({json:()=>({uninstalled:t,type:o[0].type,targets:[...new Set(o.map(a=>a.target))]}),human:()=>O("Uninstalled %s",t)})}catch(i){$("%s",Z(i))}}),e.command("installed").description("List installed skills and agents").option("--skills","show skills only").option("--agents","show agents only").option("--global","list installed items in home directory (~/) instead of project root").option(...sa).action(async t=>{try{let n=ia(t.target),i=oa(t.global),r=lD(i,n);if(t.skills&&(r=r.filter(o=>o.type==="skill")),t.agents&&(r=r.filter(o=>o.type==="agent")),r.length===0){_({json:()=>({items:[]}),human:()=>Q("No skills or agents installed.")});return}_({json:()=>({items:r}),human:()=>{ee(["NAME","TYPE","TARGETS"],r.map(o=>[o.name,o.type,o.targets.join(", ")]))}})}catch(n){$("%s",Z(n))}}),e.command("update").description("Update installed items to the latest kit version").argument("[name]","skill, agent, or persona name (omit with --all)").option("--all","update all installed items").option("--global","update items in home directory (~/) instead of project root").option(...sa).action(async(t,n)=>{!t&&!n.all&&$("provide <name> or use --all"),t&&n.all&&$("use either <name> or --all, not both");let i=ia(n.target),r=oa(n.global),o=await C("Checking for updates...",()=>On()),a;if(n.all){a=new Map;let u=lD(r,i),c=new Set(o.items.map(l=>l.name));for(let l of u)c.has(l.name)&&a.set(l.name,l.targets)}else a=new Map([[t,i]]);if(a.size===0){Q("No kit items installed to update.");return}let s=[];for(let[u,c]of a){let l=ra(o,u);if(!l){s.push({name:u,action:"not-found"});continue}let d=await C(`Updating ${u}...`,()=>na(l.name,l.type));for(let p of c){let m=aa(r,u,l.type,p);l.type==="skill"?((0,W.existsSync)(m)&&(0,W.rmSync)(m,{recursive:!0}),dD(d,m)):pD(d,m)}s.push({name:u,action:"updated",targets:c})}_({json:()=>({version:o.version,results:s}),human:()=>{for(let u of s)u.action==="updated"?O("%s: updated to v%s",u.name,o.version):Q("%s: not found in agent-kit (may have been removed)",u.name)}})}),e}function mD(e){e.addCommand(kx())}var ua=require("node:child_process"),de=require("node:fs"),gD=require("node:os"),kt=require("node:path");function hD(){return!0}var vD="https://registry.npmjs.org",Cx=15e3,DD="@zenku";function Ix(){let{platform:e,arch:t}=process,n=["darwin-arm64","darwin-x64","linux-arm64","linux-x64"],i=`${e}-${t}`;return n.includes(i)||$("Unsupported platform: %s",i),`cli-${i}`}async function Sx(e){let t=`${vD}/${DD}/${e}/latest`,n=new AbortController,i=setTimeout(()=>n.abort(),Cx);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 Ex(e,t){let n=`${e}-${t}.tgz`,i=`${vD}/${DD}/${e}/-/${n}`,r=(0,de.mkdtempSync)((0,kt.join)((0,gD.tmpdir)(),"zenku-upgrade-"));try{(0,ua.execSync)(`curl -fsSL "${i}" -o "${(0,kt.join)(r,n)}"`,{stdio:"pipe"}),(0,ua.execSync)(`tar xzf "${(0,kt.join)(r,n)}" -C "${r}"`,{stdio:"pipe"});let o=(0,kt.join)(r,"package","zenku"),a=process.execPath,s=(0,kt.dirname)(a),u=(0,kt.join)(s,`.zenku-upgrade-${process.pid}`),c=!1;try{(0,de.accessSync)(s,de.constants.W_OK)}catch{c=!0}if(c)(0,ua.execSync)(`sudo install -m 755 "${o}" "${a}"`,{stdio:"inherit"});else{(0,de.copyFileSync)(o,u),(0,de.chmodSync)(u,493);try{(0,de.renameSync)(u,a)}catch{try{(0,de.unlinkSync)(u)}catch{}throw new Error(`failed to replace binary at ${a}`)}}}finally{(0,de.rmSync)(r,{recursive:!0,force:!0})}}function yD(e){e.addCommand(new T("upgrade").description("Upgrade zenku to the latest version").action(async()=>{if(hD()){_({json:()=>({mode:"bundle",message:"Self-upgrade not available in bundle mode. Use: npm update -g @zenku/cli-node"}),human:()=>{Q("Self-upgrade is not available in bundle mode."),Q("Update via npm: npm update -g @zenku/cli-node")}});return}let t=Xp(),n=Ix(),i=await C("Checking for updates...",()=>Sx(n));if(t===i){_({json:()=>({previous:t,latest:i,upgraded:!1}),human:()=>Q("Already up to date (v%s).",t)});return}Q("v%s \u2192 v%s",t,i),await C(`Downloading v${i}...`,async()=>{Ex(n,i)}),_({json:()=>({previous:t,latest:i,upgraded:!0}),human:()=>Q("Upgraded zenku to v%s.",i)})}))}var Fx={};function Xp(){return"0.1.20"}function _D(){let e=new T;return e.name("zenku").description("Zenku CLI \u2014 manage PocketBase services from the terminal.").version(Xp()).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();Av(n.profile??""),bv(n.tenant??""),$v(n.account??""),vv(!!n.json),n.interactive&&n.nonInteractive&&$("--interactive and --non-interactive cannot be used together"),n.interactive?Td("interactive"):n.nonInteractive&&Td("non-interactive")}),e.commandsGroup("Core Commands:"),Gv(e),Kv(e),Yv(e),mD(e),e.commandsGroup("Platform Commands:"),Vv(e),qv(e),e.commandsGroup("Auth & Config:"),Nv(e),Bv(e),Rv(e),Lv(e),e.commandsGroup("Other:"),yD(e),e.addHelpCommand(new T("help").argument("[command]")),e}var Ox=_D();Ox.parse();
|