@getjusto/team-cli 0.0.11 → 0.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.js +343 -334
- package/package.json +2 -1
package/bin/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
function
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function
|
|
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) {
|
|
5
5
|
website(websiteId: $websiteId) {
|
|
6
6
|
_id
|
|
7
7
|
name
|
|
@@ -13,7 +13,7 @@ function ie(e){let r=[],t={},o={};for(let a=0;a<e.length;a++)if(e[a].startsWith(
|
|
|
13
13
|
timezone
|
|
14
14
|
defaultMenuId
|
|
15
15
|
}
|
|
16
|
-
}`,variables:{websiteId:
|
|
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
|
|
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
|
|
38
|
+
Uso: team-cli admin <websiteId|domain> coupons <accion> [opciones]`}var jm=`
|
|
39
39
|
availableAtPeriods
|
|
40
40
|
closedDays
|
|
41
41
|
closedUntilDate
|
|
@@ -51,7 +51,7 @@ Modulos:
|
|
|
51
51
|
fromMinute
|
|
52
52
|
toMinute
|
|
53
53
|
}
|
|
54
|
-
`,
|
|
54
|
+
`,oa=`
|
|
55
55
|
_id
|
|
56
56
|
websiteId
|
|
57
57
|
name
|
|
@@ -86,13 +86,13 @@ Modulos:
|
|
|
86
86
|
requiredBINs
|
|
87
87
|
extraRequirementsForPaymentTypes
|
|
88
88
|
schedule {
|
|
89
|
-
${
|
|
89
|
+
${jm}
|
|
90
90
|
}
|
|
91
91
|
scheduleAtUse {
|
|
92
|
-
${
|
|
92
|
+
${jm}
|
|
93
93
|
}
|
|
94
94
|
codesCode
|
|
95
|
-
`,
|
|
95
|
+
`,Jm=`
|
|
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
|
|
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) {
|
|
105
105
|
coupon(couponId: $couponId) {
|
|
106
106
|
_id
|
|
107
107
|
websiteId
|
|
108
108
|
}
|
|
109
|
-
}`,variables:{couponId:
|
|
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) {
|
|
110
110
|
couponCodes(couponId: $couponId, filter: $filter, limit: $limit, page: $page) {
|
|
111
111
|
items {
|
|
112
|
-
${
|
|
112
|
+
${Jm}
|
|
113
113
|
}
|
|
114
114
|
totalCount
|
|
115
115
|
totalPages
|
|
116
116
|
hasNextPage
|
|
117
117
|
hasPreviousPage
|
|
118
118
|
}
|
|
119
|
-
}`,variables:{couponId:
|
|
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) {
|
|
120
120
|
createCouponCodes(couponId: $couponId, codesWithEmail: $codesWithEmail, useCodeWithEmail: $useCodeWithEmail)
|
|
121
|
-
}`,variables:{couponId:
|
|
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) {
|
|
122
122
|
createRandomCouponCodes(couponId: $couponId, couponQuantity: $couponQuantity, couponCodePrefix: $couponCodePrefix)
|
|
123
|
-
}`,variables:{couponId:
|
|
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]) {
|
|
124
124
|
deleteCouponCodes(couponId: $couponId, couponCodesIds: $couponCodesIds, globalCoupon: false)
|
|
125
|
-
}`,variables:{couponId:
|
|
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
|
|
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
|
|
149
|
-
createCoupon(${
|
|
150
|
-
${
|
|
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}) {
|
|
149
|
+
createCoupon(${s}) {
|
|
150
|
+
${oa}
|
|
151
151
|
}
|
|
152
|
-
}`}async function
|
|
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) {
|
|
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:
|
|
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) {
|
|
173
173
|
coupon(couponId: $couponId) {
|
|
174
|
-
${
|
|
174
|
+
${oa}
|
|
175
175
|
}
|
|
176
|
-
}`,variables:{couponId:
|
|
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) {
|
|
177
177
|
updateCoupon(couponId: $couponId, coupon: $coupon) {
|
|
178
|
-
${
|
|
178
|
+
${oa}
|
|
179
179
|
}
|
|
180
|
-
}`,variables:{couponId:
|
|
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]) {
|
|
181
181
|
deleteCoupons(couponsIds: $couponsIds, globalCoupon: false)
|
|
182
|
-
}`,variables:{couponsIds:[
|
|
182
|
+
}`,variables:{couponsIds:[a]}});return{context:m,couponId:a,deleted:o.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
|
|
230
|
+
El schema actual no expone update para coupon codes.`}function Fm(){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
|
|
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
|
|
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
|
|
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) {
|
|
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:
|
|
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
|
|
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
|
|
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) {
|
|
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:
|
|
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!) {
|
|
370
370
|
requestLoginCode(email: $email)
|
|
371
|
-
}`,variables:{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!) {
|
|
372
372
|
loginWithCode(email: $email, token: $token, code: $code) {
|
|
373
373
|
token
|
|
374
374
|
refreshToken
|
|
375
375
|
}
|
|
376
|
-
}`,variables:{email:
|
|
377
|
-
`);let
|
|
378
|
-
`);let
|
|
379
|
-
`);let
|
|
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
|
|
380
380
|
|
|
381
381
|
Gestion de sesion.
|
|
382
382
|
|
|
@@ -402,7 +402,287 @@ 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{
|
|
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) {
|
|
407
|
+
aggregationQuery(aggregationQueryId: $aggregationQueryId) {
|
|
408
|
+
_id
|
|
409
|
+
name
|
|
410
|
+
description
|
|
411
|
+
collection
|
|
412
|
+
currentVersionIndex
|
|
413
|
+
allowedUsersIds
|
|
414
|
+
tags
|
|
415
|
+
pipeline
|
|
416
|
+
variables {
|
|
417
|
+
key
|
|
418
|
+
fieldType
|
|
419
|
+
fieldParams
|
|
420
|
+
}
|
|
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) {
|
|
423
|
+
justoUsers(filter: $filter, limit: $limit) {
|
|
424
|
+
items {
|
|
425
|
+
_id
|
|
426
|
+
email
|
|
427
|
+
fullName
|
|
428
|
+
}
|
|
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) {
|
|
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]) {
|
|
435
|
+
addAggregationQueryVersion(
|
|
436
|
+
aggregationQueryId: $aggregationQueryId
|
|
437
|
+
pipeline: $pipeline
|
|
438
|
+
variables: $variables
|
|
439
|
+
) {
|
|
440
|
+
_id
|
|
441
|
+
currentVersionIndex
|
|
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) {
|
|
444
|
+
updateAggregationQuery(
|
|
445
|
+
aggregationQueryId: $aggregationQueryId
|
|
446
|
+
aggregationQuery: $aggregationQuery
|
|
447
|
+
) {
|
|
448
|
+
_id
|
|
449
|
+
name
|
|
450
|
+
description
|
|
451
|
+
collection
|
|
452
|
+
allowedUsersIds
|
|
453
|
+
tags
|
|
454
|
+
currentVersionIndex
|
|
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 {
|
|
457
|
+
createAggregationQuery {
|
|
458
|
+
_id
|
|
459
|
+
name
|
|
460
|
+
description
|
|
461
|
+
collection
|
|
462
|
+
currentVersionIndex
|
|
463
|
+
allowedUsersIds
|
|
464
|
+
tags
|
|
465
|
+
pipeline
|
|
466
|
+
variables {
|
|
467
|
+
key
|
|
468
|
+
fieldType
|
|
469
|
+
fieldParams
|
|
470
|
+
}
|
|
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(
|
|
473
|
+
$prompt: String
|
|
474
|
+
$name: String
|
|
475
|
+
$description: String
|
|
476
|
+
$fullCollectionName: String
|
|
477
|
+
$variables: [JSON]
|
|
478
|
+
$pipeline: String
|
|
479
|
+
$preview: [JSON]
|
|
480
|
+
) {
|
|
481
|
+
generateAdminQuery(
|
|
482
|
+
prompt: $prompt
|
|
483
|
+
name: $name
|
|
484
|
+
description: $description
|
|
485
|
+
fullCollectionName: $fullCollectionName
|
|
486
|
+
variables: $variables
|
|
487
|
+
pipeline: $pipeline
|
|
488
|
+
preview: $preview
|
|
489
|
+
canUseVariables: true
|
|
490
|
+
) {
|
|
491
|
+
responseText
|
|
492
|
+
fullCollectionName
|
|
493
|
+
pipeline
|
|
494
|
+
variables
|
|
495
|
+
aggregationDescription
|
|
496
|
+
aggregationName
|
|
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) {
|
|
499
|
+
explainAdminQuery(prompt: $prompt) {
|
|
500
|
+
responseText
|
|
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) {
|
|
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) {
|
|
509
|
+
getAsyncReport(id: $id) {
|
|
510
|
+
_id
|
|
511
|
+
status
|
|
512
|
+
estimatedRecordsCount
|
|
513
|
+
fileUrl
|
|
514
|
+
}
|
|
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(`
|
|
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
|
|
519
|
+
|
|
520
|
+
Comandos de datos y reportes.
|
|
521
|
+
|
|
522
|
+
Recomendado:
|
|
523
|
+
Si necesitas obtener data y no existe un query listo, usa explain -> create -> ai-edit.
|
|
524
|
+
Flujo sugerido: explain -> create -> ai-edit -> preview -> run o download.
|
|
525
|
+
Usa queries cuando quieras que la consulta quede guardada, versionada y compartible.
|
|
526
|
+
Usa execute solo para correr un pipeline una vez.
|
|
527
|
+
Para spaces, prefiere siempre queries guardados en vez de execute directo.
|
|
528
|
+
Siempre que puedas, prefiere varias queries simples antes que un solo pipeline con lookup.
|
|
529
|
+
Para dashboards suele ser mejor resolver joins en la UI o con queries separadas.
|
|
530
|
+
Caso común:
|
|
531
|
+
1. Usa explain para investigar servicio, colección, fields o resolvers.
|
|
532
|
+
2. Usa execute para probar un pipeline una sola vez.
|
|
533
|
+
3. Si lo vas a reutilizar, conviértelo en query guardado con create + ai-edit.
|
|
534
|
+
|
|
535
|
+
Uso:
|
|
536
|
+
team-cli data <subcomando> [opciones]
|
|
537
|
+
|
|
538
|
+
Subcomandos:
|
|
539
|
+
explain
|
|
540
|
+
Pedir una explicación guiada para investigar cómo construir un query o cómo consultar datos por GraphQL usando el subagente de repo.
|
|
541
|
+
Uso: team-cli data explain --prompt '<texto>' [--format toon|json]
|
|
542
|
+
Solo disponible para usuarios con rol queries.
|
|
543
|
+
|
|
544
|
+
execute
|
|
545
|
+
Ejecutar un pipeline directo sin crear un query guardado.
|
|
546
|
+
Piensa en esto como ejecución ad-hoc de una sola vez.
|
|
547
|
+
Solo lectura: bloquea stages de escritura como $out y $merge.
|
|
548
|
+
Usa timeout de 1 minuto, read preference secondaryPreferred y requiere rol queries.
|
|
549
|
+
Para spaces y dashboards compartibles, prefiere queries guardados con data queries create + ai-edit.
|
|
550
|
+
Uso: team-cli data execute --collection <db.collection> --pipeline '<array js>' [--params '<json>'] [--limit <n>] [--format toon|json]
|
|
551
|
+
|
|
552
|
+
queries
|
|
553
|
+
Administrar y ejecutar aggregation queries guardados.
|
|
554
|
+
|
|
555
|
+
Uso de queries:
|
|
556
|
+
team-cli data queries <subcomando> [opciones]
|
|
557
|
+
|
|
558
|
+
Subcomandos de queries:
|
|
559
|
+
create
|
|
560
|
+
Crear un query nuevo.
|
|
561
|
+
Devuelve el _id para seguir con edit, ai-edit, view o preview.
|
|
562
|
+
|
|
563
|
+
edit <queryId>
|
|
564
|
+
Editar un query manualmente en tu editor local usando JSON.
|
|
565
|
+
Campos editables: name, description, collection, allowedUsersIds, tags, pipeline, variables.
|
|
566
|
+
El pipeline debe quedar como string con un array JavaScript válido.
|
|
567
|
+
|
|
568
|
+
ai-edit <queryId>
|
|
569
|
+
Editar un query con IA.
|
|
570
|
+
Uso: team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>'] [--format toon|json]
|
|
571
|
+
Si envías --params, primero se ejecuta preview y esos resultados se adjuntan al prompt.
|
|
572
|
+
|
|
573
|
+
view <queryId>
|
|
574
|
+
Ver informacion de un query.
|
|
575
|
+
|
|
576
|
+
view-pipeline <queryId>
|
|
577
|
+
Ver el pipeline de un query.
|
|
578
|
+
|
|
579
|
+
preview <queryId>
|
|
580
|
+
Ejecutar un query de prueba.
|
|
581
|
+
Uso: team-cli data queries preview <queryId> --params '<json>' [--format toon|json]
|
|
582
|
+
|
|
583
|
+
run <queryId>
|
|
584
|
+
Ejecutar un query completo en streaming NDJSON.
|
|
585
|
+
Usa timeout de 5 minutos y read preference secondaryPreferred.
|
|
586
|
+
Uso: team-cli data queries run <queryId> --limit <n> [--params '<json>']
|
|
587
|
+
|
|
588
|
+
download <queryId>
|
|
589
|
+
Descargar resultado completo como Excel.
|
|
590
|
+
Uso: team-cli data queries download <queryId> --path <filepath> [--params '<json>'] [--format toon|json]
|
|
591
|
+
|
|
592
|
+
add-viewers <queryId>
|
|
593
|
+
Agregar personas con acceso a un query usando sus emails de Justo.
|
|
594
|
+
Uso: team-cli data queries add-viewers <queryId> --emails 'ana@justo.com,bob@justo.com'
|
|
595
|
+
Esto actualiza allowedUsersIds sin cambiar el pipeline ni crear una versión nueva.
|
|
596
|
+
|
|
597
|
+
Opciones:
|
|
598
|
+
--params '<json>' Parametros del query. Default: {}
|
|
599
|
+
--limit <n> Requerido para run. En execute es opcional y limita resultados.
|
|
600
|
+
--emails '<csv>' Requerido para add-viewers. Lista separada por comas.
|
|
601
|
+
--prompt '<texto>' Prompt para ai-edit. Si no viene, se pide interactivamente.
|
|
602
|
+
--collection <db.collection> Requerido para execute.
|
|
603
|
+
--pipeline '<array js>' Requerido para execute.
|
|
604
|
+
--format <toon|json> Usa toon por defecto cuando el comando lo ejecute un agente como Codex o Claude.
|
|
605
|
+
--path <filepath> Requerido para download
|
|
606
|
+
|
|
607
|
+
Ejemplos:
|
|
608
|
+
team-cli data explain --prompt 'Quiero entender dónde viven los campos de courier de los pedidos'
|
|
609
|
+
team-cli data explain --prompt 'Quiero saber cómo consultar tabs por GraphQL y qué resolvers mirar'
|
|
610
|
+
team-cli data execute --collection justo.users --pipeline '[{$limit: 5}, {$project: {_id: 1, createdAt: 1}}]'
|
|
611
|
+
team-cli data queries create
|
|
612
|
+
team-cli data queries edit abc123
|
|
613
|
+
team-cli data queries ai-edit abc123 --prompt 'Filtra solo ordenes canceladas'
|
|
614
|
+
team-cli data queries ai-edit abc123 --prompt 'Ajusta el pipeline' --params '{"websiteId":"w1"}'
|
|
615
|
+
team-cli data queries preview abc123 --params '{"startDate": "2026-01-01"}'
|
|
616
|
+
team-cli data queries run abc123 --limit 1000 --params '{"startDate": "2026-01-01"}'
|
|
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=`
|
|
619
|
+
query ResolverInfo($name: ID!, $mutation: Boolean!) {
|
|
620
|
+
params(name: $name, mutation: $mutation) {
|
|
621
|
+
name
|
|
622
|
+
params
|
|
623
|
+
result
|
|
624
|
+
basicResultQuery
|
|
625
|
+
}
|
|
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
|
|
629
|
+
|
|
630
|
+
Ejecutar queries y mutations GraphQL.
|
|
631
|
+
|
|
632
|
+
Uso:
|
|
633
|
+
team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]
|
|
634
|
+
team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]
|
|
635
|
+
|
|
636
|
+
Comando info:
|
|
637
|
+
Consulta la metadata publicada por OrionJS para un query o mutation.
|
|
638
|
+
Devuelve el tipo de operación, los params serializados, el resultado y un basicResultQuery.
|
|
639
|
+
Si no indicas si es query o mutation, la CLI prueba ambas automáticamente.
|
|
640
|
+
|
|
641
|
+
Formato:
|
|
642
|
+
Por defecto usa toon. Usa --format json para JSON estándar.
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
Servicios disponibles: ${a}.
|
|
647
|
+
|
|
648
|
+
Ejemplos:
|
|
649
|
+
\`\`\`bash
|
|
650
|
+
npx @getjusto/team-cli graphql main 'query { me { _id roles } }'
|
|
651
|
+
npx @getjusto/team-cli graphql main 'query($id: ID) { user(userId: $id) { _id } }' --variables '{"id": "abc123"}'
|
|
652
|
+
npx @getjusto/team-cli graphql tabs 'query { tab(tabId: "t123") { _id status } }' --format json
|
|
653
|
+
\`\`\`
|
|
654
|
+
|
|
655
|
+
### graphql info
|
|
656
|
+
|
|
657
|
+
Úsalo cuando conoces el nombre del resolver pero no su contrato exacto.
|
|
658
|
+
|
|
659
|
+
\`\`\`bash
|
|
660
|
+
npx @getjusto/team-cli graphql <service> info <queryName|mutationName> [--format toon|json]
|
|
661
|
+
\`\`\`
|
|
662
|
+
|
|
663
|
+
Devuelve:
|
|
664
|
+
- \`operationType\`
|
|
665
|
+
- \`info.params\`
|
|
666
|
+
- \`info.result\`
|
|
667
|
+
- \`info.basicResultQuery\`
|
|
668
|
+
|
|
669
|
+
Ejemplos:
|
|
670
|
+
\`\`\`bash
|
|
671
|
+
npx @getjusto/team-cli graphql main info website
|
|
672
|
+
npx @getjusto/team-cli graphql auth info requestLoginCode --format json
|
|
673
|
+
\`\`\`
|
|
674
|
+
|
|
675
|
+
### Mapa de servicios GraphQL
|
|
676
|
+
|
|
677
|
+
Usa esto para mapear una URL GraphQL al valor correcto de \`team-cli graphql <service>\`.
|
|
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'
|
|
406
686
|
import {Badge} from '@/components/ui/badge'
|
|
407
687
|
import {Button} from '@/components/ui/button'
|
|
408
688
|
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from '@/components/ui/card'
|
|
@@ -420,8 +700,8 @@ import {justoCli} from '@/lib/justo'
|
|
|
420
700
|
const defaultCommand = 'auth status'
|
|
421
701
|
const queryExample = "data queries preview <queryId> --params '{\\"limit\\":10}'"
|
|
422
702
|
const mapTilerToken =
|
|
423
|
-
(import.meta.env as {${
|
|
424
|
-
'${
|
|
703
|
+
(import.meta.env as {${Lc}?: string}).${Lc} ||
|
|
704
|
+
'${Ca}'
|
|
425
705
|
const chartData = [
|
|
426
706
|
{day: 'Lun', sessions: 12},
|
|
427
707
|
{day: 'Mar', sessions: 18},
|
|
@@ -632,7 +912,7 @@ export function App() {
|
|
|
632
912
|
}
|
|
633
913
|
|
|
634
914
|
export default App
|
|
635
|
-
`}function
|
|
915
|
+
`}function So(){return`type JustoCliFunction = <T = unknown>(command: string) => Promise<T>
|
|
636
916
|
type JustoStreamFunction = <T = unknown>(
|
|
637
917
|
command: string,
|
|
638
918
|
onRow: (row: T) => Promise<void> | void,
|
|
@@ -774,7 +1054,7 @@ export async function justoStream<T = unknown>(
|
|
|
774
1054
|
}
|
|
775
1055
|
|
|
776
1056
|
ensurePreviewWindowJusto()
|
|
777
|
-
`}function
|
|
1057
|
+
`}function Lo(c){return`# ${c}
|
|
778
1058
|
|
|
779
1059
|
Starter de Justo Spaces generado por \`team-cli spaces init\`.
|
|
780
1060
|
|
|
@@ -809,301 +1089,24 @@ Tip:
|
|
|
809
1089
|
- después de \`spaces init\`, haz un initial commit para fijar el scaffold base
|
|
810
1090
|
- después de cada publish, haz commit para que el repo refleje exactamente lo que quedó publicado
|
|
811
1091
|
- 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'\`
|
|
812
|
-
`}function
|
|
1092
|
+
`}function No(){return`import {StrictMode} from 'react'
|
|
813
1093
|
import {createRoot} from 'react-dom/client'
|
|
814
1094
|
import App from './App.tsx'
|
|
815
1095
|
import './index.css'
|
|
816
1096
|
import './lib/justo'
|
|
817
|
-
import {ThemeProvider} from '@/components/theme-provider.tsx'
|
|
818
1097
|
|
|
819
1098
|
createRoot(document.getElementById('root')!).render(
|
|
820
1099
|
<StrictMode>
|
|
821
|
-
<
|
|
822
|
-
<App />
|
|
823
|
-
</ThemeProvider>
|
|
1100
|
+
<App />
|
|
824
1101
|
</StrictMode>,
|
|
825
1102
|
)
|
|
826
|
-
`}function
|
|
827
|
-
base: './',`);
|
|
828
|
-
`)}function
|
|
829
|
-
${
|
|
830
|
-
`),Pe(w(e,".git"),{recursive:!0,force:!0})}function fa(e){ee("git",["init"],e)}function wa(e){Pe(w(e,"package-lock.json"),{force:!0})}function _e(e){let r=Dr(e);if(!ye(r))throw Error(`No existe la app del space: ${r}`);if(!ye(w(r,Xr)))throw Error("Este publish solo acepta apps creadas con team-cli spaces init. Debes apuntar al root de esa app.");return r}function kr(e){let r=_e(e);ee(_("yarn"),["build"],r);let t=w(r,"dist");if(!ye(w(t,"index.html")))throw Error("El build no generó dist/index.html");return t}function Hr(e){let r=ua(e),t=zr(r),o=Fr(r);return ee(_("npx"),["shadcn@latest","init","-t","vite","-d","-y","-n",o],t),ee(_("npx"),["shadcn@latest","add","-a","-y"],r),wa(r),da(r),ee(_("yarn"),["install"],r),la(r),ma(r),pa(r),ga(r),fa(r),{path:r,nextSteps:[`cd ${r}`,'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"']}}function Zr(e){let r=[],t="",o=null,a=!1;for(let i of e){if(a){t+=i,a=!1;continue}if(i==="\\"){a=!0;continue}if(o){if(i===o)o=null;else t+=i;continue}if(i==='"'||i==="'"){o=i;continue}if(/\s/.test(i)){if(t)r.push(t),t="";continue}t+=i}if(o)throw Error("Comando inválido: falta cerrar una comilla");if(t)r.push(t);return r}var Ea=".justo-space-preview",va="preview.json",ja=30000;function Ie(e){return xe(e,Ea)}function at(e){return xe(Ie(e),va)}function Yr(e){return xe(Ie(e),"bridge.log")}function Vr(e){return xe(Ie(e),"vite.log")}function it(e){ya(Ie(e),{recursive:!0})}function qe(e){if(!e)return;try{process.kill(e,"SIGTERM")}catch{return}}function Aa(e){if(process.platform==="darwin")return{command:"open",args:[e]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",e]};return{command:"xdg-open",args:[e]}}async function Ra(e,r){if(!r)return{attempted:!1,opened:!1};let t=Aa(e);return await new Promise((o)=>{let a=he(t.command,t.args,{stdio:"ignore",detached:!0});a.once("error",()=>{o({attempted:!0,opened:!1,message:"No se pudo abrir el navegador por defecto automáticamente. Abre la URL manualmente."})}),a.once("spawn",()=>{a.unref(),o({attempted:!0,opened:!0})})})}function Na(e){let r=at(e);if(!ba(r))return;try{let t=JSON.parse(qa(r,"utf-8"));qe(t.appPid),qe(t.bridgePid)}catch{}ha(r,{force:!0})}function Kr(){return new Promise((e,r)=>{let t=tt();t.listen(0,"127.0.0.1",()=>{let o=t.address();if(!o||typeof o==="string"){t.close(),r(Error("No se pudo obtener un puerto libre"));return}let{port:a}=o;t.close((i)=>{if(i){r(i);return}e(a)})}),t.on("error",r)})}function Lr(e){return new Promise((r)=>setTimeout(r,e))}function Ta(e){return new Promise((r,t)=>{let i=(new URL(e).protocol==="https:"?$a:Sa)(e,{method:"GET"},(n)=>{r(n.statusCode||0),n.resume()});i.on("error",t),i.end()})}async function et(e,r=ja){let t=Date.now();while(Date.now()-t<r){try{if(await Ta(e)>0)return}catch{await Lr(500);continue}await Lr(500)}throw Error(`Timeout esperando que el preview responda en ${e}`)}function Oa(e){return it(Ia(e)),Ca(e,"a")}function rt(e,r,t,o,a){let i=Oa(o),n=he(e,r,{cwd:t,detached:!0,stdio:["ignore",i,i],env:{...process.env,...a}});if(!n.pid)throw Error(`No se pudo iniciar el proceso ${e}`);return n.unref(),n.pid}function nt(){let e=nr("prod");if(!e)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 e}async function Ua(e){let r=[];for await(let t of e)r.push(Buffer.isBuffer(t)?t:Buffer.from(t));return Buffer.concat(r).toString("utf-8")}function re(e,r,t){e.writeHead(r,{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Methods":"POST,OPTIONS,GET"}),e.end(JSON.stringify(t))}function Be(e){let r=e.trim(),t=new Set([0]);for(let a=0;a<r.length;a++)if(r[a]==="{"||r[a]==="[")t.add(a);let o=[...t].sort((a,i)=>i-a);for(let a of o)try{return JSON.parse(r.slice(a))}catch{continue}return r}function st(e){return{...process.env,NODE_OPTIONS:"",__JUSTO_REPL_PORT:"",JUSTO_TEAM_CLI_EMAIL:e.email,JUSTO_TEAM_CLI_TOKEN:e.token,JUSTO_TEAM_CLI_REFRESH_TOKEN:e.refreshToken,JUSTO_TEAM_CLI_INTERACTIVE:"false",JUSTO_TEAM_CLI_DEVICE_ID:"spaces-preview"}}function Qa(e,r){return{VITE_JUSTO_CLI_ENDPOINT:e,VITE_JUSTO_STREAM_ENDPOINT:r,VITE_JUSTO_CLI_MODE:"preview",[L]:we}}function Pa(e,r,t,o){return new Promise((a,i)=>{let n=he(be(),[r,"--env","prod",...o,"--format","json"],{cwd:process.cwd(),env:st(t),stdio:["ignore","pipe","pipe"]}),s="";n.stdout.on("data",(c)=>{if(!e.headersSent)e.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"});e.write(c)}),n.stderr.on("data",(c)=>{s+=Buffer.from(c).toString("utf-8")}),n.on("error",i),n.on("close",(c)=>{if(!c){if(!e.headersSent)e.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"});e.end(),a();return}let l=Be(s.trim());i(Error(l.error||s.trim()||"justoStream failed"))})})}async function ct(e){let r=Number(e.port);if(!r)throw Error("Falta --port para el bridge interno de preview");let t=nt(),o=ot(e["cli-path"]||process.argv[1]||""),a=tt(async(i,n)=>{if(i.method==="OPTIONS"){re(n,200,{ok:!0});return}if(i.method==="GET"&&i.url==="/__justo/health"){re(n,200,{ok:!0});return}if(i.method!=="POST"||i.url!=="/__justo/cli"&&i.url!=="/__justo/stream"){re(n,404,{ok:!1,error:"Not found"});return}try{let s=await Ua(i),l=JSON.parse(s||"{}").command;if(!l)throw Error("Debes indicar un comando");let m=Array.isArray(l)?l:Zr(l);if(i.url==="/__justo/stream"){await Pa(n,o,t,m);return}let p=await new Promise((d,b)=>{let f=he(be(),[o,"--env","prod",...m,"--format","json"],{cwd:process.cwd(),env:st(t),stdio:["ignore","pipe","pipe"]}),T=[],O=[];f.stdout.on("data",(U)=>T.push(Buffer.from(U))),f.stderr.on("data",(U)=>O.push(Buffer.from(U))),f.on("error",b),f.on("close",(U)=>{let X=Buffer.concat(T).toString("utf-8")||Buffer.concat(O).toString("utf-8");if(U&&U!==0){let co=Be(X);b(Error(co.error||X||"justoCli failed"));return}d(Be(X))})});re(n,200,{result:p})}catch(s){let c=s instanceof Error?s.message:"Unexpected error";re(n,400,{error:c})}});await new Promise((i,n)=>{a.listen(r,"127.0.0.1",()=>i()),a.on("error",n)}),C(`Space preview bridge listening on http://127.0.0.1:${r}
|
|
831
|
-
`),await new Promise((
|
|
832
|
-
`);let
|
|
833
|
-
`);let a=`${r} ${Fa(o)}`,i=Ga(a,{shell:!0,stdio:"inherit"});if(i.error)throw Error(`No se pudo abrir el editor "${r}": ${i.error.message}`);if(i.status!==0)throw Error(`El editor terminó con código ${i.status}.`);try{let n=Ba(o,"utf-8");if(!n.trim())throw Error("El archivo quedó vacío.");let s;try{s=JSON.parse(n)}catch{throw Error("El archivo editado no contiene JSON válido.")}return Da(s)}finally{Ja(t,{recursive:!0,force:!0})}}function h(){if(!g())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 N(e,r){let t=e[3];if(!t)throw Error(`Uso: ${r}`);return t}function z(e){if(!e.params)return{};try{return JSON.parse(e.params)}catch{throw Error("--params debe ser un JSON válido.")}}function Je(e){let r=e.limit;if(!r)throw Error("--limit es requerido. Ejemplo: --limit 1000");let t=Number(r);if(!Number.isInteger(t)||t<=0)throw Error("--limit debe ser un entero positivo.");return t}function pt(e){let r=e.emails;if(!r)throw Error("--emails es requerido. Ejemplo: --emails ana@justo.com,bob@justo.com");let t=r.split(",").map((a)=>a.trim().toLowerCase()).filter(Boolean);if(!t.length)throw Error("--emails debe contener al menos un email.");let o=t.find((a)=>!a.includes("@"));if(o)throw Error(`Email inválido: ${o}`);return[...new Set(t)]}function We(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return{value:e}}}async function D(e){return(await u({service:"data",query:`query ($aggregationQueryId: String) {
|
|
834
|
-
aggregationQuery(aggregationQueryId: $aggregationQueryId) {
|
|
835
|
-
_id
|
|
836
|
-
name
|
|
837
|
-
description
|
|
838
|
-
collection
|
|
839
|
-
currentVersionIndex
|
|
840
|
-
allowedUsersIds
|
|
841
|
-
tags
|
|
842
|
-
pipeline
|
|
843
|
-
variables {
|
|
844
|
-
key
|
|
845
|
-
fieldType
|
|
846
|
-
fieldParams
|
|
847
|
-
}
|
|
848
|
-
}
|
|
849
|
-
}`,variables:{aggregationQueryId:e}})).aggregationQuery}async function gt(e){return await Promise.all(e.map(async(t)=>{let a=(await u({service:"main",query:`query ($filter: String, $limit: BigInt) {
|
|
850
|
-
justoUsers(filter: $filter, limit: $limit) {
|
|
851
|
-
items {
|
|
852
|
-
_id
|
|
853
|
-
email
|
|
854
|
-
fullName
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
}`,variables:{filter:t,limit:10}})).justoUsers?.items?.find((i)=>i.email?.toLowerCase()===t);if(!a?._id)throw Error(`No encontramos un usuario de Justo para ${t}`);return a}))}function ft(e){return{name:e.name,description:e.description,collection:e.collection,allowedUsersIds:e.allowedUsersIds??[],tags:e.tags??[],pipeline:e.pipeline,variables:e.variables??[]}}async function Me(e,r){let t=await u({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
|
|
858
|
-
testAggregationQuery(aggregationQueryId: $aggregationQueryId, params: $params)
|
|
859
|
-
}`,variables:{aggregationQueryId:e,params:r}});return We(t.testAggregationQuery)}async function wt(e){let r=await fetch(`${q("data")}/execute-pipeline`,{method:"POST",headers:await pe(),body:JSON.stringify({collection:e.collection,pipeline:e.pipeline,params:e.queryParams,limit:e.limit}),signal:AbortSignal.timeout(75000)});if(!r.ok){let t=await r.text();throw Error(bt(t)||"No se pudo ejecutar el pipeline.")}return await r.json()}function bt(e){try{return JSON.parse(e).error||e}catch{return e}}async function yt(e,r,t){let o=await fetch(`${q("data")}/aggregation-queries/${e}/run`,{method:"POST",headers:await pe(),body:JSON.stringify({params:r,limit:t}),signal:AbortSignal.timeout(315000)});if(!o.ok){let l=await o.text();throw Error(bt(l)||"No se pudo ejecutar el query.")}if(!o.body)throw Error("El servidor no devolvió un stream de datos.");let a=o.body.getReader(),i=new TextDecoder,n="",s=0;while(!0){let{done:l,value:m}=await a.read();if(l)break;let p=i.decode(m,{stream:!0});process.stdout.write(p),n+=p;let d=n.indexOf(`
|
|
860
|
-
`);while(d>=0){if(n.slice(0,d).trim())s++;n=n.slice(d+1),d=n.indexOf(`
|
|
861
|
-
`)}}let c=i.decode();if(c)process.stdout.write(c),n+=c;if(n.trim())s++;return{ok:!0,queryId:e,limit:t,rows:s}}async function Ge(e,r){await Fe(e,{name:r.name,description:r.description,collection:r.collection,allowedUsersIds:r.allowedUsersIds,tags:r.tags}),await u({service:"data",query:`mutation ($aggregationQueryId: String, $pipeline: String, $variables: [AggregationQueryVariableInput]) {
|
|
862
|
-
addAggregationQueryVersion(
|
|
863
|
-
aggregationQueryId: $aggregationQueryId
|
|
864
|
-
pipeline: $pipeline
|
|
865
|
-
variables: $variables
|
|
866
|
-
) {
|
|
867
|
-
_id
|
|
868
|
-
currentVersionIndex
|
|
869
|
-
}
|
|
870
|
-
}`,variables:{aggregationQueryId:e,pipeline:r.pipeline,variables:r.variables}})}async function Fe(e,r){await u({service:"data",query:`mutation ($aggregationQueryId: String, $aggregationQuery: UpdateAggregationQueryInput) {
|
|
871
|
-
updateAggregationQuery(
|
|
872
|
-
aggregationQueryId: $aggregationQueryId
|
|
873
|
-
aggregationQuery: $aggregationQuery
|
|
874
|
-
) {
|
|
875
|
-
_id
|
|
876
|
-
name
|
|
877
|
-
description
|
|
878
|
-
collection
|
|
879
|
-
allowedUsersIds
|
|
880
|
-
tags
|
|
881
|
-
currentVersionIndex
|
|
882
|
-
}
|
|
883
|
-
}`,variables:{aggregationQueryId:e,aggregationQuery:{name:r.name,description:r.description,collection:r.collection,allowedUsersIds:r.allowedUsersIds,tags:r.tags}}})}async function Ct(){return(await u({service:"data",query:`mutation {
|
|
884
|
-
createAggregationQuery {
|
|
885
|
-
_id
|
|
886
|
-
name
|
|
887
|
-
description
|
|
888
|
-
collection
|
|
889
|
-
currentVersionIndex
|
|
890
|
-
allowedUsersIds
|
|
891
|
-
tags
|
|
892
|
-
pipeline
|
|
893
|
-
variables {
|
|
894
|
-
key
|
|
895
|
-
fieldType
|
|
896
|
-
fieldParams
|
|
897
|
-
}
|
|
898
|
-
}
|
|
899
|
-
}`})).createAggregationQuery}function ka(e){if(!Array.isArray(e))throw Error("El preview del query debe devolver un arreglo para usar AI edit.");return e}async function Ha(e){let r=await u({service:"messenger",query:`mutation generateAdminQuery(
|
|
900
|
-
$prompt: String
|
|
901
|
-
$name: String
|
|
902
|
-
$description: String
|
|
903
|
-
$fullCollectionName: String
|
|
904
|
-
$variables: [JSON]
|
|
905
|
-
$pipeline: String
|
|
906
|
-
$preview: [JSON]
|
|
907
|
-
) {
|
|
908
|
-
generateAdminQuery(
|
|
909
|
-
prompt: $prompt
|
|
910
|
-
name: $name
|
|
911
|
-
description: $description
|
|
912
|
-
fullCollectionName: $fullCollectionName
|
|
913
|
-
variables: $variables
|
|
914
|
-
pipeline: $pipeline
|
|
915
|
-
preview: $preview
|
|
916
|
-
canUseVariables: true
|
|
917
|
-
) {
|
|
918
|
-
responseText
|
|
919
|
-
fullCollectionName
|
|
920
|
-
pipeline
|
|
921
|
-
variables
|
|
922
|
-
aggregationDescription
|
|
923
|
-
aggregationName
|
|
924
|
-
}
|
|
925
|
-
}`,variables:e});if(!r.generateAdminQuery?.pipeline||!r.generateAdminQuery.fullCollectionName)throw Error("La IA no devolvió una versión válida del query.");return r.generateAdminQuery}async function Za(e){let r=await u({service:"messenger",timeoutMs:120000,query:`mutation explainAdminQuery($prompt: String) {
|
|
926
|
-
explainAdminQuery(prompt: $prompt) {
|
|
927
|
-
responseText
|
|
928
|
-
}
|
|
929
|
-
}`,variables:{prompt:e}});if(!r.explainAdminQuery?.responseText)throw Error("La IA no devolvió una explicación válida.");return r.explainAdminQuery}async function qt(){return h(),await Ct()}async function ht(e){h();let r=e.prompt||await F("Explica qué query quieres investigar o construir: ");if(!r)throw Error("Debes indicar un prompt para explain.");return(await Za(r)).responseText}async function xt(e){if(h(),!e.collection)throw Error("Debes indicar --collection con formato db.collection. Ejemplo: --collection justo.users");if(!e.pipeline)throw Error("Debes indicar --pipeline. Ejemplo: --pipeline '[{$limit: 5}]'");let r=e.limit?Je(e):void 0;return await wt({collection:e.collection,pipeline:e.pipeline,queryParams:z(e),limit:r})}async function It(e){h();let r=N(e,"team-cli data queries edit <queryId>"),t=await D(r),o=dt(ft(t));return await Ge(r,o),{ok:!0,queryId:r,name:o.name,collection:o.collection}}async function St(e,r){h();let t=N(e,"team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>']"),o=await D(t),a=r.prompt||await F("Describe los cambios para la IA: ");if(!a)throw Error("Debes indicar un prompt para AI edit.");let i=z(r),n;if(r.params){C(`Obteniendo preview del query actual...
|
|
930
|
-
`);try{let c=await Me(t,i);n=ka(c)}catch(c){let l=c instanceof Error?c.message:String(c);throw Error(`No se pudo obtener el preview para AI edit: ${l}`)}}C(`Generando propuesta con IA...
|
|
931
|
-
`);let s=await Ha({prompt:a,fullCollectionName:o.collection,pipeline:o.pipeline,preview:n,description:o.description,name:o.name,variables:o.variables});return await Ge(t,{name:o.name==="Nuevo query"?s.aggregationName||o.name:o.name,description:o.description||s.aggregationDescription,collection:s.fullCollectionName,allowedUsersIds:o.allowedUsersIds??[],tags:o.tags??[],pipeline:s.pipeline,variables:s.variables??[]}),{ok:!0,queryId:t,responseText:s.responseText,collection:s.fullCollectionName,name:s.aggregationName,description:s.aggregationDescription}}async function $t(e){h();let r=N(e,"team-cli data queries view <queryId>");return await D(r)}async function Et(e){h();let r=N(e,"team-cli data queries view-pipeline <queryId>"),t=await D(r);return{queryId:r,pipeline:t.pipeline}}async function vt(e,r){h();let t=N(e,"team-cli data queries preview <queryId> --params '<json>'"),o=z(r),a=await Me(t,o);return We(a)}async function jt(e,r){h();let t=N(e,"team-cli data queries run <queryId> --limit <n> --params '<json>'"),o=z(r),a=Je(r);return await yt(t,o,a),{__streamHandled:!0}}async function At(e,r){h();let t=N(e,"team-cli data queries add-viewers <queryId> --emails 'ana@justo.com,bob@justo.com'"),o=pt(r),a=await D(t),i=await gt(o),n=[...new Set([...a.allowedUsersIds??[],...i.map((s)=>s._id)])];return await Fe(t,{name:a.name,description:a.description,collection:a.collection,allowedUsersIds:n,tags:a.tags??[]}),{ok:!0,queryId:t,addedViewers:i.map((s)=>({_id:s._id,email:s.email,fullName:s.fullName})),allowedUsersIds:n}}function Ya(e){return new Promise((r)=>setTimeout(r,e))}async function Rt(e,r){h();let t=N(e,"team-cli data queries download <queryId> --params '<json>'"),o=z(r);if(!r.path)throw Error("--path es requerido. Ejemplo: --path resultado.xlsx");C(`Iniciando descarga...
|
|
932
|
-
`);let i=(await u({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
|
|
933
|
-
downloadAggregationQueryData(aggregationQueryId: $aggregationQueryId, params: $params)
|
|
934
|
-
}`,variables:{aggregationQueryId:t,params:o}})).downloadAggregationQueryData;C(`Reporte en proceso (${i})...
|
|
935
|
-
`);let n=null;while(!n){await Ya(1000);let l=await u({service:"data",query:`query ($id: String) {
|
|
936
|
-
getAsyncReport(id: $id) {
|
|
937
|
-
_id
|
|
938
|
-
status
|
|
939
|
-
estimatedRecordsCount
|
|
940
|
-
fileUrl
|
|
941
|
-
}
|
|
942
|
-
getAsyncReportRecordsCount(id: $id)
|
|
943
|
-
}`,variables:{id:i}}),m=l.getAsyncReport,p=l.getAsyncReportRecordsCount;if(m.status==="error")throw Error("El reporte falló al generarse.");if(m.fileUrl)n=m.fileUrl;else{let d=m.estimatedRecordsCount?` (~${m.estimatedRecordsCount} registros)`:"",b=p!=null?` ${p} procesados`:"";C(`\rGenerando...${d}${b}`)}}C(`
|
|
944
|
-
Descargando archivo...
|
|
945
|
-
`);let s=await fetch(n);if(!s.ok)throw Error(`Error descargando archivo: ${s.status}`);let c=Buffer.from(await s.arrayBuffer());return Xa(r.path,c),{ok:!0,queryId:t,asyncReportId:i,outputPath:r.path,fileUrl:n}}function ze(){return`team-cli data
|
|
946
|
-
|
|
947
|
-
Comandos de datos y reportes.
|
|
948
|
-
|
|
949
|
-
Recomendado:
|
|
950
|
-
Si necesitas obtener data y no existe un query listo, usa explain -> create -> ai-edit.
|
|
951
|
-
Flujo sugerido: explain -> create -> ai-edit -> preview -> run o download.
|
|
952
|
-
Usa queries cuando quieras que la consulta quede guardada, versionada y compartible.
|
|
953
|
-
Usa execute solo para correr un pipeline una vez.
|
|
954
|
-
Para spaces, prefiere siempre queries guardados en vez de execute directo.
|
|
955
|
-
Siempre que puedas, prefiere varias queries simples antes que un solo pipeline con lookup.
|
|
956
|
-
Para dashboards suele ser mejor resolver joins en la UI o con queries separadas.
|
|
957
|
-
Caso común:
|
|
958
|
-
1. Usa explain para investigar servicio, colección, fields o resolvers.
|
|
959
|
-
2. Usa execute para probar un pipeline una sola vez.
|
|
960
|
-
3. Si lo vas a reutilizar, conviértelo en query guardado con create + ai-edit.
|
|
961
|
-
|
|
962
|
-
Uso:
|
|
963
|
-
team-cli data <subcomando> [opciones]
|
|
964
|
-
|
|
965
|
-
Subcomandos:
|
|
966
|
-
explain
|
|
967
|
-
Pedir una explicación guiada para investigar cómo construir un query o cómo consultar datos por GraphQL usando el subagente de repo.
|
|
968
|
-
Uso: team-cli data explain --prompt '<texto>' [--format toon|json]
|
|
969
|
-
Solo disponible para usuarios con rol queries.
|
|
970
|
-
|
|
971
|
-
execute
|
|
972
|
-
Ejecutar un pipeline directo sin crear un query guardado.
|
|
973
|
-
Piensa en esto como ejecución ad-hoc de una sola vez.
|
|
974
|
-
Solo lectura: bloquea stages de escritura como $out y $merge.
|
|
975
|
-
Usa timeout de 1 minuto, read preference secondaryPreferred y requiere rol queries.
|
|
976
|
-
Para spaces y dashboards compartibles, prefiere queries guardados con data queries create + ai-edit.
|
|
977
|
-
Uso: team-cli data execute --collection <db.collection> --pipeline '<array js>' [--params '<json>'] [--limit <n>] [--format toon|json]
|
|
978
|
-
|
|
979
|
-
queries
|
|
980
|
-
Administrar y ejecutar aggregation queries guardados.
|
|
981
|
-
|
|
982
|
-
Uso de queries:
|
|
983
|
-
team-cli data queries <subcomando> [opciones]
|
|
984
|
-
|
|
985
|
-
Subcomandos de queries:
|
|
986
|
-
create
|
|
987
|
-
Crear un query nuevo.
|
|
988
|
-
Devuelve el _id para seguir con edit, ai-edit, view o preview.
|
|
989
|
-
|
|
990
|
-
edit <queryId>
|
|
991
|
-
Editar un query manualmente en tu editor local usando JSON.
|
|
992
|
-
Campos editables: name, description, collection, allowedUsersIds, tags, pipeline, variables.
|
|
993
|
-
El pipeline debe quedar como string con un array JavaScript válido.
|
|
994
|
-
|
|
995
|
-
ai-edit <queryId>
|
|
996
|
-
Editar un query con IA.
|
|
997
|
-
Uso: team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>'] [--format toon|json]
|
|
998
|
-
Si envías --params, primero se ejecuta preview y esos resultados se adjuntan al prompt.
|
|
999
|
-
|
|
1000
|
-
view <queryId>
|
|
1001
|
-
Ver informacion de un query.
|
|
1002
|
-
|
|
1003
|
-
view-pipeline <queryId>
|
|
1004
|
-
Ver el pipeline de un query.
|
|
1005
|
-
|
|
1006
|
-
preview <queryId>
|
|
1007
|
-
Ejecutar un query de prueba.
|
|
1008
|
-
Uso: team-cli data queries preview <queryId> --params '<json>' [--format toon|json]
|
|
1009
|
-
|
|
1010
|
-
run <queryId>
|
|
1011
|
-
Ejecutar un query completo en streaming NDJSON.
|
|
1012
|
-
Usa timeout de 5 minutos y read preference secondaryPreferred.
|
|
1013
|
-
Uso: team-cli data queries run <queryId> --limit <n> [--params '<json>']
|
|
1014
|
-
|
|
1015
|
-
download <queryId>
|
|
1016
|
-
Descargar resultado completo como Excel.
|
|
1017
|
-
Uso: team-cli data queries download <queryId> --path <filepath> [--params '<json>'] [--format toon|json]
|
|
1018
|
-
|
|
1019
|
-
add-viewers <queryId>
|
|
1020
|
-
Agregar personas con acceso a un query usando sus emails de Justo.
|
|
1021
|
-
Uso: team-cli data queries add-viewers <queryId> --emails 'ana@justo.com,bob@justo.com'
|
|
1022
|
-
Esto actualiza allowedUsersIds sin cambiar el pipeline ni crear una versión nueva.
|
|
1023
|
-
|
|
1024
|
-
Opciones:
|
|
1025
|
-
--params '<json>' Parametros del query. Default: {}
|
|
1026
|
-
--limit <n> Requerido para run. En execute es opcional y limita resultados.
|
|
1027
|
-
--emails '<csv>' Requerido para add-viewers. Lista separada por comas.
|
|
1028
|
-
--prompt '<texto>' Prompt para ai-edit. Si no viene, se pide interactivamente.
|
|
1029
|
-
--collection <db.collection> Requerido para execute.
|
|
1030
|
-
--pipeline '<array js>' Requerido para execute.
|
|
1031
|
-
--format <toon|json> Usa toon por defecto cuando el comando lo ejecute un agente como Codex o Claude.
|
|
1032
|
-
--path <filepath> Requerido para download
|
|
1033
|
-
|
|
1034
|
-
Ejemplos:
|
|
1035
|
-
team-cli data explain --prompt 'Quiero entender dónde viven los campos de courier de los pedidos'
|
|
1036
|
-
team-cli data explain --prompt 'Quiero saber cómo consultar tabs por GraphQL y qué resolvers mirar'
|
|
1037
|
-
team-cli data execute --collection justo.users --pipeline '[{$limit: 5}, {$project: {_id: 1, createdAt: 1}}]'
|
|
1038
|
-
team-cli data queries create
|
|
1039
|
-
team-cli data queries edit abc123
|
|
1040
|
-
team-cli data queries ai-edit abc123 --prompt 'Filtra solo ordenes canceladas'
|
|
1041
|
-
team-cli data queries ai-edit abc123 --prompt 'Ajusta el pipeline' --params '{"websiteId":"w1"}'
|
|
1042
|
-
team-cli data queries preview abc123 --params '{"startDate": "2026-01-01"}'
|
|
1043
|
-
team-cli data queries run abc123 --limit 1000 --params '{"startDate": "2026-01-01"}'
|
|
1044
|
-
team-cli data queries download abc123 --params '{"startDate": "2026-01-01"}' --path resultado.xlsx
|
|
1045
|
-
team-cli data queries add-viewers abc123 --emails 'ana@justo.com,bob@justo.com'`}var Nt=["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"],Tt=`
|
|
1046
|
-
query ResolverInfo($name: ID!, $mutation: Boolean!) {
|
|
1047
|
-
params(name: $name, mutation: $mutation) {
|
|
1048
|
-
name
|
|
1049
|
-
params
|
|
1050
|
-
result
|
|
1051
|
-
basicResultQuery
|
|
1052
|
-
}
|
|
1053
|
-
}
|
|
1054
|
-
`;function Va(e){if(!e)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");if(!Nt.includes(e))throw Error(`Servicio "${e}" no válido. Servicios disponibles: ${Nt.join(", ")}`)}async function Ka(e,r){let t;try{let o=await u({service:e,query:Tt,variables:{name:r,mutation:!1}});return{service:e,operationName:r,operationType:"query",info:o.params}}catch(o){t=o}try{let o=await u({service:e,query:Tt,variables:{name:r,mutation:!0}});return{service:e,operationName:r,operationType:"mutation",info:o.params}}catch(o){let a=t instanceof Error?t.message:"",i=o instanceof Error?o.message:"";if(a.includes('Cannot query field "params"')||i.includes('Cannot query field "params"'))throw Error(`El servicio "${e}" no expone metadata de resolvers por GraphQL.`);throw t instanceof Error?t:o}}async function Ot(e,r){let t=e[1],o=e[2],a=e[2];if(!g())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(Va(t),o==="info"){let s=e[3];if(!s)throw Error("Uso: team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]");return await Ka(t,s)}if(!a)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");let i;if(r.variables)try{i=JSON.parse(r.variables)}catch{throw Error("Las variables deben ser un JSON válido.")}return await u({service:t,query:a,variables:i})}function Ut(){return Object.keys(ce)}function La(){return Ut().map((e)=>{let r=ce[e].prod;return`- \`${e}\`: \`${r}/graphql\``}).join(`
|
|
1055
|
-
`)}function Qt(){let r=Ut().join(", "),t=La();return`team-cli graphql
|
|
1056
|
-
|
|
1057
|
-
Ejecutar queries y mutations GraphQL.
|
|
1058
|
-
|
|
1059
|
-
Uso:
|
|
1060
|
-
team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]
|
|
1061
|
-
team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]
|
|
1062
|
-
|
|
1063
|
-
Comando info:
|
|
1064
|
-
Consulta la metadata publicada por OrionJS para un query o mutation.
|
|
1065
|
-
Devuelve el tipo de operación, los params serializados, el resultado y un basicResultQuery.
|
|
1066
|
-
Si no indicas si es query o mutation, la CLI prueba ambas automáticamente.
|
|
1067
|
-
|
|
1068
|
-
Formato:
|
|
1069
|
-
Por defecto usa toon. Usa --format json para JSON estándar.
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
Servicios disponibles: ${r}.
|
|
1074
|
-
|
|
1075
|
-
Ejemplos:
|
|
1076
|
-
\`\`\`bash
|
|
1077
|
-
npx @getjusto/team-cli graphql main 'query { me { _id roles } }'
|
|
1078
|
-
npx @getjusto/team-cli graphql main 'query($id: ID) { user(userId: $id) { _id } }' --variables '{"id": "abc123"}'
|
|
1079
|
-
npx @getjusto/team-cli graphql tabs 'query { tab(tabId: "t123") { _id status } }' --format json
|
|
1080
|
-
\`\`\`
|
|
1081
|
-
|
|
1082
|
-
### graphql info
|
|
1083
|
-
|
|
1084
|
-
Úsalo cuando conoces el nombre del resolver pero no su contrato exacto.
|
|
1085
|
-
|
|
1086
|
-
\`\`\`bash
|
|
1087
|
-
npx @getjusto/team-cli graphql <service> info <queryName|mutationName> [--format toon|json]
|
|
1088
|
-
\`\`\`
|
|
1089
|
-
|
|
1090
|
-
Devuelve:
|
|
1091
|
-
- \`operationType\`
|
|
1092
|
-
- \`info.params\`
|
|
1093
|
-
- \`info.result\`
|
|
1094
|
-
- \`info.basicResultQuery\`
|
|
1095
|
-
|
|
1096
|
-
Ejemplos:
|
|
1097
|
-
\`\`\`bash
|
|
1098
|
-
npx @getjusto/team-cli graphql main info website
|
|
1099
|
-
npx @getjusto/team-cli graphql auth info requestLoginCode --format json
|
|
1100
|
-
\`\`\`
|
|
1101
|
-
|
|
1102
|
-
### Mapa de servicios GraphQL
|
|
1103
|
-
|
|
1104
|
-
Usa esto para mapear una URL GraphQL al valor correcto de \`team-cli graphql <service>\`.
|
|
1105
|
-
|
|
1106
|
-
${t}`}import{existsSync as $i,mkdirSync as Ei,readdirSync as vi}from"node:fs";import{resolve as Yt}from"node:path";import{readdirSync as Jt,readFileSync as Wt,statSync as Mt}from"node:fs";import{gzipSync as ci}from"node:zlib";import{join as Gt,relative as Ft,resolve as _t}from"node:path";import{existsSync as ei,readFileSync as ri}from"node:fs";import{join as ti}from"node:path";var oi=[".git","node_modules","dist",".justo-space-preview",".DS_Store"];function ai(e){return e.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function ii(e){let r="";for(let t=0;t<e.length;t++){let o=e[t],a=e[t+1];if(o==="*"){if(a==="*"){r+=".*",t+=1;continue}r+="[^/]*";continue}if(o==="?"){r+="[^/]";continue}r+=ai(o)}return r}function ni(e){let r=e.trim();if(!r||r.startsWith("#"))return null;let t=r.startsWith("!"),o=t?r.slice(1).trim():r;if(!o)return null;let a=o.endsWith("/"),i=o.replace(/^\/+/,"").replace(/\/+$/,"");if(!i)return null;let n=i.includes("/"),s=ii(i),c=n?`^${s}${a?"(?:/.*)?":""}$`:`(?:^|/)${s}${a?"(?:/.*)?":"(?:$|/)"}`;return{negate:t,directoryOnly:a,regex:new RegExp(c)}}function si(e){let r=ti(e,".gitignore"),t=[...oi];if(ei(r))t.push(...ri(r,"utf-8").split(/\r?\n/));return t.map(ni).filter((o)=>Boolean(o))}function Pt(e){let r=si(e);return(t,o)=>{let a=t.replaceAll("\\","/").replace(/^\/+/,""),i=!1;for(let n of r){if(!n.regex.test(a))continue;i=!n.negate}return i}}var Se=512,ui=2,li="repo",mi="dist";function di(e){let r=e.replaceAll("\\","/");if(r.startsWith("/")||r.includes("../"))throw Error(`Ruta inválida en el space: ${e}`);return r}function pi(e){let r=di(e);if(Buffer.from(r).length<=100)return{name:r,prefix:""};let o=r.lastIndexOf("/");if(o<=0)throw Error(`La ruta es demasiado larga para el paquete del space: ${e}`);let a=r.slice(0,o),i=r.slice(o+1);if(Buffer.from(a).length>155||Buffer.from(i).length>100)throw Error(`La ruta es demasiado larga para el paquete del space: ${e}`);return{name:i,prefix:a}}function B(e,r,t,o){let a=Buffer.from(o);a.copy(e,r,0,Math.min(a.length,t))}function te(e,r,t,o){let a=Math.max(0,Math.trunc(o)).toString(8).padStart(t-1,"0");B(e,r,t,`${a}\x00`)}function gi(e){let r=Buffer.alloc(Se,0),{name:t,prefix:o}=pi(e.path);B(r,0,100,t),te(r,100,8,e.mode),te(r,108,8,0),te(r,116,8,0),te(r,124,12,e.content.length),te(r,136,12,e.mtime),r.fill(32,148,156),B(r,156,1,"0"),B(r,257,6,"ustar"),B(r,263,2,"00"),B(r,345,155,o);let a=0;for(let n of r)a+=n;let i=`${a.toString(8).padStart(6,"0")}\x00 `;return B(r,148,8,i),r}function fi(e){let r=e%Se;return r===0?0:Se-r}function zt(e,r=e){return Jt(r,{withFileTypes:!0}).sort((o,a)=>o.name.localeCompare(a.name)).flatMap((o)=>{let a=Gt(r,o.name);if(o.isDirectory())return zt(e,a);if(!o.isFile())return[];let i=Ft(e,a),n=Mt(a);return[{path:i,content:Wt(a),mode:n.mode&511,mtime:Math.floor(n.mtimeMs/1000)}]})}function Bt(e,r){return e.map((t)=>({...t,path:`${r}/${t.path.replaceAll("\\","/")}`}))}function Dt(e,r=e){let t=Pt(e);return Jt(r,{withFileTypes:!0}).sort((a,i)=>a.name.localeCompare(i.name)).flatMap((a)=>{let i=Gt(r,a.name),n=Ft(e,i).replaceAll("\\","/");if(t(n,a.isDirectory()))return[];if(a.isDirectory())return Dt(e,i);if(!a.isFile())return[];let s=Mt(i);return[{path:n,content:Wt(i),mode:s.mode&511,mtime:Math.floor(s.mtimeMs/1000)}]})}function Xt(e,r){let t=_t(e),o=_t(r),a=[...Bt(Dt(t),li),...Bt(zt(o),mi)];if(!a.length)throw Error("El build del space no contiene archivos para publicar");let i=[];for(let n of a){i.push(gi(n)),i.push(n.content);let s=fi(n.content.length);if(s>0)i.push(Buffer.alloc(s,0))}return i.push(Buffer.alloc(Se*ui,0)),ci(Buffer.concat(i))}import{mkdirSync as kt,writeFileSync as wi}from"node:fs";import{dirname as bi,join as yi,normalize as Ci,sep as Ht}from"node:path";import{gunzipSync as qi}from"node:zlib";var oe=512;function $e(e,r,t){let o=e.subarray(r,r+t),a=o.indexOf(0);return(a>=0?o.subarray(0,a):o).toString("utf-8").trim()}function hi(e,r,t){let o=$e(e,r,t).replaceAll("\x00","").trim();if(!o)return 0;return Number.parseInt(o,8)}function xi(e){let r=e%oe;return r===0?0:oe-r}function Ii(e){let r=$e(e,0,100),t=$e(e,345,155);return t?`${t}/${r}`:r}function Si(e){let r=Ci(e);if(!e||e.startsWith("/")||r.startsWith("..")||r.includes(`${Ht}..${Ht}`)||r==="..")throw Error("El paquete del space contiene rutas inválidas")}function Zt(e,r,t){let o=qi(e),a=r.replaceAll("\\","/").replace(/^\/+|\/+$/g,""),i=`${a}/`,n=0,s=0;while(n+oe<=o.length){let c=o.subarray(n,n+oe),l=c.every((O)=>O===0);if(n+=oe,l)break;let m=Ii(c),p=$e(c,156,1)||"0",d=hi(c,124,12),b=o.subarray(n,n+d);if(n+=d+xi(d),!m.startsWith(i))continue;let f=m.slice(i.length);if(!f)continue;Si(f);let T=yi(t,...f.split("/"));if(p==="5"){kt(T,{recursive:!0});continue}if(p!=="0")continue;kt(bi(T),{recursive:!0}),wi(T,b),s+=1}if(!s)throw Error(`El paquete del space no contiene la carpeta ${a}/`);return s}function Ee(){if(!g())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 ae(e,r,t){let o=e[r];if(!o)throw Error(`Falta --${r}. Ejemplo: ${t}`);return o}function Vt(e,r){let t=e[2];if(!t)throw Error(`Uso: ${r}`);return t}function De(){let e=ue();if(e==="local")return"http://intra.localhost:5173";if(e==="develop")return"https://intra.bejusto.com";return"https://intra.getjusto.com"}async function ji(e,r){let t=await de(),o=await fetch(`${q("data")}/spaces/publish/${e}`,{method:"POST",headers:{"Content-Type":"application/gzip",...t?{"X-ORION-JWT":t}:{}},body:r}),a=await o.json();if(!o.ok||a.error)throw Error(a.error||"No se pudo publicar el space.");return a}async function Ai(e){let r=await de(),t=await fetch(`${q("data")}/spaces/fork/${e}`,{method:"GET",headers:r?{"X-ORION-JWT":r}:{}});if(!t.ok){let o=await t.json().catch(()=>({}));throw Error(o.error||"No se pudo descargar el repo del space.")}return Buffer.from(await t.arrayBuffer())}function Ri(e){let r=Yt(e);if($i(r)&&vi(r).length>0)throw Error(`La carpeta ya existe y no está vacía: ${r}`);return Ei(r,{recursive:!0}),r}function Xe(){return`team-cli spaces
|
|
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
|
|
1107
1110
|
|
|
1108
1111
|
Spaces son aplicaciones internas en React, pensadas para que las construyan agentes.
|
|
1109
1112
|
El flujo oficial parte con \`spaces init\` y \`spaces publish\` solo acepta apps creadas así.
|
|
@@ -1126,6 +1129,8 @@ Cada space:
|
|
|
1126
1129
|
- para queries grandes también reciben \`window.justo.stream(command, onRow)\`
|
|
1127
1130
|
- \`window.justo.stream(...)\` consume NDJSON, parsea cada fila a JSON y llama tu callback
|
|
1128
1131
|
- \`spaces init\`, \`spaces preview\` y \`spaces publish\` funcionan en macOS, Linux y Windows sin depender de \`tar\` global
|
|
1132
|
+
- el archivo \`.justo-space.json\` puede declarar \`collections\` para que el publish sincronice índices en Mongo
|
|
1133
|
+
- esas collections se exponen con \`team-cli spaces db\` usando el prefijo físico \`spaces.<slug_sanitized>.<collection>\`
|
|
1129
1134
|
|
|
1130
1135
|
Flujo sugerido para agentes:
|
|
1131
1136
|
1. \`team-cli spaces init --path ./mi-space-app\`
|
|
@@ -1135,7 +1140,7 @@ Flujo sugerido para agentes:
|
|
|
1135
1140
|
5. desarrollar la app React dentro de esa carpeta
|
|
1136
1141
|
6. \`team-cli spaces publish <spaceId> --path ./mi-space-app\`
|
|
1137
1142
|
7. hacer commit del repo después de publicar
|
|
1138
|
-
8. abrir \`${
|
|
1143
|
+
8. abrir \`${da()}/spaces/<slug>\`
|
|
1139
1144
|
9. si necesitas retomarlo en otra carpeta: \`team-cli spaces fork <slug> --path ./mi-space-app\`
|
|
1140
1145
|
|
|
1141
1146
|
Slugs:
|
|
@@ -1190,6 +1195,9 @@ import {justoCli, justoStream} from '@/lib/justo'
|
|
|
1190
1195
|
|
|
1191
1196
|
const me = await justoCli("graphql main 'query { me { _id email roles } }'")
|
|
1192
1197
|
const rows = await justoCli("data queries preview <queryId> --params '{\\"limit\\":10}'")
|
|
1198
|
+
const events = await justoCli(
|
|
1199
|
+
"spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{},"limit":10}'",
|
|
1200
|
+
)
|
|
1193
1201
|
await justoStream(
|
|
1194
1202
|
"data queries run <queryId> --limit 1000 --params '{\\"websiteId\\":\\"w1\\"}'",
|
|
1195
1203
|
row => {
|
|
@@ -1205,7 +1213,8 @@ Comandos:
|
|
|
1205
1213
|
- \`spaces publish <spaceId> --path ./mi-space-app\`
|
|
1206
1214
|
- \`spaces fork <slug> --path ./mi-space-app\`
|
|
1207
1215
|
- \`spaces archive <spaceId>\`
|
|
1208
|
-
|
|
1216
|
+
- \`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) {
|
|
1209
1218
|
createSpace(name: $name, description: $description, slug: $slug) {
|
|
1210
1219
|
_id
|
|
1211
1220
|
name
|
|
@@ -1216,7 +1225,7 @@ Comandos:
|
|
|
1216
1225
|
createdByEmail
|
|
1217
1226
|
createdById
|
|
1218
1227
|
}
|
|
1219
|
-
}`,variables:{name:
|
|
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) {
|
|
1220
1229
|
archiveSpace(spaceId: $spaceId) {
|
|
1221
1230
|
_id
|
|
1222
1231
|
name
|
|
@@ -1228,11 +1237,11 @@ Comandos:
|
|
|
1228
1237
|
createdById
|
|
1229
1238
|
archivedAt
|
|
1230
1239
|
}
|
|
1231
|
-
}`,variables:{spaceId:
|
|
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
|
|
1232
1241
|
|
|
1233
1242
|
Herramienta CLI para el equipo Justo.
|
|
1234
1243
|
|
|
1235
|
-
${
|
|
1244
|
+
${c}
|
|
1236
1245
|
|
|
1237
1246
|
Si necesitas obtener data y no existe un query listo, usa create + ai-edit.
|
|
1238
1247
|
Flujo sugerido: create -> ai-edit -> preview -> run o download.
|
|
@@ -1289,4 +1298,4 @@ Si todavía no sabes bien dónde vive la data, primero usa \`data explain\` para
|
|
|
1289
1298
|
Cuando ya tengas claro un pipeline y solo quieras probarlo una vez, usa \`data execute\`.
|
|
1290
1299
|
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\`.
|
|
1291
1300
|
|
|
1292
|
-
`}function
|
|
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();
|