@getjusto/team-cli 0.0.12 → 0.0.13

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.
Files changed (2) hide show
  1. package/bin/cli.js +126 -82
  2. package/package.json +1 -1
package/bin/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- function Bc(c){let a=[],m={},o={};for(let s=0;s<c.length;s++)if(c[s].startsWith("--")&&c[s+1]&&!c[s+1].startsWith("--")){let t=c[s].slice(2);if(m[t]=c[s+1],!o[t])o[t]=[];o[t].push(c[s+1]),s++}else if(c[s].startsWith("--"))m[c[s].slice(2)]="true";else a.push(c[s]);return{positional:a,flags:m,arrayFlags:o}}function hc(c,a){let m=c[a];if(!m)throw Error(`--${a} es requerido.`);return m}var ys={comma:",",tab:"\t",pipe:"|"},kc=ys.comma;function ba(c){return c.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function Ss(c){return c==="true"||c==="false"||c==="null"}function x(c){if(c===null)return null;if(typeof c==="object"&&c!==null&&"toJSON"in c&&typeof c.toJSON==="function"){let a=c.toJSON();if(a!==c)return x(a)}if(typeof c==="string"||typeof c==="boolean")return c;if(typeof c==="number"){if(Object.is(c,-0))return 0;if(!Number.isFinite(c))return null;return c}if(typeof c==="bigint"){if(c>=Number.MIN_SAFE_INTEGER&&c<=Number.MAX_SAFE_INTEGER)return Number(c);return c.toString()}if(c instanceof Date)return c.toISOString();if(Array.isArray(c))return c.map(x);if(c instanceof Set)return Array.from(c).map(x);if(c instanceof Map)return Object.fromEntries(Array.from(c,([a,m])=>[String(a),x(m)]));if(Ls(c)){let a={};for(let m in c)if(Object.prototype.hasOwnProperty.call(c,m))a[m]=x(c[m]);return a}return null}function $c(c){return c===null||typeof c==="string"||typeof c==="number"||typeof c==="boolean"}function pc(c){return Array.isArray(c)}function u(c){return c!==null&&typeof c==="object"&&!Array.isArray(c)}function Kc(c){return Object.keys(c).length===0}function Ls(c){if(c===null||typeof c!=="object")return!1;let a=Object.getPrototypeOf(c);return a===null||a===Object.prototype}function _c(c){return c.length===0||c.every((a)=>$c(a))}function Ns(c){return c.length===0||c.every((a)=>pc(a))}function va(c){return c.length===0||c.every((a)=>u(a))}function us(c){return/^[A-Z_][\w.]*$/i.test(c)}function Os(c){return/^[A-Z_]\w*$/i.test(c)}function ds(c,a=kc){if(!c)return!1;if(c!==c.trim())return!1;if(Ss(c)||is(c))return!1;if(c.includes(":"))return!1;if(c.includes('"')||c.includes("\\"))return!1;if(/[[\]{}]/.test(c))return!1;if(/[\n\r\t]/.test(c))return!1;if(c.includes(a))return!1;if(c.startsWith("-"))return!1;return!0}function is(c){return/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(c)||/^0\d+$/.test(c)}var ep=Symbol("quotedKey");function Bs(c,a,m,o,s,t,w){if(o.keyFolding!=="safe")return;if(!u(a))return;let{segments:r,tail:C,leafValue:g}=bs(c,a,w??o.flattenDepth);if(r.length<2)return;if(!r.every((R)=>Os(R)))return;let q=vs(r),J=t?`${t}.${q}`:q;if(m.includes(q))return;if(s&&s.has(J))return;return{foldedKey:q,remainder:C,leafValue:g,segmentCount:r.length}}function bs(c,a,m){let o=[c],s=a;while(o.length<m){if(!u(s))break;let t=Object.keys(s);if(t.length!==1)break;let w=t[0],r=s[w];o.push(w),s=r}if(!u(s)||Kc(s))return{segments:o,tail:void 0,leafValue:s};return{segments:o,tail:s,leafValue:s}}function vs(c){return c.join(".")}function Wc(c,a){if(c===null)return"null";if(typeof c==="boolean")return String(c);if(typeof c==="number")return String(c);return xs(c,a)}function xs(c,a=kc){if(ds(c,a))return c;return`"${ba(c)}"`}function Ec(c){if(us(c))return c;return`"${ba(c)}"`}function xa(c,a=kc){return c.map((m)=>Wc(m,a)).join(a)}function e(c,a){let m=a?.key,o=a?.fields,s=a?.delimiter??",",t="";if(m)t+=Ec(m);if(t+=`[${c}${s!==kc?s:""}]`,o){let w=o.map((r)=>Ec(r));t+=`{${w.join(s)}}`}return t+=":",t}function*es(c,a,m){if($c(c)){let o=Wc(c,a.delimiter);if(o!=="")yield o;return}if(pc(c))yield*Ra(void 0,c,m,a);else if(u(c))yield*lc(c,m,a)}function*lc(c,a,m,o,s,t){let w=Object.keys(c);if(a===0&&!o)o=new Set(w.filter((C)=>C.includes(".")));let r=t??m.flattenDepth;for(let[C,g]of Object.entries(c))yield*fs(C,g,a,m,w,o,s,r)}function*fs(c,a,m,o,s,t,w,r){let C=w?`${w}.${c}`:c,g=r??o.flattenDepth;if(o.keyFolding==="safe"&&s){let J=Bs(c,a,s,o,t,w,g);if(J){let{foldedKey:R,remainder:F,leafValue:P,segmentCount:W}=J,H=Ec(R);if(F===void 0){if($c(P)){yield V(m,`${H}: ${Wc(P,o.delimiter)}`,o.indent);return}else if(pc(P)){yield*Ra(R,P,m,o);return}else if(u(P)&&Kc(P)){yield V(m,`${H}:`,o.indent);return}}if(u(F)){yield V(m,`${H}:`,o.indent);let I=g-W,n=w?`${w}.${R}`:R;yield*lc(F,m+1,o,t,n,I);return}}}let q=Ec(c);if($c(a))yield V(m,`${q}: ${Wc(a,o.delimiter)}`,o.indent);else if(pc(a))yield*Ra(c,a,m,o);else if(u(a)){if(yield V(m,`${q}:`,o.indent),!Kc(a))yield*lc(a,m+1,o,t,C,g)}}function*Ra(c,a,m,o){if(a.length===0){yield V(m,e(0,{key:c,delimiter:o.delimiter}),o.indent);return}if(_c(a)){yield V(m,vc(a,o.delimiter,c),o.indent);return}if(Ns(a)){if(a.every((s)=>_c(s))){yield*ct(c,a,m,o);return}}if(va(a)){let s=ea(a);if(s)yield*at(c,a,s,m,o);else yield*Ba(c,a,m,o);return}yield*Ba(c,a,m,o)}function*ct(c,a,m,o){yield V(m,e(a.length,{key:c,delimiter:o.delimiter}),o.indent);for(let s of a)if(_c(s)){let t=vc(s,o.delimiter);yield B(m+1,t,o.indent)}}function vc(c,a,m){let o=e(c.length,{key:m,delimiter:a}),s=xa(c,a);if(c.length===0)return o;return`${o} ${s}`}function*at(c,a,m,o,s){yield V(o,e(a.length,{key:c,fields:m,delimiter:s.delimiter}),s.indent),yield*fa(a,m,o+1,s)}function ea(c){if(c.length===0)return;let a=c[0],m=Object.keys(a);if(m.length===0)return;if(mt(c,m))return m}function mt(c,a){for(let m of c){if(Object.keys(m).length!==a.length)return!1;for(let o of a){if(!(o in m))return!1;if(!$c(m[o]))return!1}}return!0}function*fa(c,a,m,o){for(let s of c)yield V(m,xa(a.map((t)=>s[t]),o.delimiter),o.indent)}function*Ba(c,a,m,o){yield V(m,e(a.length,{key:c,delimiter:o.delimiter}),o.indent);for(let s of a)yield*la(s,m+1,o)}function*ot(c,a,m){if(Kc(c)){yield V(a,"-",m.indent);return}let o=Object.entries(c),[s,t]=o[0],w=o.slice(1);if(pc(t)&&va(t)){let C=ea(t);if(C){if(yield B(a,e(t.length,{key:s,fields:C,delimiter:m.delimiter}),m.indent),yield*fa(t,C,a+2,m),w.length>0)yield*lc(Object.fromEntries(w),a+1,m);return}}let r=Ec(s);if($c(t))yield B(a,`${r}: ${Wc(t,m.delimiter)}`,m.indent);else if(pc(t))if(t.length===0)yield B(a,`${r}${e(0,{delimiter:m.delimiter})}`,m.indent);else if(_c(t))yield B(a,`${r}${vc(t,m.delimiter)}`,m.indent);else{yield B(a,`${r}${e(t.length,{delimiter:m.delimiter})}`,m.indent);for(let C of t)yield*la(C,a+2,m)}else if(u(t)){if(yield B(a,`${r}:`,m.indent),!Kc(t))yield*lc(t,a+2,m)}if(w.length>0)yield*lc(Object.fromEntries(w),a+1,m)}function*la(c,a,m){if($c(c))yield B(a,Wc(c,m.delimiter),m.indent);else if(pc(c))if(_c(c))yield B(a,vc(c,m.delimiter),m.indent);else{yield B(a,e(c.length,{delimiter:m.delimiter}),m.indent);for(let o of c)yield*la(o,a+1,m)}else if(u(c))yield*ot(c,a,m)}function V(c,a,m){return" ".repeat(m*c)+a}function B(c,a,m){return V(c,"- "+a,m)}function st(c,a){let m=a("",c,[]);if(m===void 0)return bc(c,a,[]);return bc(x(m),a,[])}function bc(c,a,m){if(u(c))return tt(c,a,m);if(pc(c))return wt(c,a,m);return c}function tt(c,a,m){let o={};for(let[s,t]of Object.entries(c)){let w=[...m,s],r=a(s,t,w);if(r===void 0)continue;o[s]=bc(x(r),a,w)}return o}function wt(c,a,m){let o=[];for(let s=0;s<c.length;s++){let t=c[s],w=[...m,s],r=a(String(s),t,w);if(r===void 0)continue;let C=x(r);o.push(bc(C,a,w))}return o}function Wa(c,a){return Array.from(pt(c,a)).join(`
3
- `)}function pt(c,a){let m=x(c),o=rt(a);return es(o.replacer?st(m,o.replacer):m,o,0)}function rt(c){return{indent:c?.indent??2,delimiter:c?.delimiter??kc,keyFolding:c?.keyFolding??"off",flattenDepth:c?.flattenDepth??Number.POSITIVE_INFINITY,replacer:c?.replacer}}function Ct(c){let a=c.format??"toon";if(a!=="toon"&&a!=="json")throw Error("--format debe ser toon o json.");return a}function cm(c,a){if(Ct(a)==="json"){console.log(JSON.stringify(c,null,2));return}console.log(Wa(c))}function am(c){process.stdout.write(`${c}
4
- `)}function mm(c,a){let o={ok:!1,error:c instanceof Error?c.message:String(c)};if((a.format==="json"?"json":"toon")==="json"){console.error(JSON.stringify(o,null,2));return}console.error(Wa(o))}function D(c){process.stderr.write(c)}import{existsSync as fc,mkdirSync as $t,readFileSync as sm,writeFileSync as Qt,unlinkSync as jt}from"node:fs";import{join as tm}from"node:path";import{homedir as Jt}from"node:os";import{AsyncLocalStorage as qt}from"node:async_hooks";var gt=new qt;function O(){return gt.getStore()}var xc={main:{local:"http://localhost:3000",develop:"https://api.bejusto.com",prod:"https://api.getjusto.com"},auth:{local:"http://localhost:4112",develop:"https://auth.service.bejusto.com",prod:"https://auth.service.getjusto.com"},webdata:{local:"http://localhost:4125",develop:"https://webdata.service.bejusto.com",prod:"https://webdatacdn.getjusto.com"},preferences:{local:"http://localhost:4120",develop:"https://preferences.service.bejusto.com",prod:"https://preferences.service.getjusto.com"},buckets:{local:"http://localhost:4106",develop:"https://buckets.service.bejusto.com",prod:"https://buckets.service.getjusto.com"},reservations:{local:"http://localhost:4113",develop:"https://reservations.service.bejusto.com",prod:"https://reservations.service.getjusto.com"},data:{local:"http://localhost:4107",develop:"https://data.service.bejusto.com",prod:"https://data.service.getjusto.com"},finances:{local:"http://localhost:4105",develop:"https://finances.service.bejusto.com",prod:"https://finances.service.getjusto.com"},"url-shortener":{local:"http://localhost:4102",develop:"https://url-shortener.service.bejusto.com",prod:"https://url-shortener.service.getjusto.com"},files:{local:"http://localhost:4108",develop:"https://files.service.bejusto.com",prod:"https://files.service.getjusto.com"},tabs:{local:"http://localhost:4115",develop:"https://tabs.service.bejusto.com",prod:"https://tabs.service.getjusto.com"},commander:{local:"http://localhost:4109",develop:"https://commander.service.bejusto.com",prod:"https://commander.service.getjusto.com"},experiments:{local:"http://localhost:4114",develop:"https://experiments.service.bejusto.com",prod:"https://experiments.service.getjusto.com"},sales:{local:"http://localhost:4117",develop:"https://sales.service.bejusto.com",prod:"https://sales.service.getjusto.com"},delivery:{local:"http://localhost:3410",develop:"https://api-delivery.bejusto.com",prod:"https://api-delivery-2.getjusto.com"},payments:{local:"http://localhost:4118",develop:"https://payments.service.bejusto.com",prod:"https://payments.service.getjusto.com"},addresses:{local:"http://localhost:4051",develop:"https://addresses.service.bejusto.com",prod:"https://addresses.service.getjusto.com"},royalty:{local:"http://localhost:4121",develop:"https://royalty.service.bejusto.com",prod:"https://royalty.service.getjusto.com"},marketing:{local:"http://localhost:4005",develop:"https://marketing.service.bejusto.com",prod:"https://marketing.service.getjusto.com"},api:{local:"http://localhost:4119",develop:"https://api.service.bejusto.com",prod:"https://api.service.getjusto.com"},messenger:{local:"http://localhost:4122",develop:"https://messenger.service.bejusto.com",prod:"https://messenger.service.getjusto.com"},invoice:{local:"http://localhost:4123",develop:"https://invoice.service.bejusto.com",prod:"https://invoice.service.getjusto.com"},"drivers-server":{local:"http://localhost:3410",develop:"https://api-delivery.bejusto.com",prod:"https://api-delivery-2.getjusto.com"}},Ga="prod";function om(c){Ga=c}function ec(){let c=process.env.JUSTO_TEAM_CLI_ENV;if(c)return c;let a=O()?.environment;if(a)return a;return Ga}function K(c){return xc[c][Ga]}var Ia=tm(Jt(),".justo-team");function wm(c){let a=c==="prod"?"credentials.json":`credentials.${c}.json`;return tm(Ia,a)}function Xa(){return wm(ec())}function At(){if(!fc(Ia))$t(Ia,{recursive:!0})}function ca(c){let a=O();if(a&&a.canPersistCredentials===!1)throw Error("Este entorno no permite guardar credenciales.");At(),Qt(Xa(),JSON.stringify(c,null,2))}function U(){let c=process.env.JUSTO_TEAM_CLI_TOKEN,a=process.env.JUSTO_TEAM_CLI_EMAIL,m=process.env.JUSTO_TEAM_CLI_REFRESH_TOKEN;if(c&&a)return{email:a,token:c,refreshToken:m||""};let o=O()?.credentials;if(o!==void 0)return o?{email:o.email,token:o.token,refreshToken:o.refreshToken||""}:null;let s=Xa();if(!fc(s))return null;try{let t=sm(s,"utf-8");return JSON.parse(t)}catch{return null}}function pm(c){let a=wm(c);if(!fc(a))return null;try{let m=sm(a,"utf-8");return JSON.parse(m)}catch{return null}}function Za(){let c=O();if(c&&c.canPersistCredentials===!1)throw Error("Este entorno no permite borrar credenciales.");let a=Xa();if(fc(a))jt(a)}import{existsSync as rm,readFileSync as Pt,writeFileSync as Rt,mkdirSync as lt}from"node:fs";import{join as Cm}from"node:path";import{homedir as Wt}from"node:os";function Gt(){let c=process.env.JUSTO_TEAM_CLI_DEVICE_ID;if(c)return c;let a=O()?.deviceId;if(a)return a;let m=Cm(Wt(),".justo-team"),o=Cm(m,"device-id");if(rm(o))return Pt(o,"utf-8").trim();let s=crypto.randomUUID();if(!rm(m))lt(m,{recursive:!0});return Rt(o,s),s}var gm={required:({label:c})=>`${c} no es opcional`,notAString:({label:c})=>`${c} no es un texto`,notANumber:({label:c})=>`${c} no es un número`,notAnInteger:({label:c})=>`${c} no es un número entero`,notABoolean:({label:c})=>`${c} no es un valor verdadero o falso`,notAnEmail:({label:c})=>`${c} no es un email`,notAnId:({label:c})=>`${c} no es un ID válido`,notADate:({label:c})=>`${c} no es una fecha válida`,notAnArray:({label:c})=>`${c} no es un arreglo`,notAnObject:({label:c})=>`${c} no es un objeto`,stringTooShort:({label:c})=>`${c} no tiene el largo suficiente`,stringTooLong:"El largo es mayor al permitido",numberTooSmall:({label:c})=>`${c} es un número muy pequeño`,numberTooBig:({label:c})=>`${c} es un número muy grande`,notInSchema:({label:c})=>`${c} no esta permitido`,notUnique:({label:c})=>`${c} no es único`,notFound:({label:c})=>`${c} no se encontró`,invalid:"No es válido",rateLimitExceeded:"Has excedido el límite de intentos. Intenta de nuevo más tarde.",incorrectLoginCode:"El código es incorrecto",loginCodeExpired:"El código expiró. Solicita un nuevo",loginCodeLocked:"El código se bloqueó. Genera un nuevo código para continuar",userNotFound:"No existe una cuenta con este email"};function It(c,a){let m=gm[c];if(!m)return`${a}: ${c}`;if(typeof m==="function")return m({label:a});return m}function qm(c){return Object.entries(c).map(([a,m])=>It(m,a)).join(", ")}function Xt(c){if(c.error==="validationError"&&c.validationErrors)return qm(c.validationErrors);if(c.extensions?.code==="PermissionsError"){let s=c.extensions.info?.type;if(s?.includes("User doesn't have permissions for "))return`Tu usuario no tiene permisos para [${s.split("User doesn't have permissions for ")[1]}]`;return c.message}if(c.validationErrors)return`${c.message} (${qm(c.validationErrors)})`;let a=c.message||"Error desconocido",m=gm[a];if(m)return typeof m==="function"?m({label:""}).trim():m;let o=c.error||c.code||c.type;return o?`${a} [${o}]`:a}function Zt(c){try{return JSON.parse(Buffer.from(c.split(".")[1],"base64").toString()).exp*1000<Date.now()}catch{return!0}}async function Mt(){let c=U();if(!c?.refreshToken)return null;let a=`${K("auth")}/refresh-token`,o=await(await fetch(a,{method:"POST",headers:{"X-ORION-REFRESH":c.refreshToken}})).json();if(!o.token)return null;if(O()?.canPersistCredentials!==!1)ca({...c,token:o.token});return o.token}async function aa(){let c=U();if(!c?.token)return;if(!Zt(c.token))return c.token;return await Mt()??void 0}async function Gc(c="application/json"){let a=await aa(),m={"Content-Type":c,"X-ORION-DEVICEID":Gt(),"X-ORION-PLATFORM":"web"};if(a)m["x-orion-jwt"]=a;return m}async function l(c){let a=`${K(c.service)}/graphql`,m=await Gc(),o;try{o=await fetch(a,{method:"POST",headers:m,body:JSON.stringify({query:c.query,variables:c.variables}),signal:AbortSignal.timeout(c.timeoutMs||15000)})}catch{throw Error("La solicitud tardó demasiado. Intenta de nuevo.")}let s=await o.json();if(s.errors?.length)throw Error(Xt(s.errors[0]));if(!s.data)throw Error("No data returned from server");return s.data}function Ht(c){return c.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,"")}function Yt(c){return c.includes(".")||c.startsWith("http://")||c.startsWith("https://")}async function Ic(c){if(Yt(c)){let a=Ht(c),m=await fetch(`${K("main")}/website-id/${a}`,{signal:AbortSignal.timeout(1e4)});if(!m.ok)throw Error(`No se encontro el sitio "${a}"`);let o=await m.json();if(!o.websiteId)throw Error(`No se pudo resolver el websiteId para "${a}"`);return{input:c,websiteId:o.websiteId,targetType:"domain"}}return{input:c,websiteId:c,targetType:"websiteId"}}async function $m(c){let a=await l({service:"main",query:`query ($websiteId: ID) {
2
+ function bc(c){let a=[],o={},m={};for(let s=0;s<c.length;s++)if(c[s].startsWith("--")&&c[s+1]&&!c[s+1].startsWith("--")){let t=c[s].slice(2);if(o[t]=c[s+1],!m[t])m[t]=[];m[t].push(c[s+1]),s++}else if(c[s].startsWith("--"))o[c[s].slice(2)]="true";else a.push(c[s]);return{positional:a,flags:o,arrayFlags:m}}function hc(c,a){let o=c[a];if(!o)throw Error(`--${a} es requerido.`);return o}var ys={comma:",",tab:"\t",pipe:"|"},kc=ys.comma;function Ba(c){return c.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function Ss(c){return c==="true"||c==="false"||c==="null"}function e(c){if(c===null)return null;if(typeof c==="object"&&c!==null&&"toJSON"in c&&typeof c.toJSON==="function"){let a=c.toJSON();if(a!==c)return e(a)}if(typeof c==="string"||typeof c==="boolean")return c;if(typeof c==="number"){if(Object.is(c,-0))return 0;if(!Number.isFinite(c))return null;return c}if(typeof c==="bigint"){if(c>=Number.MIN_SAFE_INTEGER&&c<=Number.MAX_SAFE_INTEGER)return Number(c);return c.toString()}if(c instanceof Date)return c.toISOString();if(Array.isArray(c))return c.map(e);if(c instanceof Set)return Array.from(c).map(e);if(c instanceof Map)return Object.fromEntries(Array.from(c,([a,o])=>[String(a),e(o)]));if(us(c)){let a={};for(let o in c)if(Object.prototype.hasOwnProperty.call(c,o))a[o]=e(c[o]);return a}return null}function $c(c){return c===null||typeof c==="string"||typeof c==="number"||typeof c==="boolean"}function rc(c){return Array.isArray(c)}function N(c){return c!==null&&typeof c==="object"&&!Array.isArray(c)}function Kc(c){return Object.keys(c).length===0}function us(c){if(c===null||typeof c!=="object")return!1;let a=Object.getPrototypeOf(c);return a===null||a===Object.prototype}function _c(c){return c.length===0||c.every((a)=>$c(a))}function Ls(c){return c.length===0||c.every((a)=>rc(a))}function va(c){return c.length===0||c.every((a)=>N(a))}function Ns(c){return/^[A-Z_][\w.]*$/i.test(c)}function is(c){return/^[A-Z_]\w*$/i.test(c)}function ds(c,a=kc){if(!c)return!1;if(c!==c.trim())return!1;if(Ss(c)||Os(c))return!1;if(c.includes(":"))return!1;if(c.includes('"')||c.includes("\\"))return!1;if(/[[\]{}]/.test(c))return!1;if(/[\n\r\t]/.test(c))return!1;if(c.includes(a))return!1;if(c.startsWith("-"))return!1;return!0}function Os(c){return/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(c)||/^0\d+$/.test(c)}var cw=Symbol("quotedKey");function bs(c,a,o,m,s,t,p){if(m.keyFolding!=="safe")return;if(!N(a))return;let{segments:w,tail:C,leafValue:q}=Bs(c,a,p??m.flattenDepth);if(w.length<2)return;if(!w.every((A)=>is(A)))return;let g=vs(w),Q=t?`${t}.${g}`:g;if(o.includes(g))return;if(s&&s.has(Q))return;return{foldedKey:g,remainder:C,leafValue:q,segmentCount:w.length}}function Bs(c,a,o){let m=[c],s=a;while(m.length<o){if(!N(s))break;let t=Object.keys(s);if(t.length!==1)break;let p=t[0],w=s[p];m.push(p),s=w}if(!N(s)||Kc(s))return{segments:m,tail:void 0,leafValue:s};return{segments:m,tail:s,leafValue:s}}function vs(c){return c.join(".")}function Pc(c,a){if(c===null)return"null";if(typeof c==="boolean")return String(c);if(typeof c==="number")return String(c);return es(c,a)}function es(c,a=kc){if(ds(c,a))return c;return`"${Ba(c)}"`}function Ec(c){if(Ns(c))return c;return`"${Ba(c)}"`}function ea(c,a=kc){return c.map((o)=>Pc(o,a)).join(a)}function x(c,a){let o=a?.key,m=a?.fields,s=a?.delimiter??",",t="";if(o)t+=Ec(o);if(t+=`[${c}${s!==kc?s:""}]`,m){let p=m.map((w)=>Ec(w));t+=`{${p.join(s)}}`}return t+=":",t}function*xs(c,a,o){if($c(c)){let m=Pc(c,a.delimiter);if(m!=="")yield m;return}if(rc(c))yield*Aa(void 0,c,o,a);else if(N(c))yield*Rc(c,o,a)}function*Rc(c,a,o,m,s,t){let p=Object.keys(c);if(a===0&&!m)m=new Set(p.filter((C)=>C.includes(".")));let w=t??o.flattenDepth;for(let[C,q]of Object.entries(c))yield*fs(C,q,a,o,p,m,s,w)}function*fs(c,a,o,m,s,t,p,w){let C=p?`${p}.${c}`:c,q=w??m.flattenDepth;if(m.keyFolding==="safe"&&s){let Q=bs(c,a,s,m,t,p,q);if(Q){let{foldedKey:A,remainder:Y,leafValue:J,segmentCount:P}=Q,Z=Ec(A);if(Y===void 0){if($c(J)){yield V(o,`${Z}: ${Pc(J,m.delimiter)}`,m.indent);return}else if(rc(J)){yield*Aa(A,J,o,m);return}else if(N(J)&&Kc(J)){yield V(o,`${Z}:`,m.indent);return}}if(N(Y)){yield V(o,`${Z}:`,m.indent);let G=q-P,T=p?`${p}.${A}`:A;yield*Rc(Y,o+1,m,t,T,G);return}}}let g=Ec(c);if($c(a))yield V(o,`${g}: ${Pc(a,m.delimiter)}`,m.indent);else if(rc(a))yield*Aa(c,a,o,m);else if(N(a)){if(yield V(o,`${g}:`,m.indent),!Kc(a))yield*Rc(a,o+1,m,t,C,q)}}function*Aa(c,a,o,m){if(a.length===0){yield V(o,x(0,{key:c,delimiter:m.delimiter}),m.indent);return}if(_c(a)){yield V(o,vc(a,m.delimiter,c),m.indent);return}if(Ls(a)){if(a.every((s)=>_c(s))){yield*ct(c,a,o,m);return}}if(va(a)){let s=xa(a);if(s)yield*at(c,a,s,o,m);else yield*ba(c,a,o,m);return}yield*ba(c,a,o,m)}function*ct(c,a,o,m){yield V(o,x(a.length,{key:c,delimiter:m.delimiter}),m.indent);for(let s of a)if(_c(s)){let t=vc(s,m.delimiter);yield b(o+1,t,m.indent)}}function vc(c,a,o){let m=x(c.length,{key:o,delimiter:a}),s=ea(c,a);if(c.length===0)return m;return`${m} ${s}`}function*at(c,a,o,m,s){yield V(m,x(a.length,{key:c,fields:o,delimiter:s.delimiter}),s.indent),yield*fa(a,o,m+1,s)}function xa(c){if(c.length===0)return;let a=c[0],o=Object.keys(a);if(o.length===0)return;if(ot(c,o))return o}function ot(c,a){for(let o of c){if(Object.keys(o).length!==a.length)return!1;for(let m of a){if(!(m in o))return!1;if(!$c(o[m]))return!1}}return!0}function*fa(c,a,o,m){for(let s of c)yield V(o,ea(a.map((t)=>s[t]),m.delimiter),m.indent)}function*ba(c,a,o,m){yield V(o,x(a.length,{key:c,delimiter:m.delimiter}),m.indent);for(let s of a)yield*Ra(s,o+1,m)}function*mt(c,a,o){if(Kc(c)){yield V(a,"-",o.indent);return}let m=Object.entries(c),[s,t]=m[0],p=m.slice(1);if(rc(t)&&va(t)){let C=xa(t);if(C){if(yield b(a,x(t.length,{key:s,fields:C,delimiter:o.delimiter}),o.indent),yield*fa(t,C,a+2,o),p.length>0)yield*Rc(Object.fromEntries(p),a+1,o);return}}let w=Ec(s);if($c(t))yield b(a,`${w}: ${Pc(t,o.delimiter)}`,o.indent);else if(rc(t))if(t.length===0)yield b(a,`${w}${x(0,{delimiter:o.delimiter})}`,o.indent);else if(_c(t))yield b(a,`${w}${vc(t,o.delimiter)}`,o.indent);else{yield b(a,`${w}${x(t.length,{delimiter:o.delimiter})}`,o.indent);for(let C of t)yield*Ra(C,a+2,o)}else if(N(t)){if(yield b(a,`${w}:`,o.indent),!Kc(t))yield*Rc(t,a+2,o)}if(p.length>0)yield*Rc(Object.fromEntries(p),a+1,o)}function*Ra(c,a,o){if($c(c))yield b(a,Pc(c,o.delimiter),o.indent);else if(rc(c))if(_c(c))yield b(a,vc(c,o.delimiter),o.indent);else{yield b(a,x(c.length,{delimiter:o.delimiter}),o.indent);for(let m of c)yield*Ra(m,a+1,o)}else if(N(c))yield*mt(c,a,o)}function V(c,a,o){return" ".repeat(o*c)+a}function b(c,a,o){return V(c,"- "+a,o)}function st(c,a){let o=a("",c,[]);if(o===void 0)return Bc(c,a,[]);return Bc(e(o),a,[])}function Bc(c,a,o){if(N(c))return tt(c,a,o);if(rc(c))return pt(c,a,o);return c}function tt(c,a,o){let m={};for(let[s,t]of Object.entries(c)){let p=[...o,s],w=a(s,t,p);if(w===void 0)continue;m[s]=Bc(e(w),a,p)}return m}function pt(c,a,o){let m=[];for(let s=0;s<c.length;s++){let t=c[s],p=[...o,s],w=a(String(s),t,p);if(w===void 0)continue;let C=e(w);m.push(Bc(C,a,p))}return m}function Pa(c,a){return Array.from(rt(c,a)).join(`
3
+ `)}function rt(c,a){let o=e(c),m=wt(a);return xs(m.replacer?st(o,m.replacer):o,m,0)}function wt(c){return{indent:c?.indent??2,delimiter:c?.delimiter??kc,keyFolding:c?.keyFolding??"off",flattenDepth:c?.flattenDepth??Number.POSITIVE_INFINITY,replacer:c?.replacer}}function Ct(c){let a=c.format??"toon";if(a!=="toon"&&a!=="json")throw Error("--format debe ser toon o json.");return a}function co(c,a){if(Ct(a)==="json"){console.log(JSON.stringify(c,null,2));return}console.log(Pa(c))}function ao(c){process.stdout.write(`${c}
4
+ `)}function oo(c,a){let m={ok:!1,error:c instanceof Error?c.message:String(c)};if((a.format==="json"?"json":"toon")==="json"){console.error(JSON.stringify(m,null,2));return}console.error(Pa(m))}function D(c){process.stderr.write(c)}import{existsSync as fc,mkdirSync as $t,readFileSync as so,writeFileSync as lt,unlinkSync as jt}from"node:fs";import{join as to}from"node:path";import{homedir as Qt}from"node:os";import{AsyncLocalStorage as gt}from"node:async_hooks";var qt=new gt;function i(){return qt.getStore()}var ec={main:{local:"http://localhost:3000",develop:"https://api.bejusto.com",prod:"https://api.getjusto.com"},auth:{local:"http://localhost:4112",develop:"https://auth.service.bejusto.com",prod:"https://auth.service.getjusto.com"},webdata:{local:"http://localhost:4125",develop:"https://webdata.service.bejusto.com",prod:"https://webdatacdn.getjusto.com"},preferences:{local:"http://localhost:4120",develop:"https://preferences.service.bejusto.com",prod:"https://preferences.service.getjusto.com"},buckets:{local:"http://localhost:4106",develop:"https://buckets.service.bejusto.com",prod:"https://buckets.service.getjusto.com"},reservations:{local:"http://localhost:4113",develop:"https://reservations.service.bejusto.com",prod:"https://reservations.service.getjusto.com"},data:{local:"http://localhost:4107",develop:"https://data.service.bejusto.com",prod:"https://data.service.getjusto.com"},finances:{local:"http://localhost:4105",develop:"https://finances.service.bejusto.com",prod:"https://finances.service.getjusto.com"},"url-shortener":{local:"http://localhost:4102",develop:"https://url-shortener.service.bejusto.com",prod:"https://url-shortener.service.getjusto.com"},files:{local:"http://localhost:4108",develop:"https://files.service.bejusto.com",prod:"https://files.service.getjusto.com"},tabs:{local:"http://localhost:4115",develop:"https://tabs.service.bejusto.com",prod:"https://tabs.service.getjusto.com"},commander:{local:"http://localhost:4109",develop:"https://commander.service.bejusto.com",prod:"https://commander.service.getjusto.com"},experiments:{local:"http://localhost:4114",develop:"https://experiments.service.bejusto.com",prod:"https://experiments.service.getjusto.com"},sales:{local:"http://localhost:4117",develop:"https://sales.service.bejusto.com",prod:"https://sales.service.getjusto.com"},delivery:{local:"http://localhost:3410",develop:"https://api-delivery.bejusto.com",prod:"https://api-delivery-2.getjusto.com"},payments:{local:"http://localhost:4118",develop:"https://payments.service.bejusto.com",prod:"https://payments.service.getjusto.com"},addresses:{local:"http://localhost:4051",develop:"https://addresses.service.bejusto.com",prod:"https://addresses.service.getjusto.com"},royalty:{local:"http://localhost:4121",develop:"https://royalty.service.bejusto.com",prod:"https://royalty.service.getjusto.com"},marketing:{local:"http://localhost:4005",develop:"https://marketing.service.bejusto.com",prod:"https://marketing.service.getjusto.com"},api:{local:"http://localhost:4119",develop:"https://api.service.bejusto.com",prod:"https://api.service.getjusto.com"},messenger:{local:"http://localhost:4122",develop:"https://messenger.service.bejusto.com",prod:"https://messenger.service.getjusto.com"},invoice:{local:"http://localhost:4123",develop:"https://invoice.service.bejusto.com",prod:"https://invoice.service.getjusto.com"},"drivers-server":{local:"http://localhost:3410",develop:"https://api-delivery.bejusto.com",prod:"https://api-delivery-2.getjusto.com"}},Wa="prod";function mo(c){Wa=c}function xc(){let c=process.env.JUSTO_TEAM_CLI_ENV;if(c)return c;let a=i()?.environment;if(a)return a;return Wa}function K(c){return ec[c][Wa]}var Ga=to(Qt(),".justo-team");function po(c){let a=c==="prod"?"credentials.json":`credentials.${c}.json`;return to(Ga,a)}function Ia(){return po(xc())}function nt(){if(!fc(Ga))$t(Ga,{recursive:!0})}function ca(c){let a=i();if(a&&a.canPersistCredentials===!1)throw Error("Este entorno no permite guardar credenciales.");nt(),lt(Ia(),JSON.stringify(c,null,2))}function F(){let c=process.env.JUSTO_TEAM_CLI_TOKEN,a=process.env.JUSTO_TEAM_CLI_EMAIL,o=process.env.JUSTO_TEAM_CLI_REFRESH_TOKEN;if(c&&a)return{email:a,token:c,refreshToken:o||""};let m=i()?.credentials;if(m!==void 0)return m?{email:m.email,token:m.token,refreshToken:m.refreshToken||""}:null;let s=Ia();if(!fc(s))return null;try{let t=so(s,"utf-8");return JSON.parse(t)}catch{return null}}function ro(c){let a=po(c);if(!fc(a))return null;try{let o=so(a,"utf-8");return JSON.parse(o)}catch{return null}}function Ma(){let c=i();if(c&&c.canPersistCredentials===!1)throw Error("Este entorno no permite borrar credenciales.");let a=Ia();if(fc(a))jt(a)}import{existsSync as wo,readFileSync as Jt,writeFileSync as At,mkdirSync as Rt}from"node:fs";import{join as Co}from"node:path";import{homedir as Pt}from"node:os";function Wt(){let c=process.env.JUSTO_TEAM_CLI_DEVICE_ID;if(c)return c;let a=i()?.deviceId;if(a)return a;let o=Co(Pt(),".justo-team"),m=Co(o,"device-id");if(wo(m))return Jt(m,"utf-8").trim();let s=crypto.randomUUID();if(!wo(o))Rt(o,{recursive:!0});return At(m,s),s}var qo={required:({label:c})=>`${c} no es opcional`,notAString:({label:c})=>`${c} no es un texto`,notANumber:({label:c})=>`${c} no es un número`,notAnInteger:({label:c})=>`${c} no es un número entero`,notABoolean:({label:c})=>`${c} no es un valor verdadero o falso`,notAnEmail:({label:c})=>`${c} no es un email`,notAnId:({label:c})=>`${c} no es un ID válido`,notADate:({label:c})=>`${c} no es una fecha válida`,notAnArray:({label:c})=>`${c} no es un arreglo`,notAnObject:({label:c})=>`${c} no es un objeto`,stringTooShort:({label:c})=>`${c} no tiene el largo suficiente`,stringTooLong:"El largo es mayor al permitido",numberTooSmall:({label:c})=>`${c} es un número muy pequeño`,numberTooBig:({label:c})=>`${c} es un número muy grande`,notInSchema:({label:c})=>`${c} no esta permitido`,notUnique:({label:c})=>`${c} no es único`,notFound:({label:c})=>`${c} no se encontró`,invalid:"No es válido",rateLimitExceeded:"Has excedido el límite de intentos. Intenta de nuevo más tarde.",incorrectLoginCode:"El código es incorrecto",loginCodeExpired:"El código expiró. Solicita un nuevo",loginCodeLocked:"El código se bloqueó. Genera un nuevo código para continuar",userNotFound:"No existe una cuenta con este email"};function Gt(c,a){let o=qo[c];if(!o)return`${a}: ${c}`;if(typeof o==="function")return o({label:a});return o}function go(c){return Object.entries(c).map(([a,o])=>Gt(o,a)).join(", ")}function It(c){if(c.error==="validationError"&&c.validationErrors)return go(c.validationErrors);if(c.extensions?.code==="PermissionsError"){let s=c.extensions.info?.type;if(s?.includes("User doesn't have permissions for "))return`Tu usuario no tiene permisos para [${s.split("User doesn't have permissions for ")[1]}]`;return c.message}if(c.validationErrors)return`${c.message} (${go(c.validationErrors)})`;let a=c.message||"Error desconocido",o=qo[a];if(o)return typeof o==="function"?o({label:""}).trim():o;let m=c.error||c.code||c.type;return m?`${a} [${m}]`:a}function Mt(c){try{return JSON.parse(Buffer.from(c.split(".")[1],"base64").toString()).exp*1000<Date.now()}catch{return!0}}async function Xt(){let c=F();if(!c?.refreshToken)return null;let a=`${K("auth")}/refresh-token`,m=await(await fetch(a,{method:"POST",headers:{"X-ORION-REFRESH":c.refreshToken}})).json();if(!m.token)return null;if(i()?.canPersistCredentials!==!1)ca({...c,token:m.token});return m.token}async function aa(){let c=F();if(!c?.token)return;if(!Mt(c.token))return c.token;return await Xt()??void 0}async function Wc(c="application/json"){let a=await aa(),o={"Content-Type":c,"X-ORION-DEVICEID":Wt(),"X-ORION-PLATFORM":"web"};if(a)o["x-orion-jwt"]=a;return o}async function R(c){let a=`${K(c.service)}/graphql`,o=await Wc(),m;try{m=await fetch(a,{method:"POST",headers:o,body:JSON.stringify({query:c.query,variables:c.variables}),signal:AbortSignal.timeout(c.timeoutMs||15000)})}catch{throw Error("La solicitud tardó demasiado. Intenta de nuevo.")}let s=await m.json();if(s.errors?.length)throw Error(It(s.errors[0]));if(!s.data)throw Error("No data returned from server");return s.data}function Zt(c){return c.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,"")}function Ht(c){return c.includes(".")||c.startsWith("http://")||c.startsWith("https://")}async function Gc(c){if(Ht(c)){let a=Zt(c),o=await fetch(`${K("main")}/website-id/${a}`,{signal:AbortSignal.timeout(1e4)});if(!o.ok)throw Error(`No se encontro el sitio "${a}"`);let m=await o.json();if(!m.websiteId)throw Error(`No se pudo resolver el websiteId para "${a}"`);return{input:c,websiteId:m.websiteId,targetType:"domain"}}return{input:c,websiteId:c,targetType:"websiteId"}}async function $o(c){let a=await R({service:"main",query:`query ($websiteId: ID) {
5
5
  website(websiteId: $websiteId) {
6
6
  _id
7
7
  name
@@ -13,7 +13,7 @@ function Bc(c){let a=[],m={},o={};for(let s=0;s<c.length;s++)if(c[s].startsWith(
13
13
  timezone
14
14
  defaultMenuId
15
15
  }
16
- }`,variables:{websiteId:c}});if(!a.website)throw Error(`No se encontro el website "${c}"`);return a.website}function Ft(){if(!U())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}async function Qm(c){if(Ft(),!c)throw Error("Uso: team-cli admin <websiteId|domain> show");let a=await Ic(c),m=await $m(a.websiteId);return{context:a,website:m}}function ma(){return`team-cli admin
16
+ }`,variables:{websiteId:c}});if(!a.website)throw Error(`No se encontro el website "${c}"`);return a.website}function Yt(){if(!F())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}async function lo(c){if(Yt(),!c)throw Error("Uso: team-cli admin <websiteId|domain> show");let a=await Gc(c),o=await $o(a.websiteId);return{context:a,website:o}}function oa(){return`team-cli admin
17
17
 
18
18
  Comandos administrativos con contexto de website.
19
19
 
@@ -35,7 +35,7 @@ Modulos:
35
35
 
36
36
  coupons
37
37
  Administrar cupones y sus códigos.
38
- Uso: team-cli admin <websiteId|domain> coupons <accion> [opciones]`}var jm=`
38
+ Uso: team-cli admin <websiteId|domain> coupons <accion> [opciones]`}var jo=`
39
39
  availableAtPeriods
40
40
  closedDays
41
41
  closedUntilDate
@@ -51,7 +51,7 @@ Modulos:
51
51
  fromMinute
52
52
  toMinute
53
53
  }
54
- `,oa=`
54
+ `,ma=`
55
55
  _id
56
56
  websiteId
57
57
  name
@@ -86,13 +86,13 @@ Modulos:
86
86
  requiredBINs
87
87
  extraRequirementsForPaymentTypes
88
88
  schedule {
89
- ${jm}
89
+ ${jo}
90
90
  }
91
91
  scheduleAtUse {
92
- ${jm}
92
+ ${jo}
93
93
  }
94
94
  codesCode
95
- `,Jm=`
95
+ `,Qo=`
96
96
  _id
97
97
  code
98
98
  couponId
@@ -101,28 +101,28 @@ Modulos:
101
101
  sentToEmail
102
102
  totalRedemptions
103
103
  createdAt
104
- `;function Ma(){if(!U())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function Xc(c,a){let m=c[a];if(!m)throw Error(`--${a} es requerido.`);try{return JSON.parse(m)}catch{throw Error(`--${a} debe ser un JSON válido.`)}}function b(c,a){let m=c[a];if(!m)return;let o=Number.parseInt(m,10);if(Number.isNaN(o))throw Error(`--${a} debe ser un número entero.`);return o}function Am(c,a){let m=c[a];if(!m)return;if(m==="true")return!0;if(m==="false")return!1;throw Error(`--${a} debe ser true o false.`)}async function d(c){if(Ma(),!c)throw Error("Debes indicar <websiteId|domain>.");return Ic(c)}async function f(c,a){let m=await l({service:"main",query:`query ($couponId: ID) {
104
+ `;function Xa(){if(!F())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function Ic(c,a){let o=c[a];if(!o)throw Error(`--${a} es requerido.`);try{return JSON.parse(o)}catch{throw Error(`--${a} debe ser un JSON válido.`)}}function B(c,a){let o=c[a];if(!o)return;let m=Number.parseInt(o,10);if(Number.isNaN(m))throw Error(`--${a} debe ser un número entero.`);return m}function no(c,a){let o=c[a];if(!o)return;if(o==="true")return!0;if(o==="false")return!1;throw Error(`--${a} debe ser true o false.`)}async function d(c){if(Xa(),!c)throw Error("Debes indicar <websiteId|domain>.");return Gc(c)}async function f(c,a){let o=await R({service:"main",query:`query ($couponId: ID) {
105
105
  coupon(couponId: $couponId) {
106
106
  _id
107
107
  websiteId
108
108
  }
109
- }`,variables:{couponId:c}});if(!m.coupon)throw Error(`No se encontró el cupón "${c}"`);if(m.coupon.websiteId!==a)throw Error(`El cupón "${c}" no pertenece al website seleccionado.`);return m.coupon}function Ut(c){if(!Array.isArray(c))throw Error("--input debe ser un arreglo JSON.");return c.map((a)=>{if(!a||typeof a!=="object"||typeof a.code!=="string")throw Error('Cada item de --input debe tener al menos { "code": "..." }.');if(a.userEmail!=null&&typeof a.userEmail!=="string")throw Error("userEmail debe ser string cuando viene informado.");return{code:a.code,userEmail:a.userEmail}})}function Tt(c){if(!Array.isArray(c)||c.some((a)=>typeof a!=="string"))throw Error("--ids debe ser un arreglo JSON de strings.");return c}async function Pm(c,a,m){let o=await d(c);await f(a,o.websiteId);let s=b(m,"limit"),t=b(m,"page"),w=m.filter,r=await l({service:"main",query:`query ($couponId: ID, $filter: String, $limit: BigInt, $page: BigInt) {
109
+ }`,variables:{couponId:c}});if(!o.coupon)throw Error(`No se encontró el cupón "${c}"`);if(o.coupon.websiteId!==a)throw Error(`El cupón "${c}" no pertenece al website seleccionado.`);return o.coupon}function Ft(c){if(!Array.isArray(c))throw Error("--input debe ser un arreglo JSON.");return c.map((a)=>{if(!a||typeof a!=="object"||typeof a.code!=="string")throw Error('Cada item de --input debe tener al menos { "code": "..." }.');if(a.userEmail!=null&&typeof a.userEmail!=="string")throw Error("userEmail debe ser string cuando viene informado.");return{code:a.code,userEmail:a.userEmail}})}function Ut(c){if(!Array.isArray(c)||c.some((a)=>typeof a!=="string"))throw Error("--ids debe ser un arreglo JSON de strings.");return c}async function Jo(c,a,o){let m=await d(c);await f(a,m.websiteId);let s=B(o,"limit"),t=B(o,"page"),p=o.filter,w=await R({service:"main",query:`query ($couponId: ID, $filter: String, $limit: BigInt, $page: BigInt) {
110
110
  couponCodes(couponId: $couponId, filter: $filter, limit: $limit, page: $page) {
111
111
  items {
112
- ${Jm}
112
+ ${Qo}
113
113
  }
114
114
  totalCount
115
115
  totalPages
116
116
  hasNextPage
117
117
  hasPreviousPage
118
118
  }
119
- }`,variables:{couponId:a,filter:w,limit:s,page:t}});return{context:o,couponId:a,codes:r.couponCodes.items??[],pagination:{totalCount:r.couponCodes.totalCount??0,totalPages:r.couponCodes.totalPages??0,hasNextPage:Boolean(r.couponCodes.hasNextPage),hasPreviousPage:Boolean(r.couponCodes.hasPreviousPage),page:t??1,limit:s??null}}}async function Rm(c,a,m){let o=await d(c);await f(a,o.websiteId);let s=Ut(Xc(m,"input")),t=s.some((r)=>r.userEmail),w=await l({service:"main",query:`mutation ($couponId: ID, $codesWithEmail: [CodeWithEmailInput], $useCodeWithEmail: Boolean) {
119
+ }`,variables:{couponId:a,filter:p,limit:s,page:t}});return{context:m,couponId:a,codes:w.couponCodes.items??[],pagination:{totalCount:w.couponCodes.totalCount??0,totalPages:w.couponCodes.totalPages??0,hasNextPage:Boolean(w.couponCodes.hasNextPage),hasPreviousPage:Boolean(w.couponCodes.hasPreviousPage),page:t??1,limit:s??null}}}async function Ao(c,a,o){let m=await d(c);await f(a,m.websiteId);let s=Ft(Ic(o,"input")),t=s.some((w)=>w.userEmail),p=await R({service:"main",query:`mutation ($couponId: ID, $codesWithEmail: [CodeWithEmailInput], $useCodeWithEmail: Boolean) {
120
120
  createCouponCodes(couponId: $couponId, codesWithEmail: $codesWithEmail, useCodeWithEmail: $useCodeWithEmail)
121
- }`,variables:{couponId:a,codesWithEmail:s,useCodeWithEmail:t}});return{context:o,couponId:a,requestedCount:s.length,result:w.createCouponCodes}}async function lm(c,a,m){let o=await d(c);await f(a,o.websiteId);let s=b(m,"quantity");if(!s)throw Error("--quantity es requerido.");let t=await l({service:"main",query:`mutation ($couponId: ID, $couponQuantity: Float, $couponCodePrefix: String) {
121
+ }`,variables:{couponId:a,codesWithEmail:s,useCodeWithEmail:t}});return{context:m,couponId:a,requestedCount:s.length,result:p.createCouponCodes}}async function Ro(c,a,o){let m=await d(c);await f(a,m.websiteId);let s=B(o,"quantity");if(!s)throw Error("--quantity es requerido.");let t=await R({service:"main",query:`mutation ($couponId: ID, $couponQuantity: Float, $couponCodePrefix: String) {
122
122
  createRandomCouponCodes(couponId: $couponId, couponQuantity: $couponQuantity, couponCodePrefix: $couponCodePrefix)
123
- }`,variables:{couponId:a,couponQuantity:s,couponCodePrefix:m.prefix}});return{context:o,couponId:a,quantity:s,prefix:m.prefix??null,result:t.createRandomCouponCodes}}async function Wm(c,a,m){let o=await d(c);await f(a,o.websiteId);let s=Tt(Xc(m,"ids")),t=await l({service:"main",query:`mutation ($couponId: ID, $couponCodesIds: [ID]) {
123
+ }`,variables:{couponId:a,couponQuantity:s,couponCodePrefix:o.prefix}});return{context:m,couponId:a,quantity:s,prefix:o.prefix??null,result:t.createRandomCouponCodes}}async function Po(c,a,o){let m=await d(c);await f(a,m.websiteId);let s=Ut(Ic(o,"ids")),t=await R({service:"main",query:`mutation ($couponId: ID, $couponCodesIds: [ID]) {
124
124
  deleteCouponCodes(couponId: $couponId, couponCodesIds: $couponCodesIds, globalCoupon: false)
125
- }`,variables:{couponId:a,couponCodesIds:s}});return{context:o,couponId:a,deleted:t.deleteCouponCodes,couponCodesIds:s}}function Gm(){return`team-cli admin coupons codes create
125
+ }`,variables:{couponId:a,couponCodesIds:s}});return{context:m,couponId:a,deleted:t.deleteCouponCodes,couponCodesIds:s}}function Wo(){return`team-cli admin coupons codes create
126
126
 
127
127
  Crea códigos explícitos para un cupón.
128
128
 
@@ -145,11 +145,11 @@ Ejemplo:
145
145
 
146
146
  Notas:
147
147
  Si algún item trae userEmail, team-cli activa useCodeWithEmail automáticamente.
148
- couponId se valida contra el website seleccionado antes de ejecutar la mutation.`}var Im={active:"Boolean",allowedEmails:"[String]",applyDeliveryDiscount:"Boolean",code:"ID",deliveryDiscountPercentage:"Float",deliveryDiscountType:"String",deliveryDiscountValue:"Float",description:"String",discountAmount:"Float",dontApplyToProductsIds:"[ID]",endDate:"Date",externalId:"String",extraRequirementsForPaymentTypes:"JSON",fixedAmount:"Float",fromDate:"Date",isBirthdayCoupon:"Boolean",isHidden:"Boolean",maxPercentageOffDiscount:"Float",maxProductsPerOrder:"Float",maxRedemptions:"Float",maxRedemptionsPerUser:"Float",maxRedemptionsPerUserPerDay:"Boolean",maximumOrderPrice:"Float",minimumOrderPrice:"Float",name:"String",onlyForNewUsers:"Boolean",onlyForProductsWithoutDiscount:"Boolean",onlyRedeemOnBirthday:"Boolean",percentageOff:"Float",requireChannels:"[ID]",requirePhoneVerification:"Boolean",requiredBINs:"[String]",requiresCategoriesIds:"[ID]",requiresMenusIds:"[ID]",requiresPaymentTypes:"[ID]",requiresProductsIds:"[ID]",requiresStoresIds:"[ID]",schedule:"ScheduleInput",scheduleAtUse:"ScheduleInput",type:"ID",websiteId:"ID"};function nt(c){let a=Object.entries(c).filter(([,t])=>t!==void 0),m=a.map(([t])=>t).filter((t)=>!Im[t]);if(m.length)throw Error(`Campos no soportados para create: ${m.join(", ")}`);let o=a.map(([t])=>`$${t}: ${Im[t]}`).join(", "),s=a.map(([t])=>`${t}: $${t}`).join(", ");return`mutation (${o}) {
148
+ couponId se valida contra el website seleccionado antes de ejecutar la mutation.`}var Go={active:"Boolean",allowedEmails:"[String]",applyDeliveryDiscount:"Boolean",code:"ID",deliveryDiscountPercentage:"Float",deliveryDiscountType:"String",deliveryDiscountValue:"Float",description:"String",discountAmount:"Float",dontApplyToProductsIds:"[ID]",endDate:"Date",externalId:"String",extraRequirementsForPaymentTypes:"JSON",fixedAmount:"Float",fromDate:"Date",isBirthdayCoupon:"Boolean",isHidden:"Boolean",maxPercentageOffDiscount:"Float",maxProductsPerOrder:"Float",maxRedemptions:"Float",maxRedemptionsPerUser:"Float",maxRedemptionsPerUserPerDay:"Boolean",maximumOrderPrice:"Float",minimumOrderPrice:"Float",name:"String",onlyForNewUsers:"Boolean",onlyForProductsWithoutDiscount:"Boolean",onlyRedeemOnBirthday:"Boolean",percentageOff:"Float",requireChannels:"[ID]",requirePhoneVerification:"Boolean",requiredBINs:"[String]",requiresCategoriesIds:"[ID]",requiresMenusIds:"[ID]",requiresPaymentTypes:"[ID]",requiresProductsIds:"[ID]",requiresStoresIds:"[ID]",schedule:"ScheduleInput",scheduleAtUse:"ScheduleInput",type:"ID",websiteId:"ID"};function Tt(c){let a=Object.entries(c).filter(([,t])=>t!==void 0),o=a.map(([t])=>t).filter((t)=>!Go[t]);if(o.length)throw Error(`Campos no soportados para create: ${o.join(", ")}`);let m=a.map(([t])=>`$${t}: ${Go[t]}`).join(", "),s=a.map(([t])=>`${t}: $${t}`).join(", ");return`mutation (${m}) {
149
149
  createCoupon(${s}) {
150
- ${oa}
150
+ ${ma}
151
151
  }
152
- }`}async function Xm(c,a){let m=await d(c),o=b(a,"limit"),s=b(a,"page"),t=a.filter,w=await l({service:"main",query:`query ($websiteId: ID, $filter: String, $limit: BigInt, $page: BigInt) {
152
+ }`}async function Io(c,a){let o=await d(c),m=B(a,"limit"),s=B(a,"page"),t=a.filter,p=await R({service:"main",query:`query ($websiteId: ID, $filter: String, $limit: BigInt, $page: BigInt) {
153
153
  coupons(websiteId: $websiteId, filter: $filter, limit: $limit, page: $page) {
154
154
  items {
155
155
  _id
@@ -169,17 +169,17 @@ Notas:
169
169
  hasNextPage
170
170
  hasPreviousPage
171
171
  }
172
- }`,variables:{websiteId:m.websiteId,filter:t,limit:o,page:s}});return{context:m,coupons:w.coupons.items??[],pagination:{totalCount:w.coupons.totalCount??0,totalPages:w.coupons.totalPages??0,hasNextPage:Boolean(w.coupons.hasNextPage),hasPreviousPage:Boolean(w.coupons.hasPreviousPage),page:s??1,limit:o??null}}}async function Zm(c,a){let m=await d(c);await f(a,m.websiteId);let o=await l({service:"main",query:`query ($couponId: ID) {
172
+ }`,variables:{websiteId:o.websiteId,filter:t,limit:m,page:s}});return{context:o,coupons:p.coupons.items??[],pagination:{totalCount:p.coupons.totalCount??0,totalPages:p.coupons.totalPages??0,hasNextPage:Boolean(p.coupons.hasNextPage),hasPreviousPage:Boolean(p.coupons.hasPreviousPage),page:s??1,limit:m??null}}}async function Mo(c,a){let o=await d(c);await f(a,o.websiteId);let m=await R({service:"main",query:`query ($couponId: ID) {
173
173
  coupon(couponId: $couponId) {
174
- ${oa}
174
+ ${ma}
175
175
  }
176
- }`,variables:{couponId:a}});return{context:m,coupon:o.coupon}}async function Mm(c,a){let m=await d(c),o=Xc(a,"input");if(o.websiteId&&o.websiteId!==m.websiteId)throw Error("El websiteId del input no coincide con el website seleccionado.");let s={...o,websiteId:m.websiteId},t=nt(s),w=await l({service:"main",query:t,variables:s});return{context:m,coupon:w.createCoupon}}async function Hm(c,a,m){let o=await d(c);await f(a,o.websiteId);let s=Xc(m,"input"),t=await l({service:"main",query:`mutation ($couponId: ID, $coupon: UpdateCouponInput) {
176
+ }`,variables:{couponId:a}});return{context:o,coupon:m.coupon}}async function Xo(c,a){let o=await d(c),m=Ic(a,"input");if(m.websiteId&&m.websiteId!==o.websiteId)throw Error("El websiteId del input no coincide con el website seleccionado.");let s={...m,websiteId:o.websiteId},t=Tt(s),p=await R({service:"main",query:t,variables:s});return{context:o,coupon:p.createCoupon}}async function Zo(c,a,o){let m=await d(c);await f(a,m.websiteId);let s=Ic(o,"input"),t=await R({service:"main",query:`mutation ($couponId: ID, $coupon: UpdateCouponInput) {
177
177
  updateCoupon(couponId: $couponId, coupon: $coupon) {
178
- ${oa}
178
+ ${ma}
179
179
  }
180
- }`,variables:{couponId:a,coupon:s}});return{context:o,coupon:t.updateCoupon}}async function Ym(c,a){let m=await d(c);await f(a,m.websiteId);let o=await l({service:"main",query:`mutation ($couponsIds: [ID]) {
180
+ }`,variables:{couponId:a,coupon:s}});return{context:m,coupon:t.updateCoupon}}async function Ho(c,a){let o=await d(c);await f(a,o.websiteId);let m=await R({service:"main",query:`mutation ($couponsIds: [ID]) {
181
181
  deleteCoupons(couponsIds: $couponsIds, globalCoupon: false)
182
- }`,variables:{couponsIds:[a]}});return{context:m,couponId:a,deleted:o.deleteCoupons}}function Vc(){return`team-cli admin coupons
182
+ }`,variables:{couponsIds:[a]}});return{context:o,couponId:a,deleted:m.deleteCoupons}}function Vc(){return`team-cli admin coupons
183
183
 
184
184
  Administracion de cupones para el website seleccionado.
185
185
 
@@ -227,7 +227,7 @@ Acciones:
227
227
  Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1","id2"]'
228
228
 
229
229
  Nota:
230
- El schema actual no expone update para coupon codes.`}function Fm(){return`team-cli admin coupons create
230
+ El schema actual no expone update para coupon codes.`}function Yo(){return`team-cli admin coupons create
231
231
 
232
232
  Crea un cupón para el website seleccionado.
233
233
 
@@ -276,7 +276,7 @@ Ejemplo con schedule:
276
276
  Tips:
277
277
  Usa comillas simples afuera del JSON en shell.
278
278
  Usa arrays JSON reales para ids o listas.
279
- Si necesitas el shape exacto de un cupón existente, parte con: team-cli admin <web> coupons show <couponId>`}function Um(){return`team-cli admin coupons update
279
+ Si necesitas el shape exacto de un cupón existente, parte con: team-cli admin <web> coupons show <couponId>`}function Fo(){return`team-cli admin coupons update
280
280
 
281
281
  Actualiza un cupón existente.
282
282
 
@@ -318,7 +318,7 @@ Ejemplo reemplazando restricciones:
318
318
  team-cli admin <web> coupons update <couponId> --input '{"requiresStoresIds":["store1"],"requiresPaymentTypes":["card"]}'
319
319
 
320
320
  Tip:
321
- Primero mira el cupón actual con: team-cli admin <web> coupons show <couponId>`}async function Tm(c,a){Ma();let m=c[2]??a.filter;if(!m)throw Error("Debes indicar un término de búsqueda. Uso: team-cli admin search <texto>");let o=b(a,"limit"),s=b(a,"page"),t=Am(a,"only-active"),w=await l({service:"main",query:`query ($filter: String, $limit: BigInt, $page: BigInt, $onlyActiveWebsites: Boolean) {
321
+ Primero mira el cupón actual con: team-cli admin <web> coupons show <couponId>`}async function Uo(c,a){Xa();let o=c[2]??a.filter;if(!o)throw Error("Debes indicar un término de búsqueda. Uso: team-cli admin search <texto>");let m=B(a,"limit"),s=B(a,"page"),t=no(a,"only-active"),p=await R({service:"main",query:`query ($filter: String, $limit: BigInt, $page: BigInt, $onlyActiveWebsites: Boolean) {
322
322
  websites(filter: $filter, limit: $limit, page: $page, onlyActiveWebsites: $onlyActiveWebsites) {
323
323
  items {
324
324
  _id
@@ -334,7 +334,7 @@ Tip:
334
334
  hasNextPage
335
335
  hasPreviousPage
336
336
  }
337
- }`,variables:{filter:m,limit:o,page:s,onlyActiveWebsites:t}});return{searchTerm:m,websites:w.websites.items??[],pagination:{totalCount:w.websites.totalCount??0,totalPages:w.websites.totalPages??0,hasNextPage:Boolean(w.websites.hasNextPage),hasPreviousPage:Boolean(w.websites.hasPreviousPage),page:s??1,limit:o??null}}}function nm(){return`team-cli admin search
337
+ }`,variables:{filter:o,limit:m,page:s,onlyActiveWebsites:t}});return{searchTerm:o,websites:p.websites.items??[],pagination:{totalCount:p.websites.totalCount??0,totalPages:p.websites.totalPages??0,hasNextPage:Boolean(p.websites.hasNextPage),hasPreviousPage:Boolean(p.websites.hasPreviousPage),page:s??1,limit:m??null}}}function To(){return`team-cli admin search
338
338
 
339
339
  Buscar websites en admin.
340
340
 
@@ -354,7 +354,7 @@ Opciones:
354
354
  Ejemplos:
355
355
  team-cli admin search milas
356
356
  team-cli admin search buffalo --limit 5
357
- team-cli admin search pizza --only-active true`}function ht(){if(!U())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function Kt(c){let a=[c.address?.streetAddress,c.address?.extendedAddress,c.address?.locality].filter(Boolean);if(!a.length)return null;return a.join(", ")}async function hm(c){if(ht(),!c)throw Error("Uso: team-cli admin <websiteId|domain> stores list");let a=await Ic(c),o=((await l({service:"main",query:`query ($websiteId: ID) {
357
+ team-cli admin search pizza --only-active true`}function ht(){if(!F())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function Kt(c){let a=[c.address?.streetAddress,c.address?.extendedAddress,c.address?.locality].filter(Boolean);if(!a.length)return null;return a.join(", ")}async function ho(c){if(ht(),!c)throw Error("Uso: team-cli admin <websiteId|domain> stores list");let a=await Gc(c),m=((await R({service:"main",query:`query ($websiteId: ID) {
358
358
  stores(websiteId: $websiteId) {
359
359
  items {
360
360
  _id
@@ -366,17 +366,17 @@ Ejemplos:
366
366
  }
367
367
  }
368
368
  }
369
- }`,variables:{websiteId:a.websiteId}})).stores.items??[]).map((s)=>({_id:s._id,name:s.name,address:Kt(s)})).sort((s,t)=>s.name.localeCompare(t.name,"es",{sensitivity:"base"}));return{context:a,stores:o,totalCount:o.length}}import{createInterface as _t}from"node:readline";function Zc(c){if(process.env.JUSTO_TEAM_CLI_INTERACTIVE==="false")throw Error("Este entorno no soporta prompts interactivos.");if(O()?.interactive===!1)throw Error("Este entorno no soporta prompts interactivos.");let a=_t({input:process.stdin,output:process.stderr});return new Promise((m)=>{a.question(c,(o)=>{a.close(),m(o.trim())})})}async function Km(c){return(await l({service:"auth",query:`mutation ($email: String!) {
369
+ }`,variables:{websiteId:a.websiteId}})).stores.items??[]).map((s)=>({_id:s._id,name:s.name,address:Kt(s)})).sort((s,t)=>s.name.localeCompare(t.name,"es",{sensitivity:"base"}));return{context:a,stores:m,totalCount:m.length}}import{createInterface as _t}from"node:readline";function Mc(c){if(process.env.JUSTO_TEAM_CLI_INTERACTIVE==="false")throw Error("Este entorno no soporta prompts interactivos.");if(i()?.interactive===!1)throw Error("Este entorno no soporta prompts interactivos.");let a=_t({input:process.stdin,output:process.stderr});return new Promise((o)=>{a.question(c,(m)=>{a.close(),o(m.trim())})})}async function Ko(c){return(await R({service:"auth",query:`mutation ($email: String!) {
370
370
  requestLoginCode(email: $email)
371
- }`,variables:{email:c}})).requestLoginCode}async function _m(c,a,m){let o=await l({service:"auth",query:`mutation ($email: String!, $token: String!, $code: String!) {
371
+ }`,variables:{email:c}})).requestLoginCode}async function _o(c,a,o){let m=await R({service:"auth",query:`mutation ($email: String!, $token: String!, $code: String!) {
372
372
  loginWithCode(email: $email, token: $token, code: $code) {
373
373
  token
374
374
  refreshToken
375
375
  }
376
- }`,variables:{email:c,token:a,code:m.toUpperCase()}});ca({email:c,token:o.loginWithCode.token,refreshToken:o.loginWithCode.refreshToken}),await Et()}async function Et(){if(!(await l({service:"main",query:"query { me { roles } }"})).me?.roles?.length)throw Za(),Error("Solo miembros del equipo Justo pueden usar esta herramienta.")}async function Em(){let c=await Zc("Email: ");D(`Enviando codigo de verificacion...
377
- `);let a=await Km(c);D(`Codigo enviado a tu email.
378
- `);let m=await Zc("Codigo: ");return await _m(c,a,m),{ok:!0,authenticated:!0,email:c}}async function km(c){let a=hc(c,"email"),m=hc(c,"token"),o=hc(c,"code");return await _m(a,m,o),{ok:!0,authenticated:!0,email:a}}async function Vm(c){let a=hc(c,"email");D(`Enviando codigo de verificacion...
379
- `);let m=await Km(a);return{ok:!0,email:a,token:m,nextCommand:`npx @getjusto/team-cli auth login-with-token --email ${a} --token ${m} --code <CODIGO>`}}async function Dm(){return Za(),{ok:!0,authenticated:!1}}async function zm(){let c=U();if(!c)return{authenticated:!1,loginCommand:"npx @getjusto/team-cli auth request-code --email <email>",nextCommand:"npx @getjusto/team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>"};return{authenticated:!0,email:c.email}}function Ha(){return`team-cli auth
376
+ }`,variables:{email:c,token:a,code:o.toUpperCase()}});ca({email:c,token:m.loginWithCode.token,refreshToken:m.loginWithCode.refreshToken}),await Et()}async function Et(){if(!(await R({service:"main",query:"query { me { roles } }"})).me?.roles?.length)throw Ma(),Error("Solo miembros del equipo Justo pueden usar esta herramienta.")}async function Eo(){let c=await Mc("Email: ");D(`Enviando codigo de verificacion...
377
+ `);let a=await Ko(c);D(`Codigo enviado a tu email.
378
+ `);let o=await Mc("Codigo: ");return await _o(c,a,o),{ok:!0,authenticated:!0,email:c}}async function ko(c){let a=hc(c,"email"),o=hc(c,"token"),m=hc(c,"code");return await _o(a,o,m),{ok:!0,authenticated:!0,email:a}}async function Vo(c){let a=hc(c,"email");D(`Enviando codigo de verificacion...
379
+ `);let o=await Ko(a);return{ok:!0,email:a,token:o,nextCommand:`npx @getjusto/team-cli auth login-with-token --email ${a} --token ${o} --code <CODIGO>`}}async function Do(){return Ma(),{ok:!0,authenticated:!1}}async function zo(){let c=F();if(!c)return{authenticated:!1,loginCommand:"npx @getjusto/team-cli auth request-code --email <email>",nextCommand:"npx @getjusto/team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>"};return{authenticated:!0,email:c.email}}function Za(){return`team-cli auth
380
380
 
381
381
  Gestion de sesion.
382
382
 
@@ -402,8 +402,8 @@ Subcomandos:
402
402
 
403
403
  login-with-token
404
404
  Iniciar sesion sin prompts. Recomendado para agentes.
405
- Uso: team-cli auth login-with-token --email <email> --token <token> --code <codigo>`}import{writeFileSync as Ot}from"node:fs";import{mkdtempSync as kt,readFileSync as Vt,rmSync as Dt,writeFileSync as zt}from"node:fs";import{tmpdir as yt}from"node:os";import{join as ym}from"node:path";import{spawnSync as St}from"node:child_process";function Lt(c){return`'${c.replaceAll("'",`'"'"'`)}'`}function Sm(c,a){if(c==null)return;if(!Array.isArray(c)||c.some((m)=>typeof m!=="string"))throw Error(`${a} debe ser un arreglo de strings.`);return c}function Nt(c){if(!Array.isArray(c))throw Error("variables debe ser un arreglo.");return c.map((a,m)=>{if(!a||typeof a!=="object"||Array.isArray(a))throw Error(`variables[${m}] debe ser un objeto.`);let o=a;if(typeof o.key!=="string"||!o.key)throw Error(`variables[${m}].key debe ser un string no vacío.`);if(typeof o.fieldType!=="string"||!o.fieldType)throw Error(`variables[${m}].fieldType debe ser un string no vacío.`);if(o.fieldParams!=null&&typeof o.fieldParams!=="string")throw Error(`variables[${m}].fieldParams debe ser un string.`);return{key:o.key,fieldType:o.fieldType,fieldParams:typeof o.fieldParams==="string"?o.fieldParams:void 0}})}function ut(c){if(!c||typeof c!=="object"||Array.isArray(c))throw Error("El archivo editado debe contener un objeto JSON.");let a=c;if(typeof a.name!=="string"||!a.name.trim())throw Error("name debe ser un string no vacío.");if(a.description!=null&&typeof a.description!=="string")throw Error("description debe ser un string.");if(typeof a.collection!=="string"||!a.collection.trim())throw Error("collection debe ser un string no vacío.");if(typeof a.pipeline!=="string")throw Error("pipeline debe ser un string.");return{name:a.name.trim(),description:a.description?.trim()||void 0,collection:a.collection.trim(),allowedUsersIds:Sm(a.allowedUsersIds,"allowedUsersIds")??[],tags:Sm(a.tags,"tags")??[],pipeline:a.pipeline,variables:Nt(a.variables)}}function Lm(c){let a=process.env.VISUAL||process.env.EDITOR||"vi",m=kt(ym(yt(),"team-cli-query-")),o=ym(m,"aggregation-query.json");zt(o,`${JSON.stringify(c,null,2)}
406
- `);let s=`${a} ${Lt(o)}`,t=St(s,{shell:!0,stdio:"inherit"});if(t.error)throw Error(`No se pudo abrir el editor "${a}": ${t.error.message}`);if(t.status!==0)throw Error(`El editor terminó con código ${t.status}.`);try{let w=Vt(o,"utf-8");if(!w.trim())throw Error("El archivo quedó vacío.");let r;try{r=JSON.parse(w)}catch{throw Error("El archivo editado no contiene JSON válido.")}return ut(r)}finally{Dt(m,{recursive:!0,force:!0})}}function L(){if(!U())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function cc(c,a){let m=c[3];if(!m)throw Error(`Uso: ${a}`);return m}function Mc(c){if(!c.params)return{};try{return JSON.parse(c.params)}catch{throw Error("--params debe ser un JSON válido.")}}function Ya(c){let a=c.limit;if(!a)throw Error("--limit es requerido. Ejemplo: --limit 1000");let m=Number(a);if(!Number.isInteger(m)||m<=0)throw Error("--limit debe ser un entero positivo.");return m}function Nm(c){let a=c.emails;if(!a)throw Error("--emails es requerido. Ejemplo: --emails ana@justo.com,bob@justo.com");let m=a.split(",").map((s)=>s.trim().toLowerCase()).filter(Boolean);if(!m.length)throw Error("--emails debe contener al menos un email.");let o=m.find((s)=>!s.includes("@"));if(o)throw Error(`Email inválido: ${o}`);return[...new Set(m)]}function Fa(c){if(typeof c!=="string")return c;try{return JSON.parse(c)}catch{return{value:c}}}async function Hc(c){return(await l({service:"data",query:`query ($aggregationQueryId: String) {
405
+ Uso: team-cli auth login-with-token --email <email> --token <token> --code <codigo>`}import{writeFileSync as it}from"node:fs";import{mkdtempSync as kt,readFileSync as Vt,rmSync as Dt,writeFileSync as zt}from"node:fs";import{tmpdir as yt}from"node:os";import{join as yo}from"node:path";import{spawnSync as St}from"node:child_process";function ut(c){return`'${c.replaceAll("'",`'"'"'`)}'`}function So(c,a){if(c==null)return;if(!Array.isArray(c)||c.some((o)=>typeof o!=="string"))throw Error(`${a} debe ser un arreglo de strings.`);return c}function Lt(c){if(!Array.isArray(c))throw Error("variables debe ser un arreglo.");return c.map((a,o)=>{if(!a||typeof a!=="object"||Array.isArray(a))throw Error(`variables[${o}] debe ser un objeto.`);let m=a;if(typeof m.key!=="string"||!m.key)throw Error(`variables[${o}].key debe ser un string no vacío.`);if(typeof m.fieldType!=="string"||!m.fieldType)throw Error(`variables[${o}].fieldType debe ser un string no vacío.`);if(m.fieldParams!=null&&typeof m.fieldParams!=="string")throw Error(`variables[${o}].fieldParams debe ser un string.`);return{key:m.key,fieldType:m.fieldType,fieldParams:typeof m.fieldParams==="string"?m.fieldParams:void 0}})}function Nt(c){if(!c||typeof c!=="object"||Array.isArray(c))throw Error("El archivo editado debe contener un objeto JSON.");let a=c;if(typeof a.name!=="string"||!a.name.trim())throw Error("name debe ser un string no vacío.");if(a.description!=null&&typeof a.description!=="string")throw Error("description debe ser un string.");if(typeof a.collection!=="string"||!a.collection.trim())throw Error("collection debe ser un string no vacío.");if(typeof a.pipeline!=="string")throw Error("pipeline debe ser un string.");return{name:a.name.trim(),description:a.description?.trim()||void 0,collection:a.collection.trim(),allowedUsersIds:So(a.allowedUsersIds,"allowedUsersIds")??[],tags:So(a.tags,"tags")??[],pipeline:a.pipeline,variables:Lt(a.variables)}}function uo(c){let a=process.env.VISUAL||process.env.EDITOR||"vi",o=kt(yo(yt(),"team-cli-query-")),m=yo(o,"aggregation-query.json");zt(m,`${JSON.stringify(c,null,2)}
406
+ `);let s=`${a} ${ut(m)}`,t=St(s,{shell:!0,stdio:"inherit"});if(t.error)throw Error(`No se pudo abrir el editor "${a}": ${t.error.message}`);if(t.status!==0)throw Error(`El editor terminó con código ${t.status}.`);try{let p=Vt(m,"utf-8");if(!p.trim())throw Error("El archivo quedó vacío.");let w;try{w=JSON.parse(p)}catch{throw Error("El archivo editado no contiene JSON válido.")}return Nt(w)}finally{Dt(o,{recursive:!0,force:!0})}}function u(){if(!F())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function cc(c,a){let o=c[3];if(!o)throw Error(`Uso: ${a}`);return o}function Xc(c){if(!c.params)return{};try{return JSON.parse(c.params)}catch{throw Error("--params debe ser un JSON válido.")}}function Ha(c){let a=c.limit;if(!a)throw Error("--limit es requerido. Ejemplo: --limit 1000");let o=Number(a);if(!Number.isInteger(o)||o<=0)throw Error("--limit debe ser un entero positivo.");return o}function Lo(c){let a=c.emails;if(!a)throw Error("--emails es requerido. Ejemplo: --emails ana@justo.com,bob@justo.com");let o=a.split(",").map((s)=>s.trim().toLowerCase()).filter(Boolean);if(!o.length)throw Error("--emails debe contener al menos un email.");let m=o.find((s)=>!s.includes("@"));if(m)throw Error(`Email inválido: ${m}`);return[...new Set(o)]}function Ya(c){if(typeof c!=="string")return c;try{return JSON.parse(c)}catch{return{value:c}}}async function Zc(c){return(await R({service:"data",query:`query ($aggregationQueryId: String) {
407
407
  aggregationQuery(aggregationQueryId: $aggregationQueryId) {
408
408
  _id
409
409
  name
@@ -419,7 +419,7 @@ Subcomandos:
419
419
  fieldParams
420
420
  }
421
421
  }
422
- }`,variables:{aggregationQueryId:c}})).aggregationQuery}async function um(c){return await Promise.all(c.map(async(m)=>{let s=(await l({service:"main",query:`query ($filter: String, $limit: BigInt) {
422
+ }`,variables:{aggregationQueryId:c}})).aggregationQuery}async function No(c){return await Promise.all(c.map(async(o)=>{let s=(await R({service:"main",query:`query ($filter: String, $limit: BigInt) {
423
423
  justoUsers(filter: $filter, limit: $limit) {
424
424
  items {
425
425
  _id
@@ -427,11 +427,11 @@ Subcomandos:
427
427
  fullName
428
428
  }
429
429
  }
430
- }`,variables:{filter:m,limit:10}})).justoUsers?.items?.find((t)=>t.email?.toLowerCase()===m);if(!s?._id)throw Error(`No encontramos un usuario de Justo para ${m}`);return s}))}function Om(c){return{name:c.name,description:c.description,collection:c.collection,allowedUsersIds:c.allowedUsersIds??[],tags:c.tags??[],pipeline:c.pipeline,variables:c.variables??[]}}async function Ua(c,a){let m=await l({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
430
+ }`,variables:{filter:o,limit:10}})).justoUsers?.items?.find((t)=>t.email?.toLowerCase()===o);if(!s?._id)throw Error(`No encontramos un usuario de Justo para ${o}`);return s}))}function io(c){return{name:c.name,description:c.description,collection:c.collection,allowedUsersIds:c.allowedUsersIds??[],tags:c.tags??[],pipeline:c.pipeline,variables:c.variables??[]}}async function Fa(c,a){let o=await R({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
431
431
  testAggregationQuery(aggregationQueryId: $aggregationQueryId, params: $params)
432
- }`,variables:{aggregationQueryId:c,params:a}});return Fa(m.testAggregationQuery)}async function dm(c){let a=await fetch(`${K("data")}/execute-pipeline`,{method:"POST",headers:await Gc(),body:JSON.stringify({collection:c.collection,pipeline:c.pipeline,params:c.queryParams,limit:c.limit}),signal:AbortSignal.timeout(75000)});if(!a.ok){let m=await a.text();throw Error(im(m)||"No se pudo ejecutar el pipeline.")}return await a.json()}function im(c){try{return JSON.parse(c).error||c}catch{return c}}async function Bm(c,a,m){let o=await fetch(`${K("data")}/aggregation-queries/${c}/run`,{method:"POST",headers:await Gc(),body:JSON.stringify({params:a,limit:m}),signal:AbortSignal.timeout(315000)});if(!o.ok){let g=await o.text();throw Error(im(g)||"No se pudo ejecutar el query.")}if(!o.body)throw Error("El servidor no devolvió un stream de datos.");let s=o.body.getReader(),t=new TextDecoder,w="",r=0;while(!0){let{done:g,value:q}=await s.read();if(g)break;let J=t.decode(q,{stream:!0});process.stdout.write(J),w+=J;let R=w.indexOf(`
433
- `);while(R>=0){if(w.slice(0,R).trim())r++;w=w.slice(R+1),R=w.indexOf(`
434
- `)}}let C=t.decode();if(C)process.stdout.write(C),w+=C;if(w.trim())r++;return{ok:!0,queryId:c,limit:m,rows:r}}async function Ta(c,a){await na(c,{name:a.name,description:a.description,collection:a.collection,allowedUsersIds:a.allowedUsersIds,tags:a.tags}),await l({service:"data",query:`mutation ($aggregationQueryId: String, $pipeline: String, $variables: [AggregationQueryVariableInput]) {
432
+ }`,variables:{aggregationQueryId:c,params:a}});return Ya(o.testAggregationQuery)}async function Oo(c){let a=await fetch(`${K("data")}/execute-pipeline`,{method:"POST",headers:await Wc(),body:JSON.stringify({collection:c.collection,pipeline:c.pipeline,params:c.queryParams,limit:c.limit}),signal:AbortSignal.timeout(75000)});if(!a.ok){let o=await a.text();throw Error(bo(o)||"No se pudo ejecutar el pipeline.")}return await a.json()}function bo(c){try{return JSON.parse(c).error||c}catch{return c}}async function Bo(c,a,o){let m=await fetch(`${K("data")}/aggregation-queries/${c}/run`,{method:"POST",headers:await Wc(),body:JSON.stringify({params:a,limit:o}),signal:AbortSignal.timeout(315000)});if(!m.ok){let q=await m.text();throw Error(bo(q)||"No se pudo ejecutar el query.")}if(!m.body)throw Error("El servidor no devolvió un stream de datos.");let s=m.body.getReader(),t=new TextDecoder,p="",w=0;while(!0){let{done:q,value:g}=await s.read();if(q)break;let Q=t.decode(g,{stream:!0});process.stdout.write(Q),p+=Q;let A=p.indexOf(`
433
+ `);while(A>=0){if(p.slice(0,A).trim())w++;p=p.slice(A+1),A=p.indexOf(`
434
+ `)}}let C=t.decode();if(C)process.stdout.write(C),p+=C;if(p.trim())w++;return{ok:!0,queryId:c,limit:o,rows:w}}async function Ua(c,a){await Ta(c,{name:a.name,description:a.description,collection:a.collection,allowedUsersIds:a.allowedUsersIds,tags:a.tags}),await R({service:"data",query:`mutation ($aggregationQueryId: String, $pipeline: String, $variables: [AggregationQueryVariableInput]) {
435
435
  addAggregationQueryVersion(
436
436
  aggregationQueryId: $aggregationQueryId
437
437
  pipeline: $pipeline
@@ -440,7 +440,7 @@ Subcomandos:
440
440
  _id
441
441
  currentVersionIndex
442
442
  }
443
- }`,variables:{aggregationQueryId:c,pipeline:a.pipeline,variables:a.variables}})}async function na(c,a){await l({service:"data",query:`mutation ($aggregationQueryId: String, $aggregationQuery: UpdateAggregationQueryInput) {
443
+ }`,variables:{aggregationQueryId:c,pipeline:a.pipeline,variables:a.variables}})}async function Ta(c,a){await R({service:"data",query:`mutation ($aggregationQueryId: String, $aggregationQuery: UpdateAggregationQueryInput) {
444
444
  updateAggregationQuery(
445
445
  aggregationQueryId: $aggregationQueryId
446
446
  aggregationQuery: $aggregationQuery
@@ -453,7 +453,7 @@ Subcomandos:
453
453
  tags
454
454
  currentVersionIndex
455
455
  }
456
- }`,variables:{aggregationQueryId:c,aggregationQuery:{name:a.name,description:a.description,collection:a.collection,allowedUsersIds:a.allowedUsersIds,tags:a.tags}}})}async function bm(){return(await l({service:"data",query:`mutation {
456
+ }`,variables:{aggregationQueryId:c,aggregationQuery:{name:a.name,description:a.description,collection:a.collection,allowedUsersIds:a.allowedUsersIds,tags:a.tags}}})}async function vo(){return(await R({service:"data",query:`mutation {
457
457
  createAggregationQuery {
458
458
  _id
459
459
  name
@@ -469,7 +469,7 @@ Subcomandos:
469
469
  fieldParams
470
470
  }
471
471
  }
472
- }`})).createAggregationQuery}function dt(c){if(!Array.isArray(c))throw Error("El preview del query debe devolver un arreglo para usar AI edit.");return c}async function it(c){let a=await l({service:"messenger",query:`mutation generateAdminQuery(
472
+ }`})).createAggregationQuery}function dt(c){if(!Array.isArray(c))throw Error("El preview del query debe devolver un arreglo para usar AI edit.");return c}async function Ot(c){let a=await R({service:"messenger",query:`mutation generateAdminQuery(
473
473
  $prompt: String
474
474
  $name: String
475
475
  $description: String
@@ -495,17 +495,17 @@ Subcomandos:
495
495
  aggregationDescription
496
496
  aggregationName
497
497
  }
498
- }`,variables:c});if(!a.generateAdminQuery?.pipeline||!a.generateAdminQuery.fullCollectionName)throw Error("La IA no devolvió una versión válida del query.");return a.generateAdminQuery}async function Bt(c){let a=await l({service:"messenger",timeoutMs:120000,query:`mutation explainAdminQuery($prompt: String) {
498
+ }`,variables:c});if(!a.generateAdminQuery?.pipeline||!a.generateAdminQuery.fullCollectionName)throw Error("La IA no devolvió una versión válida del query.");return a.generateAdminQuery}async function bt(c){let a=await R({service:"messenger",timeoutMs:120000,query:`mutation explainAdminQuery($prompt: String) {
499
499
  explainAdminQuery(prompt: $prompt) {
500
500
  responseText
501
501
  }
502
- }`,variables:{prompt:c}});if(!a.explainAdminQuery?.responseText)throw Error("La IA no devolvió una explicación válida.");return a.explainAdminQuery}async function vm(){return L(),await bm()}async function xm(c){L();let a=c.prompt||await Zc("Explica qué query quieres investigar o construir: ");if(!a)throw Error("Debes indicar un prompt para explain.");return(await Bt(a)).responseText}async function em(c){if(L(),!c.collection)throw Error("Debes indicar --collection con formato db.collection. Ejemplo: --collection justo.users");if(!c.pipeline)throw Error("Debes indicar --pipeline. Ejemplo: --pipeline '[{$limit: 5}]'");let a=c.limit?Ya(c):void 0;return await dm({collection:c.collection,pipeline:c.pipeline,queryParams:Mc(c),limit:a})}async function fm(c){L();let a=cc(c,"team-cli data queries edit <queryId>"),m=await Hc(a),o=Lm(Om(m));return await Ta(a,o),{ok:!0,queryId:a,name:o.name,collection:o.collection}}async function co(c,a){L();let m=cc(c,"team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>']"),o=await Hc(m),s=a.prompt||await Zc("Describe los cambios para la IA: ");if(!s)throw Error("Debes indicar un prompt para AI edit.");let t=Mc(a),w;if(a.params){D(`Obteniendo preview del query actual...
503
- `);try{let C=await Ua(m,t);w=dt(C)}catch(C){let g=C instanceof Error?C.message:String(C);throw Error(`No se pudo obtener el preview para AI edit: ${g}`)}}D(`Generando propuesta con IA...
504
- `);let r=await it({prompt:s,fullCollectionName:o.collection,pipeline:o.pipeline,preview:w,description:o.description,name:o.name,variables:o.variables});return await Ta(m,{name:o.name==="Nuevo query"?r.aggregationName||o.name:o.name,description:o.description||r.aggregationDescription,collection:r.fullCollectionName,allowedUsersIds:o.allowedUsersIds??[],tags:o.tags??[],pipeline:r.pipeline,variables:r.variables??[]}),{ok:!0,queryId:m,responseText:r.responseText,collection:r.fullCollectionName,name:r.aggregationName,description:r.aggregationDescription}}async function ao(c){L();let a=cc(c,"team-cli data queries view <queryId>");return await Hc(a)}async function mo(c){L();let a=cc(c,"team-cli data queries view-pipeline <queryId>"),m=await Hc(a);return{queryId:a,pipeline:m.pipeline}}async function oo(c,a){L();let m=cc(c,"team-cli data queries preview <queryId> --params '<json>'"),o=Mc(a),s=await Ua(m,o);return Fa(s)}async function so(c,a){L();let m=cc(c,"team-cli data queries run <queryId> --limit <n> --params '<json>'"),o=Mc(a),s=Ya(a);return await Bm(m,o,s),{__streamHandled:!0}}async function to(c,a){L();let m=cc(c,"team-cli data queries add-viewers <queryId> --emails 'ana@justo.com,bob@justo.com'"),o=Nm(a),s=await Hc(m),t=await um(o),w=[...new Set([...s.allowedUsersIds??[],...t.map((r)=>r._id)])];return await na(m,{name:s.name,description:s.description,collection:s.collection,allowedUsersIds:w,tags:s.tags??[]}),{ok:!0,queryId:m,addedViewers:t.map((r)=>({_id:r._id,email:r.email,fullName:r.fullName})),allowedUsersIds:w}}function bt(c){return new Promise((a)=>setTimeout(a,c))}async function wo(c,a){L();let m=cc(c,"team-cli data queries download <queryId> --params '<json>'"),o=Mc(a);if(!a.path)throw Error("--path es requerido. Ejemplo: --path resultado.xlsx");D(`Iniciando descarga...
505
- `);let t=(await l({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
502
+ }`,variables:{prompt:c}});if(!a.explainAdminQuery?.responseText)throw Error("La IA no devolvió una explicación válida.");return a.explainAdminQuery}async function eo(){return u(),await vo()}async function xo(c){u();let a=c.prompt||await Mc("Explica qué query quieres investigar o construir: ");if(!a)throw Error("Debes indicar un prompt para explain.");return(await bt(a)).responseText}async function fo(c){if(u(),!c.collection)throw Error("Debes indicar --collection con formato db.collection. Ejemplo: --collection justo.users");if(!c.pipeline)throw Error("Debes indicar --pipeline. Ejemplo: --pipeline '[{$limit: 5}]'");let a=c.limit?Ha(c):void 0;return await Oo({collection:c.collection,pipeline:c.pipeline,queryParams:Xc(c),limit:a})}async function cm(c){u();let a=cc(c,"team-cli data queries edit <queryId>"),o=await Zc(a),m=uo(io(o));return await Ua(a,m),{ok:!0,queryId:a,name:m.name,collection:m.collection}}async function am(c,a){u();let o=cc(c,"team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>']"),m=await Zc(o),s=a.prompt||await Mc("Describe los cambios para la IA: ");if(!s)throw Error("Debes indicar un prompt para AI edit.");let t=Xc(a),p;if(a.params){D(`Obteniendo preview del query actual...
503
+ `);try{let C=await Fa(o,t);p=dt(C)}catch(C){let q=C instanceof Error?C.message:String(C);throw Error(`No se pudo obtener el preview para AI edit: ${q}`)}}D(`Generando propuesta con IA...
504
+ `);let w=await Ot({prompt:s,fullCollectionName:m.collection,pipeline:m.pipeline,preview:p,description:m.description,name:m.name,variables:m.variables});return await Ua(o,{name:m.name==="Nuevo query"?w.aggregationName||m.name:m.name,description:m.description||w.aggregationDescription,collection:w.fullCollectionName,allowedUsersIds:m.allowedUsersIds??[],tags:m.tags??[],pipeline:w.pipeline,variables:w.variables??[]}),{ok:!0,queryId:o,responseText:w.responseText,collection:w.fullCollectionName,name:w.aggregationName,description:w.aggregationDescription}}async function om(c){u();let a=cc(c,"team-cli data queries view <queryId>");return await Zc(a)}async function mm(c){u();let a=cc(c,"team-cli data queries view-pipeline <queryId>"),o=await Zc(a);return{queryId:a,pipeline:o.pipeline}}async function sm(c,a){u();let o=cc(c,"team-cli data queries preview <queryId> --params '<json>'"),m=Xc(a),s=await Fa(o,m);return Ya(s)}async function tm(c,a){u();let o=cc(c,"team-cli data queries run <queryId> --limit <n> --params '<json>'"),m=Xc(a),s=Ha(a);return await Bo(o,m,s),{__streamHandled:!0}}async function pm(c,a){u();let o=cc(c,"team-cli data queries add-viewers <queryId> --emails 'ana@justo.com,bob@justo.com'"),m=Lo(a),s=await Zc(o),t=await No(m),p=[...new Set([...s.allowedUsersIds??[],...t.map((w)=>w._id)])];return await Ta(o,{name:s.name,description:s.description,collection:s.collection,allowedUsersIds:p,tags:s.tags??[]}),{ok:!0,queryId:o,addedViewers:t.map((w)=>({_id:w._id,email:w.email,fullName:w.fullName})),allowedUsersIds:p}}function Bt(c){return new Promise((a)=>setTimeout(a,c))}async function rm(c,a){u();let o=cc(c,"team-cli data queries download <queryId> --params '<json>'"),m=Xc(a);if(!a.path)throw Error("--path es requerido. Ejemplo: --path resultado.xlsx");D(`Iniciando descarga...
505
+ `);let t=(await R({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
506
506
  downloadAggregationQueryData(aggregationQueryId: $aggregationQueryId, params: $params)
507
- }`,variables:{aggregationQueryId:m,params:o}})).downloadAggregationQueryData;D(`Reporte en proceso (${t})...
508
- `);let w=null;while(!w){await bt(1000);let g=await l({service:"data",query:`query ($id: String) {
507
+ }`,variables:{aggregationQueryId:o,params:m}})).downloadAggregationQueryData;D(`Reporte en proceso (${t})...
508
+ `);let p=null;while(!p){await Bt(1000);let q=await R({service:"data",query:`query ($id: String) {
509
509
  getAsyncReport(id: $id) {
510
510
  _id
511
511
  status
@@ -513,9 +513,9 @@ Subcomandos:
513
513
  fileUrl
514
514
  }
515
515
  getAsyncReportRecordsCount(id: $id)
516
- }`,variables:{id:t}}),q=g.getAsyncReport,J=g.getAsyncReportRecordsCount;if(q.status==="error")throw Error("El reporte falló al generarse.");if(q.fileUrl)w=q.fileUrl;else{let R=q.estimatedRecordsCount?` (~${q.estimatedRecordsCount} registros)`:"",F=J!=null?` ${J} procesados`:"";D(`\rGenerando...${R}${F}`)}}D(`
516
+ }`,variables:{id:t}}),g=q.getAsyncReport,Q=q.getAsyncReportRecordsCount;if(g.status==="error")throw Error("El reporte falló al generarse.");if(g.fileUrl)p=g.fileUrl;else{let A=g.estimatedRecordsCount?` (~${g.estimatedRecordsCount} registros)`:"",Y=Q!=null?` ${Q} procesados`:"";D(`\rGenerando...${A}${Y}`)}}D(`
517
517
  Descargando archivo...
518
- `);let r=await fetch(w);if(!r.ok)throw Error(`Error descargando archivo: ${r.status}`);let C=Buffer.from(await r.arrayBuffer());return Ot(a.path,C),{ok:!0,queryId:m,asyncReportId:t,outputPath:a.path,fileUrl:w}}function ha(){return`team-cli data
518
+ `);let w=await fetch(p);if(!w.ok)throw Error(`Error descargando archivo: ${w.status}`);let C=Buffer.from(await w.arrayBuffer());return it(a.path,C),{ok:!0,queryId:o,asyncReportId:t,outputPath:a.path,fileUrl:p}}function ha(){return`team-cli data
519
519
 
520
520
  Comandos de datos y reportes.
521
521
 
@@ -615,7 +615,7 @@ Ejemplos:
615
615
  team-cli data queries preview abc123 --params '{"startDate": "2026-01-01"}'
616
616
  team-cli data queries run abc123 --limit 1000 --params '{"startDate": "2026-01-01"}'
617
617
  team-cli data queries download abc123 --params '{"startDate": "2026-01-01"}' --path resultado.xlsx
618
- team-cli data queries add-viewers abc123 --emails 'ana@justo.com,bob@justo.com'`}var po=["main","auth","webdata","preferences","buckets","reservations","data","finances","url-shortener","files","tabs","commander","experiments","sales","delivery","payments","addresses","royalty","marketing","api","messenger","invoice","drivers-server"],ro=`
618
+ team-cli data queries add-viewers abc123 --emails 'ana@justo.com,bob@justo.com'`}var wm=["main","auth","webdata","preferences","buckets","reservations","data","finances","url-shortener","files","tabs","commander","experiments","sales","delivery","payments","addresses","royalty","marketing","api","messenger","invoice","drivers-server"],Cm=`
619
619
  query ResolverInfo($name: ID!, $mutation: Boolean!) {
620
620
  params(name: $name, mutation: $mutation) {
621
621
  name
@@ -624,8 +624,8 @@ Ejemplos:
624
624
  basicResultQuery
625
625
  }
626
626
  }
627
- `;function vt(c){if(!c)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");if(!po.includes(c))throw Error(`Servicio "${c}" no válido. Servicios disponibles: ${po.join(", ")}`)}async function xt(c,a){let m;try{let o=await l({service:c,query:ro,variables:{name:a,mutation:!1}});return{service:c,operationName:a,operationType:"query",info:o.params}}catch(o){m=o}try{let o=await l({service:c,query:ro,variables:{name:a,mutation:!0}});return{service:c,operationName:a,operationType:"mutation",info:o.params}}catch(o){let s=m instanceof Error?m.message:"",t=o instanceof Error?o.message:"";if(s.includes('Cannot query field "params"')||t.includes('Cannot query field "params"'))throw Error(`El servicio "${c}" no expone metadata de resolvers por GraphQL.`);throw m instanceof Error?m:o}}async function Co(c,a){let m=c[1],o=c[2],s=c[2];if(!U())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>");if(vt(m),o==="info"){let r=c[3];if(!r)throw Error("Uso: team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]");return await xt(m,r)}if(!s)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");let t;if(a.variables)try{t=JSON.parse(a.variables)}catch{throw Error("Las variables deben ser un JSON válido.")}return await l({service:m,query:s,variables:t})}function qo(){return Object.keys(xc)}function et(){return qo().map((c)=>{let a=xc[c].prod;return`- \`${c}\`: \`${a}/graphql\``}).join(`
628
- `)}function go(){let a=qo().join(", "),m=et();return`team-cli graphql
627
+ `;function vt(c){if(!c)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");if(!wm.includes(c))throw Error(`Servicio "${c}" no válido. Servicios disponibles: ${wm.join(", ")}`)}async function et(c,a){let o;try{let m=await R({service:c,query:Cm,variables:{name:a,mutation:!1}});return{service:c,operationName:a,operationType:"query",info:m.params}}catch(m){o=m}try{let m=await R({service:c,query:Cm,variables:{name:a,mutation:!0}});return{service:c,operationName:a,operationType:"mutation",info:m.params}}catch(m){let s=o instanceof Error?o.message:"",t=m instanceof Error?m.message:"";if(s.includes('Cannot query field "params"')||t.includes('Cannot query field "params"'))throw Error(`El servicio "${c}" no expone metadata de resolvers por GraphQL.`);throw o instanceof Error?o:m}}async function gm(c,a){let o=c[1],m=c[2],s=c[2];if(!F())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>");if(vt(o),m==="info"){let w=c[3];if(!w)throw Error("Uso: team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]");return await et(o,w)}if(!s)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");let t;if(a.variables)try{t=JSON.parse(a.variables)}catch{throw Error("Las variables deben ser un JSON válido.")}return await R({service:o,query:s,variables:t})}function qm(){return Object.keys(ec)}function xt(){return qm().map((c)=>{let a=ec[c].prod;return`- \`${c}\`: \`${a}/graphql\``}).join(`
628
+ `)}function $m(){let a=qm().join(", "),o=xt();return`team-cli graphql
629
629
 
630
630
  Ejecutar queries y mutations GraphQL.
631
631
 
@@ -676,13 +676,13 @@ npx @getjusto/team-cli graphql auth info requestLoginCode --format json
676
676
 
677
677
  Usa esto para mapear una URL GraphQL al valor correcto de \`team-cli graphql <service>\`.
678
678
 
679
- ${m}`}import{existsSync as Np,mkdirSync as up,readdirSync as Op}from"node:fs";import{resolve as Ms}from"node:path";import{randomBytes as ft}from"crypto";var cw=(()=>{let c=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return(a)=>c.call(a)})();function Mo(c){return cw(c)==="Uint8Array"}function aw(c){return typeof c==="object"&&c!=null&&Symbol.toStringTag in c&&(c[Symbol.toStringTag]==="ArrayBuffer"||c[Symbol.toStringTag]==="SharedArrayBuffer")}function mw(c){return c instanceof RegExp||Object.prototype.toString.call(c)==="[object RegExp]"}function Ho(c){return typeof c==="object"&&c!=null&&Symbol.toStringTag in c&&c[Symbol.toStringTag]==="Map"}function ow(c){return c instanceof Date||Object.prototype.toString.call(c)==="[object Date]"}function y(c,a){return JSON.stringify(c,(m,o)=>{if(typeof o==="bigint")return{$numberLong:`${o}`};else if(Ho(o))return Object.fromEntries(o);return o})}function sw(c){if(c!=null&&typeof c==="object"&&"stylize"in c&&typeof c.stylize==="function")return c.stylize}var za=6,Yo=Symbol.for("@@mdb.bson.version"),ya=2147483647,Sa=-2147483648,Fo=Math.pow(2,63)-1,Uo=-Math.pow(2,63),tw=Math.pow(2,53),ww=-Math.pow(2,53);var To=4,RC=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127});class $ extends Error{get bsonError(){return!0}get name(){return"BSONError"}constructor(c,a){super(c,a)}static isBSONError(c){return c!=null&&typeof c==="object"&&"bsonError"in c&&c.bsonError===!0&&"name"in c&&"message"in c&&"stack"in c}}class no extends ${get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${za}.x.x`)}}class Da extends ${get name(){return"BSONRuntimeError"}constructor(c){super(c)}}class ac extends ${get name(){return"BSONOffsetError"}constructor(c,a,m){super(`${c}. offset: ${a}`,m);this.offset=a}}var $o,Qo;function ho(c,a,m,o){if(o){$o??=new TextDecoder("utf8",{fatal:!0});try{return $o.decode(c.subarray(a,m))}catch(s){throw new $("Invalid UTF-8 string in BSON document",{cause:s})}}return Qo??=new TextDecoder("utf8",{fatal:!1}),Qo.decode(c.subarray(a,m))}function Ko(c,a,m){if(c.length===0)return"";let o=m-a;if(o===0)return"";if(o>20)return null;if(o===1&&c[a]<128)return String.fromCharCode(c[a]);if(o===2&&c[a]<128&&c[a+1]<128)return String.fromCharCode(c[a])+String.fromCharCode(c[a+1]);if(o===3&&c[a]<128&&c[a+1]<128&&c[a+2]<128)return String.fromCharCode(c[a])+String.fromCharCode(c[a+1])+String.fromCharCode(c[a+2]);let s=[];for(let t=a;t<m;t++){let w=c[t];if(w>127)return null;s.push(w)}return String.fromCharCode(...s)}function pw(c,a,m){if(a.length===0)return 0;if(a.length>25)return null;if(c.length-m<a.length)return null;for(let o=0,s=m;o<a.length;o++,s++){let t=a.charCodeAt(o);if(t>127)return null;c[s]=t}return a.length}var Cc={toLocalBufferType(c){if(Buffer.isBuffer(c))return c;if(ArrayBuffer.isView(c))return Buffer.from(c.buffer,c.byteOffset,c.byteLength);let a=c?.[Symbol.toStringTag]??Object.prototype.toString.call(c);if(a==="ArrayBuffer"||a==="SharedArrayBuffer"||a==="[object ArrayBuffer]"||a==="[object SharedArrayBuffer]")return Buffer.from(c);throw new $("Cannot create Buffer from the passed potentialBuffer.")},allocate(c){return Buffer.alloc(c)},allocateUnsafe(c){return Buffer.allocUnsafe(c)},equals(c,a){return Cc.toLocalBufferType(c).equals(a)},fromNumberArray(c){return Buffer.from(c)},fromBase64(c){return Buffer.from(c,"base64")},toBase64(c){return Cc.toLocalBufferType(c).toString("base64")},fromISO88591(c){return Buffer.from(c,"binary")},toISO88591(c){return Cc.toLocalBufferType(c).toString("binary")},fromHex(c){return Buffer.from(c,"hex")},toHex(c){return Cc.toLocalBufferType(c).toString("hex")},toUTF8(c,a,m,o){let s=m-a<=20?Ko(c,a,m):null;if(s!=null)return s;let t=Cc.toLocalBufferType(c).toString("utf8",a,m);if(o){for(let w=0;w<t.length;w++)if(t.charCodeAt(w)===65533){ho(c,a,m,!0);break}}return t},utf8ByteLength(c){return Buffer.byteLength(c,"utf8")},encodeUTF8Into(c,a,m){let o=pw(c,a,m);if(o!=null)return o;return Cc.toLocalBufferType(c).write(a,m,void 0,"utf8")},randomBytes:ft,swap32(c){return Cc.toLocalBufferType(c).swap32()}};function rw(){let{navigator:c}=globalThis;return typeof c==="object"&&c.product==="ReactNative"}function Cw(c){if(c<0)throw RangeError(`The argument 'byteLength' is invalid. Received ${c}`);return yc.fromNumberArray(Array.from({length:c},()=>Math.floor(Math.random()*256)))}var qw=(()=>{let{crypto:c}=globalThis;if(c!=null&&typeof c.getRandomValues==="function")return(a)=>{return c.getRandomValues(yc.allocate(a))};else{if(rw()){let{console:a}=globalThis;a?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return Cw}})(),jo=/(\d|[a-f])/i,yc={toLocalBufferType(c){let a=c?.[Symbol.toStringTag]??Object.prototype.toString.call(c);if(a==="Uint8Array")return c;if(ArrayBuffer.isView(c))return new Uint8Array(c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength));if(a==="ArrayBuffer"||a==="SharedArrayBuffer"||a==="[object ArrayBuffer]"||a==="[object SharedArrayBuffer]")return new Uint8Array(c);throw new $("Cannot make a Uint8Array from passed potentialBuffer.")},allocate(c){if(typeof c!=="number")throw TypeError(`The "size" argument must be of type number. Received ${String(c)}`);return new Uint8Array(c)},allocateUnsafe(c){return yc.allocate(c)},equals(c,a){if(c.byteLength!==a.byteLength)return!1;for(let m=0;m<c.byteLength;m++)if(c[m]!==a[m])return!1;return!0},fromNumberArray(c){return Uint8Array.from(c)},fromBase64(c){return Uint8Array.from(atob(c),(a)=>a.charCodeAt(0))},toBase64(c){return btoa(yc.toISO88591(c))},fromISO88591(c){return Uint8Array.from(c,(a)=>a.charCodeAt(0)&255)},toISO88591(c){return Array.from(Uint16Array.from(c),(a)=>String.fromCharCode(a)).join("")},fromHex(c){let a=c.length%2===0?c:c.slice(0,c.length-1),m=[];for(let o=0;o<a.length;o+=2){let s=a[o],t=a[o+1];if(!jo.test(s))break;if(!jo.test(t))break;let w=Number.parseInt(`${s}${t}`,16);m.push(w)}return Uint8Array.from(m)},toHex(c){return Array.from(c,(a)=>a.toString(16).padStart(2,"0")).join("")},toUTF8(c,a,m,o){let s=m-a<=20?Ko(c,a,m):null;if(s!=null)return s;return ho(c,a,m,o)},utf8ByteLength(c){return new TextEncoder().encode(c).byteLength},encodeUTF8Into(c,a,m){let o=new TextEncoder().encode(a);return c.set(o,m),o.byteLength},randomBytes:qw,swap32(c){if(c.length%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let a=0;a<c.length;a+=4){let m=c[a],o=c[a+1],s=c[a+2],t=c[a+3];c[a]=t,c[a+1]=s,c[a+2]=o,c[a+3]=m}return c}},gw=typeof Buffer==="function"&&Buffer.prototype?._isBuffer!==!0,j=gw?Cc:yc;class S{get[Yo](){return za}[Symbol.for("nodejs.util.inspect.custom")](c,a,m){return this.inspect(c,a,m)}}var Fc=new Float64Array(1),G=new Uint8Array(Fc.buffer,0,8);Fc[0]=-1;var Ka=G[7]===0,jc={isBigEndian:Ka,getNonnegativeInt32LE(c,a){if(c[a+3]>127)throw RangeError(`Size cannot be negative at offset: ${a}`);return c[a]|c[a+1]<<8|c[a+2]<<16|c[a+3]<<24},getInt32LE(c,a){return c[a]|c[a+1]<<8|c[a+2]<<16|c[a+3]<<24},getUint32LE(c,a){return c[a]+c[a+1]*256+c[a+2]*65536+c[a+3]*16777216},getUint32BE(c,a){return c[a+3]+c[a+2]*256+c[a+1]*65536+c[a]*16777216},getBigInt64LE(c,a){let m=BigInt(c[a+4]+c[a+5]*256+c[a+6]*65536+(c[a+7]<<24)),o=BigInt(c[a]+c[a+1]*256+c[a+2]*65536+c[a+3]*16777216);return(m<<BigInt(32))+o},getFloat64LE:Ka?(c,a)=>{return G[7]=c[a],G[6]=c[a+1],G[5]=c[a+2],G[4]=c[a+3],G[3]=c[a+4],G[2]=c[a+5],G[1]=c[a+6],G[0]=c[a+7],Fc[0]}:(c,a)=>{return G[0]=c[a],G[1]=c[a+1],G[2]=c[a+2],G[3]=c[a+3],G[4]=c[a+4],G[5]=c[a+5],G[6]=c[a+6],G[7]=c[a+7],Fc[0]},setInt32BE(c,a,m){return c[a+3]=m,m>>>=8,c[a+2]=m,m>>>=8,c[a+1]=m,m>>>=8,c[a]=m,4},setInt32LE(c,a,m){return c[a]=m,m>>>=8,c[a+1]=m,m>>>=8,c[a+2]=m,m>>>=8,c[a+3]=m,4},setBigInt64LE(c,a,m){let o=BigInt(4294967295),s=Number(m&o);c[a]=s,s>>=8,c[a+1]=s,s>>=8,c[a+2]=s,s>>=8,c[a+3]=s;let t=Number(m>>BigInt(32)&o);return c[a+4]=t,t>>=8,c[a+5]=t,t>>=8,c[a+6]=t,t>>=8,c[a+7]=t,8},setFloat64LE:Ka?(c,a,m)=>{return Fc[0]=m,c[a]=G[7],c[a+1]=G[6],c[a+2]=G[5],c[a+3]=G[4],c[a+4]=G[3],c[a+5]=G[2],c[a+6]=G[1],c[a+7]=G[0],8}:(c,a,m)=>{return Fc[0]=m,c[a]=G[0],c[a+1]=G[1],c[a+2]=G[2],c[a+3]=G[3],c[a+4]=G[4],c[a+5]=G[5],c[a+6]=G[6],c[a+7]=G[7],8}};class A extends S{get _bsontype(){return"Binary"}constructor(c,a){super();if(c!=null&&typeof c==="string"&&!ArrayBuffer.isView(c)&&!aw(c)&&!Array.isArray(c))throw new $("Binary can only be constructed from Uint8Array or number[]");if(this.sub_type=a??A.BSON_BINARY_SUBTYPE_DEFAULT,c==null)this.buffer=j.allocate(A.BUFFER_SIZE),this.position=0;else this.buffer=Array.isArray(c)?j.fromNumberArray(c):j.toLocalBufferType(c),this.position=this.buffer.byteLength}put(c){if(typeof c==="string"&&c.length!==1)throw new $("only accepts single character String");else if(typeof c!=="number"&&c.length!==1)throw new $("only accepts single character Uint8Array or Array");let a;if(typeof c==="string")a=c.charCodeAt(0);else if(typeof c==="number")a=c;else a=c[0];if(a<0||a>255)throw new $("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.byteLength>this.position)this.buffer[this.position++]=a;else{let m=j.allocate(A.BUFFER_SIZE+this.buffer.length);m.set(this.buffer,0),this.buffer=m,this.buffer[this.position++]=a}}write(c,a){if(a=typeof a==="number"?a:this.position,this.buffer.byteLength<a+c.length){let m=j.allocate(this.buffer.byteLength+c.length);m.set(this.buffer,0),this.buffer=m}if(ArrayBuffer.isView(c))this.buffer.set(j.toLocalBufferType(c),a),this.position=a+c.byteLength>this.position?a+c.length:this.position;else if(typeof c==="string")throw new $("input cannot be string")}read(c,a){a=a&&a>0?a:this.position;let m=c+a;return this.buffer.subarray(c,m>this.position?this.position:m)}value(){return this.buffer.length===this.position?this.buffer:this.buffer.subarray(0,this.position)}length(){return this.position}toJSON(){return j.toBase64(this.buffer.subarray(0,this.position))}toString(c){if(c==="hex")return j.toHex(this.buffer.subarray(0,this.position));if(c==="base64")return j.toBase64(this.buffer.subarray(0,this.position));if(c==="utf8"||c==="utf-8")return j.toUTF8(this.buffer,0,this.position,!1);return j.toUTF8(this.buffer,0,this.position,!1)}toExtendedJSON(c){if(c=c||{},this.sub_type===A.SUBTYPE_VECTOR)rc(this);let a=j.toBase64(this.buffer),m=Number(this.sub_type).toString(16);if(c.legacy)return{$binary:a,$type:m.length===1?"0"+m:m};return{$binary:{base64:a,subType:m.length===1?"0"+m:m}}}toUUID(){if(this.sub_type===A.SUBTYPE_UUID)return new _(this.buffer.subarray(0,this.position));throw new $(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${A.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString(c,a){return new A(j.fromHex(c),a)}static createFromBase64(c,a){return new A(j.fromBase64(c),a)}static fromExtendedJSON(c,a){a=a||{};let m,o;if("$binary"in c){if(a.legacy&&typeof c.$binary==="string"&&"$type"in c)o=c.$type?parseInt(c.$type,16):0,m=j.fromBase64(c.$binary);else if(typeof c.$binary!=="string")o=c.$binary.subType?parseInt(c.$binary.subType,16):0,m=j.fromBase64(c.$binary.base64)}else if("$uuid"in c)o=4,m=_.bytesFromString(c.$uuid);if(!m)throw new $(`Unexpected Binary Extended JSON format ${JSON.stringify(c)}`);return o===To?new _(m):new A(m,o)}inspect(c,a,m){m??=y;let o=j.toBase64(this.buffer.subarray(0,this.position)),s=m(o,a),t=m(this.sub_type,a);return`Binary.createFromBase64(${s}, ${t})`}toInt8Array(){if(this.sub_type!==A.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==A.VECTOR_TYPE.Int8)throw new $("Binary datatype field is not Int8");return rc(this),new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toFloat32Array(){if(this.sub_type!==A.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==A.VECTOR_TYPE.Float32)throw new $("Binary datatype field is not Float32");rc(this);let c=new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position));if(jc.isBigEndian)j.swap32(c);return new Float32Array(c.buffer)}toPackedBits(){if(this.sub_type!==A.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==A.VECTOR_TYPE.PackedBit)throw new $("Binary datatype field is not packed bit");return rc(this),new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toBits(){if(this.sub_type!==A.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==A.VECTOR_TYPE.PackedBit)throw new $("Binary datatype field is not packed bit");rc(this);let a=(this.length()-2)*8-this.buffer[1],m=new Int8Array(a);for(let o=0;o<m.length;o++){let s=o/8|0,t=this.buffer[s+2],w=7-o%8,r=t>>w&1;m[o]=r}return m}static fromInt8Array(c){let a=j.allocate(c.byteLength+2);a[0]=A.VECTOR_TYPE.Int8,a[1]=0;let m=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);a.set(m,2);let o=new this(a,this.SUBTYPE_VECTOR);return rc(o),o}static fromFloat32Array(c){let a=j.allocate(c.byteLength+2);a[0]=A.VECTOR_TYPE.Float32,a[1]=0;let m=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);if(a.set(m,2),jc.isBigEndian)j.swap32(new Uint8Array(a.buffer,2));let o=new this(a,this.SUBTYPE_VECTOR);return rc(o),o}static fromPackedBits(c,a=0){let m=j.allocate(c.byteLength+2);m[0]=A.VECTOR_TYPE.PackedBit,m[1]=a,m.set(c,2);let o=new this(m,this.SUBTYPE_VECTOR);return rc(o),o}static fromBits(c){let a=c.length+7>>>3,m=new Uint8Array(a+2);m[0]=A.VECTOR_TYPE.PackedBit;let o=c.length%8;m[1]=o===0?0:8-o;for(let s=0;s<c.length;s++){let t=s>>>3,w=c[s];if(w!==0&&w!==1)throw new $(`Invalid bit value at ${s}: must be 0 or 1, found ${c[s]}`);if(w===0)continue;let r=7-s%8;m[t+2]|=w<<r}return new this(m,A.SUBTYPE_VECTOR)}}A.BSON_BINARY_SUBTYPE_DEFAULT=0;A.BUFFER_SIZE=256;A.SUBTYPE_DEFAULT=0;A.SUBTYPE_FUNCTION=1;A.SUBTYPE_BYTE_ARRAY=2;A.SUBTYPE_UUID_OLD=3;A.SUBTYPE_UUID=4;A.SUBTYPE_MD5=5;A.SUBTYPE_ENCRYPTED=6;A.SUBTYPE_COLUMN=7;A.SUBTYPE_SENSITIVE=8;A.SUBTYPE_VECTOR=9;A.SUBTYPE_USER_DEFINED=128;A.VECTOR_TYPE=Object.freeze({Int8:3,Float32:39,PackedBit:16});function rc(c){if(c.sub_type!==A.SUBTYPE_VECTOR)return;let a=c.position,m=c.buffer[0],o=c.buffer[1];if((m===A.VECTOR_TYPE.Float32||m===A.VECTOR_TYPE.Int8)&&o!==0)throw new $("Invalid Vector: padding must be zero for int8 and float32 vectors");if(m===A.VECTOR_TYPE.Float32){if(a!==0&&a-2!==0&&(a-2)%4!==0)throw new $("Invalid Vector: Float32 vector must contain a multiple of 4 bytes")}if(m===A.VECTOR_TYPE.PackedBit&&o!==0&&a===2)throw new $("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(m===A.VECTOR_TYPE.PackedBit&&o>7)throw new $(`Invalid Vector: padding must be a value between 0 and 7. found: ${o}`)}var _a=16,$w=/^[0-9A-F]{32}$/i,Qw=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;class _ extends A{constructor(c){let a;if(c==null)a=_.generate();else if(c instanceof _)a=j.toLocalBufferType(new Uint8Array(c.buffer));else if(ArrayBuffer.isView(c)&&c.byteLength===_a)a=j.toLocalBufferType(c);else if(typeof c==="string")a=_.bytesFromString(c);else throw new $("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");super(a,To)}get id(){return this.buffer}set id(c){this.buffer=c}toHexString(c=!0){if(c)return[j.toHex(this.buffer.subarray(0,4)),j.toHex(this.buffer.subarray(4,6)),j.toHex(this.buffer.subarray(6,8)),j.toHex(this.buffer.subarray(8,10)),j.toHex(this.buffer.subarray(10,16))].join("-");return j.toHex(this.buffer)}toString(c){if(c==="hex")return j.toHex(this.id);if(c==="base64")return j.toBase64(this.id);return this.toHexString()}toJSON(){return this.toHexString()}equals(c){if(!c)return!1;if(c instanceof _)return j.equals(c.id,this.id);try{return j.equals(new _(c).id,this.id)}catch{return!1}}toBinary(){return new A(this.id,A.SUBTYPE_UUID)}static generate(){let c=j.randomBytes(_a);return c[6]=c[6]&15|64,c[8]=c[8]&63|128,c}static isValid(c){if(!c)return!1;if(typeof c==="string")return _.isValidUUIDString(c);if(Mo(c))return c.byteLength===_a;return c._bsontype==="Binary"&&c.sub_type===this.SUBTYPE_UUID&&c.buffer.byteLength===16}static createFromHexString(c){let a=_.bytesFromString(c);return new _(a)}static createFromBase64(c){return new _(j.fromBase64(c))}static bytesFromString(c){if(!_.isValidUUIDString(c))throw new $("UUID string representation must be 32 hex digits or canonical hyphenated representation");return j.fromHex(c.replace(/-/g,""))}static isValidUUIDString(c){return $w.test(c)||Qw.test(c)}inspect(c,a,m){return m??=y,`new UUID(${m(this.toHexString(),a)})`}}class Sc extends S{get _bsontype(){return"Code"}constructor(c,a){super();this.code=c.toString(),this.scope=a??null}toJSON(){if(this.scope!=null)return{code:this.code,scope:this.scope};return{code:this.code}}toExtendedJSON(){if(this.scope)return{$code:this.code,$scope:this.scope};return{$code:this.code}}static fromExtendedJSON(c){return new Sc(c.$code,c.$scope)}inspect(c,a,m){m??=y;let o=m(this.code,a),s=o.includes(`
680
- `);if(this.scope!=null)o+=`,${s?`
681
- `:" "}${m(this.scope,a)}`;let t=s&&this.scope===null;return`new Code(${s?`
682
- `:""}${o}${t?`
683
- `:""})`}}function jw(c){return c!=null&&typeof c==="object"&&"$id"in c&&c.$id!=null&&"$ref"in c&&typeof c.$ref==="string"&&(!("$db"in c)||("$db"in c)&&typeof c.$db==="string")}class Tc extends S{get _bsontype(){return"DBRef"}constructor(c,a,m,o){super();let s=c.split(".");if(s.length===2)m=s.shift(),c=s.shift();this.collection=c,this.oid=a,this.db=m,this.fields=o||{}}get namespace(){return this.collection}set namespace(c){this.collection=c}toJSON(){let c=Object.assign({$ref:this.collection,$id:this.oid},this.fields);if(this.db!=null)c.$db=this.db;return c}toExtendedJSON(c){c=c||{};let a={$ref:this.collection,$id:this.oid};if(c.legacy)return a;if(this.db)a.$db=this.db;return a=Object.assign(a,this.fields),a}static fromExtendedJSON(c){let a=Object.assign({},c);return delete a.$ref,delete a.$id,delete a.$db,new Tc(c.$ref,c.$id,c.$db,a)}inspect(c,a,m){m??=y;let o=[m(this.namespace,a),m(this.oid,a),...this.db?[m(this.db,a)]:[],...Object.keys(this.fields).length>0?[m(this.fields,a)]:[]];return o[1]=m===y?`new ObjectId(${o[1]})`:o[1],`new DBRef(${o.join(", ")})`}}function _o(c){if(c==="")return c;let a=0,m=c[a]==="-",o=c[a]==="+";if(o||m)a+=1;let s=!1;for(;a<c.length&&c[a]==="0";++a)s=!0;if(!s)return o?c.slice(1):c;return`${m?"-":""}${c.length===a?"0":c.slice(a)}`}function Jw(c,a){a=a??10;let m="0123456789abcdefghijklmnopqrstuvwxyz".slice(0,a);return new RegExp(`[^-+${m}]`,"i").test(c)?!1:c}var N=void 0;try{N=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var Jo=65536,Aw=16777216,Uc=Jo*Jo,Eo=Uc*Uc,Pw=Eo/2,Ao={},Po={},Rw=20,lw=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;class p extends S{get _bsontype(){return"Long"}get __isLong__(){return!0}constructor(c=0,a,m){super();let o=typeof a==="boolean"?a:Boolean(m),s=typeof a==="number"?a:0,t=typeof c==="string"?p.fromString(c,o):typeof c==="bigint"?p.fromBigInt(c,o):{low:c|0,high:s|0,unsigned:o};this.low=t.low,this.high=t.high,this.unsigned=t.unsigned}static fromBits(c,a,m){return new p(c,a,m)}static fromInt(c,a){let m,o,s;if(a){if(c>>>=0,s=0<=c&&c<256){if(o=Po[c],o)return o}if(m=p.fromBits(c,(c|0)<0?-1:0,!0),s)Po[c]=m;return m}else{if(c|=0,s=-128<=c&&c<128){if(o=Ao[c],o)return o}if(m=p.fromBits(c,c<0?-1:0,!1),s)Ao[c]=m;return m}}static fromNumber(c,a){if(isNaN(c))return a?p.UZERO:p.ZERO;if(a){if(c<0)return p.UZERO;if(c>=Eo)return p.MAX_UNSIGNED_VALUE}else{if(c<=-9223372036854776000)return p.MIN_VALUE;if(c+1>=Pw)return p.MAX_VALUE}if(c<0)return p.fromNumber(-c,a).neg();return p.fromBits(c%Uc|0,c/Uc|0,a)}static fromBigInt(c,a){let m=BigInt(4294967295),o=BigInt(32);return new p(Number(c&m),Number(c>>o&m),a)}static _fromString(c,a,m){if(c.length===0)throw new $("empty string");if(m<2||36<m)throw new $("radix");let o;if((o=c.indexOf("-"))>0)throw new $("interior hyphen");else if(o===0)return p._fromString(c.substring(1),a,m).neg();let s=p.fromNumber(Math.pow(m,8)),t=p.ZERO;for(let w=0;w<c.length;w+=8){let r=Math.min(8,c.length-w),C=parseInt(c.substring(w,w+r),m);if(r<8){let g=p.fromNumber(Math.pow(m,r));t=t.mul(g).add(p.fromNumber(C))}else t=t.mul(s),t=t.add(p.fromNumber(C))}return t.unsigned=a,t}static fromStringStrict(c,a,m){let o=!1;if(typeof a==="number")m=a,a=!1;else o=!!a;if(m??=10,c.trim()!==c)throw new $(`Input: '${c}' contains leading and/or trailing whitespace`);if(!Jw(c,m))throw new $(`Input: '${c}' contains invalid characters for radix: ${m}`);let s=_o(c),t=p._fromString(s,o,m);if(t.toString(m).toLowerCase()!==s.toLowerCase())throw new $(`Input: ${c} is not representable as ${t.unsigned?"an unsigned":"a signed"} 64-bit Long ${m!=null?`with radix: ${m}`:""}`);return t}static fromString(c,a,m){let o=!1;if(typeof a==="number")m=a,a=!1;else o=!!a;if(m??=10,c==="NaN"&&m<24)return p.ZERO;else if((c==="Infinity"||c==="+Infinity"||c==="-Infinity")&&m<35)return p.ZERO;return p._fromString(c,o,m)}static fromBytes(c,a,m){return m?p.fromBytesLE(c,a):p.fromBytesBE(c,a)}static fromBytesLE(c,a){return new p(c[0]|c[1]<<8|c[2]<<16|c[3]<<24,c[4]|c[5]<<8|c[6]<<16|c[7]<<24,a)}static fromBytesBE(c,a){return new p(c[4]<<24|c[5]<<16|c[6]<<8|c[7],c[0]<<24|c[1]<<16|c[2]<<8|c[3],a)}static isLong(c){return c!=null&&typeof c==="object"&&"__isLong__"in c&&c.__isLong__===!0}static fromValue(c,a){if(typeof c==="number")return p.fromNumber(c,a);if(typeof c==="string")return p.fromString(c,a);return p.fromBits(c.low,c.high,typeof a==="boolean"?a:c.unsigned)}add(c){if(!p.isLong(c))c=p.fromValue(c);let a=this.high>>>16,m=this.high&65535,o=this.low>>>16,s=this.low&65535,t=c.high>>>16,w=c.high&65535,r=c.low>>>16,C=c.low&65535,g=0,q=0,J=0,R=0;return R+=s+C,J+=R>>>16,R&=65535,J+=o+r,q+=J>>>16,J&=65535,q+=m+w,g+=q>>>16,q&=65535,g+=a+t,g&=65535,p.fromBits(J<<16|R,g<<16|q,this.unsigned)}and(c){if(!p.isLong(c))c=p.fromValue(c);return p.fromBits(this.low&c.low,this.high&c.high,this.unsigned)}compare(c){if(!p.isLong(c))c=p.fromValue(c);if(this.eq(c))return 0;let a=this.isNegative(),m=c.isNegative();if(a&&!m)return-1;if(!a&&m)return 1;if(!this.unsigned)return this.sub(c).isNegative()?-1:1;return c.high>>>0>this.high>>>0||c.high===this.high&&c.low>>>0>this.low>>>0?-1:1}comp(c){return this.compare(c)}divide(c){if(!p.isLong(c))c=p.fromValue(c);if(c.isZero())throw new $("division by zero");if(N){if(!this.unsigned&&this.high===-2147483648&&c.low===-1&&c.high===-1)return this;let s=(this.unsigned?N.div_u:N.div_s)(this.low,this.high,c.low,c.high);return p.fromBits(s,N.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?p.UZERO:p.ZERO;let a,m,o;if(!this.unsigned){if(this.eq(p.MIN_VALUE))if(c.eq(p.ONE)||c.eq(p.NEG_ONE))return p.MIN_VALUE;else if(c.eq(p.MIN_VALUE))return p.ONE;else if(a=this.shr(1).div(c).shl(1),a.eq(p.ZERO))return c.isNegative()?p.ONE:p.NEG_ONE;else return m=this.sub(c.mul(a)),o=a.add(m.div(c)),o;else if(c.eq(p.MIN_VALUE))return this.unsigned?p.UZERO:p.ZERO;if(this.isNegative()){if(c.isNegative())return this.neg().div(c.neg());return this.neg().div(c).neg()}else if(c.isNegative())return this.div(c.neg()).neg();o=p.ZERO}else{if(!c.unsigned)c=c.toUnsigned();if(c.gt(this))return p.UZERO;if(c.gt(this.shru(1)))return p.UONE;o=p.UZERO}m=this;while(m.gte(c)){a=Math.max(1,Math.floor(m.toNumber()/c.toNumber()));let s=Math.ceil(Math.log(a)/Math.LN2),t=s<=48?1:Math.pow(2,s-48),w=p.fromNumber(a),r=w.mul(c);while(r.isNegative()||r.gt(m))a-=t,w=p.fromNumber(a,this.unsigned),r=w.mul(c);if(w.isZero())w=p.ONE;o=o.add(w),m=m.sub(r)}return o}div(c){return this.divide(c)}equals(c){if(!p.isLong(c))c=p.fromValue(c);if(this.unsigned!==c.unsigned&&this.high>>>31===1&&c.high>>>31===1)return!1;return this.high===c.high&&this.low===c.low}eq(c){return this.equals(c)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative())return this.eq(p.MIN_VALUE)?64:this.neg().getNumBitsAbs();let c=this.high!==0?this.high:this.low,a;for(a=31;a>0;a--)if((c&1<<a)!==0)break;return this.high!==0?a+33:a+1}greaterThan(c){return this.comp(c)>0}gt(c){return this.greaterThan(c)}greaterThanOrEqual(c){return this.comp(c)>=0}gte(c){return this.greaterThanOrEqual(c)}ge(c){return this.greaterThanOrEqual(c)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(c){return this.comp(c)<0}lt(c){return this.lessThan(c)}lessThanOrEqual(c){return this.comp(c)<=0}lte(c){return this.lessThanOrEqual(c)}modulo(c){if(!p.isLong(c))c=p.fromValue(c);if(N){let a=(this.unsigned?N.rem_u:N.rem_s)(this.low,this.high,c.low,c.high);return p.fromBits(a,N.get_high(),this.unsigned)}return this.sub(this.div(c).mul(c))}mod(c){return this.modulo(c)}rem(c){return this.modulo(c)}multiply(c){if(this.isZero())return p.ZERO;if(!p.isLong(c))c=p.fromValue(c);if(N){let F=N.mul(this.low,this.high,c.low,c.high);return p.fromBits(F,N.get_high(),this.unsigned)}if(c.isZero())return p.ZERO;if(this.eq(p.MIN_VALUE))return c.isOdd()?p.MIN_VALUE:p.ZERO;if(c.eq(p.MIN_VALUE))return this.isOdd()?p.MIN_VALUE:p.ZERO;if(this.isNegative())if(c.isNegative())return this.neg().mul(c.neg());else return this.neg().mul(c).neg();else if(c.isNegative())return this.mul(c.neg()).neg();if(this.lt(p.TWO_PWR_24)&&c.lt(p.TWO_PWR_24))return p.fromNumber(this.toNumber()*c.toNumber(),this.unsigned);let a=this.high>>>16,m=this.high&65535,o=this.low>>>16,s=this.low&65535,t=c.high>>>16,w=c.high&65535,r=c.low>>>16,C=c.low&65535,g=0,q=0,J=0,R=0;return R+=s*C,J+=R>>>16,R&=65535,J+=o*C,q+=J>>>16,J&=65535,J+=s*r,q+=J>>>16,J&=65535,q+=m*C,g+=q>>>16,q&=65535,q+=o*r,g+=q>>>16,q&=65535,q+=s*w,g+=q>>>16,q&=65535,g+=a*C+m*r+o*w+s*t,g&=65535,p.fromBits(J<<16|R,g<<16|q,this.unsigned)}mul(c){return this.multiply(c)}negate(){if(!this.unsigned&&this.eq(p.MIN_VALUE))return p.MIN_VALUE;return this.not().add(p.ONE)}neg(){return this.negate()}not(){return p.fromBits(~this.low,~this.high,this.unsigned)}notEquals(c){return!this.equals(c)}neq(c){return this.notEquals(c)}ne(c){return this.notEquals(c)}or(c){if(!p.isLong(c))c=p.fromValue(c);return p.fromBits(this.low|c.low,this.high|c.high,this.unsigned)}shiftLeft(c){if(p.isLong(c))c=c.toInt();if((c&=63)===0)return this;else if(c<32)return p.fromBits(this.low<<c,this.high<<c|this.low>>>32-c,this.unsigned);else return p.fromBits(0,this.low<<c-32,this.unsigned)}shl(c){return this.shiftLeft(c)}shiftRight(c){if(p.isLong(c))c=c.toInt();if((c&=63)===0)return this;else if(c<32)return p.fromBits(this.low>>>c|this.high<<32-c,this.high>>c,this.unsigned);else return p.fromBits(this.high>>c-32,this.high>=0?0:-1,this.unsigned)}shr(c){return this.shiftRight(c)}shiftRightUnsigned(c){if(p.isLong(c))c=c.toInt();if(c&=63,c===0)return this;else{let a=this.high;if(c<32){let m=this.low;return p.fromBits(m>>>c|a<<32-c,a>>>c,this.unsigned)}else if(c===32)return p.fromBits(a,0,this.unsigned);else return p.fromBits(a>>>c-32,0,this.unsigned)}}shr_u(c){return this.shiftRightUnsigned(c)}shru(c){return this.shiftRightUnsigned(c)}subtract(c){if(!p.isLong(c))c=p.fromValue(c);return this.add(c.neg())}sub(c){return this.subtract(c)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){if(this.unsigned)return(this.high>>>0)*Uc+(this.low>>>0);return this.high*Uc+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(c){return c?this.toBytesLE():this.toBytesBE()}toBytesLE(){let c=this.high,a=this.low;return[a&255,a>>>8&255,a>>>16&255,a>>>24,c&255,c>>>8&255,c>>>16&255,c>>>24]}toBytesBE(){let c=this.high,a=this.low;return[c>>>24,c>>>16&255,c>>>8&255,c&255,a>>>24,a>>>16&255,a>>>8&255,a&255]}toSigned(){if(!this.unsigned)return this;return p.fromBits(this.low,this.high,!1)}toString(c){if(c=c||10,c<2||36<c)throw new $("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(p.MIN_VALUE)){let s=p.fromNumber(c),t=this.div(s),w=t.mul(s).sub(this);return t.toString(c)+w.toInt().toString(c)}else return"-"+this.neg().toString(c);let a=p.fromNumber(Math.pow(c,6),this.unsigned),m=this,o="";while(!0){let s=m.div(a),w=(m.sub(s.mul(a)).toInt()>>>0).toString(c);if(m=s,m.isZero())return w+o;else{while(w.length<6)w="0"+w;o=""+w+o}}}toUnsigned(){if(this.unsigned)return this;return p.fromBits(this.low,this.high,!0)}xor(c){if(!p.isLong(c))c=p.fromValue(c);return p.fromBits(this.low^c.low,this.high^c.high,this.unsigned)}eqz(){return this.isZero()}le(c){return this.lessThanOrEqual(c)}toExtendedJSON(c){if(c&&c.relaxed)return this.toNumber();return{$numberLong:this.toString()}}static fromExtendedJSON(c,a){let{useBigInt64:m=!1,relaxed:o=!0}={...a};if(c.$numberLong.length>Rw)throw new $("$numberLong string is too long");if(!lw.test(c.$numberLong))throw new $(`$numberLong string "${c.$numberLong}" is in an invalid format`);if(m){let t=BigInt(c.$numberLong);return BigInt.asIntN(64,t)}let s=p.fromString(c.$numberLong);if(o)return s.toNumber();return s}inspect(c,a,m){m??=y;let o=m(this.toString(),a),s=this.unsigned?`, ${m(this.unsigned,a)}`:"";return`new Long(${o}${s})`}}p.TWO_PWR_24=p.fromInt(Aw);p.MAX_UNSIGNED_VALUE=p.fromBits(-1,-1,!0);p.ZERO=p.fromInt(0);p.UZERO=p.fromInt(0,!0);p.ONE=p.fromInt(1);p.UONE=p.fromInt(1,!0);p.NEG_ONE=p.fromInt(-1);p.MAX_VALUE=p.fromBits(-1,2147483647,!1);p.MIN_VALUE=p.fromBits(0,-2147483648,!1);var Ww=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,Gw=/^(\+|-)?(Infinity|inf)$/i,Iw=/^(\+|-)?NaN$/i,Yc=6111,Dc=-6176,Ro=6176,lo=34,Ea=j.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Wo=j.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Go=j.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Xw=/^([-+])?(\d+)?$/,Zw=31,Io=16383,Mw=30,Hw=31;function Xo(c){return!isNaN(parseInt(c,10))}function Yw(c){let a=p.fromNumber(1e9),m=p.fromNumber(0);if(!c.parts[0]&&!c.parts[1]&&!c.parts[2]&&!c.parts[3])return{quotient:c,rem:m};for(let o=0;o<=3;o++)m=m.shiftLeft(32),m=m.add(new p(c.parts[o],0)),c.parts[o]=m.div(a).low,m=m.modulo(a);return{quotient:c,rem:m}}function Fw(c,a){if(!c&&!a)return{high:p.fromNumber(0),low:p.fromNumber(0)};let m=c.shiftRightUnsigned(32),o=new p(c.getLowBits(),0),s=a.shiftRightUnsigned(32),t=new p(a.getLowBits(),0),w=m.multiply(s),r=m.multiply(t),C=o.multiply(s),g=o.multiply(t);return w=w.add(r.shiftRightUnsigned(32)),r=new p(r.getLowBits(),0).add(C).add(g.shiftRightUnsigned(32)),w=w.add(r.shiftRightUnsigned(32)),g=r.shiftLeft(32).add(new p(g.getLowBits(),0)),{high:w,low:g}}function Uw(c,a){let m=c.high>>>0,o=a.high>>>0;if(m<o)return!0;else if(m===o){let s=c.low>>>0,t=a.low>>>0;if(s<t)return!0}return!1}function i(c,a){throw new $(`"${c}" is not a valid Decimal128 string - ${a}`)}class z extends S{get _bsontype(){return"Decimal128"}constructor(c){super();if(typeof c==="string")this.bytes=z.fromString(c).bytes;else if(c instanceof Uint8Array||Mo(c)){if(c.byteLength!==16)throw new $("Decimal128 must take a Buffer of 16 bytes");this.bytes=c}else throw new $("Decimal128 must take a Buffer or string")}static fromString(c){return z._fromString(c,{allowRounding:!1})}static fromStringWithRounding(c){return z._fromString(c,{allowRounding:!0})}static _fromString(c,a){let m=!1,o=!1,s=!1,t=!1,w=0,r=0,C=0,g=0,q=0,J=[0],R=0,F=0,P=0,W=0,H=new p(0,0),I=new p(0,0),n=0,Q=0;if(c.length>=7000)throw new $(""+c+" not a valid Decimal128 string");let h=c.match(Ww),Ds=c.match(Gw),zs=c.match(Iw);if(!h&&!Ds&&!zs||c.length===0)throw new $(""+c+" not a valid Decimal128 string");if(h){let Z=h[2],Pc=h[4],Rc=h[5],k=h[6];if(Pc&&k===void 0)i(c,"missing exponent power");if(Pc&&Z===void 0)i(c,"missing exponent base");if(Pc===void 0&&(Rc||k))i(c,"missing e before exponent")}if(c[Q]==="+"||c[Q]==="-")o=!0,m=c[Q++]==="-";if(!Xo(c[Q])&&c[Q]!=="."){if(c[Q]==="i"||c[Q]==="I")return new z(m?Wo:Go);else if(c[Q]==="N")return new z(Ea)}while(Xo(c[Q])||c[Q]==="."){if(c[Q]==="."){if(s)i(c,"contains multiple periods");s=!0,Q=Q+1;continue}if(R<lo){if(c[Q]!=="0"||t){if(!t)q=r;t=!0,J[F++]=parseInt(c[Q],10),R=R+1}}if(t)C=C+1;if(s)g=g+1;r=r+1,Q=Q+1}if(s&&!r)throw new $(""+c+" not a valid Decimal128 string");if(c[Q]==="e"||c[Q]==="E"){let Z=c.substr(++Q).match(Xw);if(!Z||!Z[2])return new z(Ea);W=parseInt(Z[0],10),Q=Q+Z[0].length}if(c[Q])return new z(Ea);if(!R)J[0]=0,C=1,R=1,w=0;else if(P=R-1,w=C,w!==1)while(c[q+w-1+Number(o)+Number(s)]==="0")w=w-1;if(W<=g&&g>W+16384)W=Dc;else W=W-g;while(W>Yc){if(P=P+1,P>=lo){if(w===0){W=Yc;break}i(c,"overflow")}W=W-1}if(a.allowRounding){while(W<Dc||R<C){if(P===0&&w<R){W=Dc,w=0;break}if(R<C)C=C-1;else P=P-1;if(W<Yc)W=W+1;else{if(J.join("").match(/^0+$/)){W=Yc;break}i(c,"overflow")}}if(P+1<w){let Z=r;if(s)q=q+1,Z=Z+1;if(o)q=q+1,Z=Z+1;let Pc=parseInt(c[q+P+1],10),Rc=0;if(Pc>=5){if(Rc=1,Pc===5){Rc=J[P]%2===1?1:0;for(let k=q+P+2;k<Z;k++)if(parseInt(c[k],10)){Rc=1;break}}}if(Rc){let k=P;for(;k>=0;k--)if(++J[k]>9){if(J[k]=0,k===0)if(W<Yc)W=W+1,J[k]=1;else return new z(m?Wo:Go)}else break}}}else{while(W<Dc||R<C){if(P===0){if(w===0){W=Dc;break}i(c,"exponent underflow")}if(R<C){if(c[C-1+Number(o)+Number(s)]!=="0"&&w!==0)i(c,"inexact rounding");C=C-1}else{if(J[P]!==0)i(c,"inexact rounding");P=P-1}if(W<Yc)W=W+1;else i(c,"overflow")}if(P+1<w){if(s)q=q+1;if(o)q=q+1;if(parseInt(c[q+P+1],10)!==0)i(c,"inexact rounding")}}if(H=p.fromNumber(0),I=p.fromNumber(0),w===0)H=p.fromNumber(0),I=p.fromNumber(0);else if(P<17){let Z=0;I=p.fromNumber(J[Z++]),H=new p(0,0);for(;Z<=P;Z++)I=I.multiply(p.fromNumber(10)),I=I.add(p.fromNumber(J[Z]))}else{let Z=0;H=p.fromNumber(J[Z++]);for(;Z<=P-17;Z++)H=H.multiply(p.fromNumber(10)),H=H.add(p.fromNumber(J[Z]));I=p.fromNumber(J[Z++]);for(;Z<=P;Z++)I=I.multiply(p.fromNumber(10)),I=I.add(p.fromNumber(J[Z]))}let v=Fw(H,p.fromString("100000000000000000"));if(v.low=v.low.add(I),Uw(v.low,I))v.high=v.high.add(p.fromNumber(1));n=W+Ro;let X={low:p.fromNumber(0),high:p.fromNumber(0)};if(v.high.shiftRightUnsigned(49).and(p.fromNumber(1)).equals(p.fromNumber(1)))X.high=X.high.or(p.fromNumber(3).shiftLeft(61)),X.high=X.high.or(p.fromNumber(n).and(p.fromNumber(16383).shiftLeft(47))),X.high=X.high.or(v.high.and(p.fromNumber(140737488355327)));else X.high=X.high.or(p.fromNumber(n&16383).shiftLeft(49)),X.high=X.high.or(v.high.and(p.fromNumber(562949953421311)));if(X.low=v.low,m)X.high=X.high.or(p.fromString("9223372036854775808"));let T=j.allocateUnsafe(16);return Q=0,T[Q++]=X.low.low&255,T[Q++]=X.low.low>>8&255,T[Q++]=X.low.low>>16&255,T[Q++]=X.low.low>>24&255,T[Q++]=X.low.high&255,T[Q++]=X.low.high>>8&255,T[Q++]=X.low.high>>16&255,T[Q++]=X.low.high>>24&255,T[Q++]=X.high.low&255,T[Q++]=X.high.low>>8&255,T[Q++]=X.high.low>>16&255,T[Q++]=X.high.low>>24&255,T[Q++]=X.high.high&255,T[Q++]=X.high.high>>8&255,T[Q++]=X.high.high>>16&255,T[Q++]=X.high.high>>24&255,new z(T)}toString(){let c,a=0,m=Array(36);for(let Q=0;Q<m.length;Q++)m[Q]=0;let o=0,s=!1,t,w={parts:[0,0,0,0]},r,C,g=[];o=0;let q=this.bytes,J=q[o++]|q[o++]<<8|q[o++]<<16|q[o++]<<24,R=q[o++]|q[o++]<<8|q[o++]<<16|q[o++]<<24,F=q[o++]|q[o++]<<8|q[o++]<<16|q[o++]<<24,P=q[o++]|q[o++]<<8|q[o++]<<16|q[o++]<<24;if(o=0,{low:new p(J,R),high:new p(F,P)}.high.lessThan(p.ZERO))g.push("-");let H=P>>26&Zw;if(H>>3===3)if(H===Mw)return g.join("")+"Infinity";else if(H===Hw)return"NaN";else c=P>>15&Io,t=8+(P>>14&1);else t=P>>14&7,c=P>>17&Io;let I=c-Ro;if(w.parts[0]=(P&16383)+((t&15)<<14),w.parts[1]=F,w.parts[2]=R,w.parts[3]=J,w.parts[0]===0&&w.parts[1]===0&&w.parts[2]===0&&w.parts[3]===0)s=!0;else for(C=3;C>=0;C--){let Q=0,h=Yw(w);if(w=h.quotient,Q=h.rem.low,!Q)continue;for(r=8;r>=0;r--)m[C*9+r]=Q%10,Q=Math.floor(Q/10)}if(s)a=1,m[o]=0;else{a=36;while(!m[o])a=a-1,o=o+1}let n=a-1+I;if(n>=34||n<=-7||I>0){if(a>34){if(g.push("0"),I>0)g.push(`E+${I}`);else if(I<0)g.push(`E${I}`);return g.join("")}if(g.push(`${m[o++]}`),a=a-1,a)g.push(".");for(let Q=0;Q<a;Q++)g.push(`${m[o++]}`);if(g.push("E"),n>0)g.push(`+${n}`);else g.push(`${n}`)}else if(I>=0)for(let Q=0;Q<a;Q++)g.push(`${m[o++]}`);else{let Q=a+I;if(Q>0)for(let h=0;h<Q;h++)g.push(`${m[o++]}`);else g.push("0");g.push(".");while(Q++<0)g.push("0");for(let h=0;h<a-Math.max(Q-1,0);h++)g.push(`${m[o++]}`)}return g.join("")}toJSON(){return{$numberDecimal:this.toString()}}toExtendedJSON(){return{$numberDecimal:this.toString()}}static fromExtendedJSON(c){return z.fromString(c.$numberDecimal)}inspect(c,a,m){return m??=y,`new Decimal128(${m(this.toString(),a)})`}}class oc extends S{get _bsontype(){return"Double"}constructor(c){super();if(c instanceof Number)c=c.valueOf();this.value=+c}static fromString(c){let a=Number(c);if(c==="NaN")return new oc(NaN);if(c==="Infinity")return new oc(1/0);if(c==="-Infinity")return new oc(-1/0);if(!Number.isFinite(a))throw new $(`Input: ${c} is not representable as a Double`);if(c.trim()!==c)throw new $(`Input: '${c}' contains whitespace`);if(c==="")throw new $("Input is an empty string");if(/[^-0-9.+eE]/.test(c))throw new $(`Input: '${c}' is not in decimal or exponential notation`);return new oc(a)}valueOf(){return this.value}toJSON(){return this.value}toString(c){return this.value.toString(c)}toExtendedJSON(c){if(c&&(c.legacy||c.relaxed&&isFinite(this.value)))return this.value;if(Object.is(Math.sign(this.value),-0))return{$numberDouble:"-0.0"};return{$numberDouble:Number.isInteger(this.value)?this.value.toFixed(1):this.value.toString()}}static fromExtendedJSON(c,a){let m=parseFloat(c.$numberDouble);return a&&a.relaxed?m:new oc(m)}inspect(c,a,m){return m??=y,`new Double(${m(this.value,a)})`}}class nc extends S{get _bsontype(){return"Int32"}constructor(c){super();if(c instanceof Number)c=c.valueOf();this.value=+c|0}static fromString(c){let a=_o(c),m=Number(c);if(ya<m)throw new $(`Input: '${c}' is larger than the maximum value for Int32`);else if(Sa>m)throw new $(`Input: '${c}' is smaller than the minimum value for Int32`);else if(!Number.isSafeInteger(m))throw new $(`Input: '${c}' is not a safe integer`);else if(m.toString()!==a)throw new $(`Input: '${c}' is not a valid Int32 string`);return new nc(m)}valueOf(){return this.value}toString(c){return this.value.toString(c)}toJSON(){return this.value}toExtendedJSON(c){if(c&&(c.relaxed||c.legacy))return this.value;return{$numberInt:this.value.toString()}}static fromExtendedJSON(c,a){return a&&a.relaxed?parseInt(c.$numberInt,10):new nc(c.$numberInt)}inspect(c,a,m){return m??=y,`new Int32(${m(this.value,a)})`}}class sa extends S{get _bsontype(){return"MaxKey"}toExtendedJSON(){return{$maxKey:1}}static fromExtendedJSON(){return new sa}inspect(){return"new MaxKey()"}}class ta extends S{get _bsontype(){return"MinKey"}toExtendedJSON(){return{$minKey:1}}static fromExtendedJSON(){return new ta}inspect(){return"new MinKey()"}}var Qc=null,zc=new WeakMap;class Y extends S{get _bsontype(){return"ObjectId"}constructor(c){super();let a;if(typeof c==="object"&&c&&"id"in c){if(typeof c.id!=="string"&&!ArrayBuffer.isView(c.id))throw new $("Argument passed in must have an id that is of type string or Buffer");if("toHexString"in c&&typeof c.toHexString==="function")a=j.fromHex(c.toHexString());else a=c.id}else a=c;if(a==null||typeof a==="number")this.buffer=Y.generate(typeof a==="number"?a:void 0);else if(ArrayBuffer.isView(a)&&a.byteLength===12)this.buffer=j.toLocalBufferType(a);else if(typeof a==="string")if(Y.validateHexString(a)){if(this.buffer=j.fromHex(a),Y.cacheHexString)zc.set(this,a)}else throw new $("input must be a 24 character hex string, 12 byte Uint8Array, or an integer");else throw new $("Argument passed in does not match the accepted types")}get id(){return this.buffer}set id(c){if(this.buffer=c,Y.cacheHexString)zc.set(this,j.toHex(c))}static validateHexString(c){if(c?.length!==24)return!1;for(let a=0;a<24;a++){let m=c.charCodeAt(a);if(m>=48&&m<=57||m>=97&&m<=102||m>=65&&m<=70)continue;return!1}return!0}toHexString(){if(Y.cacheHexString){let a=zc.get(this);if(a)return a}let c=j.toHex(this.id);if(Y.cacheHexString)zc.set(this,c);return c}static getInc(){return Y.index=(Y.index+1)%16777215}static generate(c){if(typeof c!=="number")c=Math.floor(Date.now()/1000);let a=Y.getInc(),m=j.allocateUnsafe(12);if(jc.setInt32BE(m,0,c),Qc===null)Qc=j.randomBytes(5);return m[4]=Qc[0],m[5]=Qc[1],m[6]=Qc[2],m[7]=Qc[3],m[8]=Qc[4],m[11]=a&255,m[10]=a>>8&255,m[9]=a>>16&255,m}toString(c){if(c==="base64")return j.toBase64(this.id);if(c==="hex")return this.toHexString();return this.toHexString()}toJSON(){return this.toHexString()}static is(c){return c!=null&&typeof c==="object"&&"_bsontype"in c&&c._bsontype==="ObjectId"}equals(c){if(c===void 0||c===null)return!1;if(Y.is(c))return this.buffer[11]===c.buffer[11]&&j.equals(this.buffer,c.buffer);if(typeof c==="string")return c.toLowerCase()===this.toHexString();if(typeof c==="object"&&typeof c.toHexString==="function"){let a=c.toHexString(),m=this.toHexString();return typeof a==="string"&&a.toLowerCase()===m}return!1}getTimestamp(){let c=new Date,a=jc.getUint32BE(this.buffer,0);return c.setTime(Math.floor(a)*1000),c}static createPk(){return new Y}serializeInto(c,a){return c[a]=this.buffer[0],c[a+1]=this.buffer[1],c[a+2]=this.buffer[2],c[a+3]=this.buffer[3],c[a+4]=this.buffer[4],c[a+5]=this.buffer[5],c[a+6]=this.buffer[6],c[a+7]=this.buffer[7],c[a+8]=this.buffer[8],c[a+9]=this.buffer[9],c[a+10]=this.buffer[10],c[a+11]=this.buffer[11],12}static createFromTime(c){let a=j.allocate(12);for(let m=11;m>=4;m--)a[m]=0;return jc.setInt32BE(a,0,c),new Y(a)}static createFromHexString(c){if(c?.length!==24)throw new $("hex string must be 24 characters");return new Y(j.fromHex(c))}static createFromBase64(c){if(c?.length!==16)throw new $("base64 string must be 16 characters");return new Y(j.fromBase64(c))}static isValid(c){if(c==null)return!1;if(typeof c==="string")return Y.validateHexString(c);try{return new Y(c),!0}catch{return!1}}toExtendedJSON(){if(this.toHexString)return{$oid:this.toHexString()};return{$oid:this.toString("hex")}}static fromExtendedJSON(c){return new Y(c.$oid)}isCached(){return Y.cacheHexString&&zc.has(this)}inspect(c,a,m){return m??=y,`new ObjectId(${m(this.toHexString(),a)})`}}Y.index=Math.floor(Math.random()*16777215);function Tw(c){return c.split("").sort().join("")}class tc extends S{get _bsontype(){return"BSONRegExp"}constructor(c,a){super();if(this.pattern=c,this.options=Tw(a??""),this.pattern.indexOf("\x00")!==-1)throw new $(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);if(this.options.indexOf("\x00")!==-1)throw new $(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);for(let m=0;m<this.options.length;m++)if(!(this.options[m]==="i"||this.options[m]==="m"||this.options[m]==="x"||this.options[m]==="l"||this.options[m]==="s"||this.options[m]==="u"))throw new $(`The regular expression option [${this.options[m]}] is not supported`)}static parseOptions(c){return c?c.split("").sort().join(""):""}toExtendedJSON(c){if(c=c||{},c.legacy)return{$regex:this.pattern,$options:this.options};return{$regularExpression:{pattern:this.pattern,options:this.options}}}static fromExtendedJSON(c){if("$regex"in c)if(typeof c.$regex!=="string"){if(c.$regex._bsontype==="BSONRegExp")return c}else return new tc(c.$regex,tc.parseOptions(c.$options));if("$regularExpression"in c)return new tc(c.$regularExpression.pattern,tc.parseOptions(c.$regularExpression.options));throw new $(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(c)}`)}inspect(c,a,m){let o=sw(a)??((w)=>w);m??=y;let s=o(m(this.pattern),"regexp"),t=o(m(this.options),"regexp");return`new BSONRegExp(${s}, ${t})`}}class wa extends S{get _bsontype(){return"BSONSymbol"}constructor(c){super();this.value=c}valueOf(){return this.value}toString(){return this.value}toJSON(){return this.value}toExtendedJSON(){return{$symbol:this.value}}static fromExtendedJSON(c){return new wa(c.$symbol)}inspect(c,a,m){return m??=y,`new BSONSymbol(${m(this.value,a)})`}}var nw=p;class sc extends nw{get _bsontype(){return"Timestamp"}get i(){return this.low>>>0}get t(){return this.high>>>0}constructor(c){if(c==null)super(0,0,!0);else if(typeof c==="bigint")super(c,!0);else if(p.isLong(c))super(c.low,c.high,!0);else if(typeof c==="object"&&"t"in c&&"i"in c){if(typeof c.t!=="number"&&(typeof c.t!=="object"||c.t._bsontype!=="Int32"))throw new $("Timestamp constructed from { t, i } must provide t as a number");if(typeof c.i!=="number"&&(typeof c.i!=="object"||c.i._bsontype!=="Int32"))throw new $("Timestamp constructed from { t, i } must provide i as a number");let a=Number(c.t),m=Number(c.i);if(a<0||Number.isNaN(a))throw new $("Timestamp constructed from { t, i } must provide a positive t");if(m<0||Number.isNaN(m))throw new $("Timestamp constructed from { t, i } must provide a positive i");if(a>4294967295)throw new $("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");if(m>4294967295)throw new $("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");super(m,a,!0)}else throw new $("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}toJSON(){return{$timestamp:this.toString()}}static fromInt(c){return new sc(p.fromInt(c,!0))}static fromNumber(c){return new sc(p.fromNumber(c,!0))}static fromBits(c,a){return new sc({i:c,t:a})}static fromString(c,a){return new sc(p.fromString(c,!0,a))}toExtendedJSON(){return{$timestamp:{t:this.t,i:this.i}}}static fromExtendedJSON(c){let a=p.isLong(c.$timestamp.i)?c.$timestamp.i.getLowBitsUnsigned():c.$timestamp.i,m=p.isLong(c.$timestamp.t)?c.$timestamp.t.getLowBitsUnsigned():c.$timestamp.t;return new sc({t:m,i:a})}inspect(c,a,m){m??=y;let o=m(this.t,a),s=m(this.i,a);return`new Timestamp({ t: ${o}, i: ${s} })`}}sc.MAX_VALUE=p.MAX_UNSIGNED_VALUE;var lC=p.fromNumber(tw),WC=p.fromNumber(ww);function hw(c){return c!=null&&typeof c==="object"&&"_bsontype"in c&&typeof c._bsontype==="string"}var Kw={$oid:Y,$binary:A,$uuid:A,$symbol:wa,$numberInt:nc,$numberDecimal:z,$numberDouble:oc,$numberLong:p,$minKey:ta,$maxKey:sa,$regex:tc,$regularExpression:tc,$timestamp:sc};function ko(c,a={}){if(typeof c==="number"){let o=c<=ya&&c>=Sa,s=c<=Fo&&c>=Uo;if(a.relaxed||a.legacy)return c;if(Number.isInteger(c)&&!Object.is(c,-0)){if(o)return new nc(c);if(s){if(a.useBigInt64)return BigInt(c);return p.fromNumber(c)}}return new oc(c)}if(c==null||typeof c!=="object")return c;if(c.$undefined)return null;let m=Object.keys(c).filter((o)=>o.startsWith("$")&&c[o]!=null);for(let o=0;o<m.length;o++){let s=Kw[m[o]];if(s)return s.fromExtendedJSON(c,a)}if(c.$date!=null){let o=c.$date,s=new Date;if(a.legacy)if(typeof o==="number")s.setTime(o);else if(typeof o==="string")s.setTime(Date.parse(o));else if(typeof o==="bigint")s.setTime(Number(o));else throw new Da(`Unrecognized type for EJSON date: ${typeof o}`);else if(typeof o==="string")s.setTime(Date.parse(o));else if(p.isLong(o))s.setTime(o.toNumber());else if(typeof o==="number"&&a.relaxed)s.setTime(o);else if(typeof o==="bigint")s.setTime(Number(o));else throw new Da(`Unrecognized type for EJSON date: ${typeof o}`);return s}if(c.$code!=null){let o=Object.assign({},c);if(c.$scope)o.$scope=ko(c.$scope);return Sc.fromExtendedJSON(c)}if(jw(c)||c.$dbPointer){let o=c.$ref?c:c.$dbPointer;if(o instanceof Tc)return o;let s=Object.keys(o).filter((w)=>w.startsWith("$")),t=!0;if(s.forEach((w)=>{if(["$ref","$id","$db"].indexOf(w)===-1)t=!1}),t)return Tc.fromExtendedJSON(o)}return c}function _w(c,a){return c.map((m,o)=>{a.seenObjects.push({propertyName:`index ${o}`,obj:null});try{return mc(m,a)}finally{a.seenObjects.pop()}})}function Zo(c){let a=c.toISOString();return c.getUTCMilliseconds()!==0?a:a.slice(0,-5)+"Z"}function mc(c,a){if(c instanceof Map||Ho(c)){let m=Object.create(null);for(let[o,s]of c){if(typeof o!=="string")throw new $("Can only serialize maps with string keys");m[o]=s}return mc(m,a)}if((typeof c==="object"||typeof c==="function")&&c!==null){let m=a.seenObjects.findIndex((o)=>o.obj===c);if(m!==-1){let o=a.seenObjects.map((q)=>q.propertyName),s=o.slice(0,m).map((q)=>`${q} -> `).join(""),t=o[m],w=" -> "+o.slice(m+1,o.length-1).map((q)=>`${q} -> `).join(""),r=o[o.length-1],C=" ".repeat(s.length+t.length/2),g="-".repeat(w.length+(t.length+r.length)/2-1);throw new $(`Converting circular structure to EJSON:
684
- ${s}${t}${w}${r}
685
- ${C}\\${g}/`)}a.seenObjects[a.seenObjects.length-1].obj=c}if(Array.isArray(c))return _w(c,a);if(c===void 0)return null;if(c instanceof Date||ow(c)){let m=c.getTime(),o=m>-1&&m<253402318800000;if(a.legacy)return a.relaxed&&o?{$date:c.getTime()}:{$date:Zo(c)};return a.relaxed&&o?{$date:Zo(c)}:{$date:{$numberLong:c.getTime().toString()}}}if(typeof c==="number"&&(!a.relaxed||!isFinite(c))){if(Number.isInteger(c)&&!Object.is(c,-0)){if(c>=Sa&&c<=ya)return{$numberInt:c.toString()};if(c>=Uo&&c<=Fo)return{$numberLong:c.toString()}}return{$numberDouble:Object.is(c,-0)?"-0.0":c.toString()}}if(typeof c==="bigint"){if(!a.relaxed)return{$numberLong:BigInt.asIntN(64,c).toString()};return Number(BigInt.asIntN(64,c))}if(c instanceof RegExp||mw(c)){let m=c.flags;if(m===void 0){let s=c.toString().match(/[gimuy]*$/);if(s)m=s[0]}return new tc(c.source,m).toExtendedJSON(a)}if(c!=null&&typeof c==="object")return kw(c,a);return c}var Ew={Binary:(c)=>new A(c.value(),c.sub_type),Code:(c)=>new Sc(c.code,c.scope),DBRef:(c)=>new Tc(c.collection||c.namespace,c.oid,c.db,c.fields),Decimal128:(c)=>new z(c.bytes),Double:(c)=>new oc(c.value),Int32:(c)=>new nc(c.value),Long:(c)=>p.fromBits(c.low!=null?c.low:c.low_,c.low!=null?c.high:c.high_,c.low!=null?c.unsigned:c.unsigned_),MaxKey:()=>new sa,MinKey:()=>new ta,ObjectId:(c)=>new Y(c),BSONRegExp:(c)=>new tc(c.pattern,c.options),BSONSymbol:(c)=>new wa(c.value),Timestamp:(c)=>sc.fromBits(c.low,c.high)};function kw(c,a){if(c==null||typeof c!=="object")throw new $("not an object instance");let m=c._bsontype;if(typeof m>"u"){let o={};for(let s of Object.keys(c)){a.seenObjects.push({propertyName:s,obj:null});try{let t=mc(c[s],a);if(s==="__proto__")Object.defineProperty(o,s,{value:t,writable:!0,enumerable:!0,configurable:!0});else o[s]=t}finally{a.seenObjects.pop()}}return o}else if(c!=null&&typeof c==="object"&&typeof c._bsontype==="string"&&c[Yo]!==za)throw new no;else if(hw(c)){let o=c;if(typeof o.toExtendedJSON!=="function"){let s=Ew[c._bsontype];if(!s)throw new $("Unrecognized or invalid _bsontype: "+c._bsontype);o=s(o)}if(m==="Code"&&o.scope)o=new Sc(o.code,mc(o.scope,a));else if(m==="DBRef"&&o.oid)o=new Tc(mc(o.collection,a),mc(o.oid,a),mc(o.db,a),mc(o.fields,a));return o.toExtendedJSON(a)}else throw new $("_bsontype must be a string, but was: "+typeof m)}function Vo(c,a){let m={useBigInt64:a?.useBigInt64??!1,relaxed:a?.relaxed??!0,legacy:a?.legacy??!1};return JSON.parse(c,(o,s)=>{if(o.indexOf("\x00")!==-1)throw new $(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(o)}`);return ko(s,m)})}function Do(c,a,m,o){if(m!=null&&typeof m==="object")o=m,m=0;if(a!=null&&typeof a==="object"&&!Array.isArray(a))o=a,a=void 0,m=0;let s=Object.assign({relaxed:!0,legacy:!1},o,{seenObjects:[{propertyName:"(root)",obj:null}]}),t=mc(c,s);return JSON.stringify(t,a,m)}function Vw(c,a){return a=a||{},JSON.parse(Do(c,a))}function Dw(c,a){return a=a||{},Vo(JSON.stringify(c),a)}var qc=Object.create(null);qc.parse=Vo;qc.stringify=Do;qc.serialize=Vw;qc.deserialize=Dw;Object.freeze(qc);var M={double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:255,maxKey:127};function ka(c,a){try{return jc.getNonnegativeInt32LE(c,a)}catch(m){throw new ac("BSON size cannot be negative",a,{cause:m})}}function Va(c,a){let m=a;for(;c[m]!==0;m++);if(m===c.length-1)throw new ac("Null terminator not found",a);return m}function zw(c,a=0){if(a??=0,c.length<5)throw new ac(`Input must be at least 5 bytes, got ${c.length} bytes`,a);let m=ka(c,a);if(m>c.length-a)throw new ac(`Parsed documentSize (${m} bytes) does not match input length (${c.length} bytes)`,a);if(c[a+m-1]!==0)throw new ac("BSON documents must end in 0x00",a+m);let o=[],s=a+4;while(s<=m+a){let t=c[s];if(s+=1,t===0){if(s-a!==m)throw new ac("Invalid 0x00 type byte",s);break}let w=s,r=Va(c,s)-w;s+=r+1;let C;if(t===M.double||t===M.long||t===M.date||t===M.timestamp)C=8;else if(t===M.int)C=4;else if(t===M.objectId)C=12;else if(t===M.decimal)C=16;else if(t===M.bool)C=1;else if(t===M.null||t===M.undefined||t===M.maxKey||t===M.minKey)C=0;else if(t===M.regex)C=Va(c,Va(c,s)+1)+1-s;else if(t===M.object||t===M.array||t===M.javascriptWithScope)C=ka(c,s);else if(t===M.string||t===M.binData||t===M.dbPointer||t===M.javascript||t===M.symbol){if(C=ka(c,s)+4,t===M.binData)C+=1;if(t===M.dbPointer)C+=12}else throw new ac(`Invalid 0x${t.toString(16).padStart(2,"0")} type byte`,s);if(C>m)throw new ac("value reports length larger than document",s);o.push([t,w,r,s,C]),s+=C}return o}var pa=Object.create(null);pa.parseToElements=zw;pa.ByteUtils=j;pa.NumberUtils=jc;Object.freeze(pa);var yw=17825792,GC=j.allocate(yw);import{execFileSync as Sw}from"node:child_process";import{existsSync as qa,mkdirSync as Lw,readdirSync as Nw,readFileSync as ga,rmSync as Na,writeFileSync as wc}from"node:fs";import{basename as uo,dirname as Oo,join as E,resolve as io}from"node:path";var La=".justo-space.json";function zo(){return{template:"react-vite-shadcn",version:2,collections:{}}}function ra(){return process.execPath}function Jc(c){if(process.platform==="win32")return`${c}.cmd`;return c}var Ca="iUzDOAFCUx33tmT6OCea",Lc="VITE_JUSTO_MAP_TILER_TOKEN";function yo(){return`import {useState, type FormEvent} from 'react'
679
+ ${o}`}import{existsSync as Lr,mkdirSync as Nr,readdirSync as ir}from"node:fs";import{resolve as Xs}from"node:path";import{randomBytes as ft}from"crypto";var cp=(()=>{let c=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return(a)=>c.call(a)})();function Zm(c){return cp(c)==="Uint8Array"}function ap(c){return typeof c==="object"&&c!=null&&Symbol.toStringTag in c&&(c[Symbol.toStringTag]==="ArrayBuffer"||c[Symbol.toStringTag]==="SharedArrayBuffer")}function op(c){return c instanceof RegExp||Object.prototype.toString.call(c)==="[object RegExp]"}function Hm(c){return typeof c==="object"&&c!=null&&Symbol.toStringTag in c&&c[Symbol.toStringTag]==="Map"}function mp(c){return c instanceof Date||Object.prototype.toString.call(c)==="[object Date]"}function y(c,a){return JSON.stringify(c,(o,m)=>{if(typeof m==="bigint")return{$numberLong:`${m}`};else if(Hm(m))return Object.fromEntries(m);return m})}function sp(c){if(c!=null&&typeof c==="object"&&"stylize"in c&&typeof c.stylize==="function")return c.stylize}var za=6,Ym=Symbol.for("@@mdb.bson.version"),ya=2147483647,Sa=-2147483648,Fm=Math.pow(2,63)-1,Um=-Math.pow(2,63),tp=Math.pow(2,53),pp=-Math.pow(2,53);var Tm=4,PC=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127});class $ extends Error{get bsonError(){return!0}get name(){return"BSONError"}constructor(c,a){super(c,a)}static isBSONError(c){return c!=null&&typeof c==="object"&&"bsonError"in c&&c.bsonError===!0&&"name"in c&&"message"in c&&"stack"in c}}class hm extends ${get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${za}.x.x`)}}class Da extends ${get name(){return"BSONRuntimeError"}constructor(c){super(c)}}class ac extends ${get name(){return"BSONOffsetError"}constructor(c,a,o){super(`${c}. offset: ${a}`,o);this.offset=a}}var lm,jm;function Km(c,a,o,m){if(m){lm??=new TextDecoder("utf8",{fatal:!0});try{return lm.decode(c.subarray(a,o))}catch(s){throw new $("Invalid UTF-8 string in BSON document",{cause:s})}}return jm??=new TextDecoder("utf8",{fatal:!1}),jm.decode(c.subarray(a,o))}function _m(c,a,o){if(c.length===0)return"";let m=o-a;if(m===0)return"";if(m>20)return null;if(m===1&&c[a]<128)return String.fromCharCode(c[a]);if(m===2&&c[a]<128&&c[a+1]<128)return String.fromCharCode(c[a])+String.fromCharCode(c[a+1]);if(m===3&&c[a]<128&&c[a+1]<128&&c[a+2]<128)return String.fromCharCode(c[a])+String.fromCharCode(c[a+1])+String.fromCharCode(c[a+2]);let s=[];for(let t=a;t<o;t++){let p=c[t];if(p>127)return null;s.push(p)}return String.fromCharCode(...s)}function rp(c,a,o){if(a.length===0)return 0;if(a.length>25)return null;if(c.length-o<a.length)return null;for(let m=0,s=o;m<a.length;m++,s++){let t=a.charCodeAt(m);if(t>127)return null;c[s]=t}return a.length}var Cc={toLocalBufferType(c){if(Buffer.isBuffer(c))return c;if(ArrayBuffer.isView(c))return Buffer.from(c.buffer,c.byteOffset,c.byteLength);let a=c?.[Symbol.toStringTag]??Object.prototype.toString.call(c);if(a==="ArrayBuffer"||a==="SharedArrayBuffer"||a==="[object ArrayBuffer]"||a==="[object SharedArrayBuffer]")return Buffer.from(c);throw new $("Cannot create Buffer from the passed potentialBuffer.")},allocate(c){return Buffer.alloc(c)},allocateUnsafe(c){return Buffer.allocUnsafe(c)},equals(c,a){return Cc.toLocalBufferType(c).equals(a)},fromNumberArray(c){return Buffer.from(c)},fromBase64(c){return Buffer.from(c,"base64")},toBase64(c){return Cc.toLocalBufferType(c).toString("base64")},fromISO88591(c){return Buffer.from(c,"binary")},toISO88591(c){return Cc.toLocalBufferType(c).toString("binary")},fromHex(c){return Buffer.from(c,"hex")},toHex(c){return Cc.toLocalBufferType(c).toString("hex")},toUTF8(c,a,o,m){let s=o-a<=20?_m(c,a,o):null;if(s!=null)return s;let t=Cc.toLocalBufferType(c).toString("utf8",a,o);if(m){for(let p=0;p<t.length;p++)if(t.charCodeAt(p)===65533){Km(c,a,o,!0);break}}return t},utf8ByteLength(c){return Buffer.byteLength(c,"utf8")},encodeUTF8Into(c,a,o){let m=rp(c,a,o);if(m!=null)return m;return Cc.toLocalBufferType(c).write(a,o,void 0,"utf8")},randomBytes:ft,swap32(c){return Cc.toLocalBufferType(c).swap32()}};function wp(){let{navigator:c}=globalThis;return typeof c==="object"&&c.product==="ReactNative"}function Cp(c){if(c<0)throw RangeError(`The argument 'byteLength' is invalid. Received ${c}`);return yc.fromNumberArray(Array.from({length:c},()=>Math.floor(Math.random()*256)))}var gp=(()=>{let{crypto:c}=globalThis;if(c!=null&&typeof c.getRandomValues==="function")return(a)=>{return c.getRandomValues(yc.allocate(a))};else{if(wp()){let{console:a}=globalThis;a?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return Cp}})(),Qm=/(\d|[a-f])/i,yc={toLocalBufferType(c){let a=c?.[Symbol.toStringTag]??Object.prototype.toString.call(c);if(a==="Uint8Array")return c;if(ArrayBuffer.isView(c))return new Uint8Array(c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength));if(a==="ArrayBuffer"||a==="SharedArrayBuffer"||a==="[object ArrayBuffer]"||a==="[object SharedArrayBuffer]")return new Uint8Array(c);throw new $("Cannot make a Uint8Array from passed potentialBuffer.")},allocate(c){if(typeof c!=="number")throw TypeError(`The "size" argument must be of type number. Received ${String(c)}`);return new Uint8Array(c)},allocateUnsafe(c){return yc.allocate(c)},equals(c,a){if(c.byteLength!==a.byteLength)return!1;for(let o=0;o<c.byteLength;o++)if(c[o]!==a[o])return!1;return!0},fromNumberArray(c){return Uint8Array.from(c)},fromBase64(c){return Uint8Array.from(atob(c),(a)=>a.charCodeAt(0))},toBase64(c){return btoa(yc.toISO88591(c))},fromISO88591(c){return Uint8Array.from(c,(a)=>a.charCodeAt(0)&255)},toISO88591(c){return Array.from(Uint16Array.from(c),(a)=>String.fromCharCode(a)).join("")},fromHex(c){let a=c.length%2===0?c:c.slice(0,c.length-1),o=[];for(let m=0;m<a.length;m+=2){let s=a[m],t=a[m+1];if(!Qm.test(s))break;if(!Qm.test(t))break;let p=Number.parseInt(`${s}${t}`,16);o.push(p)}return Uint8Array.from(o)},toHex(c){return Array.from(c,(a)=>a.toString(16).padStart(2,"0")).join("")},toUTF8(c,a,o,m){let s=o-a<=20?_m(c,a,o):null;if(s!=null)return s;return Km(c,a,o,m)},utf8ByteLength(c){return new TextEncoder().encode(c).byteLength},encodeUTF8Into(c,a,o){let m=new TextEncoder().encode(a);return c.set(m,o),m.byteLength},randomBytes:gp,swap32(c){if(c.length%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let a=0;a<c.length;a+=4){let o=c[a],m=c[a+1],s=c[a+2],t=c[a+3];c[a]=t,c[a+1]=s,c[a+2]=m,c[a+3]=o}return c}},qp=typeof Buffer==="function"&&Buffer.prototype?._isBuffer!==!0,j=qp?Cc:yc;class S{get[Ym](){return za}[Symbol.for("nodejs.util.inspect.custom")](c,a,o){return this.inspect(c,a,o)}}var Yc=new Float64Array(1),W=new Uint8Array(Yc.buffer,0,8);Yc[0]=-1;var Ka=W[7]===0,jc={isBigEndian:Ka,getNonnegativeInt32LE(c,a){if(c[a+3]>127)throw RangeError(`Size cannot be negative at offset: ${a}`);return c[a]|c[a+1]<<8|c[a+2]<<16|c[a+3]<<24},getInt32LE(c,a){return c[a]|c[a+1]<<8|c[a+2]<<16|c[a+3]<<24},getUint32LE(c,a){return c[a]+c[a+1]*256+c[a+2]*65536+c[a+3]*16777216},getUint32BE(c,a){return c[a+3]+c[a+2]*256+c[a+1]*65536+c[a]*16777216},getBigInt64LE(c,a){let o=BigInt(c[a+4]+c[a+5]*256+c[a+6]*65536+(c[a+7]<<24)),m=BigInt(c[a]+c[a+1]*256+c[a+2]*65536+c[a+3]*16777216);return(o<<BigInt(32))+m},getFloat64LE:Ka?(c,a)=>{return W[7]=c[a],W[6]=c[a+1],W[5]=c[a+2],W[4]=c[a+3],W[3]=c[a+4],W[2]=c[a+5],W[1]=c[a+6],W[0]=c[a+7],Yc[0]}:(c,a)=>{return W[0]=c[a],W[1]=c[a+1],W[2]=c[a+2],W[3]=c[a+3],W[4]=c[a+4],W[5]=c[a+5],W[6]=c[a+6],W[7]=c[a+7],Yc[0]},setInt32BE(c,a,o){return c[a+3]=o,o>>>=8,c[a+2]=o,o>>>=8,c[a+1]=o,o>>>=8,c[a]=o,4},setInt32LE(c,a,o){return c[a]=o,o>>>=8,c[a+1]=o,o>>>=8,c[a+2]=o,o>>>=8,c[a+3]=o,4},setBigInt64LE(c,a,o){let m=BigInt(4294967295),s=Number(o&m);c[a]=s,s>>=8,c[a+1]=s,s>>=8,c[a+2]=s,s>>=8,c[a+3]=s;let t=Number(o>>BigInt(32)&m);return c[a+4]=t,t>>=8,c[a+5]=t,t>>=8,c[a+6]=t,t>>=8,c[a+7]=t,8},setFloat64LE:Ka?(c,a,o)=>{return Yc[0]=o,c[a]=W[7],c[a+1]=W[6],c[a+2]=W[5],c[a+3]=W[4],c[a+4]=W[3],c[a+5]=W[2],c[a+6]=W[1],c[a+7]=W[0],8}:(c,a,o)=>{return Yc[0]=o,c[a]=W[0],c[a+1]=W[1],c[a+2]=W[2],c[a+3]=W[3],c[a+4]=W[4],c[a+5]=W[5],c[a+6]=W[6],c[a+7]=W[7],8}};class n extends S{get _bsontype(){return"Binary"}constructor(c,a){super();if(c!=null&&typeof c==="string"&&!ArrayBuffer.isView(c)&&!ap(c)&&!Array.isArray(c))throw new $("Binary can only be constructed from Uint8Array or number[]");if(this.sub_type=a??n.BSON_BINARY_SUBTYPE_DEFAULT,c==null)this.buffer=j.allocate(n.BUFFER_SIZE),this.position=0;else this.buffer=Array.isArray(c)?j.fromNumberArray(c):j.toLocalBufferType(c),this.position=this.buffer.byteLength}put(c){if(typeof c==="string"&&c.length!==1)throw new $("only accepts single character String");else if(typeof c!=="number"&&c.length!==1)throw new $("only accepts single character Uint8Array or Array");let a;if(typeof c==="string")a=c.charCodeAt(0);else if(typeof c==="number")a=c;else a=c[0];if(a<0||a>255)throw new $("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.byteLength>this.position)this.buffer[this.position++]=a;else{let o=j.allocate(n.BUFFER_SIZE+this.buffer.length);o.set(this.buffer,0),this.buffer=o,this.buffer[this.position++]=a}}write(c,a){if(a=typeof a==="number"?a:this.position,this.buffer.byteLength<a+c.length){let o=j.allocate(this.buffer.byteLength+c.length);o.set(this.buffer,0),this.buffer=o}if(ArrayBuffer.isView(c))this.buffer.set(j.toLocalBufferType(c),a),this.position=a+c.byteLength>this.position?a+c.length:this.position;else if(typeof c==="string")throw new $("input cannot be string")}read(c,a){a=a&&a>0?a:this.position;let o=c+a;return this.buffer.subarray(c,o>this.position?this.position:o)}value(){return this.buffer.length===this.position?this.buffer:this.buffer.subarray(0,this.position)}length(){return this.position}toJSON(){return j.toBase64(this.buffer.subarray(0,this.position))}toString(c){if(c==="hex")return j.toHex(this.buffer.subarray(0,this.position));if(c==="base64")return j.toBase64(this.buffer.subarray(0,this.position));if(c==="utf8"||c==="utf-8")return j.toUTF8(this.buffer,0,this.position,!1);return j.toUTF8(this.buffer,0,this.position,!1)}toExtendedJSON(c){if(c=c||{},this.sub_type===n.SUBTYPE_VECTOR)wc(this);let a=j.toBase64(this.buffer),o=Number(this.sub_type).toString(16);if(c.legacy)return{$binary:a,$type:o.length===1?"0"+o:o};return{$binary:{base64:a,subType:o.length===1?"0"+o:o}}}toUUID(){if(this.sub_type===n.SUBTYPE_UUID)return new _(this.buffer.subarray(0,this.position));throw new $(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${n.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString(c,a){return new n(j.fromHex(c),a)}static createFromBase64(c,a){return new n(j.fromBase64(c),a)}static fromExtendedJSON(c,a){a=a||{};let o,m;if("$binary"in c){if(a.legacy&&typeof c.$binary==="string"&&"$type"in c)m=c.$type?parseInt(c.$type,16):0,o=j.fromBase64(c.$binary);else if(typeof c.$binary!=="string")m=c.$binary.subType?parseInt(c.$binary.subType,16):0,o=j.fromBase64(c.$binary.base64)}else if("$uuid"in c)m=4,o=_.bytesFromString(c.$uuid);if(!o)throw new $(`Unexpected Binary Extended JSON format ${JSON.stringify(c)}`);return m===Tm?new _(o):new n(o,m)}inspect(c,a,o){o??=y;let m=j.toBase64(this.buffer.subarray(0,this.position)),s=o(m,a),t=o(this.sub_type,a);return`Binary.createFromBase64(${s}, ${t})`}toInt8Array(){if(this.sub_type!==n.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==n.VECTOR_TYPE.Int8)throw new $("Binary datatype field is not Int8");return wc(this),new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toFloat32Array(){if(this.sub_type!==n.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==n.VECTOR_TYPE.Float32)throw new $("Binary datatype field is not Float32");wc(this);let c=new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position));if(jc.isBigEndian)j.swap32(c);return new Float32Array(c.buffer)}toPackedBits(){if(this.sub_type!==n.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==n.VECTOR_TYPE.PackedBit)throw new $("Binary datatype field is not packed bit");return wc(this),new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toBits(){if(this.sub_type!==n.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==n.VECTOR_TYPE.PackedBit)throw new $("Binary datatype field is not packed bit");wc(this);let a=(this.length()-2)*8-this.buffer[1],o=new Int8Array(a);for(let m=0;m<o.length;m++){let s=m/8|0,t=this.buffer[s+2],p=7-m%8,w=t>>p&1;o[m]=w}return o}static fromInt8Array(c){let a=j.allocate(c.byteLength+2);a[0]=n.VECTOR_TYPE.Int8,a[1]=0;let o=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);a.set(o,2);let m=new this(a,this.SUBTYPE_VECTOR);return wc(m),m}static fromFloat32Array(c){let a=j.allocate(c.byteLength+2);a[0]=n.VECTOR_TYPE.Float32,a[1]=0;let o=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);if(a.set(o,2),jc.isBigEndian)j.swap32(new Uint8Array(a.buffer,2));let m=new this(a,this.SUBTYPE_VECTOR);return wc(m),m}static fromPackedBits(c,a=0){let o=j.allocate(c.byteLength+2);o[0]=n.VECTOR_TYPE.PackedBit,o[1]=a,o.set(c,2);let m=new this(o,this.SUBTYPE_VECTOR);return wc(m),m}static fromBits(c){let a=c.length+7>>>3,o=new Uint8Array(a+2);o[0]=n.VECTOR_TYPE.PackedBit;let m=c.length%8;o[1]=m===0?0:8-m;for(let s=0;s<c.length;s++){let t=s>>>3,p=c[s];if(p!==0&&p!==1)throw new $(`Invalid bit value at ${s}: must be 0 or 1, found ${c[s]}`);if(p===0)continue;let w=7-s%8;o[t+2]|=p<<w}return new this(o,n.SUBTYPE_VECTOR)}}n.BSON_BINARY_SUBTYPE_DEFAULT=0;n.BUFFER_SIZE=256;n.SUBTYPE_DEFAULT=0;n.SUBTYPE_FUNCTION=1;n.SUBTYPE_BYTE_ARRAY=2;n.SUBTYPE_UUID_OLD=3;n.SUBTYPE_UUID=4;n.SUBTYPE_MD5=5;n.SUBTYPE_ENCRYPTED=6;n.SUBTYPE_COLUMN=7;n.SUBTYPE_SENSITIVE=8;n.SUBTYPE_VECTOR=9;n.SUBTYPE_USER_DEFINED=128;n.VECTOR_TYPE=Object.freeze({Int8:3,Float32:39,PackedBit:16});function wc(c){if(c.sub_type!==n.SUBTYPE_VECTOR)return;let a=c.position,o=c.buffer[0],m=c.buffer[1];if((o===n.VECTOR_TYPE.Float32||o===n.VECTOR_TYPE.Int8)&&m!==0)throw new $("Invalid Vector: padding must be zero for int8 and float32 vectors");if(o===n.VECTOR_TYPE.Float32){if(a!==0&&a-2!==0&&(a-2)%4!==0)throw new $("Invalid Vector: Float32 vector must contain a multiple of 4 bytes")}if(o===n.VECTOR_TYPE.PackedBit&&m!==0&&a===2)throw new $("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(o===n.VECTOR_TYPE.PackedBit&&m>7)throw new $(`Invalid Vector: padding must be a value between 0 and 7. found: ${m}`)}var _a=16,$p=/^[0-9A-F]{32}$/i,lp=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;class _ extends n{constructor(c){let a;if(c==null)a=_.generate();else if(c instanceof _)a=j.toLocalBufferType(new Uint8Array(c.buffer));else if(ArrayBuffer.isView(c)&&c.byteLength===_a)a=j.toLocalBufferType(c);else if(typeof c==="string")a=_.bytesFromString(c);else throw new $("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");super(a,Tm)}get id(){return this.buffer}set id(c){this.buffer=c}toHexString(c=!0){if(c)return[j.toHex(this.buffer.subarray(0,4)),j.toHex(this.buffer.subarray(4,6)),j.toHex(this.buffer.subarray(6,8)),j.toHex(this.buffer.subarray(8,10)),j.toHex(this.buffer.subarray(10,16))].join("-");return j.toHex(this.buffer)}toString(c){if(c==="hex")return j.toHex(this.id);if(c==="base64")return j.toBase64(this.id);return this.toHexString()}toJSON(){return this.toHexString()}equals(c){if(!c)return!1;if(c instanceof _)return j.equals(c.id,this.id);try{return j.equals(new _(c).id,this.id)}catch{return!1}}toBinary(){return new n(this.id,n.SUBTYPE_UUID)}static generate(){let c=j.randomBytes(_a);return c[6]=c[6]&15|64,c[8]=c[8]&63|128,c}static isValid(c){if(!c)return!1;if(typeof c==="string")return _.isValidUUIDString(c);if(Zm(c))return c.byteLength===_a;return c._bsontype==="Binary"&&c.sub_type===this.SUBTYPE_UUID&&c.buffer.byteLength===16}static createFromHexString(c){let a=_.bytesFromString(c);return new _(a)}static createFromBase64(c){return new _(j.fromBase64(c))}static bytesFromString(c){if(!_.isValidUUIDString(c))throw new $("UUID string representation must be 32 hex digits or canonical hyphenated representation");return j.fromHex(c.replace(/-/g,""))}static isValidUUIDString(c){return $p.test(c)||lp.test(c)}inspect(c,a,o){return o??=y,`new UUID(${o(this.toHexString(),a)})`}}class Sc extends S{get _bsontype(){return"Code"}constructor(c,a){super();this.code=c.toString(),this.scope=a??null}toJSON(){if(this.scope!=null)return{code:this.code,scope:this.scope};return{code:this.code}}toExtendedJSON(){if(this.scope)return{$code:this.code,$scope:this.scope};return{$code:this.code}}static fromExtendedJSON(c){return new Sc(c.$code,c.$scope)}inspect(c,a,o){o??=y;let m=o(this.code,a),s=m.includes(`
680
+ `);if(this.scope!=null)m+=`,${s?`
681
+ `:" "}${o(this.scope,a)}`;let t=s&&this.scope===null;return`new Code(${s?`
682
+ `:""}${m}${t?`
683
+ `:""})`}}function jp(c){return c!=null&&typeof c==="object"&&"$id"in c&&c.$id!=null&&"$ref"in c&&typeof c.$ref==="string"&&(!("$db"in c)||("$db"in c)&&typeof c.$db==="string")}class Uc extends S{get _bsontype(){return"DBRef"}constructor(c,a,o,m){super();let s=c.split(".");if(s.length===2)o=s.shift(),c=s.shift();this.collection=c,this.oid=a,this.db=o,this.fields=m||{}}get namespace(){return this.collection}set namespace(c){this.collection=c}toJSON(){let c=Object.assign({$ref:this.collection,$id:this.oid},this.fields);if(this.db!=null)c.$db=this.db;return c}toExtendedJSON(c){c=c||{};let a={$ref:this.collection,$id:this.oid};if(c.legacy)return a;if(this.db)a.$db=this.db;return a=Object.assign(a,this.fields),a}static fromExtendedJSON(c){let a=Object.assign({},c);return delete a.$ref,delete a.$id,delete a.$db,new Uc(c.$ref,c.$id,c.$db,a)}inspect(c,a,o){o??=y;let m=[o(this.namespace,a),o(this.oid,a),...this.db?[o(this.db,a)]:[],...Object.keys(this.fields).length>0?[o(this.fields,a)]:[]];return m[1]=o===y?`new ObjectId(${m[1]})`:m[1],`new DBRef(${m.join(", ")})`}}function Em(c){if(c==="")return c;let a=0,o=c[a]==="-",m=c[a]==="+";if(m||o)a+=1;let s=!1;for(;a<c.length&&c[a]==="0";++a)s=!0;if(!s)return m?c.slice(1):c;return`${o?"-":""}${c.length===a?"0":c.slice(a)}`}function Qp(c,a){a=a??10;let o="0123456789abcdefghijklmnopqrstuvwxyz".slice(0,a);return new RegExp(`[^-+${o}]`,"i").test(c)?!1:c}var L=void 0;try{L=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var nm=65536,np=16777216,Fc=nm*nm,km=Fc*Fc,Jp=km/2,Jm={},Am={},Ap=20,Rp=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;class r extends S{get _bsontype(){return"Long"}get __isLong__(){return!0}constructor(c=0,a,o){super();let m=typeof a==="boolean"?a:Boolean(o),s=typeof a==="number"?a:0,t=typeof c==="string"?r.fromString(c,m):typeof c==="bigint"?r.fromBigInt(c,m):{low:c|0,high:s|0,unsigned:m};this.low=t.low,this.high=t.high,this.unsigned=t.unsigned}static fromBits(c,a,o){return new r(c,a,o)}static fromInt(c,a){let o,m,s;if(a){if(c>>>=0,s=0<=c&&c<256){if(m=Am[c],m)return m}if(o=r.fromBits(c,(c|0)<0?-1:0,!0),s)Am[c]=o;return o}else{if(c|=0,s=-128<=c&&c<128){if(m=Jm[c],m)return m}if(o=r.fromBits(c,c<0?-1:0,!1),s)Jm[c]=o;return o}}static fromNumber(c,a){if(isNaN(c))return a?r.UZERO:r.ZERO;if(a){if(c<0)return r.UZERO;if(c>=km)return r.MAX_UNSIGNED_VALUE}else{if(c<=-9223372036854776000)return r.MIN_VALUE;if(c+1>=Jp)return r.MAX_VALUE}if(c<0)return r.fromNumber(-c,a).neg();return r.fromBits(c%Fc|0,c/Fc|0,a)}static fromBigInt(c,a){let o=BigInt(4294967295),m=BigInt(32);return new r(Number(c&o),Number(c>>m&o),a)}static _fromString(c,a,o){if(c.length===0)throw new $("empty string");if(o<2||36<o)throw new $("radix");let m;if((m=c.indexOf("-"))>0)throw new $("interior hyphen");else if(m===0)return r._fromString(c.substring(1),a,o).neg();let s=r.fromNumber(Math.pow(o,8)),t=r.ZERO;for(let p=0;p<c.length;p+=8){let w=Math.min(8,c.length-p),C=parseInt(c.substring(p,p+w),o);if(w<8){let q=r.fromNumber(Math.pow(o,w));t=t.mul(q).add(r.fromNumber(C))}else t=t.mul(s),t=t.add(r.fromNumber(C))}return t.unsigned=a,t}static fromStringStrict(c,a,o){let m=!1;if(typeof a==="number")o=a,a=!1;else m=!!a;if(o??=10,c.trim()!==c)throw new $(`Input: '${c}' contains leading and/or trailing whitespace`);if(!Qp(c,o))throw new $(`Input: '${c}' contains invalid characters for radix: ${o}`);let s=Em(c),t=r._fromString(s,m,o);if(t.toString(o).toLowerCase()!==s.toLowerCase())throw new $(`Input: ${c} is not representable as ${t.unsigned?"an unsigned":"a signed"} 64-bit Long ${o!=null?`with radix: ${o}`:""}`);return t}static fromString(c,a,o){let m=!1;if(typeof a==="number")o=a,a=!1;else m=!!a;if(o??=10,c==="NaN"&&o<24)return r.ZERO;else if((c==="Infinity"||c==="+Infinity"||c==="-Infinity")&&o<35)return r.ZERO;return r._fromString(c,m,o)}static fromBytes(c,a,o){return o?r.fromBytesLE(c,a):r.fromBytesBE(c,a)}static fromBytesLE(c,a){return new r(c[0]|c[1]<<8|c[2]<<16|c[3]<<24,c[4]|c[5]<<8|c[6]<<16|c[7]<<24,a)}static fromBytesBE(c,a){return new r(c[4]<<24|c[5]<<16|c[6]<<8|c[7],c[0]<<24|c[1]<<16|c[2]<<8|c[3],a)}static isLong(c){return c!=null&&typeof c==="object"&&"__isLong__"in c&&c.__isLong__===!0}static fromValue(c,a){if(typeof c==="number")return r.fromNumber(c,a);if(typeof c==="string")return r.fromString(c,a);return r.fromBits(c.low,c.high,typeof a==="boolean"?a:c.unsigned)}add(c){if(!r.isLong(c))c=r.fromValue(c);let a=this.high>>>16,o=this.high&65535,m=this.low>>>16,s=this.low&65535,t=c.high>>>16,p=c.high&65535,w=c.low>>>16,C=c.low&65535,q=0,g=0,Q=0,A=0;return A+=s+C,Q+=A>>>16,A&=65535,Q+=m+w,g+=Q>>>16,Q&=65535,g+=o+p,q+=g>>>16,g&=65535,q+=a+t,q&=65535,r.fromBits(Q<<16|A,q<<16|g,this.unsigned)}and(c){if(!r.isLong(c))c=r.fromValue(c);return r.fromBits(this.low&c.low,this.high&c.high,this.unsigned)}compare(c){if(!r.isLong(c))c=r.fromValue(c);if(this.eq(c))return 0;let a=this.isNegative(),o=c.isNegative();if(a&&!o)return-1;if(!a&&o)return 1;if(!this.unsigned)return this.sub(c).isNegative()?-1:1;return c.high>>>0>this.high>>>0||c.high===this.high&&c.low>>>0>this.low>>>0?-1:1}comp(c){return this.compare(c)}divide(c){if(!r.isLong(c))c=r.fromValue(c);if(c.isZero())throw new $("division by zero");if(L){if(!this.unsigned&&this.high===-2147483648&&c.low===-1&&c.high===-1)return this;let s=(this.unsigned?L.div_u:L.div_s)(this.low,this.high,c.low,c.high);return r.fromBits(s,L.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?r.UZERO:r.ZERO;let a,o,m;if(!this.unsigned){if(this.eq(r.MIN_VALUE))if(c.eq(r.ONE)||c.eq(r.NEG_ONE))return r.MIN_VALUE;else if(c.eq(r.MIN_VALUE))return r.ONE;else if(a=this.shr(1).div(c).shl(1),a.eq(r.ZERO))return c.isNegative()?r.ONE:r.NEG_ONE;else return o=this.sub(c.mul(a)),m=a.add(o.div(c)),m;else if(c.eq(r.MIN_VALUE))return this.unsigned?r.UZERO:r.ZERO;if(this.isNegative()){if(c.isNegative())return this.neg().div(c.neg());return this.neg().div(c).neg()}else if(c.isNegative())return this.div(c.neg()).neg();m=r.ZERO}else{if(!c.unsigned)c=c.toUnsigned();if(c.gt(this))return r.UZERO;if(c.gt(this.shru(1)))return r.UONE;m=r.UZERO}o=this;while(o.gte(c)){a=Math.max(1,Math.floor(o.toNumber()/c.toNumber()));let s=Math.ceil(Math.log(a)/Math.LN2),t=s<=48?1:Math.pow(2,s-48),p=r.fromNumber(a),w=p.mul(c);while(w.isNegative()||w.gt(o))a-=t,p=r.fromNumber(a,this.unsigned),w=p.mul(c);if(p.isZero())p=r.ONE;m=m.add(p),o=o.sub(w)}return m}div(c){return this.divide(c)}equals(c){if(!r.isLong(c))c=r.fromValue(c);if(this.unsigned!==c.unsigned&&this.high>>>31===1&&c.high>>>31===1)return!1;return this.high===c.high&&this.low===c.low}eq(c){return this.equals(c)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative())return this.eq(r.MIN_VALUE)?64:this.neg().getNumBitsAbs();let c=this.high!==0?this.high:this.low,a;for(a=31;a>0;a--)if((c&1<<a)!==0)break;return this.high!==0?a+33:a+1}greaterThan(c){return this.comp(c)>0}gt(c){return this.greaterThan(c)}greaterThanOrEqual(c){return this.comp(c)>=0}gte(c){return this.greaterThanOrEqual(c)}ge(c){return this.greaterThanOrEqual(c)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(c){return this.comp(c)<0}lt(c){return this.lessThan(c)}lessThanOrEqual(c){return this.comp(c)<=0}lte(c){return this.lessThanOrEqual(c)}modulo(c){if(!r.isLong(c))c=r.fromValue(c);if(L){let a=(this.unsigned?L.rem_u:L.rem_s)(this.low,this.high,c.low,c.high);return r.fromBits(a,L.get_high(),this.unsigned)}return this.sub(this.div(c).mul(c))}mod(c){return this.modulo(c)}rem(c){return this.modulo(c)}multiply(c){if(this.isZero())return r.ZERO;if(!r.isLong(c))c=r.fromValue(c);if(L){let Y=L.mul(this.low,this.high,c.low,c.high);return r.fromBits(Y,L.get_high(),this.unsigned)}if(c.isZero())return r.ZERO;if(this.eq(r.MIN_VALUE))return c.isOdd()?r.MIN_VALUE:r.ZERO;if(c.eq(r.MIN_VALUE))return this.isOdd()?r.MIN_VALUE:r.ZERO;if(this.isNegative())if(c.isNegative())return this.neg().mul(c.neg());else return this.neg().mul(c).neg();else if(c.isNegative())return this.mul(c.neg()).neg();if(this.lt(r.TWO_PWR_24)&&c.lt(r.TWO_PWR_24))return r.fromNumber(this.toNumber()*c.toNumber(),this.unsigned);let a=this.high>>>16,o=this.high&65535,m=this.low>>>16,s=this.low&65535,t=c.high>>>16,p=c.high&65535,w=c.low>>>16,C=c.low&65535,q=0,g=0,Q=0,A=0;return A+=s*C,Q+=A>>>16,A&=65535,Q+=m*C,g+=Q>>>16,Q&=65535,Q+=s*w,g+=Q>>>16,Q&=65535,g+=o*C,q+=g>>>16,g&=65535,g+=m*w,q+=g>>>16,g&=65535,g+=s*p,q+=g>>>16,g&=65535,q+=a*C+o*w+m*p+s*t,q&=65535,r.fromBits(Q<<16|A,q<<16|g,this.unsigned)}mul(c){return this.multiply(c)}negate(){if(!this.unsigned&&this.eq(r.MIN_VALUE))return r.MIN_VALUE;return this.not().add(r.ONE)}neg(){return this.negate()}not(){return r.fromBits(~this.low,~this.high,this.unsigned)}notEquals(c){return!this.equals(c)}neq(c){return this.notEquals(c)}ne(c){return this.notEquals(c)}or(c){if(!r.isLong(c))c=r.fromValue(c);return r.fromBits(this.low|c.low,this.high|c.high,this.unsigned)}shiftLeft(c){if(r.isLong(c))c=c.toInt();if((c&=63)===0)return this;else if(c<32)return r.fromBits(this.low<<c,this.high<<c|this.low>>>32-c,this.unsigned);else return r.fromBits(0,this.low<<c-32,this.unsigned)}shl(c){return this.shiftLeft(c)}shiftRight(c){if(r.isLong(c))c=c.toInt();if((c&=63)===0)return this;else if(c<32)return r.fromBits(this.low>>>c|this.high<<32-c,this.high>>c,this.unsigned);else return r.fromBits(this.high>>c-32,this.high>=0?0:-1,this.unsigned)}shr(c){return this.shiftRight(c)}shiftRightUnsigned(c){if(r.isLong(c))c=c.toInt();if(c&=63,c===0)return this;else{let a=this.high;if(c<32){let o=this.low;return r.fromBits(o>>>c|a<<32-c,a>>>c,this.unsigned)}else if(c===32)return r.fromBits(a,0,this.unsigned);else return r.fromBits(a>>>c-32,0,this.unsigned)}}shr_u(c){return this.shiftRightUnsigned(c)}shru(c){return this.shiftRightUnsigned(c)}subtract(c){if(!r.isLong(c))c=r.fromValue(c);return this.add(c.neg())}sub(c){return this.subtract(c)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){if(this.unsigned)return(this.high>>>0)*Fc+(this.low>>>0);return this.high*Fc+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(c){return c?this.toBytesLE():this.toBytesBE()}toBytesLE(){let c=this.high,a=this.low;return[a&255,a>>>8&255,a>>>16&255,a>>>24,c&255,c>>>8&255,c>>>16&255,c>>>24]}toBytesBE(){let c=this.high,a=this.low;return[c>>>24,c>>>16&255,c>>>8&255,c&255,a>>>24,a>>>16&255,a>>>8&255,a&255]}toSigned(){if(!this.unsigned)return this;return r.fromBits(this.low,this.high,!1)}toString(c){if(c=c||10,c<2||36<c)throw new $("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(r.MIN_VALUE)){let s=r.fromNumber(c),t=this.div(s),p=t.mul(s).sub(this);return t.toString(c)+p.toInt().toString(c)}else return"-"+this.neg().toString(c);let a=r.fromNumber(Math.pow(c,6),this.unsigned),o=this,m="";while(!0){let s=o.div(a),p=(o.sub(s.mul(a)).toInt()>>>0).toString(c);if(o=s,o.isZero())return p+m;else{while(p.length<6)p="0"+p;m=""+p+m}}}toUnsigned(){if(this.unsigned)return this;return r.fromBits(this.low,this.high,!0)}xor(c){if(!r.isLong(c))c=r.fromValue(c);return r.fromBits(this.low^c.low,this.high^c.high,this.unsigned)}eqz(){return this.isZero()}le(c){return this.lessThanOrEqual(c)}toExtendedJSON(c){if(c&&c.relaxed)return this.toNumber();return{$numberLong:this.toString()}}static fromExtendedJSON(c,a){let{useBigInt64:o=!1,relaxed:m=!0}={...a};if(c.$numberLong.length>Ap)throw new $("$numberLong string is too long");if(!Rp.test(c.$numberLong))throw new $(`$numberLong string "${c.$numberLong}" is in an invalid format`);if(o){let t=BigInt(c.$numberLong);return BigInt.asIntN(64,t)}let s=r.fromString(c.$numberLong);if(m)return s.toNumber();return s}inspect(c,a,o){o??=y;let m=o(this.toString(),a),s=this.unsigned?`, ${o(this.unsigned,a)}`:"";return`new Long(${m}${s})`}}r.TWO_PWR_24=r.fromInt(np);r.MAX_UNSIGNED_VALUE=r.fromBits(-1,-1,!0);r.ZERO=r.fromInt(0);r.UZERO=r.fromInt(0,!0);r.ONE=r.fromInt(1);r.UONE=r.fromInt(1,!0);r.NEG_ONE=r.fromInt(-1);r.MAX_VALUE=r.fromBits(-1,2147483647,!1);r.MIN_VALUE=r.fromBits(0,-2147483648,!1);var Pp=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,Wp=/^(\+|-)?(Infinity|inf)$/i,Gp=/^(\+|-)?NaN$/i,Hc=6111,Dc=-6176,Rm=6176,Pm=34,Ea=j.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Wm=j.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Gm=j.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Ip=/^([-+])?(\d+)?$/,Mp=31,Im=16383,Xp=30,Zp=31;function Mm(c){return!isNaN(parseInt(c,10))}function Hp(c){let a=r.fromNumber(1e9),o=r.fromNumber(0);if(!c.parts[0]&&!c.parts[1]&&!c.parts[2]&&!c.parts[3])return{quotient:c,rem:o};for(let m=0;m<=3;m++)o=o.shiftLeft(32),o=o.add(new r(c.parts[m],0)),c.parts[m]=o.div(a).low,o=o.modulo(a);return{quotient:c,rem:o}}function Yp(c,a){if(!c&&!a)return{high:r.fromNumber(0),low:r.fromNumber(0)};let o=c.shiftRightUnsigned(32),m=new r(c.getLowBits(),0),s=a.shiftRightUnsigned(32),t=new r(a.getLowBits(),0),p=o.multiply(s),w=o.multiply(t),C=m.multiply(s),q=m.multiply(t);return p=p.add(w.shiftRightUnsigned(32)),w=new r(w.getLowBits(),0).add(C).add(q.shiftRightUnsigned(32)),p=p.add(w.shiftRightUnsigned(32)),q=w.shiftLeft(32).add(new r(q.getLowBits(),0)),{high:p,low:q}}function Fp(c,a){let o=c.high>>>0,m=a.high>>>0;if(o<m)return!0;else if(o===m){let s=c.low>>>0,t=a.low>>>0;if(s<t)return!0}return!1}function O(c,a){throw new $(`"${c}" is not a valid Decimal128 string - ${a}`)}class z extends S{get _bsontype(){return"Decimal128"}constructor(c){super();if(typeof c==="string")this.bytes=z.fromString(c).bytes;else if(c instanceof Uint8Array||Zm(c)){if(c.byteLength!==16)throw new $("Decimal128 must take a Buffer of 16 bytes");this.bytes=c}else throw new $("Decimal128 must take a Buffer or string")}static fromString(c){return z._fromString(c,{allowRounding:!1})}static fromStringWithRounding(c){return z._fromString(c,{allowRounding:!0})}static _fromString(c,a){let o=!1,m=!1,s=!1,t=!1,p=0,w=0,C=0,q=0,g=0,Q=[0],A=0,Y=0,J=0,P=0,Z=new r(0,0),G=new r(0,0),T=0,l=0;if(c.length>=7000)throw new $(""+c+" not a valid Decimal128 string");let h=c.match(Pp),Ds=c.match(Wp),zs=c.match(Gp);if(!h&&!Ds&&!zs||c.length===0)throw new $(""+c+" not a valid Decimal128 string");if(h){let M=h[2],Jc=h[4],Ac=h[5],k=h[6];if(Jc&&k===void 0)O(c,"missing exponent power");if(Jc&&M===void 0)O(c,"missing exponent base");if(Jc===void 0&&(Ac||k))O(c,"missing e before exponent")}if(c[l]==="+"||c[l]==="-")m=!0,o=c[l++]==="-";if(!Mm(c[l])&&c[l]!=="."){if(c[l]==="i"||c[l]==="I")return new z(o?Wm:Gm);else if(c[l]==="N")return new z(Ea)}while(Mm(c[l])||c[l]==="."){if(c[l]==="."){if(s)O(c,"contains multiple periods");s=!0,l=l+1;continue}if(A<Pm){if(c[l]!=="0"||t){if(!t)g=w;t=!0,Q[Y++]=parseInt(c[l],10),A=A+1}}if(t)C=C+1;if(s)q=q+1;w=w+1,l=l+1}if(s&&!w)throw new $(""+c+" not a valid Decimal128 string");if(c[l]==="e"||c[l]==="E"){let M=c.substr(++l).match(Ip);if(!M||!M[2])return new z(Ea);P=parseInt(M[0],10),l=l+M[0].length}if(c[l])return new z(Ea);if(!A)Q[0]=0,C=1,A=1,p=0;else if(J=A-1,p=C,p!==1)while(c[g+p-1+Number(m)+Number(s)]==="0")p=p-1;if(P<=q&&q>P+16384)P=Dc;else P=P-q;while(P>Hc){if(J=J+1,J>=Pm){if(p===0){P=Hc;break}O(c,"overflow")}P=P-1}if(a.allowRounding){while(P<Dc||A<C){if(J===0&&p<A){P=Dc,p=0;break}if(A<C)C=C-1;else J=J-1;if(P<Hc)P=P+1;else{if(Q.join("").match(/^0+$/)){P=Hc;break}O(c,"overflow")}}if(J+1<p){let M=w;if(s)g=g+1,M=M+1;if(m)g=g+1,M=M+1;let Jc=parseInt(c[g+J+1],10),Ac=0;if(Jc>=5){if(Ac=1,Jc===5){Ac=Q[J]%2===1?1:0;for(let k=g+J+2;k<M;k++)if(parseInt(c[k],10)){Ac=1;break}}}if(Ac){let k=J;for(;k>=0;k--)if(++Q[k]>9){if(Q[k]=0,k===0)if(P<Hc)P=P+1,Q[k]=1;else return new z(o?Wm:Gm)}else break}}}else{while(P<Dc||A<C){if(J===0){if(p===0){P=Dc;break}O(c,"exponent underflow")}if(A<C){if(c[C-1+Number(m)+Number(s)]!=="0"&&p!==0)O(c,"inexact rounding");C=C-1}else{if(Q[J]!==0)O(c,"inexact rounding");J=J-1}if(P<Hc)P=P+1;else O(c,"overflow")}if(J+1<p){if(s)g=g+1;if(m)g=g+1;if(parseInt(c[g+J+1],10)!==0)O(c,"inexact rounding")}}if(Z=r.fromNumber(0),G=r.fromNumber(0),p===0)Z=r.fromNumber(0),G=r.fromNumber(0);else if(J<17){let M=0;G=r.fromNumber(Q[M++]),Z=new r(0,0);for(;M<=J;M++)G=G.multiply(r.fromNumber(10)),G=G.add(r.fromNumber(Q[M]))}else{let M=0;Z=r.fromNumber(Q[M++]);for(;M<=J-17;M++)Z=Z.multiply(r.fromNumber(10)),Z=Z.add(r.fromNumber(Q[M]));G=r.fromNumber(Q[M++]);for(;M<=J;M++)G=G.multiply(r.fromNumber(10)),G=G.add(r.fromNumber(Q[M]))}let v=Yp(Z,r.fromString("100000000000000000"));if(v.low=v.low.add(G),Fp(v.low,G))v.high=v.high.add(r.fromNumber(1));T=P+Rm;let I={low:r.fromNumber(0),high:r.fromNumber(0)};if(v.high.shiftRightUnsigned(49).and(r.fromNumber(1)).equals(r.fromNumber(1)))I.high=I.high.or(r.fromNumber(3).shiftLeft(61)),I.high=I.high.or(r.fromNumber(T).and(r.fromNumber(16383).shiftLeft(47))),I.high=I.high.or(v.high.and(r.fromNumber(140737488355327)));else I.high=I.high.or(r.fromNumber(T&16383).shiftLeft(49)),I.high=I.high.or(v.high.and(r.fromNumber(562949953421311)));if(I.low=v.low,o)I.high=I.high.or(r.fromString("9223372036854775808"));let U=j.allocateUnsafe(16);return l=0,U[l++]=I.low.low&255,U[l++]=I.low.low>>8&255,U[l++]=I.low.low>>16&255,U[l++]=I.low.low>>24&255,U[l++]=I.low.high&255,U[l++]=I.low.high>>8&255,U[l++]=I.low.high>>16&255,U[l++]=I.low.high>>24&255,U[l++]=I.high.low&255,U[l++]=I.high.low>>8&255,U[l++]=I.high.low>>16&255,U[l++]=I.high.low>>24&255,U[l++]=I.high.high&255,U[l++]=I.high.high>>8&255,U[l++]=I.high.high>>16&255,U[l++]=I.high.high>>24&255,new z(U)}toString(){let c,a=0,o=Array(36);for(let l=0;l<o.length;l++)o[l]=0;let m=0,s=!1,t,p={parts:[0,0,0,0]},w,C,q=[];m=0;let g=this.bytes,Q=g[m++]|g[m++]<<8|g[m++]<<16|g[m++]<<24,A=g[m++]|g[m++]<<8|g[m++]<<16|g[m++]<<24,Y=g[m++]|g[m++]<<8|g[m++]<<16|g[m++]<<24,J=g[m++]|g[m++]<<8|g[m++]<<16|g[m++]<<24;if(m=0,{low:new r(Q,A),high:new r(Y,J)}.high.lessThan(r.ZERO))q.push("-");let Z=J>>26&Mp;if(Z>>3===3)if(Z===Xp)return q.join("")+"Infinity";else if(Z===Zp)return"NaN";else c=J>>15&Im,t=8+(J>>14&1);else t=J>>14&7,c=J>>17&Im;let G=c-Rm;if(p.parts[0]=(J&16383)+((t&15)<<14),p.parts[1]=Y,p.parts[2]=A,p.parts[3]=Q,p.parts[0]===0&&p.parts[1]===0&&p.parts[2]===0&&p.parts[3]===0)s=!0;else for(C=3;C>=0;C--){let l=0,h=Hp(p);if(p=h.quotient,l=h.rem.low,!l)continue;for(w=8;w>=0;w--)o[C*9+w]=l%10,l=Math.floor(l/10)}if(s)a=1,o[m]=0;else{a=36;while(!o[m])a=a-1,m=m+1}let T=a-1+G;if(T>=34||T<=-7||G>0){if(a>34){if(q.push("0"),G>0)q.push(`E+${G}`);else if(G<0)q.push(`E${G}`);return q.join("")}if(q.push(`${o[m++]}`),a=a-1,a)q.push(".");for(let l=0;l<a;l++)q.push(`${o[m++]}`);if(q.push("E"),T>0)q.push(`+${T}`);else q.push(`${T}`)}else if(G>=0)for(let l=0;l<a;l++)q.push(`${o[m++]}`);else{let l=a+G;if(l>0)for(let h=0;h<l;h++)q.push(`${o[m++]}`);else q.push("0");q.push(".");while(l++<0)q.push("0");for(let h=0;h<a-Math.max(l-1,0);h++)q.push(`${o[m++]}`)}return q.join("")}toJSON(){return{$numberDecimal:this.toString()}}toExtendedJSON(){return{$numberDecimal:this.toString()}}static fromExtendedJSON(c){return z.fromString(c.$numberDecimal)}inspect(c,a,o){return o??=y,`new Decimal128(${o(this.toString(),a)})`}}class mc extends S{get _bsontype(){return"Double"}constructor(c){super();if(c instanceof Number)c=c.valueOf();this.value=+c}static fromString(c){let a=Number(c);if(c==="NaN")return new mc(NaN);if(c==="Infinity")return new mc(1/0);if(c==="-Infinity")return new mc(-1/0);if(!Number.isFinite(a))throw new $(`Input: ${c} is not representable as a Double`);if(c.trim()!==c)throw new $(`Input: '${c}' contains whitespace`);if(c==="")throw new $("Input is an empty string");if(/[^-0-9.+eE]/.test(c))throw new $(`Input: '${c}' is not in decimal or exponential notation`);return new mc(a)}valueOf(){return this.value}toJSON(){return this.value}toString(c){return this.value.toString(c)}toExtendedJSON(c){if(c&&(c.legacy||c.relaxed&&isFinite(this.value)))return this.value;if(Object.is(Math.sign(this.value),-0))return{$numberDouble:"-0.0"};return{$numberDouble:Number.isInteger(this.value)?this.value.toFixed(1):this.value.toString()}}static fromExtendedJSON(c,a){let o=parseFloat(c.$numberDouble);return a&&a.relaxed?o:new mc(o)}inspect(c,a,o){return o??=y,`new Double(${o(this.value,a)})`}}class Tc extends S{get _bsontype(){return"Int32"}constructor(c){super();if(c instanceof Number)c=c.valueOf();this.value=+c|0}static fromString(c){let a=Em(c),o=Number(c);if(ya<o)throw new $(`Input: '${c}' is larger than the maximum value for Int32`);else if(Sa>o)throw new $(`Input: '${c}' is smaller than the minimum value for Int32`);else if(!Number.isSafeInteger(o))throw new $(`Input: '${c}' is not a safe integer`);else if(o.toString()!==a)throw new $(`Input: '${c}' is not a valid Int32 string`);return new Tc(o)}valueOf(){return this.value}toString(c){return this.value.toString(c)}toJSON(){return this.value}toExtendedJSON(c){if(c&&(c.relaxed||c.legacy))return this.value;return{$numberInt:this.value.toString()}}static fromExtendedJSON(c,a){return a&&a.relaxed?parseInt(c.$numberInt,10):new Tc(c.$numberInt)}inspect(c,a,o){return o??=y,`new Int32(${o(this.value,a)})`}}class sa extends S{get _bsontype(){return"MaxKey"}toExtendedJSON(){return{$maxKey:1}}static fromExtendedJSON(){return new sa}inspect(){return"new MaxKey()"}}class ta extends S{get _bsontype(){return"MinKey"}toExtendedJSON(){return{$minKey:1}}static fromExtendedJSON(){return new ta}inspect(){return"new MinKey()"}}var lc=null,zc=new WeakMap;class H extends S{get _bsontype(){return"ObjectId"}constructor(c){super();let a;if(typeof c==="object"&&c&&"id"in c){if(typeof c.id!=="string"&&!ArrayBuffer.isView(c.id))throw new $("Argument passed in must have an id that is of type string or Buffer");if("toHexString"in c&&typeof c.toHexString==="function")a=j.fromHex(c.toHexString());else a=c.id}else a=c;if(a==null||typeof a==="number")this.buffer=H.generate(typeof a==="number"?a:void 0);else if(ArrayBuffer.isView(a)&&a.byteLength===12)this.buffer=j.toLocalBufferType(a);else if(typeof a==="string")if(H.validateHexString(a)){if(this.buffer=j.fromHex(a),H.cacheHexString)zc.set(this,a)}else throw new $("input must be a 24 character hex string, 12 byte Uint8Array, or an integer");else throw new $("Argument passed in does not match the accepted types")}get id(){return this.buffer}set id(c){if(this.buffer=c,H.cacheHexString)zc.set(this,j.toHex(c))}static validateHexString(c){if(c?.length!==24)return!1;for(let a=0;a<24;a++){let o=c.charCodeAt(a);if(o>=48&&o<=57||o>=97&&o<=102||o>=65&&o<=70)continue;return!1}return!0}toHexString(){if(H.cacheHexString){let a=zc.get(this);if(a)return a}let c=j.toHex(this.id);if(H.cacheHexString)zc.set(this,c);return c}static getInc(){return H.index=(H.index+1)%16777215}static generate(c){if(typeof c!=="number")c=Math.floor(Date.now()/1000);let a=H.getInc(),o=j.allocateUnsafe(12);if(jc.setInt32BE(o,0,c),lc===null)lc=j.randomBytes(5);return o[4]=lc[0],o[5]=lc[1],o[6]=lc[2],o[7]=lc[3],o[8]=lc[4],o[11]=a&255,o[10]=a>>8&255,o[9]=a>>16&255,o}toString(c){if(c==="base64")return j.toBase64(this.id);if(c==="hex")return this.toHexString();return this.toHexString()}toJSON(){return this.toHexString()}static is(c){return c!=null&&typeof c==="object"&&"_bsontype"in c&&c._bsontype==="ObjectId"}equals(c){if(c===void 0||c===null)return!1;if(H.is(c))return this.buffer[11]===c.buffer[11]&&j.equals(this.buffer,c.buffer);if(typeof c==="string")return c.toLowerCase()===this.toHexString();if(typeof c==="object"&&typeof c.toHexString==="function"){let a=c.toHexString(),o=this.toHexString();return typeof a==="string"&&a.toLowerCase()===o}return!1}getTimestamp(){let c=new Date,a=jc.getUint32BE(this.buffer,0);return c.setTime(Math.floor(a)*1000),c}static createPk(){return new H}serializeInto(c,a){return c[a]=this.buffer[0],c[a+1]=this.buffer[1],c[a+2]=this.buffer[2],c[a+3]=this.buffer[3],c[a+4]=this.buffer[4],c[a+5]=this.buffer[5],c[a+6]=this.buffer[6],c[a+7]=this.buffer[7],c[a+8]=this.buffer[8],c[a+9]=this.buffer[9],c[a+10]=this.buffer[10],c[a+11]=this.buffer[11],12}static createFromTime(c){let a=j.allocate(12);for(let o=11;o>=4;o--)a[o]=0;return jc.setInt32BE(a,0,c),new H(a)}static createFromHexString(c){if(c?.length!==24)throw new $("hex string must be 24 characters");return new H(j.fromHex(c))}static createFromBase64(c){if(c?.length!==16)throw new $("base64 string must be 16 characters");return new H(j.fromBase64(c))}static isValid(c){if(c==null)return!1;if(typeof c==="string")return H.validateHexString(c);try{return new H(c),!0}catch{return!1}}toExtendedJSON(){if(this.toHexString)return{$oid:this.toHexString()};return{$oid:this.toString("hex")}}static fromExtendedJSON(c){return new H(c.$oid)}isCached(){return H.cacheHexString&&zc.has(this)}inspect(c,a,o){return o??=y,`new ObjectId(${o(this.toHexString(),a)})`}}H.index=Math.floor(Math.random()*16777215);function Up(c){return c.split("").sort().join("")}class tc extends S{get _bsontype(){return"BSONRegExp"}constructor(c,a){super();if(this.pattern=c,this.options=Up(a??""),this.pattern.indexOf("\x00")!==-1)throw new $(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);if(this.options.indexOf("\x00")!==-1)throw new $(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);for(let o=0;o<this.options.length;o++)if(!(this.options[o]==="i"||this.options[o]==="m"||this.options[o]==="x"||this.options[o]==="l"||this.options[o]==="s"||this.options[o]==="u"))throw new $(`The regular expression option [${this.options[o]}] is not supported`)}static parseOptions(c){return c?c.split("").sort().join(""):""}toExtendedJSON(c){if(c=c||{},c.legacy)return{$regex:this.pattern,$options:this.options};return{$regularExpression:{pattern:this.pattern,options:this.options}}}static fromExtendedJSON(c){if("$regex"in c)if(typeof c.$regex!=="string"){if(c.$regex._bsontype==="BSONRegExp")return c}else return new tc(c.$regex,tc.parseOptions(c.$options));if("$regularExpression"in c)return new tc(c.$regularExpression.pattern,tc.parseOptions(c.$regularExpression.options));throw new $(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(c)}`)}inspect(c,a,o){let m=sp(a)??((p)=>p);o??=y;let s=m(o(this.pattern),"regexp"),t=m(o(this.options),"regexp");return`new BSONRegExp(${s}, ${t})`}}class pa extends S{get _bsontype(){return"BSONSymbol"}constructor(c){super();this.value=c}valueOf(){return this.value}toString(){return this.value}toJSON(){return this.value}toExtendedJSON(){return{$symbol:this.value}}static fromExtendedJSON(c){return new pa(c.$symbol)}inspect(c,a,o){return o??=y,`new BSONSymbol(${o(this.value,a)})`}}var Tp=r;class sc extends Tp{get _bsontype(){return"Timestamp"}get i(){return this.low>>>0}get t(){return this.high>>>0}constructor(c){if(c==null)super(0,0,!0);else if(typeof c==="bigint")super(c,!0);else if(r.isLong(c))super(c.low,c.high,!0);else if(typeof c==="object"&&"t"in c&&"i"in c){if(typeof c.t!=="number"&&(typeof c.t!=="object"||c.t._bsontype!=="Int32"))throw new $("Timestamp constructed from { t, i } must provide t as a number");if(typeof c.i!=="number"&&(typeof c.i!=="object"||c.i._bsontype!=="Int32"))throw new $("Timestamp constructed from { t, i } must provide i as a number");let a=Number(c.t),o=Number(c.i);if(a<0||Number.isNaN(a))throw new $("Timestamp constructed from { t, i } must provide a positive t");if(o<0||Number.isNaN(o))throw new $("Timestamp constructed from { t, i } must provide a positive i");if(a>4294967295)throw new $("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");if(o>4294967295)throw new $("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");super(o,a,!0)}else throw new $("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}toJSON(){return{$timestamp:this.toString()}}static fromInt(c){return new sc(r.fromInt(c,!0))}static fromNumber(c){return new sc(r.fromNumber(c,!0))}static fromBits(c,a){return new sc({i:c,t:a})}static fromString(c,a){return new sc(r.fromString(c,!0,a))}toExtendedJSON(){return{$timestamp:{t:this.t,i:this.i}}}static fromExtendedJSON(c){let a=r.isLong(c.$timestamp.i)?c.$timestamp.i.getLowBitsUnsigned():c.$timestamp.i,o=r.isLong(c.$timestamp.t)?c.$timestamp.t.getLowBitsUnsigned():c.$timestamp.t;return new sc({t:o,i:a})}inspect(c,a,o){o??=y;let m=o(this.t,a),s=o(this.i,a);return`new Timestamp({ t: ${m}, i: ${s} })`}}sc.MAX_VALUE=r.MAX_UNSIGNED_VALUE;var WC=r.fromNumber(tp),GC=r.fromNumber(pp);function hp(c){return c!=null&&typeof c==="object"&&"_bsontype"in c&&typeof c._bsontype==="string"}var Kp={$oid:H,$binary:n,$uuid:n,$symbol:pa,$numberInt:Tc,$numberDecimal:z,$numberDouble:mc,$numberLong:r,$minKey:ta,$maxKey:sa,$regex:tc,$regularExpression:tc,$timestamp:sc};function Vm(c,a={}){if(typeof c==="number"){let m=c<=ya&&c>=Sa,s=c<=Fm&&c>=Um;if(a.relaxed||a.legacy)return c;if(Number.isInteger(c)&&!Object.is(c,-0)){if(m)return new Tc(c);if(s){if(a.useBigInt64)return BigInt(c);return r.fromNumber(c)}}return new mc(c)}if(c==null||typeof c!=="object")return c;if(c.$undefined)return null;let o=Object.keys(c).filter((m)=>m.startsWith("$")&&c[m]!=null);for(let m=0;m<o.length;m++){let s=Kp[o[m]];if(s)return s.fromExtendedJSON(c,a)}if(c.$date!=null){let m=c.$date,s=new Date;if(a.legacy)if(typeof m==="number")s.setTime(m);else if(typeof m==="string")s.setTime(Date.parse(m));else if(typeof m==="bigint")s.setTime(Number(m));else throw new Da(`Unrecognized type for EJSON date: ${typeof m}`);else if(typeof m==="string")s.setTime(Date.parse(m));else if(r.isLong(m))s.setTime(m.toNumber());else if(typeof m==="number"&&a.relaxed)s.setTime(m);else if(typeof m==="bigint")s.setTime(Number(m));else throw new Da(`Unrecognized type for EJSON date: ${typeof m}`);return s}if(c.$code!=null){let m=Object.assign({},c);if(c.$scope)m.$scope=Vm(c.$scope);return Sc.fromExtendedJSON(c)}if(jp(c)||c.$dbPointer){let m=c.$ref?c:c.$dbPointer;if(m instanceof Uc)return m;let s=Object.keys(m).filter((p)=>p.startsWith("$")),t=!0;if(s.forEach((p)=>{if(["$ref","$id","$db"].indexOf(p)===-1)t=!1}),t)return Uc.fromExtendedJSON(m)}return c}function _p(c,a){return c.map((o,m)=>{a.seenObjects.push({propertyName:`index ${m}`,obj:null});try{return oc(o,a)}finally{a.seenObjects.pop()}})}function Xm(c){let a=c.toISOString();return c.getUTCMilliseconds()!==0?a:a.slice(0,-5)+"Z"}function oc(c,a){if(c instanceof Map||Hm(c)){let o=Object.create(null);for(let[m,s]of c){if(typeof m!=="string")throw new $("Can only serialize maps with string keys");o[m]=s}return oc(o,a)}if((typeof c==="object"||typeof c==="function")&&c!==null){let o=a.seenObjects.findIndex((m)=>m.obj===c);if(o!==-1){let m=a.seenObjects.map((g)=>g.propertyName),s=m.slice(0,o).map((g)=>`${g} -> `).join(""),t=m[o],p=" -> "+m.slice(o+1,m.length-1).map((g)=>`${g} -> `).join(""),w=m[m.length-1],C=" ".repeat(s.length+t.length/2),q="-".repeat(p.length+(t.length+w.length)/2-1);throw new $(`Converting circular structure to EJSON:
684
+ ${s}${t}${p}${w}
685
+ ${C}\\${q}/`)}a.seenObjects[a.seenObjects.length-1].obj=c}if(Array.isArray(c))return _p(c,a);if(c===void 0)return null;if(c instanceof Date||mp(c)){let o=c.getTime(),m=o>-1&&o<253402318800000;if(a.legacy)return a.relaxed&&m?{$date:c.getTime()}:{$date:Xm(c)};return a.relaxed&&m?{$date:Xm(c)}:{$date:{$numberLong:c.getTime().toString()}}}if(typeof c==="number"&&(!a.relaxed||!isFinite(c))){if(Number.isInteger(c)&&!Object.is(c,-0)){if(c>=Sa&&c<=ya)return{$numberInt:c.toString()};if(c>=Um&&c<=Fm)return{$numberLong:c.toString()}}return{$numberDouble:Object.is(c,-0)?"-0.0":c.toString()}}if(typeof c==="bigint"){if(!a.relaxed)return{$numberLong:BigInt.asIntN(64,c).toString()};return Number(BigInt.asIntN(64,c))}if(c instanceof RegExp||op(c)){let o=c.flags;if(o===void 0){let s=c.toString().match(/[gimuy]*$/);if(s)o=s[0]}return new tc(c.source,o).toExtendedJSON(a)}if(c!=null&&typeof c==="object")return kp(c,a);return c}var Ep={Binary:(c)=>new n(c.value(),c.sub_type),Code:(c)=>new Sc(c.code,c.scope),DBRef:(c)=>new Uc(c.collection||c.namespace,c.oid,c.db,c.fields),Decimal128:(c)=>new z(c.bytes),Double:(c)=>new mc(c.value),Int32:(c)=>new Tc(c.value),Long:(c)=>r.fromBits(c.low!=null?c.low:c.low_,c.low!=null?c.high:c.high_,c.low!=null?c.unsigned:c.unsigned_),MaxKey:()=>new sa,MinKey:()=>new ta,ObjectId:(c)=>new H(c),BSONRegExp:(c)=>new tc(c.pattern,c.options),BSONSymbol:(c)=>new pa(c.value),Timestamp:(c)=>sc.fromBits(c.low,c.high)};function kp(c,a){if(c==null||typeof c!=="object")throw new $("not an object instance");let o=c._bsontype;if(typeof o>"u"){let m={};for(let s of Object.keys(c)){a.seenObjects.push({propertyName:s,obj:null});try{let t=oc(c[s],a);if(s==="__proto__")Object.defineProperty(m,s,{value:t,writable:!0,enumerable:!0,configurable:!0});else m[s]=t}finally{a.seenObjects.pop()}}return m}else if(c!=null&&typeof c==="object"&&typeof c._bsontype==="string"&&c[Ym]!==za)throw new hm;else if(hp(c)){let m=c;if(typeof m.toExtendedJSON!=="function"){let s=Ep[c._bsontype];if(!s)throw new $("Unrecognized or invalid _bsontype: "+c._bsontype);m=s(m)}if(o==="Code"&&m.scope)m=new Sc(m.code,oc(m.scope,a));else if(o==="DBRef"&&m.oid)m=new Uc(oc(m.collection,a),oc(m.oid,a),oc(m.db,a),oc(m.fields,a));return m.toExtendedJSON(a)}else throw new $("_bsontype must be a string, but was: "+typeof o)}function Dm(c,a){let o={useBigInt64:a?.useBigInt64??!1,relaxed:a?.relaxed??!0,legacy:a?.legacy??!1};return JSON.parse(c,(m,s)=>{if(m.indexOf("\x00")!==-1)throw new $(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(m)}`);return Vm(s,o)})}function zm(c,a,o,m){if(o!=null&&typeof o==="object")m=o,o=0;if(a!=null&&typeof a==="object"&&!Array.isArray(a))m=a,a=void 0,o=0;let s=Object.assign({relaxed:!0,legacy:!1},m,{seenObjects:[{propertyName:"(root)",obj:null}]}),t=oc(c,s);return JSON.stringify(t,a,o)}function Vp(c,a){return a=a||{},JSON.parse(zm(c,a))}function Dp(c,a){return a=a||{},Dm(JSON.stringify(c),a)}var gc=Object.create(null);gc.parse=Dm;gc.stringify=zm;gc.serialize=Vp;gc.deserialize=Dp;Object.freeze(gc);var X={double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:255,maxKey:127};function ka(c,a){try{return jc.getNonnegativeInt32LE(c,a)}catch(o){throw new ac("BSON size cannot be negative",a,{cause:o})}}function Va(c,a){let o=a;for(;c[o]!==0;o++);if(o===c.length-1)throw new ac("Null terminator not found",a);return o}function zp(c,a=0){if(a??=0,c.length<5)throw new ac(`Input must be at least 5 bytes, got ${c.length} bytes`,a);let o=ka(c,a);if(o>c.length-a)throw new ac(`Parsed documentSize (${o} bytes) does not match input length (${c.length} bytes)`,a);if(c[a+o-1]!==0)throw new ac("BSON documents must end in 0x00",a+o);let m=[],s=a+4;while(s<=o+a){let t=c[s];if(s+=1,t===0){if(s-a!==o)throw new ac("Invalid 0x00 type byte",s);break}let p=s,w=Va(c,s)-p;s+=w+1;let C;if(t===X.double||t===X.long||t===X.date||t===X.timestamp)C=8;else if(t===X.int)C=4;else if(t===X.objectId)C=12;else if(t===X.decimal)C=16;else if(t===X.bool)C=1;else if(t===X.null||t===X.undefined||t===X.maxKey||t===X.minKey)C=0;else if(t===X.regex)C=Va(c,Va(c,s)+1)+1-s;else if(t===X.object||t===X.array||t===X.javascriptWithScope)C=ka(c,s);else if(t===X.string||t===X.binData||t===X.dbPointer||t===X.javascript||t===X.symbol){if(C=ka(c,s)+4,t===X.binData)C+=1;if(t===X.dbPointer)C+=12}else throw new ac(`Invalid 0x${t.toString(16).padStart(2,"0")} type byte`,s);if(C>o)throw new ac("value reports length larger than document",s);m.push([t,p,w,s,C]),s+=C}return m}var ra=Object.create(null);ra.parseToElements=zp;ra.ByteUtils=j;ra.NumberUtils=jc;Object.freeze(ra);var yp=17825792,IC=j.allocate(yp);import{execFileSync as Sp}from"node:child_process";import{existsSync as ga,mkdirSync as up,readdirSync as Lp,readFileSync as qa,rmSync as La,writeFileSync as pc}from"node:fs";import{basename as im,dirname as dm,join as E,resolve as Om}from"node:path";var ua=".justo-space.json";function ym(){return{template:"react-vite-shadcn",version:2,collections:{}}}function wa(){return process.execPath}function Qc(c){if(process.platform==="win32")return`${c}.cmd`;return c}var Ca="iUzDOAFCUx33tmT6OCea",uc="VITE_JUSTO_MAP_TILER_TOKEN";function Sm(){return`import {useState, type FormEvent} from 'react'
686
686
  import {Badge} from '@/components/ui/badge'
687
687
  import {Button} from '@/components/ui/button'
688
688
  import {Card, CardContent, CardDescription, CardHeader, CardTitle} from '@/components/ui/card'
@@ -700,7 +700,7 @@ import {justoCli} from '@/lib/justo'
700
700
  const defaultCommand = 'auth status'
701
701
  const queryExample = "data queries preview <queryId> --params '{\\"limit\\":10}'"
702
702
  const mapTilerToken =
703
- (import.meta.env as {${Lc}?: string}).${Lc} ||
703
+ (import.meta.env as {${uc}?: string}).${uc} ||
704
704
  '${Ca}'
705
705
  const chartData = [
706
706
  {day: 'Lun', sessions: 12},
@@ -912,7 +912,7 @@ export function App() {
912
912
  }
913
913
 
914
914
  export default App
915
- `}function So(){return`type JustoCliFunction = <T = unknown>(command: string) => Promise<T>
915
+ `}function um(){return`type JustoCliFunction = <T = unknown>(command: string) => Promise<T>
916
916
  type JustoStreamFunction = <T = unknown>(
917
917
  command: string,
918
918
  onRow: (row: T) => Promise<void> | void,
@@ -1054,7 +1054,7 @@ export async function justoStream<T = unknown>(
1054
1054
  }
1055
1055
 
1056
1056
  ensurePreviewWindowJusto()
1057
- `}function Lo(c){return`# ${c}
1057
+ `}function Lm(c){return`# ${c}
1058
1058
 
1059
1059
  Starter de Justo Spaces generado por \`team-cli spaces init\`.
1060
1060
 
@@ -1086,10 +1086,11 @@ Flujo recomendado:
1086
1086
  Tip:
1087
1087
  - usa \`spaces preview --open\` para abrir el dashboard en el navegador por defecto y mostrárselo al usuario mientras lo iteras
1088
1088
  - \`spaces publish\` sube el repo del space sin \`node_modules\` ni otros archivos ignorados por git, además del build listo para servir
1089
+ - si necesitas escritura en Mongo, declara las collections en \`.justo-space.json\` y usa \`team-cli spaces db\`
1089
1090
  - después de \`spaces init\`, haz un initial commit para fijar el scaffold base
1090
1091
  - después de cada publish, haz commit para que el repo refleje exactamente lo que quedó publicado
1091
1092
  - si alguien necesita ver el dashboard y no puede cargar data, comparte las queries del dashboard con \`team-cli data queries add-viewers <queryId> --emails 'persona@justo.com'\`
1092
- `}function No(){return`import {StrictMode} from 'react'
1093
+ `}function Nm(){return`import {StrictMode} from 'react'
1093
1094
  import {createRoot} from 'react-dom/client'
1094
1095
  import App from './App.tsx'
1095
1096
  import './index.css'
@@ -1100,13 +1101,52 @@ createRoot(document.getElementById('root')!).render(
1100
1101
  <App />
1101
1102
  </StrictMode>,
1102
1103
  )
1103
- `}function Nc(c,a,m){Sw(c,a,{cwd:m,stdio:"inherit",env:{...process.env,CI:"1"}})}function uw(c){if(!c)throw Error("Falta --path. Ejemplo: team-cli spaces init --path ./mi-space-app");let a=io(c);if(qa(a)){if(Nw(a).length>0)throw Error(`La carpeta ya existe y no está vacía: ${a}`);Na(a,{recursive:!0,force:!0})}return Lw(Oo(a),{recursive:!0}),a}function Ow(c){let a=E(c,"vite.config.ts"),m=ga(a,"utf-8");if(m.includes("base: './'"))return;let o=m.replace("export default defineConfig({",`export default defineConfig({
1104
- base: './',`);wc(a,o)}function dw(c){let a=E(c,"tsconfig.app.json"),o=ga(a,"utf-8").replace('"noUnusedLocals": true,','"noUnusedLocals": false,').replace('"noUnusedParameters": true,','"noUnusedParameters": false,');wc(a,o)}function iw(c){let a=E(c,"package.json"),m=JSON.parse(ga(a,"utf-8"));m.dependencies=m.dependencies||{},m.devDependencies=m.devDependencies||{},m.dependencies.leaflet="^1.9.4",m.dependencies["react-leaflet"]="^5.0.0",m.devDependencies["@types/leaflet"]="^1.9.20",m.justoSpaceApp=!0,wc(a,`${JSON.stringify(m,null,2)}
1105
- `)}function Bw(c){let a=E(c,"src","index.css"),m=ga(a,"utf-8");if(m.includes("leaflet/dist/leaflet.css"))return;wc(a,`@import "leaflet/dist/leaflet.css";
1106
- ${m}`)}function bw(c){let a=uo(c);wc(E(c,"README.md"),Lo(a)),wc(E(c,"src","App.tsx"),yo()),wc(E(c,"src","main.tsx"),No()),wc(E(c,"src","lib","justo.ts"),So()),wc(E(c,La),`${JSON.stringify(zo(),null,2)}
1107
- `),Na(E(c,".git"),{recursive:!0,force:!0})}function vw(c){Nc("git",["init"],c)}function xw(c){Na(E(c,"package-lock.json"),{force:!0})}function ua(c){let a=io(c);if(!qa(a))throw Error(`No existe la app del space: ${a}`);if(!qa(E(a,La)))throw Error("Este publish solo acepta apps creadas con team-cli spaces init. Debes apuntar al root de esa app.");return a}function Bo(c){let a=ua(c);Nc(Jc("yarn"),["build"],a);let m=E(a,"dist");if(!qa(E(m,"index.html")))throw Error("El build no generó dist/index.html");return m}function bo(c){let a=uw(c),m=Oo(a),o=uo(a);return Nc(Jc("npx"),["shadcn@latest","init","-t","vite","-d","-y","-n",o],m),Nc(Jc("npx"),["shadcn@latest","add","-a","-y"],a),xw(a),iw(a),Nc(Jc("yarn"),["install"],a),Ow(a),dw(a),Bw(a),bw(a),vw(a),{path:a,nextSteps:[`cd ${a}`,'git add . && git commit -m "chore: initial space scaffold"',"team-cli spaces create --name '...' --description '...' --slug dashboard-1234","team-cli spaces publish <spaceId> --path .",'git add . && git commit -m "feat: update published space"']}}import{readdirSync as fo,readFileSync as cs,statSync as as}from"node:fs";import{gzipSync as wp}from"node:zlib";import{join as ms,relative as os,resolve as xo}from"node:path";import{existsSync as ew,readFileSync as fw}from"node:fs";import{join as cp}from"node:path";var ap=[".git","node_modules","dist",".justo-space-preview",".DS_Store"];function mp(c){return c.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function op(c){let a="";for(let m=0;m<c.length;m++){let o=c[m],s=c[m+1];if(o==="*"){if(s==="*"){a+=".*",m+=1;continue}a+="[^/]*";continue}if(o==="?"){a+="[^/]";continue}a+=mp(o)}return a}function sp(c){let a=c.trim();if(!a||a.startsWith("#"))return null;let m=a.startsWith("!"),o=m?a.slice(1).trim():a;if(!o)return null;let s=o.endsWith("/"),t=o.replace(/^\/+/,"").replace(/\/+$/,"");if(!t)return null;let w=t.includes("/"),r=op(t),C=w?`^${r}${s?"(?:/.*)?":""}$`:`(?:^|/)${r}${s?"(?:/.*)?":"(?:$|/)"}`;return{negate:m,directoryOnly:s,regex:new RegExp(C)}}function tp(c){let a=cp(c,".gitignore"),m=[...ap];if(ew(a))m.push(...fw(a,"utf-8").split(/\r?\n/));return m.map(sp).filter((o)=>Boolean(o))}function vo(c){let a=tp(c);return(m,o)=>{let s=m.replaceAll("\\","/").replace(/^\/+/,""),t=!1;for(let w of a){if(!w.regex.test(s))continue;t=!w.negate}return t}}var $a=512,pp=2,rp="repo",Cp="dist";function qp(c){let a=c.replaceAll("\\","/");if(a.startsWith("/")||a.includes("../"))throw Error(`Ruta inválida en el space: ${c}`);return a}function gp(c){let a=qp(c);if(Buffer.from(a).length<=100)return{name:a,prefix:""};let o=a.lastIndexOf("/");if(o<=0)throw Error(`La ruta es demasiado larga para el paquete del space: ${c}`);let s=a.slice(0,o),t=a.slice(o+1);if(Buffer.from(s).length>155||Buffer.from(t).length>100)throw Error(`La ruta es demasiado larga para el paquete del space: ${c}`);return{name:t,prefix:s}}function Ac(c,a,m,o){let s=Buffer.from(o);s.copy(c,a,0,Math.min(s.length,m))}function uc(c,a,m,o){let s=Math.max(0,Math.trunc(o)).toString(8).padStart(m-1,"0");Ac(c,a,m,`${s}\x00`)}function $p(c){let a=Buffer.alloc($a,0),{name:m,prefix:o}=gp(c.path);Ac(a,0,100,m),uc(a,100,8,c.mode),uc(a,108,8,0),uc(a,116,8,0),uc(a,124,12,c.content.length),uc(a,136,12,c.mtime),a.fill(32,148,156),Ac(a,156,1,"0"),Ac(a,257,6,"ustar"),Ac(a,263,2,"00"),Ac(a,345,155,o);let s=0;for(let w of a)s+=w;let t=`${s.toString(8).padStart(6,"0")}\x00 `;return Ac(a,148,8,t),a}function Qp(c){let a=c%$a;return a===0?0:$a-a}function ss(c,a=c){return fo(a,{withFileTypes:!0}).sort((o,s)=>o.name.localeCompare(s.name)).flatMap((o)=>{let s=ms(a,o.name);if(o.isDirectory())return ss(c,s);if(!o.isFile())return[];let t=os(c,s),w=as(s);return[{path:t,content:cs(s),mode:w.mode&511,mtime:Math.floor(w.mtimeMs/1000)}]})}function eo(c,a){return c.map((m)=>({...m,path:`${a}/${m.path.replaceAll("\\","/")}`}))}function ts(c,a=c){let m=vo(c);return fo(a,{withFileTypes:!0}).sort((s,t)=>s.name.localeCompare(t.name)).flatMap((s)=>{let t=ms(a,s.name),w=os(c,t).replaceAll("\\","/");if(m(w,s.isDirectory()))return[];if(s.isDirectory())return ts(c,t);if(!s.isFile())return[];let r=as(t);return[{path:w,content:cs(t),mode:r.mode&511,mtime:Math.floor(r.mtimeMs/1000)}]})}function ws(c,a){let m=xo(c),o=xo(a),s=[...eo(ts(m),rp),...eo(ss(o),Cp)];if(!s.length)throw Error("El build del space no contiene archivos para publicar");let t=[];for(let w of s){t.push($p(w)),t.push(w.content);let r=Qp(w.content.length);if(r>0)t.push(Buffer.alloc(r,0))}return t.push(Buffer.alloc($a*pp,0)),wp(Buffer.concat(t))}import{mkdirSync as ps,writeFileSync as jp}from"node:fs";import{dirname as Jp,join as Ap,normalize as Pp,sep as rs}from"node:path";import{gunzipSync as Rp}from"node:zlib";var Oc=512;function Qa(c,a,m){let o=c.subarray(a,a+m),s=o.indexOf(0);return(s>=0?o.subarray(0,s):o).toString("utf-8").trim()}function lp(c,a,m){let o=Qa(c,a,m).replaceAll("\x00","").trim();if(!o)return 0;return Number.parseInt(o,8)}function Wp(c){let a=c%Oc;return a===0?0:Oc-a}function Gp(c){let a=Qa(c,0,100),m=Qa(c,345,155);return m?`${m}/${a}`:a}function Ip(c){let a=Pp(c);if(!c||c.startsWith("/")||a.startsWith("..")||a.includes(`${rs}..${rs}`)||a==="..")throw Error("El paquete del space contiene rutas inválidas")}function Cs(c,a,m){let o=Rp(c),s=a.replaceAll("\\","/").replace(/^\/+|\/+$/g,""),t=`${s}/`,w=0,r=0;while(w+Oc<=o.length){let C=o.subarray(w,w+Oc),g=C.every((H)=>H===0);if(w+=Oc,g)break;let q=Gp(C),J=Qa(C,156,1)||"0",R=lp(C,124,12),F=o.subarray(w,w+R);if(w+=R+Wp(R),!q.startsWith(t))continue;let P=q.slice(t.length);if(!P)continue;Ip(P);let W=Ap(m,...P.split("/"));if(J==="5"){ps(W,{recursive:!0});continue}if(J!=="0")continue;ps(Jp(W),{recursive:!0}),jp(W,F),r+=1}if(!r)throw Error(`El paquete del space no contiene la carpeta ${s}/`);return r}import{spawn as Ja}from"node:child_process";import{createServer as Ps}from"node:http";import{existsSync as Xp,mkdirSync as Zp,openSync as Mp,readFileSync as Hp,rmSync as Yp,writeFileSync as Fp}from"node:fs";import{dirname as Up,join as Aa,resolve as Rs}from"node:path";import{request as Tp}from"node:http";import{request as np}from"node:https";function qs(c){let a=[],m="",o=null,s=!1;for(let t of c){if(s){m+=t,s=!1;continue}if(t==="\\"){s=!0;continue}if(o){if(t===o)o=null;else m+=t;continue}if(t==='"'||t==="'"){o=t;continue}if(/\s/.test(t)){if(m)a.push(m),m="";continue}m+=t}if(o)throw Error("Comando inválido: falta cerrar una comilla");if(m)a.push(m);return a}var hp=".justo-space-preview",Kp="preview.json",_p=30000;function Pa(c){return Aa(c,hp)}function ls(c){return Aa(Pa(c),Kp)}function gs(c){return Aa(Pa(c),"bridge.log")}function $s(c){return Aa(Pa(c),"vite.log")}function Ws(c){Zp(Pa(c),{recursive:!0})}function ja(c){if(!c)return;try{process.kill(c,"SIGTERM")}catch{return}}function Ep(c){if(process.platform==="darwin")return{command:"open",args:[c]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",c]};return{command:"xdg-open",args:[c]}}async function kp(c,a){if(!a)return{attempted:!1,opened:!1};let m=Ep(c);return await new Promise((o)=>{let s=Ja(m.command,m.args,{stdio:"ignore",detached:!0});s.once("error",()=>{o({attempted:!0,opened:!1,message:"No se pudo abrir el navegador por defecto automáticamente. Abre la URL manualmente."})}),s.once("spawn",()=>{s.unref(),o({attempted:!0,opened:!0})})})}function Vp(c){let a=ls(c);if(!Xp(a))return;try{let m=JSON.parse(Hp(a,"utf-8"));ja(m.appPid),ja(m.bridgePid)}catch{}Yp(a,{force:!0})}function Qs(){return new Promise((c,a)=>{let m=Ps();m.listen(0,"127.0.0.1",()=>{let o=m.address();if(!o||typeof o==="string"){m.close(),a(Error("No se pudo obtener un puerto libre"));return}let{port:s}=o;m.close((t)=>{if(t){a(t);return}c(s)})}),m.on("error",a)})}function js(c){return new Promise((a)=>setTimeout(a,c))}function Dp(c){return new Promise((a,m)=>{let t=(new URL(c).protocol==="https:"?np:Tp)(c,{method:"GET"},(w)=>{a(w.statusCode||0),w.resume()});t.on("error",m),t.end()})}async function Js(c,a=_p){let m=Date.now();while(Date.now()-m<a){try{if(await Dp(c)>0)return}catch{await js(500);continue}await js(500)}throw Error(`Timeout esperando que el preview responda en ${c}`)}function zp(c){return Ws(Up(c)),Mp(c,"a")}function As(c,a,m,o,s){let t=zp(o),w=Ja(c,a,{cwd:m,detached:!0,stdio:["ignore",t,t],env:{...process.env,...s}});if(!w.pid)throw Error(`No se pudo iniciar el proceso ${c}`);return w.unref(),w.pid}function Gs(){let c=pm("prod");if(!c)throw Error("Debes iniciar sesión en prod antes de usar spaces preview. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>");return c}async function yp(c){let a=[];for await(let m of c)a.push(Buffer.isBuffer(m)?m:Buffer.from(m));return Buffer.concat(a).toString("utf-8")}function dc(c,a,m){c.writeHead(a,{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Methods":"POST,OPTIONS,GET"}),c.end(JSON.stringify(m))}function Oa(c){let a=c.trim(),m=new Set([0]);for(let s=0;s<a.length;s++)if(a[s]==="{"||a[s]==="[")m.add(s);let o=[...m].sort((s,t)=>t-s);for(let s of o)try{return JSON.parse(a.slice(s))}catch{continue}return a}function Is(c){return{...process.env,NODE_OPTIONS:"",__JUSTO_REPL_PORT:"",JUSTO_TEAM_CLI_EMAIL:c.email,JUSTO_TEAM_CLI_TOKEN:c.token,JUSTO_TEAM_CLI_REFRESH_TOKEN:c.refreshToken,JUSTO_TEAM_CLI_INTERACTIVE:"false",JUSTO_TEAM_CLI_DEVICE_ID:"spaces-preview"}}function Sp(c,a){return{VITE_JUSTO_CLI_ENDPOINT:c,VITE_JUSTO_STREAM_ENDPOINT:a,VITE_JUSTO_CLI_MODE:"preview",[Lc]:Ca}}function Lp(c,a,m,o){return new Promise((s,t)=>{let w=Ja(ra(),[a,"--env","prod",...o,"--format","json"],{cwd:process.cwd(),env:Is(m),stdio:["ignore","pipe","pipe"]}),r="";w.stdout.on("data",(C)=>{if(!c.headersSent)c.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Methods":"POST,OPTIONS,GET"});c.write(C)}),w.stderr.on("data",(C)=>{r+=Buffer.from(C).toString("utf-8")}),w.on("error",t),w.on("close",(C)=>{if(!C){if(!c.headersSent)c.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Methods":"POST,OPTIONS,GET"});c.end(),s();return}let g=Oa(r.trim());t(Error(g.error||r.trim()||"justoStream failed"))})})}async function Xs(c){let a=Number(c.port);if(!a)throw Error("Falta --port para el bridge interno de preview");let m=Gs(),o=Rs(c["cli-path"]||process.argv[1]||""),s=Ps(async(t,w)=>{if(t.method==="OPTIONS"){dc(w,200,{ok:!0});return}if(t.method==="GET"&&t.url==="/__justo/health"){dc(w,200,{ok:!0});return}if(t.method!=="POST"||t.url!=="/__justo/cli"&&t.url!=="/__justo/stream"){dc(w,404,{ok:!1,error:"Not found"});return}try{let r=await yp(t),g=JSON.parse(r||"{}").command;if(!g)throw Error("Debes indicar un comando");let q=Array.isArray(g)?g:qs(g);if(t.url==="/__justo/stream"){await Lp(w,o,m,q);return}let J=await new Promise((R,F)=>{let P=Ja(ra(),[o,"--env","prod",...q,"--format","json"],{cwd:process.cwd(),env:Is(m),stdio:["ignore","pipe","pipe"]}),W=[],H=[];P.stdout.on("data",(I)=>W.push(Buffer.from(I))),P.stderr.on("data",(I)=>H.push(Buffer.from(I))),P.on("error",F),P.on("close",(I)=>{let n=Buffer.concat(W).toString("utf-8")||Buffer.concat(H).toString("utf-8");if(I&&I!==0){let Q=Oa(n);F(Error(Q.error||n||"justoCli failed"));return}R(Oa(n))})});dc(w,200,{result:J})}catch(r){let C=r instanceof Error?r.message:"Unexpected error";dc(w,400,{error:C})}});await new Promise((t,w)=>{s.listen(a,"127.0.0.1",()=>t()),s.on("error",w)}),D(`Space preview bridge listening on http://127.0.0.1:${a}
1108
- `),await new Promise((t,w)=>{s.on("close",()=>t()),s.on("error",w)})}async function Zs(c){let a=c.path;if(!a)throw Error("Falta --path. Ejemplo: team-cli spaces preview --path ./mi-space-app");let m=ua(a);Gs(),Ws(m),Vp(m);let o=Number(c.port)||await Qs(),s=Number(c["bridge-port"])||await Qs(),t=c.open==="true",w=`http://127.0.0.1:${o}`,r=`http://127.0.0.1:${s}/__justo/cli`,C=`http://127.0.0.1:${s}/__justo/stream`,g=Rs(process.argv[1]||""),q=As(ra(),[g,"__spaces-preview-bridge","--port",String(s),"--cli-path",g],process.cwd(),gs(m),{}),J=As(Jc("yarn"),["dev","--host","127.0.0.1","--port",String(o)],m,$s(m),Sp(r,C));try{await Js(`http://127.0.0.1:${s}/__justo/health`),await Js(w)}catch(P){throw ja(J),ja(q),P}let R={appPid:J,bridgePid:q,previewUrl:w,bridgeUrl:r,streamUrl:C,cliEnv:"prod"};Fp(ls(m),`${JSON.stringify(R,null,2)}
1109
- `);let F=await kp(w,t);return{ok:!0,path:m,previewUrl:w,bridgeUrl:r,streamUrl:C,cliEnv:"prod",appPid:J,bridgePid:q,logs:{app:$s(m),bridge:gs(m)},open:F}}function dp(c){try{return qc.parse(c)}catch{throw Error("El valor de --operation debe ser JSON/EJSON válido")}}function ic(){if(!U())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function gc(c,a,m){let o=c[a];if(!o)throw Error(`Falta --${a}. Ejemplo: ${m}`);return o}function Hs(c,a){let m=c[2];if(!m)throw Error(`Uso: ${a}`);return m}function da(){let c=ec();if(c==="local")return"http://intra.localhost:5173";if(c==="develop")return"https://intra.bejusto.com";return"https://intra.getjusto.com"}async function ip(c,a){let m=await aa(),o=await fetch(`${K("data")}/spaces/publish/${c}`,{method:"POST",headers:{"Content-Type":"application/gzip",...m?{"X-ORION-JWT":m}:{}},body:a}),s=await o.json();if(!o.ok||s.error)throw Error(s.error||"No se pudo publicar el space.");return s}async function Bp(c){let a=await aa(),m=await fetch(`${K("data")}/spaces/fork/${c}`,{method:"GET",headers:a?{"X-ORION-JWT":a}:{}});if(!m.ok){let o=await m.json().catch(()=>({}));throw Error(o.error||"No se pudo descargar el repo del space.")}return Buffer.from(await m.arrayBuffer())}function bp(c){let a=Ms(c);if(Np(a)&&Op(a).length>0)throw Error(`La carpeta ya existe y no está vacía: ${a}`);return up(a,{recursive:!0}),a}function ia(){return`team-cli spaces
1104
+ `}function Lc(c,a,o){Sp(c,a,{cwd:o,stdio:"inherit",env:{...process.env,CI:"1"}})}function Np(c){if(!c)throw Error("Falta --path. Ejemplo: team-cli spaces init --path ./mi-space-app");let a=Om(c);if(ga(a)){if(Lp(a).length>0)throw Error(`La carpeta ya existe y no está vacía: ${a}`);La(a,{recursive:!0,force:!0})}return up(dm(a),{recursive:!0}),a}function ip(c){let a=E(c,"vite.config.ts"),o=qa(a,"utf-8");if(o.includes("base: './'"))return;let m=o.replace("export default defineConfig({",`export default defineConfig({
1105
+ base: './',`);pc(a,m)}function dp(c){let a=E(c,"tsconfig.app.json"),m=qa(a,"utf-8").replace('"noUnusedLocals": true,','"noUnusedLocals": false,').replace('"noUnusedParameters": true,','"noUnusedParameters": false,');pc(a,m)}function Op(c){let a=E(c,"package.json"),o=JSON.parse(qa(a,"utf-8"));o.dependencies=o.dependencies||{},o.devDependencies=o.devDependencies||{},o.dependencies.leaflet="^1.9.4",o.dependencies["react-leaflet"]="^5.0.0",o.devDependencies["@types/leaflet"]="^1.9.20",o.justoSpaceApp=!0,pc(a,`${JSON.stringify(o,null,2)}
1106
+ `)}function bp(c){let a=E(c,"src","index.css"),o=qa(a,"utf-8");if(o.includes("leaflet/dist/leaflet.css"))return;pc(a,`@import "leaflet/dist/leaflet.css";
1107
+ ${o}`)}function Bp(c){let a=im(c);pc(E(c,"README.md"),Lm(a)),pc(E(c,"src","App.tsx"),Sm()),pc(E(c,"src","main.tsx"),Nm()),pc(E(c,"src","lib","justo.ts"),um()),pc(E(c,ua),`${JSON.stringify(ym(),null,2)}
1108
+ `),La(E(c,".git"),{recursive:!0,force:!0})}function vp(c){Lc("git",["init"],c)}function ep(c){La(E(c,"package-lock.json"),{force:!0})}function Na(c){let a=Om(c);if(!ga(a))throw Error(`No existe la app del space: ${a}`);if(!ga(E(a,ua)))throw Error("Este publish solo acepta apps creadas con team-cli spaces init. Debes apuntar al root de esa app.");return a}function bm(c){let a=Na(c);Lc(Qc("yarn"),["build"],a);let o=E(a,"dist");if(!ga(E(o,"index.html")))throw Error("El build no generó dist/index.html");return o}function Bm(c){let a=Np(c),o=dm(a),m=im(a);return Lc(Qc("npx"),["shadcn@latest","init","-t","vite","-d","-y","-n",m],o),Lc(Qc("npx"),["shadcn@latest","add","-a","-y"],a),ep(a),Op(a),Lc(Qc("yarn"),["install"],a),ip(a),dp(a),bp(a),Bp(a),vp(a),{path:a,nextSteps:[`cd ${a}`,'git add . && git commit -m "chore: initial space scaffold"',"team-cli spaces create --name '...' --description '...' --slug dashboard-1234","team-cli spaces publish <spaceId> --path .",'git add . && git commit -m "feat: update published space"']}}import{readdirSync as fm,readFileSync as cs,statSync as as}from"node:fs";import{gzipSync as pr}from"node:zlib";import{join as os,relative as ms,resolve as em}from"node:path";import{existsSync as xp,readFileSync as fp}from"node:fs";import{join as cr}from"node:path";var ar=[".git","node_modules","dist",".justo-space-preview",".DS_Store"];function or(c){return c.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function mr(c){let a="";for(let o=0;o<c.length;o++){let m=c[o],s=c[o+1];if(m==="*"){if(s==="*"){a+=".*",o+=1;continue}a+="[^/]*";continue}if(m==="?"){a+="[^/]";continue}a+=or(m)}return a}function sr(c){let a=c.trim();if(!a||a.startsWith("#"))return null;let o=a.startsWith("!"),m=o?a.slice(1).trim():a;if(!m)return null;let s=m.endsWith("/"),t=m.replace(/^\/+/,"").replace(/\/+$/,"");if(!t)return null;let p=t.includes("/"),w=mr(t),C=p?`^${w}${s?"(?:/.*)?":""}$`:`(?:^|/)${w}${s?"(?:/.*)?":"(?:$|/)"}`;return{negate:o,directoryOnly:s,regex:new RegExp(C)}}function tr(c){let a=cr(c,".gitignore"),o=[...ar];if(xp(a))o.push(...fp(a,"utf-8").split(/\r?\n/));return o.map(sr).filter((m)=>Boolean(m))}function vm(c){let a=tr(c);return(o,m)=>{let s=o.replaceAll("\\","/").replace(/^\/+/,""),t=!1;for(let p of a){if(!p.regex.test(s))continue;t=!p.negate}return t}}var $a=512,rr=2,wr="repo",Cr="dist";function gr(c){let a=c.replaceAll("\\","/");if(a.startsWith("/")||a.includes("../"))throw Error(`Ruta inválida en el space: ${c}`);return a}function qr(c){let a=gr(c);if(Buffer.from(a).length<=100)return{name:a,prefix:""};let m=a.lastIndexOf("/");if(m<=0)throw Error(`La ruta es demasiado larga para el paquete del space: ${c}`);let s=a.slice(0,m),t=a.slice(m+1);if(Buffer.from(s).length>155||Buffer.from(t).length>100)throw Error(`La ruta es demasiado larga para el paquete del space: ${c}`);return{name:t,prefix:s}}function nc(c,a,o,m){let s=Buffer.from(m);s.copy(c,a,0,Math.min(s.length,o))}function Nc(c,a,o,m){let s=Math.max(0,Math.trunc(m)).toString(8).padStart(o-1,"0");nc(c,a,o,`${s}\x00`)}function $r(c){let a=Buffer.alloc($a,0),{name:o,prefix:m}=qr(c.path);nc(a,0,100,o),Nc(a,100,8,c.mode),Nc(a,108,8,0),Nc(a,116,8,0),Nc(a,124,12,c.content.length),Nc(a,136,12,c.mtime),a.fill(32,148,156),nc(a,156,1,"0"),nc(a,257,6,"ustar"),nc(a,263,2,"00"),nc(a,345,155,m);let s=0;for(let p of a)s+=p;let t=`${s.toString(8).padStart(6,"0")}\x00 `;return nc(a,148,8,t),a}function lr(c){let a=c%$a;return a===0?0:$a-a}function ss(c,a=c){return fm(a,{withFileTypes:!0}).sort((m,s)=>m.name.localeCompare(s.name)).flatMap((m)=>{let s=os(a,m.name);if(m.isDirectory())return ss(c,s);if(!m.isFile())return[];let t=ms(c,s),p=as(s);return[{path:t,content:cs(s),mode:p.mode&511,mtime:Math.floor(p.mtimeMs/1000)}]})}function xm(c,a){return c.map((o)=>({...o,path:`${a}/${o.path.replaceAll("\\","/")}`}))}function ts(c,a=c){let o=vm(c);return fm(a,{withFileTypes:!0}).sort((s,t)=>s.name.localeCompare(t.name)).flatMap((s)=>{let t=os(a,s.name),p=ms(c,t).replaceAll("\\","/");if(o(p,s.isDirectory()))return[];if(s.isDirectory())return ts(c,t);if(!s.isFile())return[];let w=as(t);return[{path:p,content:cs(t),mode:w.mode&511,mtime:Math.floor(w.mtimeMs/1000)}]})}function ps(c,a){let o=em(c),m=em(a),s=[...xm(ts(o),wr),...xm(ss(m),Cr)];if(!s.length)throw Error("El build del space no contiene archivos para publicar");let t=[];for(let p of s){t.push($r(p)),t.push(p.content);let w=lr(p.content.length);if(w>0)t.push(Buffer.alloc(w,0))}return t.push(Buffer.alloc($a*rr,0)),pr(Buffer.concat(t))}import{mkdirSync as rs,writeFileSync as jr}from"node:fs";import{dirname as Qr,join as nr,normalize as Jr,sep as ws}from"node:path";import{gunzipSync as Ar}from"node:zlib";var ic=512;function la(c,a,o){let m=c.subarray(a,a+o),s=m.indexOf(0);return(s>=0?m.subarray(0,s):m).toString("utf-8").trim()}function Rr(c,a,o){let m=la(c,a,o).replaceAll("\x00","").trim();if(!m)return 0;return Number.parseInt(m,8)}function Pr(c){let a=c%ic;return a===0?0:ic-a}function Wr(c){let a=la(c,0,100),o=la(c,345,155);return o?`${o}/${a}`:a}function Gr(c){let a=Jr(c);if(!c||c.startsWith("/")||a.startsWith("..")||a.includes(`${ws}..${ws}`)||a==="..")throw Error("El paquete del space contiene rutas inválidas")}function Cs(c,a,o){let m=Ar(c),s=a.replaceAll("\\","/").replace(/^\/+|\/+$/g,""),t=`${s}/`,p=0,w=0;while(p+ic<=m.length){let C=m.subarray(p,p+ic),q=C.every((Z)=>Z===0);if(p+=ic,q)break;let g=Wr(C),Q=la(C,156,1)||"0",A=Rr(C,124,12),Y=m.subarray(p,p+A);if(p+=A+Pr(A),!g.startsWith(t))continue;let J=g.slice(t.length);if(!J)continue;Gr(J);let P=nr(o,...J.split("/"));if(Q==="5"){rs(P,{recursive:!0});continue}if(Q!=="0")continue;rs(Qr(P),{recursive:!0}),jr(P,Y),w+=1}if(!w)throw Error(`El paquete del space no contiene la carpeta ${s}/`);return w}import{spawn as Qa}from"node:child_process";import{createServer as Js}from"node:http";import{existsSync as Ir,mkdirSync as Mr,openSync as Xr,readFileSync as Zr,rmSync as Hr,writeFileSync as Yr}from"node:fs";import{dirname as Fr,join as na,resolve as As}from"node:path";import{request as Ur}from"node:http";import{request as Tr}from"node:https";function gs(c){let a=[],o="",m=null,s=!1;for(let t of c){if(s){o+=t,s=!1;continue}if(t==="\\"){s=!0;continue}if(m){if(t===m)m=null;else o+=t;continue}if(t==='"'||t==="'"){m=t;continue}if(/\s/.test(t)){if(o)a.push(o),o="";continue}o+=t}if(m)throw Error("Comando inválido: falta cerrar una comilla");if(o)a.push(o);return a}var hr=".justo-space-preview",Kr="preview.json",_r=30000;function Ja(c){return na(c,hr)}function Rs(c){return na(Ja(c),Kr)}function qs(c){return na(Ja(c),"bridge.log")}function $s(c){return na(Ja(c),"vite.log")}function Ps(c){Mr(Ja(c),{recursive:!0})}function ja(c){if(!c)return;try{process.kill(c,"SIGTERM")}catch{return}}function Er(c){if(process.platform==="darwin")return{command:"open",args:[c]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",c]};return{command:"xdg-open",args:[c]}}async function kr(c,a){if(!a)return{attempted:!1,opened:!1};let o=Er(c);return await new Promise((m)=>{let s=Qa(o.command,o.args,{stdio:"ignore",detached:!0});s.once("error",()=>{m({attempted:!0,opened:!1,message:"No se pudo abrir el navegador por defecto automáticamente. Abre la URL manualmente."})}),s.once("spawn",()=>{s.unref(),m({attempted:!0,opened:!0})})})}function Vr(c){let a=Rs(c);if(!Ir(a))return;try{let o=JSON.parse(Zr(a,"utf-8"));ja(o.appPid),ja(o.bridgePid)}catch{}Hr(a,{force:!0})}function ls(){return new Promise((c,a)=>{let o=Js();o.listen(0,"127.0.0.1",()=>{let m=o.address();if(!m||typeof m==="string"){o.close(),a(Error("No se pudo obtener un puerto libre"));return}let{port:s}=m;o.close((t)=>{if(t){a(t);return}c(s)})}),o.on("error",a)})}function js(c){return new Promise((a)=>setTimeout(a,c))}function Dr(c){return new Promise((a,o)=>{let t=(new URL(c).protocol==="https:"?Tr:Ur)(c,{method:"GET"},(p)=>{a(p.statusCode||0),p.resume()});t.on("error",o),t.end()})}async function Qs(c,a=_r){let o=Date.now();while(Date.now()-o<a){try{if(await Dr(c)>0)return}catch{await js(500);continue}await js(500)}throw Error(`Timeout esperando que el preview responda en ${c}`)}function zr(c){return Ps(Fr(c)),Xr(c,"a")}function ns(c,a,o,m,s){let t=zr(m),p=Qa(c,a,{cwd:o,detached:!0,stdio:["ignore",t,t],env:{...process.env,...s}});if(!p.pid)throw Error(`No se pudo iniciar el proceso ${c}`);return p.unref(),p.pid}function Ws(){let c=ro("prod");if(!c)throw Error("Debes iniciar sesión en prod antes de usar spaces preview. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>");return c}async function yr(c){let a=[];for await(let o of c)a.push(Buffer.isBuffer(o)?o:Buffer.from(o));return Buffer.concat(a).toString("utf-8")}function dc(c,a,o){c.writeHead(a,{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Methods":"POST,OPTIONS,GET"}),c.end(JSON.stringify(o))}function ia(c){let a=c.trim(),o=new Set([0]);for(let s=0;s<a.length;s++)if(a[s]==="{"||a[s]==="[")o.add(s);let m=[...o].sort((s,t)=>t-s);for(let s of m)try{return JSON.parse(a.slice(s))}catch{continue}return a}function Gs(c){return{...process.env,NODE_OPTIONS:"",__JUSTO_REPL_PORT:"",JUSTO_TEAM_CLI_EMAIL:c.email,JUSTO_TEAM_CLI_TOKEN:c.token,JUSTO_TEAM_CLI_REFRESH_TOKEN:c.refreshToken,JUSTO_TEAM_CLI_INTERACTIVE:"false",JUSTO_TEAM_CLI_DEVICE_ID:"spaces-preview"}}function Sr(c,a){return{VITE_JUSTO_CLI_ENDPOINT:c,VITE_JUSTO_STREAM_ENDPOINT:a,VITE_JUSTO_CLI_MODE:"preview",[uc]:Ca}}function ur(c,a,o,m){return new Promise((s,t)=>{let p=Qa(wa(),[a,"--env","prod",...m,"--format","json"],{cwd:process.cwd(),env:Gs(o),stdio:["ignore","pipe","pipe"]}),w="";p.stdout.on("data",(C)=>{if(!c.headersSent)c.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Methods":"POST,OPTIONS,GET"});c.write(C)}),p.stderr.on("data",(C)=>{w+=Buffer.from(C).toString("utf-8")}),p.on("error",t),p.on("close",(C)=>{if(!C){if(!c.headersSent)c.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Methods":"POST,OPTIONS,GET"});c.end(),s();return}let q=ia(w.trim());t(Error(q.error||w.trim()||"justoStream failed"))})})}async function Is(c){let a=Number(c.port);if(!a)throw Error("Falta --port para el bridge interno de preview");let o=Ws(),m=As(c["cli-path"]||process.argv[1]||""),s=Js(async(t,p)=>{if(t.method==="OPTIONS"){dc(p,200,{ok:!0});return}if(t.method==="GET"&&t.url==="/__justo/health"){dc(p,200,{ok:!0});return}if(t.method!=="POST"||t.url!=="/__justo/cli"&&t.url!=="/__justo/stream"){dc(p,404,{ok:!1,error:"Not found"});return}try{let w=await yr(t),q=JSON.parse(w||"{}").command;if(!q)throw Error("Debes indicar un comando");let g=Array.isArray(q)?q:gs(q);if(t.url==="/__justo/stream"){await ur(p,m,o,g);return}let Q=await new Promise((A,Y)=>{let J=Qa(wa(),[m,"--env","prod",...g,"--format","json"],{cwd:process.cwd(),env:Gs(o),stdio:["ignore","pipe","pipe"]}),P=[],Z=[];J.stdout.on("data",(G)=>P.push(Buffer.from(G))),J.stderr.on("data",(G)=>Z.push(Buffer.from(G))),J.on("error",Y),J.on("close",(G)=>{let T=Buffer.concat(P).toString("utf-8")||Buffer.concat(Z).toString("utf-8");if(G&&G!==0){let l=ia(T);Y(Error(l.error||T||"justoCli failed"));return}A(ia(T))})});dc(p,200,{result:Q})}catch(w){let C=w instanceof Error?w.message:"Unexpected error";dc(p,400,{error:C})}});await new Promise((t,p)=>{s.listen(a,"127.0.0.1",()=>t()),s.on("error",p)}),D(`Space preview bridge listening on http://127.0.0.1:${a}
1109
+ `),await new Promise((t,p)=>{s.on("close",()=>t()),s.on("error",p)})}async function Ms(c){let a=c.path;if(!a)throw Error("Falta --path. Ejemplo: team-cli spaces preview --path ./mi-space-app");let o=Na(a);Ws(),Ps(o),Vr(o);let m=Number(c.port)||await ls(),s=Number(c["bridge-port"])||await ls(),t=c.open==="true",p=`http://127.0.0.1:${m}`,w=`http://127.0.0.1:${s}/__justo/cli`,C=`http://127.0.0.1:${s}/__justo/stream`,q=As(process.argv[1]||""),g=ns(wa(),[q,"__spaces-preview-bridge","--port",String(s),"--cli-path",q],process.cwd(),qs(o),{}),Q=ns(Qc("yarn"),["dev","--host","127.0.0.1","--port",String(m)],o,$s(o),Sr(w,C));try{await Qs(`http://127.0.0.1:${s}/__justo/health`),await Qs(p)}catch(J){throw ja(Q),ja(g),J}let A={appPid:Q,bridgePid:g,previewUrl:p,bridgeUrl:w,streamUrl:C,cliEnv:"prod"};Yr(Rs(o),`${JSON.stringify(A,null,2)}
1110
+ `);let Y=await kr(p,t);return{ok:!0,path:o,previewUrl:p,bridgeUrl:w,streamUrl:C,cliEnv:"prod",appPid:Q,bridgePid:g,logs:{app:$s(o),bridge:qs(o)},open:Y}}function dr(c){try{return gc.parse(c)}catch{throw Error("El valor de --operation debe ser JSON/EJSON válido")}}function Oc(){if(!F())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function qc(c,a,o){let m=c[a];if(!m)throw Error(`Falta --${a}. Ejemplo: ${o}`);return m}function Zs(c,a){let o=c[2];if(!o)throw Error(`Uso: ${a}`);return o}function da(){let c=xc();if(c==="local")return"http://intra.localhost:5173";if(c==="develop")return"https://intra.bejusto.com";return"https://intra.getjusto.com"}function Or(){return`Configuración de collections en \`.justo-space.json\`:
1111
+ - \`spaces publish\` lee \`repo/.justo-space.json\`, valida \`collections\` y sincroniza índices
1112
+ - cada collection lógica debe existir en \`collections\`
1113
+ - los nombres válidos usan solo letras, números y guion bajo
1114
+ - la collection física en Mongo queda como \`spaces.<slug_sanitized>.<collection>\`
1115
+ - el \`slug\` se sanitiza reemplazando todo lo no alfanumérico por \`_\`
1116
+ - si una collection deja de existir en \`.justo-space.json\`, no se borran sus datos, pero deja de estar autorizada para \`spaces db\`
1117
+
1118
+ Ejemplo completo:
1119
+ \`\`\`json
1120
+ {
1121
+ "template": "react-vite-shadcn",
1122
+ "version": 2,
1123
+ "collections": {
1124
+ "events": {
1125
+ "indexes": [
1126
+ {
1127
+ "name": "createdAt_desc",
1128
+ "key": {
1129
+ "createdAt": -1
1130
+ }
1131
+ },
1132
+ {
1133
+ "name": "eventId_1",
1134
+ "key": {
1135
+ "eventId": 1
1136
+ },
1137
+ "unique": true
1138
+ }
1139
+ ]
1140
+ }
1141
+ }
1142
+ }
1143
+ \`\`\`
1144
+
1145
+ Reglas de índices:
1146
+ - cada índice debe tener \`name\` y \`key\`
1147
+ - puedes usar opciones comunes de Mongo como \`unique\`, \`sparse\`, \`expireAfterSeconds\` y \`partialFilterExpression\`
1148
+ - en cada publish, los índices declarados se recrean en modo estricto para esa collection
1149
+ `}function br(){return"Acceso a Mongo con `spaces db`:\n- comando: `team-cli spaces db --slug <slug> --collection <collection> --operation '<EJSON>'`\n- el backend valida que el space exista, que no esté archivado y que la collection esté declarada\n- el acceso queda restringido siempre a una sola collection del space\n- cualquier usuario autenticado de Justo con al menos un rol puede usarlo\n- no necesitas conectar Mongo directo desde el space ni desde el CLI\n\nOperaciones permitidas:\n- `find`, `findOne`, `insertOne`, `insertMany`\n- `updateOne`, `updateMany`, `replaceOne`\n- `deleteOne`, `deleteMany`\n- `countDocuments`, `distinct`, `aggregate`\n- `findOneAndUpdate`, `findOneAndDelete`, `findOneAndReplace`\n- `bulkWrite`\n\nPayload esperado por operación:\n- `find`: `filter`, opcional `projection`, `sort`, `skip`, `limit`\n- `findOne`: `filter`, opcional `projection`, `sort`\n- `insertOne`: `document`\n- `insertMany`: `documents`, opcional `ordered`\n- `updateOne` y `updateMany`: `filter`, `update`, opcional `upsert`, `arrayFilters`\n- `replaceOne`: `filter`, `replacement`, opcional `upsert`\n- `deleteOne` y `deleteMany`: `filter`\n- `countDocuments`: `filter`\n- `distinct`: `field`, opcional `filter`\n- `aggregate`: `pipeline`, opcional `allowDiskUse`, `maxTimeMS`\n- `findOneAndUpdate`: `filter`, `update`, opcional `upsert`, `returnDocument`, `projection`, `sort`, `arrayFilters`\n- `findOneAndDelete`: `filter`, opcional `projection`, `sort`\n- `findOneAndReplace`: `filter`, `replacement`, opcional `upsert`, `returnDocument`, `projection`, `sort`\n- `bulkWrite`: `operations`, opcional `ordered`\n\nEjemplos:\n```bash\nteam-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{\"type\":\"find\",\"filter\":{},\"limit\":10}'\n\nteam-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{\"type\":\"insertOne\",\"document\":{\"eventId\":\"evt-1\",\"name\":\"Evento demo\"}}'\n\nteam-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{\"type\":\"updateOne\",\"filter\":{\"eventId\":\"evt-1\"},\"update\":{\"$set\":{\"name\":\"Evento actualizado\"}}}'\n\nteam-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{\"type\":\"aggregate\",\"pipeline\":[{\"$match\":{\"eventId\":\"evt-1\"}},{\"$project\":{\"_id\":0,\"name\":1}}]}'\n```\n\nEJSON:\n- usa EJSON cuando necesites tipos BSON como `ObjectId` o `Date`\n- ejemplo con fecha:\n```bash\nteam-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{\"type\":\"insertOne\",\"document\":{\"createdAt\":{\"$date\":\"2026-03-16T21:05:00.000Z\"}}}'\n```\n- ejemplo con object id:\n```bash\nteam-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{\"type\":\"findOne\",\"filter\":{\"_id\":{\"$oid\":\"65f4c55e8b6a5d4db9f1a123\"}}}'\n```\n"}async function Br(c,a){let o=await aa(),m=await fetch(`${K("data")}/spaces/publish/${c}`,{method:"POST",headers:{"Content-Type":"application/gzip",...o?{"X-ORION-JWT":o}:{}},body:a}),s=await m.json();if(!m.ok||s.error)throw Error(s.error||"No se pudo publicar el space.");return s}async function vr(c){let a=await aa(),o=await fetch(`${K("data")}/spaces/fork/${c}`,{method:"GET",headers:a?{"X-ORION-JWT":a}:{}});if(!o.ok){let m=await o.json().catch(()=>({}));throw Error(m.error||"No se pudo descargar el repo del space.")}return Buffer.from(await o.arrayBuffer())}function er(c){let a=Xs(c);if(Lr(a)&&ir(a).length>0)throw Error(`La carpeta ya existe y no está vacía: ${a}`);return Nr(a,{recursive:!0}),a}function Oa(){return`team-cli spaces
1110
1150
 
1111
1151
  Spaces son aplicaciones internas en React, pensadas para que las construyan agentes.
1112
1152
  El flujo oficial parte con \`spaces init\` y \`spaces publish\` solo acepta apps creadas así.
@@ -1132,6 +1172,10 @@ Cada space:
1132
1172
  - el archivo \`.justo-space.json\` puede declarar \`collections\` para que el publish sincronice índices en Mongo
1133
1173
  - esas collections se exponen con \`team-cli spaces db\` usando el prefijo físico \`spaces.<slug_sanitized>.<collection>\`
1134
1174
 
1175
+ ${Or()}
1176
+
1177
+ ${br()}
1178
+
1135
1179
  Flujo sugerido para agentes:
1136
1180
  1. \`team-cli spaces init --path ./mi-space-app\`
1137
1181
  2. hacer initial commit del repo nuevo
@@ -1196,7 +1240,7 @@ import {justoCli, justoStream} from '@/lib/justo'
1196
1240
  const me = await justoCli("graphql main 'query { me { _id email roles } }'")
1197
1241
  const rows = await justoCli("data queries preview <queryId> --params '{\\"limit\\":10}'")
1198
1242
  const events = await justoCli(
1199
- "spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{},"limit":10}'",
1243
+ \`spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{},"limit":10}'\`,
1200
1244
  )
1201
1245
  await justoStream(
1202
1246
  "data queries run <queryId> --limit 1000 --params '{\\"websiteId\\":\\"w1\\"}'",
@@ -1214,7 +1258,7 @@ Comandos:
1214
1258
  - \`spaces fork <slug> --path ./mi-space-app\`
1215
1259
  - \`spaces archive <spaceId>\`
1216
1260
  - \`spaces db --slug <slug> --collection events --operation '{"type":"find","filter":{}}'\`
1217
- `}async function Ys(c){let a=gc(c,"path","team-cli spaces init --path ./mi-space-app");return bo(a)}async function Fs(c){return await Zs(c)}async function Us(c){ic();let a=gc(c,"name","team-cli spaces create --name 'Mi space' --description '...' --slug dashboard-1234"),m=gc(c,"description","team-cli spaces create --name 'Mi space' --description 'Sitio interno' --slug dashboard-1234"),o=gc(c,"slug","team-cli spaces create --name 'Mi space' --description '...' --slug dashboard-1234"),s=await l({service:"data",query:`mutation ($name: String, $description: String, $slug: String) {
1261
+ `}async function Hs(c){let a=qc(c,"path","team-cli spaces init --path ./mi-space-app");return Bm(a)}async function Ys(c){return await Ms(c)}async function Fs(c){Oc();let a=qc(c,"name","team-cli spaces create --name 'Mi space' --description '...' --slug dashboard-1234"),o=qc(c,"description","team-cli spaces create --name 'Mi space' --description 'Sitio interno' --slug dashboard-1234"),m=qc(c,"slug","team-cli spaces create --name 'Mi space' --description '...' --slug dashboard-1234"),s=await R({service:"data",query:`mutation ($name: String, $description: String, $slug: String) {
1218
1262
  createSpace(name: $name, description: $description, slug: $slug) {
1219
1263
  _id
1220
1264
  name
@@ -1225,7 +1269,7 @@ Comandos:
1225
1269
  createdByEmail
1226
1270
  createdById
1227
1271
  }
1228
- }`,variables:{name:a,description:m,slug:o}});return{...s.createSpace,intraUrl:`${da()}/spaces/${s.createSpace.slug}`,serveUrl:`${K("data")}/spaces/${s.createSpace.slug}`}}async function Ts(c,a){ic();let m=Hs(c,"team-cli spaces publish <spaceId> --path ./mi-space-app"),o=gc(a,"path","team-cli spaces publish <spaceId> --path ./mi-space-app"),s=Bo(o),t=ws(o,s),w=await ip(m,t);return{...w,intraUrl:w.slug?`${da()}/spaces/${w.slug}`:void 0,serveUrl:w.slug?`${K("data")}/spaces/${w.slug}`:void 0,builtFrom:Ms(o)}}async function ns(c,a){ic();let m=c[2];if(!m)throw Error("Uso: team-cli spaces fork <slug> --path ./mi-space-app");let o=bp(a.path||`./${m}`),s=await Bp(m),t=Cs(s,"repo",o);return{ok:!0,slug:m,path:o,extractedFiles:t,nextSteps:[`cd ${o}`,"yarn install","team-cli spaces preview --path . --open"]}}async function hs(c){ic();let a=Hs(c,"team-cli spaces archive <spaceId>");return(await l({service:"data",query:`mutation ($spaceId: String) {
1272
+ }`,variables:{name:a,description:o,slug:m}});return{...s.createSpace,intraUrl:`${da()}/spaces/${s.createSpace.slug}`,serveUrl:`${K("data")}/spaces/${s.createSpace.slug}`}}async function Us(c,a){Oc();let o=Zs(c,"team-cli spaces publish <spaceId> --path ./mi-space-app"),m=qc(a,"path","team-cli spaces publish <spaceId> --path ./mi-space-app"),s=bm(m),t=ps(m,s),p=await Br(o,t);return{...p,intraUrl:p.slug?`${da()}/spaces/${p.slug}`:void 0,serveUrl:p.slug?`${K("data")}/spaces/${p.slug}`:void 0,builtFrom:Xs(m)}}async function Ts(c,a){Oc();let o=c[2];if(!o)throw Error("Uso: team-cli spaces fork <slug> --path ./mi-space-app");let m=er(a.path||`./${o}`),s=await vr(o),t=Cs(s,"repo",m);return{ok:!0,slug:o,path:m,extractedFiles:t,nextSteps:[`cd ${m}`,"yarn install","team-cli spaces preview --path . --open"]}}async function hs(c){Oc();let a=Zs(c,"team-cli spaces archive <spaceId>");return(await R({service:"data",query:`mutation ($spaceId: String) {
1229
1273
  archiveSpace(spaceId: $spaceId) {
1230
1274
  _id
1231
1275
  name
@@ -1237,7 +1281,7 @@ Comandos:
1237
1281
  createdById
1238
1282
  archivedAt
1239
1283
  }
1240
- }`,variables:{spaceId:a}})).archiveSpace}async function Ks(c){ic();let a=gc(c,"slug",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),m=gc(c,"collection",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),o=gc(c,"operation",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),s=qc.serialize(dp(o)),t=await Gc(),w=await fetch(`${K("data")}/spaces/${encodeURIComponent(a)}/db`,{method:"POST",headers:t,body:JSON.stringify({collection:m,operation:s})}),r=await w.json().catch(()=>({}));if(!w.ok||r.error)throw Error(r.error||"No se pudo ejecutar spaces db");return r.result}function _s(c){return`team-cli
1284
+ }`,variables:{spaceId:a}})).archiveSpace}async function Ks(c){Oc();let a=qc(c,"slug",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),o=qc(c,"collection",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),m=qc(c,"operation",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),s=gc.serialize(dr(m)),t=await Wc(),p=await fetch(`${K("data")}/spaces/${encodeURIComponent(a)}/db`,{method:"POST",headers:t,body:JSON.stringify({collection:o,operation:s})}),w=await p.json().catch(()=>({}));if(!p.ok||w.error)throw Error(w.error||"No se pudo ejecutar spaces db");return w.result}function _s(c){return`team-cli
1241
1285
 
1242
1286
  Herramienta CLI para el equipo Justo.
1243
1287
 
@@ -1269,7 +1313,7 @@ Cada grupo de comandos tiene su propia ayuda. Usa \`--help\` para ver los comand
1269
1313
  - \`graphql\` — Ejecutar queries y mutations GraphQL
1270
1314
  - \`admin\` — Comandos administrativos con contexto de website
1271
1315
  - \`data\` — Datos y reportes. Puede obtener data de todas las bases de datos de Justo
1272
- - \`spaces\` — Crea apps React para Spaces con \`spaces init\`, publícalas con \`spaces publish\` y compártelas en intra.
1316
+ - \`spaces\` — Crea apps React para Spaces con \`spaces init\`, publícalas con \`spaces publish\`, compártelas en intra y usa \`spaces db\` para collections declaradas del space.
1273
1317
 
1274
1318
  ## Tips
1275
1319
 
@@ -1298,4 +1342,4 @@ Si todavía no sabes bien dónde vive la data, primero usa \`data explain\` para
1298
1342
  Cuando ya tengas claro un pipeline y solo quieras probarlo una vez, usa \`data execute\`.
1299
1343
  Si ese resultado lo vas a reutilizar en un dashboard o un space, después conviértelo en un query guardado con \`data queries create\` + \`data queries ai-edit\`.
1300
1344
 
1301
- `}function Es(){let c=U(),a=c?`Sesión: ${c.email}`:"Sesión: no iniciada";return _s(a)}async function ks(c){let{positional:a,flags:m}=Bc(c);if(m.env)om(m.env);let o=a[0],s=a[1];if(o==="__spaces-preview-bridge")return await Xs(m);if(m.version)return{version:"0.0.12"};if(m.help&&!o)return Es();if(o==="auth"){if(s==="--help"||m.help)return Ha();if(s==="login")return await Em();if(s==="login-with-token")return await km(m);if(s==="request-code")return await Vm(m);if(s==="logout")return await Dm();if(s==="status")return await zm();return Ha()}if(o==="admin"){let t=a[1],w=a[2],r=a[3],C=a[4];if(!t||t==="--help")return ma();if(t==="search"&&m.help)return nm();if(t==="search")return await Tm(a,m);if(!w||w==="--help")return ma();if(w==="show")return await Qm(t);if(w==="stores"&&r==="list")return await hm(t);if(w==="coupons"&&(!r||r==="--help"))return Vc();if(w==="coupons"&&r==="create"&&m.help)return Fm();if(w==="coupons"&&r==="update"&&m.help)return Um();if(w==="coupons"&&r==="codes"&&a[4]==="create"&&m.help)return Gm();if(w==="coupons"&&m.help)return Vc();if(w==="coupons"&&r==="list")return await Xm(t,m);if(w==="coupons"&&r==="show"){if(!C)throw Error("Uso: team-cli admin <web> coupons show <couponId>");return await Zm(t,C)}if(w==="coupons"&&r==="create")return await Mm(t,m);if(w==="coupons"&&r==="update"){if(!C)throw Error("Uso: team-cli admin <web> coupons update <couponId> --input '<json>'");return await Hm(t,C,m)}if(w==="coupons"&&r==="delete"){if(!C)throw Error("Uso: team-cli admin <web> coupons delete <couponId>");return await Ym(t,C)}if(w==="coupons"&&r==="codes"){let g=a[4],q=a[5];if(!g||g==="--help")return Vc();if(g==="list"){if(!q)throw Error("Uso: team-cli admin <web> coupons codes list <couponId>");return await Pm(t,q,m)}if(g==="create"){if(!q)throw Error("Uso: team-cli admin <web> coupons codes create <couponId> --input '<json>'");return await Rm(t,q,m)}if(g==="create-random"){if(!q)throw Error("Uso: team-cli admin <web> coupons codes create-random <couponId> --quantity <n>");return await lm(t,q,m)}if(g==="delete"){if(!q)throw Error(`Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1"]'`);return await Wm(t,q,m)}return Vc()}return ma()}if(o==="graphql"){if(s==="--help"||m.help)return go();return await Co(a,m)}if(o==="data"){let t=a[1],w=a[2];if(m.help||s==="--help")return ha();if(t==="explain")return await xm(m);if(t==="execute")return await em(m);if(t==="queries"&&w==="create")return await vm();if(t==="queries"&&w==="edit")return await fm(a);if(t==="queries"&&w==="ai-edit")return await co(a,m);if(t==="queries"&&w==="view")return await ao(a);if(t==="queries"&&w==="view-pipeline")return await mo(a);if(t==="queries"&&w==="preview")return await oo(a,m);if(t==="queries"&&w==="run")return await so(a,m);if(t==="queries"&&w==="add-viewers")return await to(a,m);if(t==="queries"&&w==="download")return await wo(a,m);return ha()}if(o==="spaces"){let t=a[1];if(!t||t==="--help"||m.help)return ia();if(t==="init")return await Ys(m);if(t==="create")return await Us(m);if(t==="preview")return await Fs(m);if(t==="publish")return await Ts(a,m);if(t==="fork")return await ns(a,m);if(t==="archive")return await hs(a);if(t==="db")return await Ks(m);return ia()}return Es()}var{flags:Vs}=Bc(process.argv.slice(2));async function vp(){try{let c=await ks(process.argv.slice(2));if(c&&typeof c==="object"&&"__streamHandled"in c&&c.__streamHandled)return;if(typeof c==="string"){am(c);return}cm(c,Vs)}catch(c){mm(c,Vs),process.exit(1)}}vp();
1345
+ `}function Es(){let c=F(),a=c?`Sesión: ${c.email}`:"Sesión: no iniciada";return _s(a)}async function ks(c){let{positional:a,flags:o}=bc(c);if(o.env)mo(o.env);let m=a[0],s=a[1];if(m==="__spaces-preview-bridge")return await Is(o);if(o.version)return{version:"0.0.13"};if(o.help&&!m)return Es();if(m==="auth"){if(s==="--help"||o.help)return Za();if(s==="login")return await Eo();if(s==="login-with-token")return await ko(o);if(s==="request-code")return await Vo(o);if(s==="logout")return await Do();if(s==="status")return await zo();return Za()}if(m==="admin"){let t=a[1],p=a[2],w=a[3],C=a[4];if(!t||t==="--help")return oa();if(t==="search"&&o.help)return To();if(t==="search")return await Uo(a,o);if(!p||p==="--help")return oa();if(p==="show")return await lo(t);if(p==="stores"&&w==="list")return await ho(t);if(p==="coupons"&&(!w||w==="--help"))return Vc();if(p==="coupons"&&w==="create"&&o.help)return Yo();if(p==="coupons"&&w==="update"&&o.help)return Fo();if(p==="coupons"&&w==="codes"&&a[4]==="create"&&o.help)return Wo();if(p==="coupons"&&o.help)return Vc();if(p==="coupons"&&w==="list")return await Io(t,o);if(p==="coupons"&&w==="show"){if(!C)throw Error("Uso: team-cli admin <web> coupons show <couponId>");return await Mo(t,C)}if(p==="coupons"&&w==="create")return await Xo(t,o);if(p==="coupons"&&w==="update"){if(!C)throw Error("Uso: team-cli admin <web> coupons update <couponId> --input '<json>'");return await Zo(t,C,o)}if(p==="coupons"&&w==="delete"){if(!C)throw Error("Uso: team-cli admin <web> coupons delete <couponId>");return await Ho(t,C)}if(p==="coupons"&&w==="codes"){let q=a[4],g=a[5];if(!q||q==="--help")return Vc();if(q==="list"){if(!g)throw Error("Uso: team-cli admin <web> coupons codes list <couponId>");return await Jo(t,g,o)}if(q==="create"){if(!g)throw Error("Uso: team-cli admin <web> coupons codes create <couponId> --input '<json>'");return await Ao(t,g,o)}if(q==="create-random"){if(!g)throw Error("Uso: team-cli admin <web> coupons codes create-random <couponId> --quantity <n>");return await Ro(t,g,o)}if(q==="delete"){if(!g)throw Error(`Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1"]'`);return await Po(t,g,o)}return Vc()}return oa()}if(m==="graphql"){if(s==="--help"||o.help)return $m();return await gm(a,o)}if(m==="data"){let t=a[1],p=a[2];if(o.help||s==="--help")return ha();if(t==="explain")return await xo(o);if(t==="execute")return await fo(o);if(t==="queries"&&p==="create")return await eo();if(t==="queries"&&p==="edit")return await cm(a);if(t==="queries"&&p==="ai-edit")return await am(a,o);if(t==="queries"&&p==="view")return await om(a);if(t==="queries"&&p==="view-pipeline")return await mm(a);if(t==="queries"&&p==="preview")return await sm(a,o);if(t==="queries"&&p==="run")return await tm(a,o);if(t==="queries"&&p==="add-viewers")return await pm(a,o);if(t==="queries"&&p==="download")return await rm(a,o);return ha()}if(m==="spaces"){let t=a[1];if(!t||t==="--help"||o.help)return Oa();if(t==="init")return await Hs(o);if(t==="create")return await Fs(o);if(t==="preview")return await Ys(o);if(t==="publish")return await Us(a,o);if(t==="fork")return await Ts(a,o);if(t==="archive")return await hs(a);if(t==="db")return await Ks(o);return Oa()}return Es()}var{flags:Vs}=bc(process.argv.slice(2));async function xr(){try{let c=await ks(process.argv.slice(2));if(c&&typeof c==="object"&&"__streamHandled"in c&&c.__streamHandled)return;if(typeof c==="string"){ao(c);return}co(c,Vs)}catch(c){oo(c,Vs),process.exit(1)}}xr();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getjusto/team-cli",
3
- "version": "0.0.12",
3
+ "version": "0.0.13",
4
4
  "description": "CLI tool for Justo team members",
5
5
  "type": "module",
6
6
  "bin": {