@vcityio/cli 0.2.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +37 -37
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as Cc}from"node:module";var Hc=Cc(import.meta.url);var Uc=/\{[^{}]+\}/g,wc=()=>{return typeof process==="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici};function Lc(){return Math.random().toString(36).slice(2,11)}function _n(n){let{baseUrl:c="",Request:k=globalThis.Request,fetch:D=globalThis.fetch,querySerializer:g,bodySerializer:$,headers:j,requestInitExt:x=void 0,...y}={...n};x=wc()?x:void 0,c=Ln(c);let M=[];async function R(T,Y){let{baseUrl:C,fetch:Nn=D,Request:Qk=k,headers:Bn,params:z={},parseAs:En="json",querySerializer:u,bodySerializer:Cn=$??qc,body:Hn,...Jn}=Y||{},fn=c;if(C)fn=Ln(C)??c;let Gn=typeof g==="function"?g:Un(g);if(u)Gn=typeof u==="function"?u:Un({...typeof g==="object"?g:{},...u});let Tn=Hn===void 0?void 0:Cn(Hn,wn(j,Bn,z.header)),Nc=wn(Tn===void 0||Tn instanceof FormData?{}:{"Content-Type":"application/json"},j,Bn,z.header),Bc={redirect:"follow",...y,...Jn,body:Tn,headers:Nc},t,r,w=new k(Ac(T,{baseUrl:fn,params:z,querySerializer:Gn}),Bc),Z;for(let K in Jn)if(!(K in w))w[K]=Jn[K];if(M.length){t=Lc(),r=Object.freeze({baseUrl:fn,fetch:Nn,parseAs:En,querySerializer:Gn,bodySerializer:Cn});for(let K of M)if(K&&typeof K==="object"&&typeof K.onRequest==="function"){let o=await K.onRequest({request:w,schemaPath:T,params:z,options:r,id:t});if(o)if(o instanceof k)w=o;else if(o instanceof Response){Z=o;break}else throw Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!Z){try{Z=await Nn(w,x)}catch(K){let o=K;if(M.length)for(let q=M.length-1;q>=0;q--){let h=M[q];if(h&&typeof h==="object"&&typeof h.onError==="function"){let I=await h.onError({request:w,error:o,schemaPath:T,params:z,options:r,id:t});if(I){if(I instanceof Response){o=void 0,Z=I;break}if(I instanceof Error){o=I;continue}throw Error("onError: must return new Response() or instance of Error")}}}if(o)throw o}if(M.length)for(let K=M.length-1;K>=0;K--){let o=M[K];if(o&&typeof o==="object"&&typeof o.onResponse==="function"){let q=await o.onResponse({request:w,response:Z,schemaPath:T,params:z,options:r,id:t});if(q){if(!(q instanceof Response))throw Error("onResponse: must return new Response() when modifying the response");Z=q}}}}if(Z.status===204||w.method==="HEAD"||Z.headers.get("Content-Length")==="0")return Z.ok?{data:void 0,response:Z}:{error:void 0,response:Z};if(Z.ok){if(En==="stream")return{data:Z.body,response:Z};return{data:await Z[En](),response:Z}}let Wn=await Z.text();try{Wn=JSON.parse(Wn)}catch{}return{error:Wn,response:Z}}return{request(T,Y,C){return R(Y,{...C,method:T.toUpperCase()})},GET(T,Y){return R(T,{...Y,method:"GET"})},PUT(T,Y){return R(T,{...Y,method:"PUT"})},POST(T,Y){return R(T,{...Y,method:"POST"})},DELETE(T,Y){return R(T,{...Y,method:"DELETE"})},OPTIONS(T,Y){return R(T,{...Y,method:"OPTIONS"})},HEAD(T,Y){return R(T,{...Y,method:"HEAD"})},PATCH(T,Y){return R(T,{...Y,method:"PATCH"})},TRACE(T,Y){return R(T,{...Y,method:"TRACE"})},use(...T){for(let Y of T){if(!Y)continue;if(typeof Y!=="object"||!(("onRequest"in Y)||("onResponse"in Y)||("onError"in Y)))throw Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");M.push(Y)}},eject(...T){for(let Y of T){let C=M.indexOf(Y);if(C!==-1)M.splice(C,1)}}}}function p(n,c,k){if(c===void 0||c===null)return"";if(typeof c==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${n}=${k?.allowReserved===!0?c:encodeURIComponent(c)}`}function Sn(n,c,k){if(!c||typeof c!=="object")return"";let D=[],g={simple:",",label:".",matrix:";"}[k.style]||"&";if(k.style!=="deepObject"&&k.explode===!1){for(let x in c)D.push(x,k.allowReserved===!0?c[x]:encodeURIComponent(c[x]));let j=D.join(",");switch(k.style){case"form":return`${n}=${j}`;case"label":return`.${j}`;case"matrix":return`;${n}=${j}`;default:return j}}for(let j in c){let x=k.style==="deepObject"?`${n}[${j}]`:j;D.push(p(x,c[j],k))}let $=D.join(g);return k.style==="label"||k.style==="matrix"?`${g}${$}`:$}function qn(n,c,k){if(!Array.isArray(c))return"";if(k.explode===!1){let $={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[k.style]||",",j=(k.allowReserved===!0?c:c.map((x)=>encodeURIComponent(x))).join($);switch(k.style){case"simple":return j;case"label":return`.${j}`;case"matrix":return`;${n}=${j}`;default:return`${n}=${j}`}}let D={simple:",",label:".",matrix:";"}[k.style]||"&",g=[];for(let $ of c)if(k.style==="simple"||k.style==="label")g.push(k.allowReserved===!0?$:encodeURIComponent($));else g.push(p(n,$,k));return k.style==="label"||k.style==="matrix"?`${D}${g.join(D)}`:g.join(D)}function Un(n){return function(k){let D=[];if(k&&typeof k==="object")for(let g in k){let $=k[g];if($===void 0||$===null)continue;if(Array.isArray($)){if($.length===0)continue;D.push(qn(g,$,{style:"form",explode:!0,...n?.array,allowReserved:n?.allowReserved||!1}));continue}if(typeof $==="object"){D.push(Sn(g,$,{style:"deepObject",explode:!0,...n?.object,allowReserved:n?.allowReserved||!1}));continue}D.push(p(g,$,n))}return D.join("&")}}function Sc(n,c){let k=n;for(let D of n.match(Uc)??[]){let g=D.substring(1,D.length-1),$=!1,j="simple";if(g.endsWith("*"))$=!0,g=g.substring(0,g.length-1);if(g.startsWith("."))j="label",g=g.substring(1);else if(g.startsWith(";"))j="matrix",g=g.substring(1);if(!c||c[g]===void 0||c[g]===null)continue;let x=c[g];if(Array.isArray(x)){k=k.replace(D,qn(g,x,{style:j,explode:$}));continue}if(typeof x==="object"){k=k.replace(D,Sn(g,x,{style:j,explode:$}));continue}if(j==="matrix"){k=k.replace(D,`;${p(g,x)}`);continue}k=k.replace(D,j==="label"?`.${encodeURIComponent(x)}`:encodeURIComponent(x))}return k}function qc(n,c){if(n instanceof FormData)return n;if(c){if((c.get instanceof Function?c.get("Content-Type")??c.get("content-type"):c["Content-Type"]??c["content-type"])==="application/x-www-form-urlencoded")return new URLSearchParams(n).toString()}return JSON.stringify(n)}function Ac(n,c){let k=`${c.baseUrl}${n}`;if(c.params?.path)k=Sc(k,c.params.path);let D=c.querySerializer(c.params.query??{});if(D.startsWith("?"))D=D.substring(1);if(D)k+=`?${D}`;return k}function wn(...n){let c=new Headers;for(let k of n){if(!k||typeof k!=="object")continue;let D=k instanceof Headers?k.entries():Object.entries(k);for(let[g,$]of D)if($===null)c.delete(g);else if(Array.isArray($))for(let j of $)c.append(g,j);else if($!==void 0)c.set(g,$)}return c}function Ln(n){if(n.endsWith("/"))return n.substring(0,n.length-1);return n}class i extends Error{status;body;url;constructor(n,c,k,D){super(n);this.name="ApiClientError",this.status=c,this.body=k,this.url=D}}function _(n,c){if(n.error!==void 0&&n.error!==null){let k=n.response?.status??0,D=n.response?.url??"",g=typeof n.error==="object"&&n.error!==null&&"error"in n.error&&typeof n.error.error==="object"&&n.error.error?.message||`${c} failed (${k})`;throw new i(String(g),k,n.error,D)}if(n.data===void 0)throw new i(`${c}: empty response body`,n.response?.status??0,void 0,n.response?.url??"");return n.data}class s{client;constructor(n){this.client=n}async get(){let n=await this.client.GET("/api/v1/me",{});return _(n,"me.get")}}class e{client;constructor(n){this.client=n}async get(n){let c=await this.client.GET("/api/v1/orgs/{orgId}",{params:{path:{orgId:n}}});return _(c,"orgs.get")}async listMembers(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/members",{params:{path:{orgId:n},query:c}});return _(k,"orgs.listMembers")}}class l{client;constructor(n){this.client=n}async list(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/products",{params:{path:{orgId:n},query:c}});return _(k,"products.list")}async get(n,c){let k=await this.client.GET("/api/v1/orgs/{orgId}/products/{productId}",{params:{path:{orgId:n,productId:c}}});return _(k,"products.get")}async create(n,c){let k=await this.client.POST("/api/v1/orgs/{orgId}/products",{params:{path:{orgId:n}},body:c});return _(k,"products.create")}async update(n,c,k){let D=await this.client.PUT("/api/v1/orgs/{orgId}/products/{productId}",{params:{path:{orgId:n,productId:c}},body:k});return _(D,"products.update")}async delete(n,c){let k=await this.client.DELETE("/api/v1/orgs/{orgId}/products/{productId}",{params:{path:{orgId:n,productId:c}}});return _(k,"products.delete")}}class a{client;constructor(n){this.client=n}async list(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/events",{params:{path:{orgId:n},query:c}});return _(k,"events.list")}async get(n,c){let k=await this.client.GET("/api/v1/orgs/{orgId}/events/{eventId}",{params:{path:{orgId:n,eventId:c}}});return _(k,"events.get")}async create(n,c){let k=await this.client.POST("/api/v1/orgs/{orgId}/events",{params:{path:{orgId:n}},body:c});return _(k,"events.create")}async update(n,c,k){let D=await this.client.PUT("/api/v1/orgs/{orgId}/events/{eventId}",{params:{path:{orgId:n,eventId:c}},body:k});return _(D,"events.update")}async delete(n,c){let k=await this.client.DELETE("/api/v1/orgs/{orgId}/events/{eventId}",{params:{path:{orgId:n,eventId:c}}});return _(k,"events.delete")}}class nn{client;constructor(n){this.client=n}async list(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/rooms",{params:{path:{orgId:n},query:c}});return _(k,"rooms.list")}async get(n,c){let k=await this.client.GET("/api/v1/orgs/{orgId}/rooms/{roomId}",{params:{path:{orgId:n,roomId:c}}});return _(k,"rooms.get")}async create(n,c){let k=await this.client.POST("/api/v1/orgs/{orgId}/rooms",{params:{path:{orgId:n}},body:c});return _(k,"rooms.create")}async update(n,c,k){let D=await this.client.PUT("/api/v1/orgs/{orgId}/rooms/{roomId}",{params:{path:{orgId:n,roomId:c}},body:k});return _(D,"rooms.update")}async delete(n,c){let k=await this.client.DELETE("/api/v1/orgs/{orgId}/rooms/{roomId}",{params:{path:{orgId:n,roomId:c}}});return _(k,"rooms.delete")}}class cn{client;constructor(n){this.client=n}async list(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/bookings",{params:{path:{orgId:n},query:c}});return _(k,"bookings.list")}async get(n,c){let k=await this.client.GET("/api/v1/orgs/{orgId}/bookings/{bookingId}",{params:{path:{orgId:n,bookingId:c}}});return _(k,"bookings.get")}}class kn{client;constructor(n){this.client=n}async list(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/orders",{params:{path:{orgId:n},query:c}});return _(k,"orders.list")}async get(n,c){let k=await this.client.GET("/api/v1/orgs/{orgId}/orders/{orderId}",{params:{path:{orgId:n,orderId:c}}});return _(k,"orders.get")}}class Dn{client;constructor(n){this.client=n}async list(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/quotes",{params:{path:{orgId:n},query:c}});return _(k,"quotes.list")}async get(n,c){let k=await this.client.GET("/api/v1/orgs/{orgId}/quotes/{quoteId}",{params:{path:{orgId:n,quoteId:c}}});return _(k,"quotes.get")}}var zc="https://vcity.io";function ic(n,c){let k=c??globalThis.fetch;if(!k)throw Error("@vcityio/api-client: no fetch implementation found. Provide options.fetch or run on Node >=20 / a browser.");return async function(g){if(!n)return k(g);if(g.headers.has("Authorization"))return k(g);let $=new Headers(g.headers);$.set("Authorization",`Bearer ${n}`);let j=new Request(g,{headers:$});return k(j)}}class Xn{raw;me;orgs;products;events;rooms;bookings;orders;quotes;constructor(n={}){let c=n.baseUrl??zc,k=ic(n.token,n.fetch),D={baseUrl:c,fetch:k,headers:n.headers};this.raw=_n(D),this.me=new s(this.raw),this.orgs=new e(this.raw),this.products=new l(this.raw),this.events=new a(this.raw),this.rooms=new nn(this.raw),this.bookings=new cn(this.raw),this.orders=new kn(this.raw),this.quotes=new Dn(this.raw)}}function Zn(n={}){return new Xn(n)}import L from"node:fs";import mc from"node:os";import Qn from"node:path";function H(){if(process.env.VCITY_CONFIG_DIR)return process.env.VCITY_CONFIG_DIR;return Qn.join(mc.homedir(),".vcity")}function gn(){return Qn.join(H(),"auth.json")}function Rn(){return Qn.join(H(),"config.json")}function An(){return process.env.VCITY_API_BASE_URL||process.env.VCITY_PUBLIC_URL||"https://vcity.io"}function Oc(){let n=H();if(!L.existsSync(n))L.mkdirSync(n,{recursive:!0,mode:448})}function $n(){let n=gn();if(!L.existsSync(n))return;try{return JSON.parse(L.readFileSync(n,"utf-8"))}catch{return}}function jn(n){Oc();let c=gn();L.writeFileSync(c,JSON.stringify(n,null,2),{mode:384});try{L.chmodSync(c,384)}catch{}}function m(){let n=gn();if(L.existsSync(n))L.rmSync(n)}function xn(){let n=$n();if(!n)throw Error("Not logged in. Run `vcity login` first.");return n}class v extends Error{status;body;constructor(n,c,k){super(k??`HTTP ${n}`);this.status=n;this.body=c;this.name="ApiError"}}function mn(n,c,k){let D=new URL(c.startsWith("/")?c:`/${c}`,n);if(k){for(let[g,$]of Object.entries(k))if($!==void 0&&$!==null&&!Number.isNaN($))D.searchParams.set(g,String($))}return D.toString()}async function zn(n){try{let c=await fetch(mn(n.api_base_url,"/api/cli/auth/refresh"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({refresh_token:n.refresh_token})});if(!c.ok)return;let k=await c.json(),D={...n,access_token:k.access_token,refresh_token:k.refresh_token,access_expires_at:k.access_expires_at,refresh_expires_at:k.refresh_expires_at};return jn(D),D}catch{return}}async function d(n,c={}){let{authed:k=!0,method:D="GET",body:g,query:$,baseUrl:j}=c,x=k?xn():void 0,y=j??x?.api_base_url??"https://vcity.io",M={"content-type":"application/json"};if(x)M.authorization=`Bearer ${x.access_token}`;let R=await fetch(mn(y,n,$),{method:D,headers:M,body:g===void 0?void 0:JSON.stringify(g)}),Y=(R.headers.get("content-type")??"").includes("application/json")?await R.json().catch(()=>{return}):await R.text().catch(()=>{return});if(!R.ok){let C=(Y&&typeof Y==="object"&&"error"in Y?String(Y.error):void 0)??`Request failed (${R.status})`;throw new v(R.status,Y,C)}return Y}function Pc(){let n=async(c,k)=>{let D=new Headers(c.headers);D.set("authorization",`Bearer ${k}`);let g=new Request(c,{headers:D});return globalThis.fetch(g)};return async function(k){let D=xn();if(Date.now()>=D.access_expires_at){if(Date.now()>=D.refresh_expires_at)throw m(),new v(401,void 0,"Session expired. Run `vcity login` again.");let j=await zn(D);if(!j)throw m(),new v(401,void 0,"Session expired. Run `vcity login` again.");D=j}let g=await n(k,D.access_token);if(g.status!==401)return g;let $=await zn(D);if(!$)throw m(),new v(401,void 0,"Session expired. Run `vcity login` again.");return D=$,n(k,D.access_token)}}var yn;function f(){if(yn)return yn;let n=xn();return yn=Zn({baseUrl:n.api_base_url,fetch:Pc()}),yn}function S(n){if(n==null)return"";return new Date(n).toISOString().replace("T"," ").slice(0,16)}import O from"node:fs";function Fc(){let n=H();if(!O.existsSync(n))O.mkdirSync(n,{recursive:!0,mode:448})}function A(){let n=Rn();if(!O.existsSync(n))return{};try{return JSON.parse(O.readFileSync(n,"utf-8"))}catch{return{}}}function On(n){Fc();let k={...A(),...n},D=Rn();O.writeFileSync(D,JSON.stringify(k,null,2),{mode:384});try{O.chmodSync(D,384)}catch{}return k}function W(n){if(n)return n;let c=A();if(!c.active_org)throw Error("No active org. Run `vcity org use <slug>` or pass --org <slug>.");return c.active_org}var bc=/\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[P_^X][^\x07\x1b]*(?:\x07|\x1b\\)|[^[\]P_^X])/g,Ic=/[\x00-\x08\x0b-\x1f\x7f]/g;function N(n){return n.replace(bc,"").replace(Ic,"")}function Pn(n){let c;try{c=new URL(n)}catch{throw Error(`Refusing to open malformed URL: ${N(n).slice(0,100)}`)}if(c.protocol==="https:")return c;if(c.protocol==="http:"&&(c.hostname==="localhost"||c.hostname==="127.0.0.1"))return c;throw Error(`Refusing to open URL with unsafe protocol: ${c.protocol}`)}function E(n){if(n)return"json";if(!process.stdout.isTTY)return"json";return"pretty"}function J(n){process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function V(n,c){process.stdout.write(`${
|
|
5
|
-
`)}function
|
|
6
|
-
`)}}async function Fn(n={}){let c=
|
|
7
|
-
`),
|
|
8
|
-
`),
|
|
9
|
-
`);return}}let
|
|
10
|
-
`)}import{setTimeout as
|
|
2
|
+
import{createRequire as Bc}from"node:module";var Cc=Bc(import.meta.url);var Hc=/\{[^{}]+\}/g,wc=()=>{return typeof process==="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici};function Uc(){return Math.random().toString(36).slice(2,11)}function Rn(n){let{baseUrl:c="",Request:k=globalThis.Request,fetch:o=globalThis.fetch,querySerializer:D,bodySerializer:g,headers:f,requestInitExt:y=void 0,...$}={...n};y=wc()?y:void 0,c=mn(c);let x=[];async function X(J,j){let{baseUrl:B,fetch:Nn=o,Request:_k=k,headers:Bn,params:q={},parseAs:Mn="json",querySerializer:d,bodySerializer:Cn=g??Lc,body:Hn,...En}=j||{},Yn=c;if(B)Yn=mn(B)??c;let Jn=typeof D==="function"?D:wn(D);if(d)Jn=typeof d==="function"?d:wn({...typeof D==="object"?D:{},...d});let Gn=Hn===void 0?void 0:Cn(Hn,Un(f,Bn,q.header)),Vc=Un(Gn===void 0||Gn instanceof FormData?{}:{"Content-Type":"application/json"},f,Bn,q.header),Nc={redirect:"follow",...$,...En,body:Gn,headers:Vc},u,r,w=new k(Sc(J,{baseUrl:Yn,params:q,querySerializer:Jn}),Nc),W;for(let Q in En)if(!(Q in w))w[Q]=En[Q];if(x.length){u=Uc(),r=Object.freeze({baseUrl:Yn,fetch:Nn,parseAs:Mn,querySerializer:Jn,bodySerializer:Cn});for(let Q of x)if(Q&&typeof Q==="object"&&typeof Q.onRequest==="function"){let Z=await Q.onRequest({request:w,schemaPath:J,params:q,options:r,id:u});if(Z)if(Z instanceof k)w=Z;else if(Z instanceof Response){W=Z;break}else throw Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!W){try{W=await Nn(w,y)}catch(Q){let Z=Q;if(x.length)for(let L=x.length-1;L>=0;L--){let h=x[L];if(h&&typeof h==="object"&&typeof h.onError==="function"){let I=await h.onError({request:w,error:Z,schemaPath:J,params:q,options:r,id:u});if(I){if(I instanceof Response){Z=void 0,W=I;break}if(I instanceof Error){Z=I;continue}throw Error("onError: must return new Response() or instance of Error")}}}if(Z)throw Z}if(x.length)for(let Q=x.length-1;Q>=0;Q--){let Z=x[Q];if(Z&&typeof Z==="object"&&typeof Z.onResponse==="function"){let L=await Z.onResponse({request:w,response:W,schemaPath:J,params:q,options:r,id:u});if(L){if(!(L instanceof Response))throw Error("onResponse: must return new Response() when modifying the response");W=L}}}}if(W.status===204||w.method==="HEAD"||W.headers.get("Content-Length")==="0")return W.ok?{data:void 0,response:W}:{error:void 0,response:W};if(W.ok){if(Mn==="stream")return{data:W.body,response:W};return{data:await W[Mn](),response:W}}let Tn=await W.text();try{Tn=JSON.parse(Tn)}catch{}return{error:Tn,response:W}}return{request(J,j,B){return X(j,{...B,method:J.toUpperCase()})},GET(J,j){return X(J,{...j,method:"GET"})},PUT(J,j){return X(J,{...j,method:"PUT"})},POST(J,j){return X(J,{...j,method:"POST"})},DELETE(J,j){return X(J,{...j,method:"DELETE"})},OPTIONS(J,j){return X(J,{...j,method:"OPTIONS"})},HEAD(J,j){return X(J,{...j,method:"HEAD"})},PATCH(J,j){return X(J,{...j,method:"PATCH"})},TRACE(J,j){return X(J,{...j,method:"TRACE"})},use(...J){for(let j of J){if(!j)continue;if(typeof j!=="object"||!(("onRequest"in j)||("onResponse"in j)||("onError"in j)))throw Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");x.push(j)}},eject(...J){for(let j of J){let B=x.indexOf(j);if(B!==-1)x.splice(B,1)}}}}function p(n,c,k){if(c===void 0||c===null)return"";if(typeof c==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${n}=${k?.allowReserved===!0?c:encodeURIComponent(c)}`}function Ln(n,c,k){if(!c||typeof c!=="object")return"";let o=[],D={simple:",",label:".",matrix:";"}[k.style]||"&";if(k.style!=="deepObject"&&k.explode===!1){for(let y in c)o.push(y,k.allowReserved===!0?c[y]:encodeURIComponent(c[y]));let f=o.join(",");switch(k.style){case"form":return`${n}=${f}`;case"label":return`.${f}`;case"matrix":return`;${n}=${f}`;default:return f}}for(let f in c){let y=k.style==="deepObject"?`${n}[${f}]`:f;o.push(p(y,c[f],k))}let g=o.join(D);return k.style==="label"||k.style==="matrix"?`${D}${g}`:g}function Sn(n,c,k){if(!Array.isArray(c))return"";if(k.explode===!1){let g={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[k.style]||",",f=(k.allowReserved===!0?c:c.map((y)=>encodeURIComponent(y))).join(g);switch(k.style){case"simple":return f;case"label":return`.${f}`;case"matrix":return`;${n}=${f}`;default:return`${n}=${f}`}}let o={simple:",",label:".",matrix:";"}[k.style]||"&",D=[];for(let g of c)if(k.style==="simple"||k.style==="label")D.push(k.allowReserved===!0?g:encodeURIComponent(g));else D.push(p(n,g,k));return k.style==="label"||k.style==="matrix"?`${o}${D.join(o)}`:D.join(o)}function wn(n){return function(k){let o=[];if(k&&typeof k==="object")for(let D in k){let g=k[D];if(g===void 0||g===null)continue;if(Array.isArray(g)){if(g.length===0)continue;o.push(Sn(D,g,{style:"form",explode:!0,...n?.array,allowReserved:n?.allowReserved||!1}));continue}if(typeof g==="object"){o.push(Ln(D,g,{style:"deepObject",explode:!0,...n?.object,allowReserved:n?.allowReserved||!1}));continue}o.push(p(D,g,n))}return o.join("&")}}function mc(n,c){let k=n;for(let o of n.match(Hc)??[]){let D=o.substring(1,o.length-1),g=!1,f="simple";if(D.endsWith("*"))g=!0,D=D.substring(0,D.length-1);if(D.startsWith("."))f="label",D=D.substring(1);else if(D.startsWith(";"))f="matrix",D=D.substring(1);if(!c||c[D]===void 0||c[D]===null)continue;let y=c[D];if(Array.isArray(y)){k=k.replace(o,Sn(D,y,{style:f,explode:g}));continue}if(typeof y==="object"){k=k.replace(o,Ln(D,y,{style:f,explode:g}));continue}if(f==="matrix"){k=k.replace(o,`;${p(D,y)}`);continue}k=k.replace(o,f==="label"?`.${encodeURIComponent(y)}`:encodeURIComponent(y))}return k}function Lc(n,c){if(n instanceof FormData)return n;if(c){if((c.get instanceof Function?c.get("Content-Type")??c.get("content-type"):c["Content-Type"]??c["content-type"])==="application/x-www-form-urlencoded")return new URLSearchParams(n).toString()}return JSON.stringify(n)}function Sc(n,c){let k=`${c.baseUrl}${n}`;if(c.params?.path)k=mc(k,c.params.path);let o=c.querySerializer(c.params.query??{});if(o.startsWith("?"))o=o.substring(1);if(o)k+=`?${o}`;return k}function Un(...n){let c=new Headers;for(let k of n){if(!k||typeof k!=="object")continue;let o=k instanceof Headers?k.entries():Object.entries(k);for(let[D,g]of o)if(g===null)c.delete(D);else if(Array.isArray(g))for(let f of g)c.append(D,f);else if(g!==void 0)c.set(D,g)}return c}function mn(n){if(n.endsWith("/"))return n.substring(0,n.length-1);return n}class A extends Error{status;body;url;constructor(n,c,k,o){super(n);this.name="ApiClientError",this.status=c,this.body=k,this.url=o}}function T(n,c){if(n.error!==void 0&&n.error!==null){let k=n.response?.status??0,o=n.response?.url??"",D=typeof n.error==="object"&&n.error!==null&&"error"in n.error&&typeof n.error.error==="object"&&n.error.error?.message||`${c} failed (${k})`;throw new A(String(D),k,n.error,o)}if(n.data===void 0)throw new A(`${c}: empty response body`,n.response?.status??0,void 0,n.response?.url??"");return n.data}class s{client;constructor(n){this.client=n}async get(){let n=await this.client.GET("/api/v1/me",{});return T(n,"me.get")}}class e{client;constructor(n){this.client=n}async get(n){let c=await this.client.GET("/api/v1/orgs/{orgId}",{params:{path:{orgId:n}}});return T(c,"orgs.get")}async listMembers(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/members",{params:{path:{orgId:n},query:c}});return T(k,"orgs.listMembers")}}class l{client;constructor(n){this.client=n}async list(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/products",{params:{path:{orgId:n},query:c}});return T(k,"products.list")}async get(n,c){let k=await this.client.GET("/api/v1/orgs/{orgId}/products/{productId}",{params:{path:{orgId:n,productId:c}}});return T(k,"products.get")}async create(n,c){let k=await this.client.POST("/api/v1/orgs/{orgId}/products",{params:{path:{orgId:n}},body:c});return T(k,"products.create")}async update(n,c,k){let o=await this.client.PUT("/api/v1/orgs/{orgId}/products/{productId}",{params:{path:{orgId:n,productId:c}},body:k});return T(o,"products.update")}async delete(n,c){let k=await this.client.DELETE("/api/v1/orgs/{orgId}/products/{productId}",{params:{path:{orgId:n,productId:c}}});return T(k,"products.delete")}}class a{client;constructor(n){this.client=n}async list(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/events",{params:{path:{orgId:n},query:c}});return T(k,"events.list")}async get(n,c){let k=await this.client.GET("/api/v1/orgs/{orgId}/events/{eventId}",{params:{path:{orgId:n,eventId:c}}});return T(k,"events.get")}async create(n,c){let k=await this.client.POST("/api/v1/orgs/{orgId}/events",{params:{path:{orgId:n}},body:c});return T(k,"events.create")}async update(n,c,k){let o=await this.client.PUT("/api/v1/orgs/{orgId}/events/{eventId}",{params:{path:{orgId:n,eventId:c}},body:k});return T(o,"events.update")}async delete(n,c){let k=await this.client.DELETE("/api/v1/orgs/{orgId}/events/{eventId}",{params:{path:{orgId:n,eventId:c}}});return T(k,"events.delete")}}class nn{client;constructor(n){this.client=n}async list(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/rooms",{params:{path:{orgId:n},query:c}});return T(k,"rooms.list")}async get(n,c){let k=await this.client.GET("/api/v1/orgs/{orgId}/rooms/{roomId}",{params:{path:{orgId:n,roomId:c}}});return T(k,"rooms.get")}async create(n,c){let k=await this.client.POST("/api/v1/orgs/{orgId}/rooms",{params:{path:{orgId:n}},body:c});return T(k,"rooms.create")}async update(n,c,k){let o=await this.client.PUT("/api/v1/orgs/{orgId}/rooms/{roomId}",{params:{path:{orgId:n,roomId:c}},body:k});return T(o,"rooms.update")}async delete(n,c){let k=await this.client.DELETE("/api/v1/orgs/{orgId}/rooms/{roomId}",{params:{path:{orgId:n,roomId:c}}});return T(k,"rooms.delete")}}class cn{client;constructor(n){this.client=n}async list(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/bookings",{params:{path:{orgId:n},query:c}});return T(k,"bookings.list")}async get(n,c){let k=await this.client.GET("/api/v1/orgs/{orgId}/bookings/{bookingId}",{params:{path:{orgId:n,bookingId:c}}});return T(k,"bookings.get")}}class kn{client;constructor(n){this.client=n}async list(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/orders",{params:{path:{orgId:n},query:c}});return T(k,"orders.list")}async get(n,c){let k=await this.client.GET("/api/v1/orgs/{orgId}/orders/{orderId}",{params:{path:{orgId:n,orderId:c}}});return T(k,"orders.get")}}class on{client;constructor(n){this.client=n}async list(n,c={}){let k=await this.client.GET("/api/v1/orgs/{orgId}/quotes",{params:{path:{orgId:n},query:c}});return T(k,"quotes.list")}async get(n,c){let k=await this.client.GET("/api/v1/orgs/{orgId}/quotes/{quoteId}",{params:{path:{orgId:n,quoteId:c}}});return T(k,"quotes.get")}}var qc="https://vcity.io";function Ac(n,c){let k=c??globalThis.fetch;if(!k)throw Error("@vcityio/api-client: no fetch implementation found. Provide options.fetch or run on Node >=20 / a browser.");return async function(D){if(!n)return k(D);if(D.headers.has("Authorization"))return k(D);let g=new Headers(D.headers);g.set("Authorization",`Bearer ${n}`);let f=new Request(D,{headers:g});return k(f)}}class Wn{raw;me;orgs;products;events;rooms;bookings;orders;quotes;constructor(n={}){let c=n.baseUrl??qc,k=Ac(n.token,n.fetch),o={baseUrl:c,fetch:k,headers:n.headers};this.raw=Rn(o),this.me=new s(this.raw),this.orgs=new e(this.raw),this.products=new l(this.raw),this.events=new a(this.raw),this.rooms=new nn(this.raw),this.bookings=new cn(this.raw),this.orders=new kn(this.raw),this.quotes=new on(this.raw)}}function _n(n={}){return new Wn(n)}import U from"node:fs";import zc from"node:os";import Xn from"node:path";function C(){if(process.env.VCITY_CONFIG_DIR)return process.env.VCITY_CONFIG_DIR;return Xn.join(zc.homedir(),".vcity")}function Dn(){return Xn.join(C(),"auth.json")}function Zn(){return Xn.join(C(),"config.json")}function qn(){return process.env.VCITY_API_BASE_URL||process.env.VCITY_PUBLIC_URL||"https://vcity.io"}function Oc(){let n=C();if(!U.existsSync(n))U.mkdirSync(n,{recursive:!0,mode:448})}function gn(){let n=Dn();if(!U.existsSync(n))return;try{return JSON.parse(U.readFileSync(n,"utf-8"))}catch{return}}function fn(n){Oc();let c=Dn();U.writeFileSync(c,JSON.stringify(n,null,2),{mode:384});try{U.chmodSync(c,384)}catch{}}function z(){let n=Dn();if(U.existsSync(n))U.rmSync(n)}function yn(){let n=gn();if(!n)throw Error("Not logged in. Run `vcity login` first.");return n}class t extends Error{status;body;constructor(n,c,k){super(k??`HTTP ${n}`);this.status=n;this.body=c;this.name="ApiError"}}function zn(n,c,k){let o=new URL(c.startsWith("/")?c:`/${c}`,n);if(k){for(let[D,g]of Object.entries(k))if(g!==void 0&&g!==null&&!Number.isNaN(g))o.searchParams.set(D,String(g))}return o.toString()}async function An(n){try{let c=await fetch(zn(n.api_base_url,"/api/cli/auth/refresh"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({refresh_token:n.refresh_token})});if(!c.ok)return;let k=await c.json(),o={...n,access_token:k.access_token,refresh_token:k.refresh_token,access_expires_at:k.access_expires_at,refresh_expires_at:k.refresh_expires_at};return fn(o),o}catch{return}}async function v(n,c={}){let{authed:k=!0,method:o="GET",body:D,query:g,baseUrl:f}=c,y=k?yn():void 0,$=f??y?.api_base_url??"https://vcity.io",x={"content-type":"application/json"};if(y)x.authorization=`Bearer ${y.access_token}`;let X=await fetch(zn($,n,g),{method:o,headers:x,body:D===void 0?void 0:JSON.stringify(D)}),j=(X.headers.get("content-type")??"").includes("application/json")?await X.json().catch(()=>{return}):await X.text().catch(()=>{return});if(!X.ok){let B=(j&&typeof j==="object"&&"error"in j?String(j.error):void 0)??`Request failed (${X.status})`;throw new t(X.status,j,B)}return j}function Pc(){let n=async(c,k)=>{let o=new Headers(c.headers);o.set("authorization",`Bearer ${k}`);let D=new Request(c,{headers:o});return globalThis.fetch(D)};return async function(k){let o=yn();if(Date.now()>=o.access_expires_at){if(Date.now()>=o.refresh_expires_at)throw z(),new t(401,void 0,"Session expired. Run `vcity login` again.");let f=await An(o);if(!f)throw z(),new t(401,void 0,"Session expired. Run `vcity login` again.");o=f}let D=await n(k,o.access_token);if(D.status!==401)return D;let g=await An(o);if(!g)throw z(),new t(401,void 0,"Session expired. Run `vcity login` again.");return o=g,n(k,o.access_token)}}var $n;function E(){if($n)return $n;let n=yn();return $n=_n({baseUrl:n.api_base_url,fetch:Pc()}),$n}function m(n){if(n==null)return"";return new Date(n).toISOString().replace("T"," ").slice(0,16)}import O from"node:fs";function Fc(){let n=C();if(!O.existsSync(n))O.mkdirSync(n,{recursive:!0,mode:448})}function S(){let n=Zn();if(!O.existsSync(n))return{};try{return JSON.parse(O.readFileSync(n,"utf-8"))}catch{return{}}}function On(n){Fc();let k={...S(),...n},o=Zn();O.writeFileSync(o,JSON.stringify(k,null,2),{mode:384});try{O.chmodSync(o,384)}catch{}return k}function G(n){if(n)return n;let c=S();if(!c.active_org)throw Error("No active org. Run `vcity org use <slug>` or pass --org <slug>.");return c.active_org}var bc=/\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[P_^X][^\x07\x1b]*(?:\x07|\x1b\\)|[^[\]P_^X])/g,Ic=/[\x00-\x08\x0b-\x1f\x7f]/g;function K(n){return n.replace(bc,"").replace(Ic,"")}function Pn(n){let c;try{c=new URL(n)}catch{throw Error(`Refusing to open malformed URL: ${K(n).slice(0,100)}`)}if(c.protocol==="https:")return c;if(c.protocol==="http:"&&(c.hostname==="localhost"||c.hostname==="127.0.0.1"))return c;throw Error(`Refusing to open URL with unsafe protocol: ${c.protocol}`)}function i(n){if(n)return"json";if(!process.stdout.isTTY)return"json";return"pretty"}function M(n){process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
3
|
+
`)}function tc(n,c){if(n.length===0)return"(no rows)";let k=n.map((y)=>c.map(($)=>K($.get(y)??""))),o=c.map((y,$)=>Math.max(y.header.length,...k.map((x)=>x[$].length))),D=o.map((y)=>"-".repeat(y)).join(" "),g=c.map((y,$)=>y.header.padEnd(o[$])).join(" "),f=k.map((y)=>y.map(($,x)=>$.padEnd(o[x])).join(" "));return[g,D,...f].join(`
|
|
4
|
+
`)}function V(n,c){process.stdout.write(`${tc(n,c)}
|
|
5
|
+
`)}function _(n){for(let[c,k]of Object.entries(n)){if(k===void 0||k===null)continue;let o=typeof k==="object"?JSON.stringify(k):String(k);process.stdout.write(`${c.padEnd(20)} ${K(o)}
|
|
6
|
+
`)}}async function Fn(n={}){let c=i(n.json),k=G(n.org),o={};if(n.limit!==void 0)o.limit=n.limit;if(n.status!==void 0)o.status=n.status;let g=await E().bookings.list(k,o),f=g.data??[];if(c==="json"){M({org:k,bookings:f,total:g.total,skip:g.skip,limit:g.limit,hasMore:g.hasMore});return}V(f,[{header:"ID",get:(y)=>y.id},{header:"NAME",get:(y)=>y.name??""},{header:"EMAIL",get:(y)=>y.email??""},{header:"REQUESTED",get:(y)=>m(y.requestedDate)},{header:"STATUS",get:(y)=>y.status??""}])}async function bn(n,c={}){let k=i(c.json),o=G(c.org),g=await E().bookings.get(o,n);if(k==="json"){M(g);return}_(g)}import vc from"node:fs";function H(n){if(n===void 0)return;let c;if(n.startsWith("@")){let k=n.slice(1);if(k.length===0)throw Error("--data: missing file path after `@`");if(!/\.json$/i.test(k))throw Error(`--data: @file path must point to a .json file (got: ${k})`);try{c=vc.readFileSync(k,"utf-8")}catch(o){let D=o instanceof Error?o.message:String(o);throw Error(`--data: could not read ${k}: ${D}`)}}else c=n;try{return JSON.parse(c)}catch(k){let o=k instanceof Error?k.message:String(k);throw Error(`--data: invalid JSON (${o})`)}}import dc from"node:readline";function P(n){let c=dc.createInterface({input:process.stdin,output:process.stdout});return new Promise((k)=>{c.question(`${n} `,(o)=>{c.close();let D=o.trim().toLowerCase();k(D==="y"||D==="yes")})})}async function In(n={}){let c=i(n.json),k=G(n.org),o={};if(n.limit!==void 0)o.limit=n.limit;if(n.status!==void 0)o.status=n.status;let g=await E().events.list(k,o),f=g.data??[];if(c==="json"){M({org:k,events:f,total:g.total,skip:g.skip,limit:g.limit,hasMore:g.hasMore});return}V(f,[{header:"ID",get:(y)=>y.id},{header:"NAME",get:(y)=>y.name??""},{header:"STARTS_AT",get:(y)=>y.startsAt!==void 0?new Date(y.startsAt).toISOString():""},{header:"STATUS",get:(y)=>y.status??""},{header:"CATEGORIES",get:(y)=>(y.categories??[]).join(",")}])}async function tn(n,c={}){let k=i(c.json),o=G(c.org),g=await E().events.get(o,n);if(k==="json"){M(g);return}_(g)}function xn(n,c){if(/^-?\d+$/.test(n)){let o=Number(n);if(Number.isFinite(o))return o}let k=Date.parse(n);if(Number.isFinite(k))return k;throw Error(`${c}: expected ISO 8601 or epoch ms (got: ${n})`)}async function vn(n={}){let c=i(n.json),k=G(n.org),o=H(n.data),D=o&&typeof o==="object"?{...o}:{};if(n.name!==void 0)D.name=n.name;if(n.slug!==void 0)D.slug=n.slug;if(n.startsAt!==void 0)D.startsAt=xn(n.startsAt,"--starts-at");if(n.endsAt!==void 0)D.endsAt=xn(n.endsAt,"--ends-at");if(D.name===void 0)throw Error("events create: --name is required (or supply it via --data)");let f=await E().events.create(k,D);if(c==="json"){M(f);return}process.stdout.write(`Created event:
|
|
7
|
+
`),_(f)}async function dn(n,c={}){let k=i(c.json),o=G(c.org),D=H(c.data),g=D&&typeof D==="object"?{...D}:{};if(c.name!==void 0)g.name=c.name;if(c.slug!==void 0)g.slug=c.slug;if(c.status!==void 0)g.status=c.status;if(c.startsAt!==void 0)g.startsAt=xn(c.startsAt,"--starts-at");if(c.endsAt!==void 0)g.endsAt=xn(c.endsAt,"--ends-at");if(Object.keys(g).length===0)throw Error("events update: nothing to update (pass at least one field or --data)");let y=await E().events.update(o,n,g);if(k==="json"){M(y);return}process.stdout.write(`Updated event:
|
|
8
|
+
`),_(y)}async function un(n,c={}){let k=i(c.json),o=G(c.org);if(!c.yes){if(k==="json")throw Error("events delete: --yes is required in JSON / non-interactive mode");if(!await P(`Delete event ${n} in org ${o}? [y/N]`)){process.stdout.write(`Aborted.
|
|
9
|
+
`);return}}let g=await E().events.delete(o,n);if(k==="json"){M(g);return}process.stdout.write(`Deleted event ${n}.
|
|
10
|
+
`)}import{setTimeout as uc}from"node:timers/promises";var rn=1;function rc(n){if(n===!1)return!1;if(process.env.VCITY_NO_OPEN_BROWSER)return!1;if(!process.stdout.isTTY)return!1;return!0}async function hc(n){try{let c=(await import("open")).default;await c(n)}catch{}}function pc(n){let c;try{c=new URL(n)}catch{throw Error(`Invalid --api-base-url: ${n.slice(0,200)}`)}if(c.protocol==="https:")return c;if(c.protocol==="http:"&&(c.hostname==="localhost"||c.hostname==="127.0.0.1"))return c;throw Error(`--api-base-url must use https:// (got: ${c.protocol}//${c.hostname}).`)}async function hn(n={}){let c=n.apiBaseUrl??qn(),k=pc(c),o=await v("/api/cli/auth/device/code",{method:"POST",body:{},authed:!1,baseUrl:k.toString()}),D=new URL("/cli-auth",k),g=new URL(D);if(g.searchParams.set("user_code",o.user_code),process.stdout.write(`
|
|
11
11
|
Open this URL to approve the session:
|
|
12
|
-
${
|
|
12
|
+
${D.toString()}
|
|
13
13
|
`),process.stdout.write(`Enter this code:
|
|
14
|
-
${
|
|
14
|
+
${K(o.user_code)}
|
|
15
15
|
|
|
16
16
|
`),process.stdout.write(`Waiting for approval…
|
|
17
|
-
`),rc(n.openBrowser))await hc(Pn(
|
|
18
|
-
Logged in as ${
|
|
19
|
-
`);return}throw Error(`Login ${
|
|
20
|
-
`);return}try{await
|
|
21
|
-
`)}async function sn(n={}){let c=
|
|
22
|
-
`)}async function cc(n={}){let c=
|
|
23
|
-
`),
|
|
24
|
-
`),
|
|
25
|
-
`);return}}let
|
|
26
|
-
`)}var
|
|
27
|
-
`),
|
|
28
|
-
`),
|
|
29
|
-
`);return}}let
|
|
30
|
-
`)}import{spawn as
|
|
17
|
+
`),rc(n.openBrowser))await hc(Pn(g.toString()).toString());let f=Date.now()+o.expires_in*1000,y=Math.max(o.interval,rn);while(Date.now()<f){await uc(y*1000);let $=await v("/api/cli/auth/device/token",{method:"POST",body:{device_code:o.device_code},authed:!1,baseUrl:k.toString()}).catch((x)=>{if(x&&typeof x==="object"&&"status"in x&&x.status===400)return x.body;throw x});if(!$)continue;if($.status==="pending"){y=Math.max($.interval,rn);continue}if($.status==="approved"){fn({api_base_url:k.toString(),access_token:$.access_token,refresh_token:$.refresh_token,access_expires_at:$.access_expires_at,refresh_expires_at:$.refresh_expires_at,user:$.user});let x=$.user.email??$.user.name??$.user.id;process.stdout.write(`
|
|
18
|
+
Logged in as ${K(x)}.
|
|
19
|
+
`);return}throw Error(`Login ${$.status}. Run \`vcity login\` again.`)}throw Error("Login timed out. Run `vcity login` again.")}async function pn(){let n=gn();if(!n){process.stdout.write(`Not logged in.
|
|
20
|
+
`);return}try{await v("/api/cli/auth/logout",{method:"POST",body:{refresh_token:n.refresh_token}})}catch{}z(),process.stdout.write(`Logged out.
|
|
21
|
+
`)}async function sn(n={}){let c=i(n.json),k=G(n.org),o={};if(n.limit!==void 0)o.limit=n.limit;if(n.status!==void 0)o.status=n.status;let g=await E().orders.list(k,o),f=g.data??[];if(c==="json"){M({org:k,orders:f,total:g.total,skip:g.skip,limit:g.limit,hasMore:g.hasMore});return}V(f,[{header:"ID",get:(y)=>y.id},{header:"STATUS",get:(y)=>y.status??""},{header:"TOTAL",get:(y)=>y.total!==void 0?`${y.total.toLocaleString()} ${y.currencyCode??""}`.trim():""},{header:"CREATED",get:(y)=>m(y.createdAt)}])}async function en(n,c={}){let k=i(c.json),o=G(c.org),g=await E().orders.get(o,n);if(k==="json"){M(g);return}_(g)}async function ln(){let c=await E().me.get();if(c&&typeof c==="object"&&"orgs"in c){let k=c.orgs;return Array.isArray(k)?k:[]}return[]}async function an(n={}){let c=i(n.json),k=await ln(),o=S().active_org;if(c==="json"){M({orgs:k,active_org:o??null});return}V(k,[{header:"*",get:(D)=>D.slug===o?"*":" "},{header:"SLUG",get:(D)=>D.slug},{header:"NAME",get:(D)=>D.name??""},{header:"ID",get:(D)=>D.id}])}async function nc(n){let k=(await ln()).find((o)=>o.slug===n||o.id===n);if(!k)throw Error(`No accessible org matches "${n}". Run \`vcity org list\` to see options.`);On({active_org:k.slug}),process.stdout.write(`Active org set to ${k.slug} (${k.name??k.id}).
|
|
22
|
+
`)}async function cc(n={}){let c=i(n.json),k=G(n.org),D=await E().products.list(k,n.limit!==void 0?{limit:n.limit}:{}),g=D.data??[];if(c==="json"){M({org:k,products:g,total:D.total,skip:D.skip,limit:D.limit,hasMore:D.hasMore});return}V(g,[{header:"ID",get:(f)=>f.id},{header:"NAME",get:(f)=>f.name??""},{header:"PRICE",get:(f)=>f.price!==void 0?`${f.price.toLocaleString()} ${f.currencyCode??""}`.trim():""},{header:"SKU",get:(f)=>f.sku??""},{header:"VISIBILITY",get:(f)=>f.visibility??""},{header:"STOCK",get:(f)=>f.availability!==void 0?String(f.availability):""}])}async function kc(n,c={}){let k=i(c.json),o=G(c.org),g=await E().products.get(o,n);if(k==="json"){M(g);return}_(g)}async function oc(n={}){let c=i(n.json),k=G(n.org),o=H(n.data),D=o&&typeof o==="object"?{...o}:{};if(n.name!==void 0)D.name=n.name;if(n.price!==void 0)D.price=n.price;if(n.currency!==void 0)D.currencyCode=n.currency;if(n.sku!==void 0)D.sku=n.sku;if(D.name===void 0)throw Error("products create: --name is required (or supply it via --data)");let f=await E().products.create(k,D);if(c==="json"){M(f);return}process.stdout.write(`Created product:
|
|
23
|
+
`),_(f)}async function Dc(n,c={}){let k=i(c.json),o=G(c.org),D=H(c.data),g=D&&typeof D==="object"?{...D}:{};if(c.name!==void 0)g.name=c.name;if(c.price!==void 0)g.price=c.price;if(c.currency!==void 0)g.currencyCode=c.currency;if(c.sku!==void 0)g.sku=c.sku;if(c.visibility!==void 0)g.visibility=c.visibility;if(c.availability!==void 0)g.availability=c.availability;if(Object.keys(g).length===0)throw Error("products update: nothing to update (pass at least one field or --data)");let y=await E().products.update(o,n,g);if(k==="json"){M(y);return}process.stdout.write(`Updated product:
|
|
24
|
+
`),_(y)}async function gc(n,c={}){let k=i(c.json),o=G(c.org);if(!c.yes){if(k==="json")throw Error("products delete: --yes is required in JSON / non-interactive mode");if(!await P(`Delete product ${n} in org ${o}? [y/N]`)){process.stdout.write(`Aborted.
|
|
25
|
+
`);return}}let g=await E().products.delete(o,n);if(k==="json"){M(g);return}process.stdout.write(`Deleted product ${n}.
|
|
26
|
+
`)}var fc=new Set(["PENDING","IN_PROGRESS","SUBMITTED","CANCELED","ORDERED"]);async function yc(n={}){let c=i(n.json),k=G(n.org);if(n.status!==void 0&&!fc.has(n.status))throw Error(`Invalid quote status: ${n.status}. Allowed: ${[...fc].join(", ")}`);let o={};if(n.limit!==void 0)o.limit=n.limit;if(n.status!==void 0)o.status=n.status;let g=await E().quotes.list(k,o),f=g.data??[];if(c==="json"){M({org:k,quotes:f,total:g.total,skip:g.skip,limit:g.limit,hasMore:g.hasMore});return}V(f,[{header:"ID",get:(y)=>y.id},{header:"NAME",get:(y)=>y.name??""},{header:"PRODUCT",get:(y)=>y.productId??""},{header:"QTY",get:(y)=>y.quantity!==void 0?String(y.quantity):""},{header:"STATUS",get:(y)=>y.status??""},{header:"CREATED",get:(y)=>m(y.createdAt)}])}async function $c(n,c={}){let k=i(c.json),o=G(c.org),g=await E().quotes.get(o,n);if(k==="json"){M(g);return}_(g)}async function xc(n={}){let c=i(n.json),k=G(n.org),o={};if(n.limit!==void 0)o.limit=n.limit;let g=await E().rooms.list(k,o),f=g.data??[];if(c==="json"){M({org:k,rooms:f,total:g.total,skip:g.skip,limit:g.limit,hasMore:g.hasMore});return}V(f,[{header:"ID",get:(y)=>y.id},{header:"TITLE",get:(y)=>y.title??""},{header:"DISABLED",get:(y)=>y.disabled?"yes":"no"},{header:"TYPE",get:(y)=>y.type??""}])}async function jc(n,c={}){let k=i(c.json),o=G(c.org),g=await E().rooms.get(o,n);if(k==="json"){M(g);return}_(g)}async function ic(n={}){let c=i(n.json),k=G(n.org),o=H(n.data),D=o&&typeof o==="object"?{...o}:{};if(n.title!==void 0)D.title=n.title;if(n.description!==void 0)D.description=n.description;if(n.type!==void 0)D.type=n.type;if(D.title===void 0)throw Error("rooms create: --title is required (or supply it via --data)");let f=await E().rooms.create(k,D);if(c==="json"){M(f);return}process.stdout.write(`Created room:
|
|
27
|
+
`),_(f)}async function Mc(n,c={}){let k=i(c.json),o=G(c.org),D=H(c.data),g=D&&typeof D==="object"?{...D}:{};if(c.title!==void 0)g.title=c.title;if(c.description!==void 0)g.description=c.description;if(c.type!==void 0)g.type=c.type;if(c.disabled!==void 0)g.disabled=c.disabled;if(Object.keys(g).length===0)throw Error("rooms update: nothing to update (pass at least one field or --data)");let y=await E().rooms.update(o,n,g);if(k==="json"){M(y);return}process.stdout.write(`Updated room:
|
|
28
|
+
`),_(y)}async function Ec(n,c={}){let k=i(c.json),o=G(c.org);if(!c.yes){if(k==="json")throw Error("rooms delete: --yes is required in JSON / non-interactive mode");if(!await P(`Delete room ${n} in org ${o}? [y/N]`)){process.stdout.write(`Aborted.
|
|
29
|
+
`);return}}let g=await E().rooms.delete(o,n);if(k==="json"){M(g);return}process.stdout.write(`Deleted room ${n}.
|
|
30
|
+
`)}import{spawn as Gc}from"node:child_process";import{mkdtempSync as ec,rmSync as lc,writeFileSync as ac}from"node:fs";import{tmpdir as nk}from"node:os";import{join as Yc}from"node:path";var Qn={name:"@vcityio/cli",version:"0.3.0",type:"module",description:"vcity command-line interface for org owners",main:"./dist/index.js",bin:{vcity:"./dist/index.js"},files:["dist","README.md","LICENSE"],engines:{node:">=20"},publishConfig:{access:"public"},optionalDependencies:{open:">=7"},keywords:["vcity","cli"],author:"Otherwise SAS",license:"MIT",homepage:"https://vcity.io",bugs:{email:"support@owsas.com"}};var N=Qn.version,F=Qn.name;var jn="https://vcity.io/cli/install.sh";function ck(){return typeof process.versions.bun==="string"?"binary":"npm"}async function kk(){let n=`https://registry.npmjs.org/${F}/latest`,c;try{c=await fetch(n,{headers:{accept:"application/json"}})}catch(o){throw Error("Could not reach the npm registry. Check your internet connection.",{cause:o})}if(!c.ok)throw Error(`Failed to fetch latest version from npm (HTTP ${c.status})`);let k=await c.json();if(!k.version)throw Error("Latest version response from npm is missing the `version` field");return k.version}function Jc(n){let[c,...k]=n.split("-"),[o,D,g]=c.split(".").map((f)=>parseInt(f,10));return{major:Number.isFinite(o)?o:0,minor:Number.isFinite(D)?D:0,patch:Number.isFinite(g)?g:0,prerelease:k.join("-")}}function Kn(n,c){let k=Jc(n),o=Jc(c);if(k.major!==o.major)return k.major-o.major;if(k.minor!==o.minor)return k.minor-o.minor;if(k.patch!==o.patch)return k.patch-o.patch;if(k.prerelease===o.prerelease)return 0;if(k.prerelease==="")return 1;if(o.prerelease==="")return-1;return k.prerelease<o.prerelease?-1:1}function Tc(n,c){return new Promise((k,o)=>{let D=Gc(n,c,{stdio:"inherit",shell:!1});D.on("error",o),D.on("exit",(g)=>k({exitCode:g??1}))})}function ok(n,c=["--version"]){return new Promise((k)=>{let o=Gc(n,c,{stdio:"ignore",shell:!1});o.on("error",()=>k(!1)),o.on("exit",(D)=>k(D===0))})}async function Dk(){let n;try{n=await fetch(jn,{headers:{accept:"text/x-shellscript, text/plain"}})}catch(D){throw Error(`Could not download installer from ${jn}.`,{cause:D})}if(!n.ok)throw Error(`Installer download failed (HTTP ${n.status}).`);let c=await n.text();if(!c.startsWith("#!"))throw Error(`Installer at ${jn} did not return a shell script (missing shebang). Refusing to execute.`);if(c.length>262144)throw Error(`Installer at ${jn} is unexpectedly large (${c.length} bytes). Refusing to execute.`);let k=ec(Yc(nk(),"vcity-install-")),o=Yc(k,"install.sh");ac(o,c,{mode:448});try{return await Tc("bash",[o])}finally{try{lc(k,{recursive:!0,force:!0})}catch{}}}async function Rc(n={}){let c=i(n.json),k=ck(),o=await kk(),D=K(o),f=Kn(N,o)<0;if(c==="json"){if(M({current:N,latest:D,outdated:f,installMethod:k}),n.check||!f)return}else{if(process.stdout.write(`current: ${N}
|
|
31
31
|
`),process.stdout.write(`latest: ${D}
|
|
32
|
-
`)
|
|
32
|
+
`),!f){process.stdout.write(`vcity is up to date.
|
|
33
33
|
`);return}process.stdout.write(`install: ${k==="binary"?"standalone binary":"npm global"}
|
|
34
34
|
`)}if(n.check)return;if(!n.yes&&c!=="json"){if(process.stdout.write(`
|
|
35
35
|
Run with --yes to apply the update, or use the command below:
|
|
@@ -37,17 +37,17 @@ Run with --yes to apply the update, or use the command below:
|
|
|
37
37
|
`);else process.stdout.write(` npm install -g ${F}@latest
|
|
38
38
|
`);return}if(k==="binary"){process.stdout.write(`
|
|
39
39
|
Fetching latest binary…
|
|
40
|
-
`);let{exitCode:
|
|
40
|
+
`);let{exitCode:y}=await Dk();if(y!==0)throw Error(`installer exited with code ${y}`)}else{if(!await ok("npm"))throw Error("`npm` is not on PATH. Install Node.js 20+ from https://nodejs.org");process.stdout.write(`
|
|
41
41
|
Installing latest from npm…
|
|
42
|
-
`);let{exitCode:
|
|
42
|
+
`);let{exitCode:y}=await Tc("npm",["install","-g",`${F}@latest`]);if(y!==0)throw Error(`npm install exited with code ${y}`)}process.stdout.write(`
|
|
43
43
|
Updated to ${D}. Run \`vcity --version\` to confirm.
|
|
44
|
-
`)}function
|
|
45
|
-
`),process.stdout.write(`User ID: ${
|
|
46
|
-
`),process.stdout.write(`Active org: ${
|
|
47
|
-
`)}var
|
|
48
|
-
→ vcity ${n} available (you have ${
|
|
49
|
-
`)}function
|
|
50
|
-
`),process.exit(1)}function
|
|
44
|
+
`)}function gk(n){if(n&&typeof n==="object"&&"user"in n){let c=n;return{user:c.user,orgs:c.orgs??[]}}throw Error("Logged-in token is an API key, not a CLI user token. `vcity whoami` is only valid for CLI sessions.")}async function Wc(n={}){let c=i(n.json),o=await E().me.get(),{user:D,orgs:g}=gk(o),f=S();if(c==="json"){M({user:D,orgs:g,active_org:f.active_org??null});return}let y=D.email??D.name??D.id;process.stdout.write(`User: ${y}
|
|
45
|
+
`),process.stdout.write(`User ID: ${D.id}
|
|
46
|
+
`),process.stdout.write(`Active org: ${f.active_org??"(none — run `vcity org use <slug>`)"}
|
|
47
|
+
`)}var fk=new Set(["json","yes","check","no-browser","disabled"]);function _c(n){let c=[],k={};for(let o=0;o<n.length;o++){let D=n[o];if(!D.startsWith("--")){c.push(D);continue}let g=D.indexOf("=");if(g>=0){k[D.slice(2,g)]=D.slice(g+1);continue}let f=D.slice(2),y=n[o+1];if(fk.has(f)||y===void 0||y.startsWith("--"))k[f]=!0;else k[f]=y,o++}return{positional:c,flags:k}}import{mkdirSync as yk,readFileSync as $k,writeFileSync as xk}from"node:fs";import jk from"node:path";var ik=86400000,Mk=1500;function Xc(){return jk.join(C(),"update-check.json")}function Ek(){try{let n=$k(Xc(),"utf8"),c=JSON.parse(n);if(typeof c.latest==="string"&&typeof c.checkedAt==="number")return c;return}catch{return}}function Yk(n){try{yk(C(),{recursive:!0}),xk(Xc(),JSON.stringify(n,null,2),{mode:384})}catch{}}async function Jk(){let n=new AbortController,c=setTimeout(()=>n.abort(),Mk);try{let k=await fetch(`https://registry.npmjs.org/${F}/latest`,{headers:{accept:"application/json"},signal:n.signal});if(!k.ok)return;let o=await k.json();return typeof o.version==="string"?o.version:void 0}catch{return}finally{clearTimeout(c)}}function Zc(n){if(process.env.VCITY_NO_UPDATE_CHECK==="1")return!1;if(!process.stderr.isTTY)return!1;if(n.includes("--json"))return!1;if(n[0]==="update")return!1;return!0}function Qc(){let n=Ek(),c=Date.now();if(n&&c-n.checkedAt<ik)return Promise.resolve(n.latest);return Jk().then((k)=>{if(k)Yk({latest:k,checkedAt:c});return k??n?.latest})}function Kc(n){if(!n)return;if(Kn(N,n)>=0)return;process.stderr.write(`
|
|
48
|
+
→ vcity ${K(n)} available (you have ${N}). Run \`vcity update\` to upgrade.
|
|
49
|
+
`)}function R(n){process.stderr.write(`error: ${K(n)}
|
|
50
|
+
`),process.exit(1)}function Gk(){process.stdout.write(`vcity ${N}
|
|
51
51
|
|
|
52
52
|
Usage:
|
|
53
53
|
vcity login [--api-base-url <url>] [--no-browser]
|
|
@@ -83,6 +83,6 @@ Environment:
|
|
|
83
83
|
VCITY_CONFIG_DIR override the config directory (default ~/.vcity)
|
|
84
84
|
VCITY_NO_OPEN_BROWSER never auto-launch a browser during \`vcity login\`
|
|
85
85
|
VCITY_NO_UPDATE_CHECK disable the background "new version available" check
|
|
86
|
-
`)}function
|
|
87
|
-
`);return}let[c,k,...
|
|
86
|
+
`)}function Tk(n){if(typeof n!=="string")return;let c=parseInt(n,10);if(Number.isNaN(c)||c<0)R(`--limit must be a non-negative integer (got: ${n})`);return c}function Vn(n,c){if(n===void 0)return;if(typeof n!=="string")return;let k=Number(n);if(!Number.isFinite(k))R(`${c} must be a number (got: ${n})`);return k}function Y(n,c){return typeof n[c]==="string"?n[c]:void 0}function b(n){return{org:typeof n.org==="string"?n.org:void 0,limit:Tk(n.limit),status:typeof n.status==="string"?n.status:void 0,json:!!n.json}}async function Rk(n){if(n.length===0||n[0]==="--help"||n[0]==="-h"||n[0]==="help"){Gk();return}if(n[0]==="--version"||n[0]==="-v"){process.stdout.write(`${N}
|
|
87
|
+
`);return}let[c,k,...o]=n,D=n.slice(1),{positional:g,flags:f}=_c(D),y=g.slice(k&&!k.startsWith("--")?1:0);switch(c){case"login":return hn({apiBaseUrl:typeof f["api-base-url"]==="string"?f["api-base-url"]:void 0,openBrowser:f["no-browser"]===!0?!1:void 0});case"logout":return pn();case"whoami":return Wc({json:!!f.json});case"org":{if(k==="list")return an({json:!!f.json});if(k==="use"){let $=y[0];if(!$)R("usage: vcity org use <slug>");return nc($)}R("usage: vcity org list | vcity org use <slug>")}case"products":{let $=b(f);if(k==="list")return cc({org:$.org,limit:$.limit,json:$.json});if(k==="get"){let x=y[0];if(!x)R("usage: vcity products get <id>");return kc(x,{org:$.org,json:$.json})}if(k==="create")return oc({org:$.org,name:Y(f,"name"),price:Vn(f.price,"--price"),currency:Y(f,"currency"),sku:Y(f,"sku"),data:Y(f,"data"),json:$.json});if(k==="update"){let x=y[0];if(!x)R("usage: vcity products update <id>");return Dc(x,{org:$.org,name:Y(f,"name"),price:Vn(f.price,"--price"),currency:Y(f,"currency"),sku:Y(f,"sku"),visibility:Y(f,"visibility"),availability:Vn(f.availability,"--availability"),data:Y(f,"data"),json:$.json})}if(k==="delete"){let x=y[0];if(!x)R("usage: vcity products delete <id>");return gc(x,{org:$.org,yes:f.yes===!0,json:$.json})}R("usage: vcity products list|get|create|update|delete")}case"events":{let $=b(f);if(k==="list"){let x=$.status;if(x!==void 0&&x!=="active"&&x!=="disabled")R(`invalid --status: ${x}. Allowed: active, disabled`);return In({org:$.org,limit:$.limit,status:x,json:$.json})}if(k==="get"){let x=y[0];if(!x)R("usage: vcity events get <id>");return tn(x,{org:$.org,json:$.json})}if(k==="create")return vn({org:$.org,name:Y(f,"name"),startsAt:Y(f,"starts-at"),endsAt:Y(f,"ends-at"),slug:Y(f,"slug"),data:Y(f,"data"),json:$.json});if(k==="update"){let x=y[0];if(!x)R("usage: vcity events update <id>");return dn(x,{org:$.org,name:Y(f,"name"),startsAt:Y(f,"starts-at"),endsAt:Y(f,"ends-at"),slug:Y(f,"slug"),status:Y(f,"status"),data:Y(f,"data"),json:$.json})}if(k==="delete"){let x=y[0];if(!x)R("usage: vcity events delete <id>");return un(x,{org:$.org,yes:f.yes===!0,json:$.json})}R("usage: vcity events list|get|create|update|delete")}case"rooms":{let $=b(f);if(k==="list")return xc({org:$.org,limit:$.limit,json:$.json});if(k==="get"){let x=y[0];if(!x)R("usage: vcity rooms get <id>");return jc(x,{org:$.org,json:$.json})}if(k==="create")return ic({org:$.org,title:Y(f,"title"),description:Y(f,"description"),type:Y(f,"type"),data:Y(f,"data"),json:$.json});if(k==="update"){let x=y[0];if(!x)R("usage: vcity rooms update <id>");return Mc(x,{org:$.org,title:Y(f,"title"),description:Y(f,"description"),type:Y(f,"type"),disabled:f.disabled===!0?!0:void 0,data:Y(f,"data"),json:$.json})}if(k==="delete"){let x=y[0];if(!x)R("usage: vcity rooms delete <id>");return Ec(x,{org:$.org,yes:f.yes===!0,json:$.json})}R("usage: vcity rooms list|get|create|update|delete")}case"bookings":{let $=b(f);if(k==="list")return Fn($);if(k==="get"){let x=y[0];if(!x)R("usage: vcity bookings get <id>");return bn(x,{org:$.org,json:$.json})}R("usage: vcity bookings list | vcity bookings get <id>")}case"orders":{let $=b(f);if(k==="list")return sn($);if(k==="get"){let x=y[0];if(!x)R("usage: vcity orders get <id>");return en(x,{org:$.org,json:$.json})}R("usage: vcity orders list | vcity orders get <id>")}case"quotes":{let $=b(f);if(k==="list")return yc($);if(k==="get"){let x=y[0];if(!x)R("usage: vcity quotes get <id>");return $c(x,{org:$.org,json:$.json})}R("usage: vcity quotes list | vcity quotes get <id>")}case"update":return Rc({check:f.check===!0,yes:f.yes===!0,json:!!f.json});default:R(`unknown command: ${c}. Run \`vcity --help\`.`)}}async function Wk(){let n=process.argv.slice(2),c=Zc(n)?Qc():void 0;try{await Rk(n)}finally{if(c)Kc(await c)}}Wk().catch((n)=>{let c=n instanceof Error?n.message:String(n);process.stderr.write(`error: ${K(c)}
|
|
88
88
|
`),process.exit(1)});
|