@getjusto/team-cli 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/cli.js +535 -69
  2. package/package.json +1 -1
package/bin/cli.js CHANGED
@@ -1,41 +1,424 @@
1
1
  #!/usr/bin/env node
2
- var sg={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"}},v="prod";function mg(g){v=g}function qg(){return v}function D(g){return sg[g][v]}function $g(g){let m=[],q={},$={};for(let j=0;j<g.length;j++)if(g[j].startsWith("--")&&g[j+1]&&!g[j+1].startsWith("--")){let w=g[j].slice(2);if(q[w]=g[j+1],!$[w])$[w]=[];$[w].push(g[j+1]),j++}else if(g[j].startsWith("--"))q[g[j].slice(2)]="true";else m.push(g[j]);return{positional:m,flags:q,arrayFlags:$}}function b(g,m){let q=g[m];if(!q)console.error(`Error: --${m} es requerido.`),process.exit(1);return q}import{existsSync as l,mkdirSync as yg,readFileSync as xg,writeFileSync as Kg,unlinkSync as og}from"node:fs";import{join as jg}from"node:path";import{homedir as ig}from"node:os";var h=jg(ig(),".justo-team");function L(){let g=qg(),m=g==="prod"?"credentials.json":`credentials.${g}.json`;return jg(h,m)}function kg(){if(!l(h))yg(h,{recursive:!0})}function y(g){kg(),Kg(L(),JSON.stringify(g,null,2))}function W(){let g=L();if(!l(g))return null;try{let m=xg(g,"utf-8");return JSON.parse(m)}catch{return null}}function d(){let g=L();if(l(g))og(g)}import{existsSync as wg,readFileSync as Vg,writeFileSync as vg,mkdirSync as Dg}from"node:fs";import{join as fg}from"node:path";import{homedir as hg}from"node:os";function lg(){let g=fg(hg(),".justo-team"),m=fg(g,"device-id");if(wg(m))return Vg(m,"utf-8").trim();let q=crypto.randomUUID();if(!wg(g))Dg(g,{recursive:!0});return vg(m,q),q}var Gg={required:({label:g})=>`${g} no es opcional`,notAString:({label:g})=>`${g} no es un texto`,notANumber:({label:g})=>`${g} no es un número`,notAnInteger:({label:g})=>`${g} no es un número entero`,notABoolean:({label:g})=>`${g} no es un valor verdadero o falso`,notAnEmail:({label:g})=>`${g} no es un email`,notAnId:({label:g})=>`${g} no es un ID válido`,notADate:({label:g})=>`${g} no es una fecha válida`,notAnArray:({label:g})=>`${g} no es un arreglo`,notAnObject:({label:g})=>`${g} no es un objeto`,stringTooShort:({label:g})=>`${g} no tiene el largo suficiente`,stringTooLong:"El largo es mayor al permitido",numberTooSmall:({label:g})=>`${g} es un número muy pequeño`,numberTooBig:({label:g})=>`${g} es un número muy grande`,notInSchema:({label:g})=>`${g} no esta permitido`,notUnique:({label:g})=>`${g} no es único`,notFound:({label:g})=>`${g} 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 Lg(g,m){let q=Gg[g];if(!q)return`${m}: ${g}`;if(typeof q==="function")return q({label:m});return q}function Cg(g){return Object.entries(g).map(([m,q])=>Lg(q,m)).join(", ")}function dg(g){if(g.error==="validationError"&&g.validationErrors)return Cg(g.validationErrors);if(g.extensions?.code==="PermissionsError"){let j=g.extensions.info?.type;if(j?.includes("User doesn't have permissions for "))return`Tu usuario no tiene permisos para [${j.split("User doesn't have permissions for ")[1]}]`;return g.message}if(g.validationErrors)return`${g.message} (${Cg(g.validationErrors)})`;let m=g.message||"Error desconocido",q=Gg[m];if(q)return typeof q==="function"?q({label:""}).trim():q;let $=g.error||g.code||g.type;return $?`${m} [${$}]`:m}function ag(g){try{return JSON.parse(Buffer.from(g.split(".")[1],"base64").toString()).exp*1000<Date.now()}catch{return!0}}async function pg(){let g=W();if(!g?.refreshToken)return null;let m=`${D("auth")}/refresh-token`,$=await(await fetch(m,{method:"POST",headers:{"X-ORION-REFRESH":g.refreshToken}})).json();if(!$.token)return null;return y({...g,token:$.token}),$.token}async function ug(){let g=W();if(!g?.token)return;if(!ag(g.token))return g.token;return await pg()??void 0}async function N(g){let m=`${D(g.service)}/graphql`,q=await ug(),$={"Content-Type":"application/json","X-ORION-DEVICEID":lg(),"X-ORION-PLATFORM":"web"};if(q)$["x-orion-jwt"]=q;let j;try{j=await fetch(m,{method:"POST",headers:$,body:JSON.stringify({query:g.query,variables:g.variables}),signal:AbortSignal.timeout(15000)})}catch{throw Error("La solicitud tardó demasiado. Intenta de nuevo.")}let w=await j.json();if(w.errors?.length)throw Error(dg(w.errors[0]));if(!w.data)throw Error("No data returned from server");return w.data}import{createInterface as ng}from"node:readline";function a(g){let m=ng({input:process.stdin,output:process.stdout});return new Promise((q)=>{m.question(g,($)=>{m.close(),q($.trim())})})}async function Rg(g){return(await N({service:"auth",query:`mutation ($email: String!) {
2
+ var Y={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"}},L="prod";function lo(o){L=o}function po(){return L}function G(o){return Y[o][L]}function wo(o){let i=[],t={},r={};for(let e=0;e<o.length;e++)if(o[e].startsWith("--")&&o[e+1]&&!o[e+1].startsWith("--")){let s=o[e].slice(2);if(t[s]=o[e+1],!r[s])r[s]=[];r[s].push(o[e+1]),e++}else if(o[e].startsWith("--"))t[o[e].slice(2)]="true";else i.push(o[e]);return{positional:i,flags:t,arrayFlags:r}}function J(o,i){let t=o[i];if(!t)throw Error(`--${i} es requerido.`);return t}import{existsSync as io,mkdirSync as fi,readFileSync as bi,writeFileSync as qi,unlinkSync as Ci}from"node:fs";import{join as fo}from"node:path";import{homedir as $i}from"node:os";var oo=fo($i(),".justo-team");function to(){let o=po(),i=o==="prod"?"credentials.json":`credentials.${o}.json`;return fo(oo,i)}function Ii(){if(!io(oo))fi(oo,{recursive:!0})}function Z(o){Ii(),qi(to(),JSON.stringify(o,null,2))}function d(){let o=to();if(!io(o))return null;try{let i=bi(o,"utf-8");return JSON.parse(i)}catch{return null}}function ro(){let o=to();if(io(o))Ci(o)}import{existsSync as bo,readFileSync as ji,writeFileSync as yi,mkdirSync as hi}from"node:fs";import{join as qo}from"node:path";import{homedir as Ri}from"node:os";function Ui(){let o=qo(Ri(),".justo-team"),i=qo(o,"device-id");if(bo(i))return ji(i,"utf-8").trim();let t=crypto.randomUUID();if(!bo(o))hi(o,{recursive:!0});return yi(i,t),t}var $o={required:({label:o})=>`${o} no es opcional`,notAString:({label:o})=>`${o} no es un texto`,notANumber:({label:o})=>`${o} no es un número`,notAnInteger:({label:o})=>`${o} no es un número entero`,notABoolean:({label:o})=>`${o} no es un valor verdadero o falso`,notAnEmail:({label:o})=>`${o} no es un email`,notAnId:({label:o})=>`${o} no es un ID válido`,notADate:({label:o})=>`${o} no es una fecha válida`,notAnArray:({label:o})=>`${o} no es un arreglo`,notAnObject:({label:o})=>`${o} no es un objeto`,stringTooShort:({label:o})=>`${o} no tiene el largo suficiente`,stringTooLong:"El largo es mayor al permitido",numberTooSmall:({label:o})=>`${o} es un número muy pequeño`,numberTooBig:({label:o})=>`${o} es un número muy grande`,notInSchema:({label:o})=>`${o} no esta permitido`,notUnique:({label:o})=>`${o} no es único`,notFound:({label:o})=>`${o} 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 xi(o,i){let t=$o[o];if(!t)return`${i}: ${o}`;if(typeof t==="function")return t({label:i});return t}function Co(o){return Object.entries(o).map(([i,t])=>xi(t,i)).join(", ")}function Ei(o){if(o.error==="validationError"&&o.validationErrors)return Co(o.validationErrors);if(o.extensions?.code==="PermissionsError"){let e=o.extensions.info?.type;if(e?.includes("User doesn't have permissions for "))return`Tu usuario no tiene permisos para [${e.split("User doesn't have permissions for ")[1]}]`;return o.message}if(o.validationErrors)return`${o.message} (${Co(o.validationErrors)})`;let i=o.message||"Error desconocido",t=$o[i];if(t)return typeof t==="function"?t({label:""}).trim():t;let r=o.error||o.code||o.type;return r?`${i} [${r}]`:i}function Pi(o){try{return JSON.parse(Buffer.from(o.split(".")[1],"base64").toString()).exp*1000<Date.now()}catch{return!0}}async function Wi(){let o=d();if(!o?.refreshToken)return null;let i=`${G("auth")}/refresh-token`,r=await(await fetch(i,{method:"POST",headers:{"X-ORION-REFRESH":o.refreshToken}})).json();if(!r.token)return null;return Z({...o,token:r.token}),r.token}async function Ni(){let o=d();if(!o?.token)return;if(!Pi(o.token))return o.token;return await Wi()??void 0}async function c(o){let i=`${G(o.service)}/graphql`,t=await Ni(),r={"Content-Type":"application/json","X-ORION-DEVICEID":Ui(),"X-ORION-PLATFORM":"web"};if(t)r["x-orion-jwt"]=t;let e;try{e=await fetch(i,{method:"POST",headers:r,body:JSON.stringify({query:o.query,variables:o.variables}),signal:AbortSignal.timeout(15000)})}catch{throw Error("La solicitud tardó demasiado. Intenta de nuevo.")}let s=await e.json();if(s.errors?.length)throw Error(Ei(s.errors[0]));if(!s.data)throw Error("No data returned from server");return s.data}import{createInterface as Ai}from"node:readline";function eo(o){let i=Ai({input:process.stdin,output:process.stderr});return new Promise((t)=>{i.question(o,(r)=>{i.close(),t(r.trim())})})}var Oi={comma:",",tab:"\t",pipe:"|"},M=Oi.comma;function jo(o){return o.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function Si(o){return o==="true"||o==="false"||o==="null"}function h(o){if(o===null)return null;if(typeof o==="object"&&o!==null&&"toJSON"in o&&typeof o.toJSON==="function"){let i=o.toJSON();if(i!==o)return h(i)}if(typeof o==="string"||typeof o==="boolean")return o;if(typeof o==="number"){if(Object.is(o,-0))return 0;if(!Number.isFinite(o))return null;return o}if(typeof o==="bigint"){if(o>=Number.MIN_SAFE_INTEGER&&o<=Number.MAX_SAFE_INTEGER)return Number(o);return o.toString()}if(o instanceof Date)return o.toISOString();if(Array.isArray(o))return o.map(h);if(o instanceof Set)return Array.from(o).map(h);if(o instanceof Map)return Object.fromEntries(Array.from(o,([i,t])=>[String(i),h(t)]));if(Qi(o)){let i={};for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t))i[t]=h(o[t]);return i}return null}function W(o){return o===null||typeof o==="string"||typeof o==="number"||typeof o==="boolean"}function E(o){return Array.isArray(o)}function w(o){return o!==null&&typeof o==="object"&&!Array.isArray(o)}function _(o){return Object.keys(o).length===0}function Qi(o){if(o===null||typeof o!=="object")return!1;let i=Object.getPrototypeOf(o);return i===null||i===Object.prototype}function F(o){return o.length===0||o.every((i)=>W(i))}function Bi(o){return o.length===0||o.every((i)=>E(i))}function yo(o){return o.length===0||o.every((i)=>w(i))}function Gi(o){return/^[A-Z_][\w.]*$/i.test(o)}function Ji(o){return/^[A-Z_]\w*$/i.test(o)}function _i(o,i=M){if(!o)return!1;if(o!==o.trim())return!1;if(Si(o)||Fi(o))return!1;if(o.includes(":"))return!1;if(o.includes('"')||o.includes("\\"))return!1;if(/[[\]{}]/.test(o))return!1;if(/[\n\r\t]/.test(o))return!1;if(o.includes(i))return!1;if(o.startsWith("-"))return!1;return!0}function Fi(o){return/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(o)||/^0\d+$/.test(o)}var St=Symbol("quotedKey");function Ti(o,i,t,r,e,s,n){if(r.keyFolding!=="safe")return;if(!w(i))return;let{segments:a,tail:u,leafValue:j}=Mi(o,i,n??r.flattenDepth);if(a.length<2)return;if(!a.every((y)=>Ji(y)))return;let b=Xi(a),q=s?`${s}.${b}`:b;if(t.includes(b))return;if(e&&e.has(q))return;return{foldedKey:b,remainder:u,leafValue:j,segmentCount:a.length}}function Mi(o,i,t){let r=[o],e=i;while(r.length<t){if(!w(e))break;let s=Object.keys(e);if(s.length!==1)break;let n=s[0],a=e[n];r.push(n),e=a}if(!w(e)||_(e))return{segments:r,tail:void 0,leafValue:e};return{segments:r,tail:e,leafValue:e}}function Xi(o){return o.join(".")}function A(o,i){if(o===null)return"null";if(typeof o==="boolean")return String(o);if(typeof o==="number")return String(o);return Yi(o,i)}function Yi(o,i=M){if(_i(o,i))return o;return`"${jo(o)}"`}function T(o){if(Gi(o))return o;return`"${jo(o)}"`}function ho(o,i=M){return o.map((t)=>A(t,i)).join(i)}function R(o,i){let t=i?.key,r=i?.fields,e=i?.delimiter??",",s="";if(t)s+=T(t);if(s+=`[${o}${e!==M?e:""}]`,r){let n=r.map((a)=>T(a));s+=`{${n.join(e)}}`}return s+=":",s}function*Zi(o,i,t){if(W(o)){let r=A(o,i.delimiter);if(r!=="")yield r;return}if(E(o))yield*so(void 0,o,t,i);else if(w(o))yield*N(o,t,i)}function*N(o,i,t,r,e,s){let n=Object.keys(o);if(i===0&&!r)r=new Set(n.filter((u)=>u.includes(".")));let a=s??t.flattenDepth;for(let[u,j]of Object.entries(o))yield*vi(u,j,i,t,n,r,e,a)}function*vi(o,i,t,r,e,s,n,a){let u=n?`${n}.${o}`:o,j=a??r.flattenDepth;if(r.keyFolding==="safe"&&e){let q=Ti(o,i,e,r,s,n,j);if(q){let{foldedKey:y,remainder:B,leafValue:x,segmentCount:li}=q,V=T(y);if(B===void 0){if(W(x)){yield p(t,`${V}: ${A(x,r.delimiter)}`,r.indent);return}else if(E(x)){yield*so(y,x,t,r);return}else if(w(x)&&_(x)){yield p(t,`${V}:`,r.indent);return}}if(w(B)){yield p(t,`${V}:`,r.indent);let pi=j-li,wi=n?`${n}.${y}`:y;yield*N(B,t+1,r,s,wi,pi);return}}}let b=T(o);if(W(i))yield p(t,`${b}: ${A(i,r.delimiter)}`,r.indent);else if(E(i))yield*so(o,i,t,r);else if(w(i)){if(yield p(t,`${b}:`,r.indent),!_(i))yield*N(i,t+1,r,s,u,j)}}function*so(o,i,t,r){if(i.length===0){yield p(t,R(0,{key:o,delimiter:r.delimiter}),r.indent);return}if(F(i)){yield p(t,z(i,r.delimiter,o),r.indent);return}if(Bi(i)){if(i.every((e)=>F(e))){yield*zi(o,i,t,r);return}}if(yo(i)){let e=Ro(i);if(e)yield*Hi(o,i,e,t,r);else yield*Io(o,i,t,r);return}yield*Io(o,i,t,r)}function*zi(o,i,t,r){yield p(t,R(i.length,{key:o,delimiter:r.delimiter}),r.indent);for(let e of i)if(F(e)){let s=z(e,r.delimiter);yield C(t+1,s,r.indent)}}function z(o,i,t){let r=R(o.length,{key:t,delimiter:i}),e=ho(o,i);if(o.length===0)return r;return`${r} ${e}`}function*Hi(o,i,t,r,e){yield p(r,R(i.length,{key:o,fields:t,delimiter:e.delimiter}),e.indent),yield*Uo(i,t,r+1,e)}function Ro(o){if(o.length===0)return;let i=o[0],t=Object.keys(i);if(t.length===0)return;if(Di(o,t))return t}function Di(o,i){for(let t of o){if(Object.keys(t).length!==i.length)return!1;for(let r of i){if(!(r in t))return!1;if(!W(t[r]))return!1}}return!0}function*Uo(o,i,t,r){for(let e of o)yield p(t,ho(i.map((s)=>e[s]),r.delimiter),r.indent)}function*Io(o,i,t,r){yield p(t,R(i.length,{key:o,delimiter:r.delimiter}),r.indent);for(let e of i)yield*no(e,t+1,r)}function*Ki(o,i,t){if(_(o)){yield p(i,"-",t.indent);return}let r=Object.entries(o),[e,s]=r[0],n=r.slice(1);if(E(s)&&yo(s)){let u=Ro(s);if(u){if(yield C(i,R(s.length,{key:e,fields:u,delimiter:t.delimiter}),t.indent),yield*Uo(s,u,i+2,t),n.length>0)yield*N(Object.fromEntries(n),i+1,t);return}}let a=T(e);if(W(s))yield C(i,`${a}: ${A(s,t.delimiter)}`,t.indent);else if(E(s))if(s.length===0)yield C(i,`${a}${R(0,{delimiter:t.delimiter})}`,t.indent);else if(F(s))yield C(i,`${a}${z(s,t.delimiter)}`,t.indent);else{yield C(i,`${a}${R(s.length,{delimiter:t.delimiter})}`,t.indent);for(let u of s)yield*no(u,i+2,t)}else if(w(s)){if(yield C(i,`${a}:`,t.indent),!_(s))yield*N(s,i+2,t)}if(n.length>0)yield*N(Object.fromEntries(n),i+1,t)}function*no(o,i,t){if(W(o))yield C(i,A(o,t.delimiter),t.indent);else if(E(o))if(F(o))yield C(i,z(o,t.delimiter),t.indent);else{yield C(i,R(o.length,{delimiter:t.delimiter}),t.indent);for(let r of o)yield*no(r,i+1,t)}else if(w(o))yield*Ki(o,i,t)}function p(o,i,t){return" ".repeat(t*o)+i}function C(o,i,t){return p(o,"- "+i,t)}function ki(o,i){let t=i("",o,[]);if(t===void 0)return v(o,i,[]);return v(h(t),i,[])}function v(o,i,t){if(w(o))return Vi(o,i,t);if(E(o))return Li(o,i,t);return o}function Vi(o,i,t){let r={};for(let[e,s]of Object.entries(o)){let n=[...t,e],a=i(e,s,n);if(a===void 0)continue;r[e]=v(h(a),i,n)}return r}function Li(o,i,t){let r=[];for(let e=0;e<o.length;e++){let s=o[e],n=[...t,e],a=i(String(e),s,n);if(a===void 0)continue;let u=h(a);r.push(v(u,i,n))}return r}function ao(o,i){return Array.from(ot(o,i)).join(`
3
+ `)}function ot(o,i){let t=h(o),r=it(i);return Zi(r.replacer?ki(t,r.replacer):t,r,0)}function it(o){return{indent:o?.indent??2,delimiter:o?.delimiter??M,keyFolding:o?.keyFolding??"off",flattenDepth:o?.flattenDepth??Number.POSITIVE_INFINITY,replacer:o?.replacer}}function tt(o){let i=o.format??"toon";if(i!=="toon"&&i!=="json")throw Error("--format debe ser toon o json.");return i}function xo(o,i){if(tt(i)==="json"){console.log(JSON.stringify(o,null,2));return}console.log(ao(o))}function g(o){process.stdout.write(`${o}
4
+ `)}function Eo(o,i){let r={ok:!1,error:o instanceof Error?o.message:String(o)};if((i.format==="json"?"json":"toon")==="json"){console.error(JSON.stringify(r,null,2));return}console.error(ao(r))}function $(o){process.stderr.write(o)}async function Po(o){return(await c({service:"auth",query:`mutation ($email: String!) {
3
5
  requestLoginCode(email: $email)
4
- }`,variables:{email:g}})).requestLoginCode}async function Qg(g,m,q){let $=await N({service:"auth",query:`mutation ($email: String!, $token: String!, $code: String!) {
6
+ }`,variables:{email:o}})).requestLoginCode}async function Wo(o,i,t){let r=await c({service:"auth",query:`mutation ($email: String!, $token: String!, $code: String!) {
5
7
  loginWithCode(email: $email, token: $token, code: $code) {
6
8
  token
7
9
  refreshToken
8
10
  }
9
- }`,variables:{email:g,token:m,code:q.toUpperCase()}});y({email:g,token:$.loginWithCode.token,refreshToken:$.loginWithCode.refreshToken}),await tg(),console.log(`Sesión iniciada como ${g}`)}async function tg(){if(!(await N({service:"main",query:"query { me { roles } }"})).me?.roles?.length)throw d(),Error("Solo miembros del equipo Justo pueden usar esta herramienta.")}async function Ng(){let g=await a("Email: ");console.log("Enviando código de verificación...");let m=await Rg(g);console.log("Código enviado a tu email.");let q=await a("Código: ");await Qg(g,m,q)}async function Wg(g){let m=b(g,"email"),q=b(g,"token"),$=b(g,"code");await Qg(m,q,$)}async function Ug(g){let m=b(g,"email");console.log("Enviando código de verificación...");let q=await Rg(m);console.log(`Código enviado a ${m}`),console.log(`Token: ${q}`),console.log(""),console.log("Ahora ejecuta:"),console.log(` npx @getjusto/team-cli auth login-with-token --email ${m} --token ${q} --code <CÓDIGO>`)}async function rg(){d(),console.log("Sesión cerrada.")}async function Xg(){let g=W();if(!g){console.log("No hay sesión activa."),console.log("Usa: npx @getjusto/team-cli@latest auth login");return}console.log(`Sesión activa: ${g.email}`)}function p(){console.log(`
10
- team-cli auth - Gestión de sesión
11
+ }`,variables:{email:o,token:i,code:t.toUpperCase()}});Z({email:o,token:r.loginWithCode.token,refreshToken:r.loginWithCode.refreshToken}),await rt()}async function rt(){if(!(await c({service:"main",query:"query { me { roles } }"})).me?.roles?.length)throw ro(),Error("Solo miembros del equipo Justo pueden usar esta herramienta.")}async function No(){let o=await eo("Email: ");$(`Enviando codigo de verificacion...
12
+ `);let i=await Po(o);$(`Codigo enviado a tu email.
13
+ `);let t=await eo("Codigo: ");return await Wo(o,i,t),{ok:!0,authenticated:!0,email:o}}async function Ao(o){let i=J(o,"email"),t=J(o,"token"),r=J(o,"code");return await Wo(i,t,r),{ok:!0,authenticated:!0,email:i}}async function Oo(o){let i=J(o,"email");$(`Enviando codigo de verificacion...
14
+ `);let t=await Po(i);return{ok:!0,email:i,token:t,nextCommand:`npx @getjusto/team-cli auth login-with-token --email ${i} --token ${t} --code <CODIGO>`}}async function So(){return ro(),{ok:!0,authenticated:!1}}async function Qo(){let o=d();if(!o)return{authenticated:!1,loginCommand:"npx @getjusto/team-cli@latest auth login"};return{authenticated:!0,email:o.email}}function co(){return`team-cli auth
11
15
 
12
- Comandos:
13
- login Iniciar sesión (interactivo, pide email y código)
14
- logout Cerrar sesión
15
- status Ver sesión actual
16
+ Gestion de sesion.
16
17
 
17
- Modo no interactivo:
18
- Primero solicita un código, luego úsalo para iniciar sesión:
18
+ Uso:
19
+ team-cli auth <subcomando> [opciones]
19
20
 
20
- 1. request-code --email <email>
21
- 2. login-with-token --email <email> --token <token> --code <código>
22
- `)}var eg={comma:",",tab:"\t",pipe:"|"},H=eg.comma;function Yg(g){return g.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function gm(g){return g==="true"||g==="false"||g==="null"}function _(g){if(g===null)return null;if(typeof g==="object"&&g!==null&&"toJSON"in g&&typeof g.toJSON==="function"){let m=g.toJSON();if(m!==g)return _(m)}if(typeof g==="string"||typeof g==="boolean")return g;if(typeof g==="number"){if(Object.is(g,-0))return 0;if(!Number.isFinite(g))return null;return g}if(typeof g==="bigint"){if(g>=Number.MIN_SAFE_INTEGER&&g<=Number.MAX_SAFE_INTEGER)return Number(g);return g.toString()}if(g instanceof Date)return g.toISOString();if(Array.isArray(g))return g.map(_);if(g instanceof Set)return Array.from(g).map(_);if(g instanceof Map)return Object.fromEntries(Array.from(g,([m,q])=>[String(m),_(q)]));if(mm(g)){let m={};for(let q in g)if(Object.prototype.hasOwnProperty.call(g,q))m[q]=_(g[q]);return m}return null}function S(g){return g===null||typeof g==="string"||typeof g==="number"||typeof g==="boolean"}function A(g){return Array.isArray(g)}function U(g){return g!==null&&typeof g==="object"&&!Array.isArray(g)}function z(g){return Object.keys(g).length===0}function mm(g){if(g===null||typeof g!=="object")return!1;let m=Object.getPrototypeOf(g);return m===null||m===Object.prototype}function I(g){return g.length===0||g.every((m)=>S(m))}function qm(g){return g.length===0||g.every((m)=>A(m))}function Jg(g){return g.length===0||g.every((m)=>U(m))}function $m(g){return/^[A-Z_][\w.]*$/i.test(g)}function jm(g){return/^[A-Z_]\w*$/i.test(g)}function wm(g,m=H){if(!g)return!1;if(g!==g.trim())return!1;if(gm(g)||fm(g))return!1;if(g.includes(":"))return!1;if(g.includes('"')||g.includes("\\"))return!1;if(/[[\]{}]/.test(g))return!1;if(/[\n\r\t]/.test(g))return!1;if(g.includes(m))return!1;if(g.startsWith("-"))return!1;return!0}function fm(g){return/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(g)||/^0\d+$/.test(g)}var lm=Symbol("quotedKey");function Cm(g,m,q,$,j,w,f){if($.keyFolding!=="safe")return;if(!U(m))return;let{segments:C,tail:G,leafValue:Y}=Gm(g,m,f??$.flattenDepth);if(C.length<2)return;if(!C.every((J)=>jm(J)))return;let r=Rm(C),X=w?`${w}.${r}`:r;if(q.includes(r))return;if(j&&j.has(X))return;return{foldedKey:r,remainder:G,leafValue:Y,segmentCount:C.length}}function Gm(g,m,q){let $=[g],j=m;while($.length<q){if(!U(j))break;let w=Object.keys(j);if(w.length!==1)break;let f=w[0],C=j[f];$.push(f),j=C}if(!U(j)||z(j))return{segments:$,tail:void 0,leafValue:j};return{segments:$,tail:j,leafValue:j}}function Rm(g){return g.join(".")}function O(g,m){if(g===null)return"null";if(typeof g==="boolean")return String(g);if(typeof g==="number")return String(g);return Qm(g,m)}function Qm(g,m=H){if(wm(g,m))return g;return`"${Yg(g)}"`}function P(g){if($m(g))return g;return`"${Yg(g)}"`}function _g(g,m=H){return g.map((q)=>O(q,m)).join(m)}function E(g,m){let q=m?.key,$=m?.fields,j=m?.delimiter??",",w="";if(q)w+=P(q);if(w+=`[${g}${j!==H?j:""}]`,$){let f=$.map((C)=>P(C));w+=`{${f.join(j)}}`}return w+=":",w}function*Nm(g,m,q){if(S(g)){let $=O(g,m.delimiter);if($!=="")yield $;return}if(A(g))yield*u(void 0,g,q,m);else if(U(g))yield*T(g,q,m)}function*T(g,m,q,$,j,w){let f=Object.keys(g);if(m===0&&!$)$=new Set(f.filter((G)=>G.includes(".")));let C=w??q.flattenDepth;for(let[G,Y]of Object.entries(g))yield*Wm(G,Y,m,q,f,$,j,C)}function*Wm(g,m,q,$,j,w,f,C){let G=f?`${f}.${g}`:g,Y=C??$.flattenDepth;if($.keyFolding==="safe"&&j){let X=Cm(g,m,j,$,w,f,Y);if(X){let{foldedKey:J,remainder:F,leafValue:M,segmentCount:Ig}=X,V=P(J);if(F===void 0){if(S(M)){yield Q(q,`${V}: ${O(M,$.delimiter)}`,$.indent);return}else if(A(M)){yield*u(J,M,q,$);return}else if(U(M)&&z(M)){yield Q(q,`${V}:`,$.indent);return}}if(U(F)){yield Q(q,`${V}:`,$.indent);let Pg=Y-Ig,Hg=f?`${f}.${J}`:J;yield*T(F,q+1,$,w,Hg,Pg);return}}}let r=P(g);if(S(m))yield Q(q,`${r}: ${O(m,$.delimiter)}`,$.indent);else if(A(m))yield*u(g,m,q,$);else if(U(m)){if(yield Q(q,`${r}:`,$.indent),!z(m))yield*T(m,q+1,$,w,G,Y)}}function*u(g,m,q,$){if(m.length===0){yield Q(q,E(0,{key:g,delimiter:$.delimiter}),$.indent);return}if(I(m)){yield Q(q,K(m,$.delimiter,g),$.indent);return}if(qm(m)){if(m.every((j)=>I(j))){yield*Um(g,m,q,$);return}}if(Jg(m)){let j=Eg(m);if(j)yield*rm(g,m,j,q,$);else yield*Zg(g,m,q,$);return}yield*Zg(g,m,q,$)}function*Um(g,m,q,$){yield Q(q,E(m.length,{key:g,delimiter:$.delimiter}),$.indent);for(let j of m)if(I(j)){let w=K(j,$.delimiter);yield Z(q+1,w,$.indent)}}function K(g,m,q){let $=E(g.length,{key:q,delimiter:m}),j=_g(g,m);if(g.length===0)return $;return`${$} ${j}`}function*rm(g,m,q,$,j){yield Q($,E(m.length,{key:g,fields:q,delimiter:j.delimiter}),j.indent),yield*cg(m,q,$+1,j)}function Eg(g){if(g.length===0)return;let m=g[0],q=Object.keys(m);if(q.length===0)return;if(Xm(g,q))return q}function Xm(g,m){for(let q of g){if(Object.keys(q).length!==m.length)return!1;for(let $ of m){if(!($ in q))return!1;if(!S(q[$]))return!1}}return!0}function*cg(g,m,q,$){for(let j of g)yield Q(q,_g(m.map((w)=>j[w]),$.delimiter),$.indent)}function*Zg(g,m,q,$){yield Q(q,E(m.length,{key:g,delimiter:$.delimiter}),$.indent);for(let j of m)yield*n(j,q+1,$)}function*Zm(g,m,q){if(z(g)){yield Q(m,"-",q.indent);return}let $=Object.entries(g),[j,w]=$[0],f=$.slice(1);if(A(w)&&Jg(w)){let G=Eg(w);if(G){if(yield Z(m,E(w.length,{key:j,fields:G,delimiter:q.delimiter}),q.indent),yield*cg(w,G,m+2,q),f.length>0)yield*T(Object.fromEntries(f),m+1,q);return}}let C=P(j);if(S(w))yield Z(m,`${C}: ${O(w,q.delimiter)}`,q.indent);else if(A(w))if(w.length===0)yield Z(m,`${C}${E(0,{delimiter:q.delimiter})}`,q.indent);else if(I(w))yield Z(m,`${C}${K(w,q.delimiter)}`,q.indent);else{yield Z(m,`${C}${E(w.length,{delimiter:q.delimiter})}`,q.indent);for(let G of w)yield*n(G,m+2,q)}else if(U(w)){if(yield Z(m,`${C}:`,q.indent),!z(w))yield*T(w,m+2,q)}if(f.length>0)yield*T(Object.fromEntries(f),m+1,q)}function*n(g,m,q){if(S(g))yield Z(m,O(g,q.delimiter),q.indent);else if(A(g))if(I(g))yield Z(m,K(g,q.delimiter),q.indent);else{yield Z(m,E(g.length,{delimiter:q.delimiter}),q.indent);for(let $ of g)yield*n($,m+1,q)}else if(U(g))yield*Zm(g,m,q)}function Q(g,m,q){return" ".repeat(q*g)+m}function Z(g,m,q){return Q(g,"- "+m,q)}function Ym(g,m){let q=m("",g,[]);if(q===void 0)return x(g,m,[]);return x(_(q),m,[])}function x(g,m,q){if(U(g))return Jm(g,m,q);if(A(g))return _m(g,m,q);return g}function Jm(g,m,q){let $={};for(let[j,w]of Object.entries(g)){let f=[...q,j],C=m(j,w,f);if(C===void 0)continue;$[j]=x(_(C),m,f)}return $}function _m(g,m,q){let $=[];for(let j=0;j<g.length;j++){let w=g[j],f=[...q,j],C=m(String(j),w,f);if(C===void 0)continue;let G=_(C);$.push(x(G,m,f))}return $}function o(g,m){return Array.from(Em(g,m)).join(`
23
- `)}function Em(g,m){let q=_(g),$=cm(m);return Nm($.replacer?Ym(q,$.replacer):q,$,0)}function cm(g){return{indent:g?.indent??2,delimiter:g?.delimiter??H,keyFolding:g?.keyFolding??"off",flattenDepth:g?.flattenDepth??Number.POSITIVE_INFINITY,replacer:g?.replacer}}var t=["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"];async function Mg(g,m){let q=g[1],$=g[2],j=m.format||"toon";if(!W())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login");if(!q||!$)e(),process.exit(1);if(!t.includes(q))console.error(`Error: servicio "${q}" no válido.`),console.error(`Servicios disponibles: ${t.join(", ")}`),process.exit(1);let w;if(m.variables)try{w=JSON.parse(m.variables)}catch{throw Error("Las variables deben ser un JSON válido.")}let f=await N({service:q,query:$,variables:w});if(j==="json")console.log(JSON.stringify(f,null,2));else console.log(o(f))}function e(){console.log(`
24
- team-cli graphql - Ejecutar queries y mutations GraphQL
21
+ Subcomandos:
22
+ login
23
+ Iniciar sesion en modo interactivo.
24
+ Uso: team-cli auth login
25
25
 
26
- Uso:
27
- team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]
26
+ logout
27
+ Cerrar sesion actual.
28
+ Uso: team-cli auth logout
28
29
 
29
- Ejemplos:
30
- team-cli graphql main 'query { me { _id roles } }'
31
- team-cli graphql main 'query($id: ID) { user(userId: $id) { _id } }' --variables '{"id": "abc123"}'
32
- team-cli graphql main 'query { me { _id } }' --format json
30
+ status
31
+ Ver la sesion actual.
32
+ Uso: team-cli auth status
33
33
 
34
- El formato por defecto es TOON. Usa --format json para obtener JSON.
34
+ request-code
35
+ Solicitar codigo para login no interactivo.
36
+ Uso: team-cli auth request-code --email <email>
35
37
 
36
- Servicios disponibles:
37
- ${t.join(", ")}
38
- `)}import{writeFileSync as Mm}from"node:fs";function i(){if(!W())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}function k(g,m){let q=g[3];if(!q)console.error(`Uso: ${m}`),process.exit(1);return q}function Ag(g){if(!g.params)return{};try{return JSON.parse(g.params)}catch{throw Error("--params debe ser un JSON válido.")}}function Bg(g,m){if((m.format||"toon")==="json")console.log(typeof g==="string"?g:JSON.stringify(g,null,2));else{let $=typeof g==="string"?JSON.parse(g):g;console.log(o($))}}async function Sg(g,m){i();let q=k(g,"team-cli data queries view <queryId>"),$=await N({service:"data",query:`query ($aggregationQueryId: String) {
38
+ login-with-token
39
+ Iniciar sesion sin prompts.
40
+ Uso: team-cli auth login-with-token --email <email> --token <token> --code <codigo>`}var mo=["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"];async function Bo(o,i){let t=o[1],r=o[2];if(!d())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login");if(!t||!r)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");if(!mo.includes(t))throw Error(`Servicio "${t}" no válido. Servicios disponibles: ${mo.join(", ")}`);let e;if(i.variables)try{e=JSON.parse(i.variables)}catch{throw Error("Las variables deben ser un JSON válido.")}return await c({service:t,query:r,variables:e})}function Go(){return`team-cli graphql
41
+
42
+ Ejecutar queries y mutations GraphQL.
43
+
44
+ Uso:
45
+ team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]
46
+
47
+ Ejemplos:
48
+ team-cli graphql main 'query { me { _id roles } }'
49
+ team-cli graphql main 'query($id: ID) { user(userId: $id) { _id } }' --variables '{"id": "abc123"}'
50
+ team-cli graphql main 'query { me { _id } }' --format json
51
+
52
+ Servicios disponibles:
53
+ ${mo.join(", ")}
54
+
55
+ Formato:
56
+ Por defecto usa toon. Usa --format json para JSON estándar.`}function et(o){return o.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,"")}function st(o){return o.includes(".")||o.startsWith("http://")||o.startsWith("https://")}async function O(o){if(st(o)){let i=et(o),t=await fetch(`${G("main")}/website-id/${i}`,{signal:AbortSignal.timeout(1e4)});if(!t.ok)throw Error(`No se encontro el sitio "${i}"`);let r=await t.json();if(!r.websiteId)throw Error(`No se pudo resolver el websiteId para "${i}"`);return{input:o,websiteId:r.websiteId,targetType:"domain"}}return{input:o,websiteId:o,targetType:"websiteId"}}async function Jo(o){let i=await c({service:"main",query:`query ($websiteId: ID) {
57
+ website(websiteId: $websiteId) {
58
+ _id
59
+ name
60
+ active
61
+ baseURL
62
+ domain
63
+ domains
64
+ countryCode
65
+ timezone
66
+ defaultMenuId
67
+ }
68
+ }`,variables:{websiteId:o}});if(!i.website)throw Error(`No se encontro el website "${o}"`);return i.website}function nt(){if(!d())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}async function _o(o){if(nt(),!o)throw Error("Uso: team-cli admin <websiteId|domain> show");let i=await O(o),t=await Jo(i.websiteId);return{context:i,website:t}}function H(){return`team-cli admin
69
+
70
+ Comandos administrativos con contexto de website.
71
+
72
+ Uso:
73
+ team-cli admin <websiteId|domain> <modulo> <accion> [opciones]
74
+
75
+ Modulos:
76
+ show
77
+ Mostrar informacion basica del website seleccionado.
78
+ Uso: team-cli admin <websiteId|domain> show
79
+
80
+ search
81
+ Buscar websites en admin.
82
+ Uso: team-cli admin search <texto> [--limit <n>] [--page <n>]
83
+
84
+ stores list
85
+ Listar las tiendas del website seleccionado.
86
+ Uso: team-cli admin <websiteId|domain> stores list
87
+
88
+ coupons
89
+ Administrar cupones y sus códigos.
90
+ Uso: team-cli admin <websiteId|domain> coupons <accion> [opciones]`}var Fo=`
91
+ availableAtPeriods
92
+ closedDays
93
+ closedUntilDate
94
+ isAvailableNow
95
+ timezone
96
+ openPeriods {
97
+ daysOfWeek
98
+ fromMinute
99
+ toMinute
100
+ }
101
+ specialPeriods {
102
+ days
103
+ fromMinute
104
+ toMinute
105
+ }
106
+ `,D=`
107
+ _id
108
+ websiteId
109
+ name
110
+ code
111
+ active
112
+ type
113
+ description
114
+ isHidden
115
+ isBirthdayCoupon
116
+ totalRedemptions
117
+ fromDate
118
+ endDate
119
+ percentageOff
120
+ discountAmount
121
+ fixedAmount
122
+ maxRedemptions
123
+ maxRedemptionsPerUser
124
+ maxRedemptionsPerUserPerDay
125
+ minimumOrderPrice
126
+ maximumOrderPrice
127
+ applyDeliveryDiscount
128
+ deliveryDiscountType
129
+ deliveryDiscountValue
130
+ deliveryDiscountPercentage
131
+ allowedEmails
132
+ requireChannels
133
+ requiresPaymentTypes
134
+ requiresStoresIds
135
+ requiresMenusIds
136
+ requiresCategoriesIds
137
+ requiresProductsIds
138
+ requiredBINs
139
+ extraRequirementsForPaymentTypes
140
+ schedule {
141
+ ${Fo}
142
+ }
143
+ scheduleAtUse {
144
+ ${Fo}
145
+ }
146
+ codesCode
147
+ `,To=`
148
+ _id
149
+ code
150
+ couponId
151
+ websiteId
152
+ userEmail
153
+ sentToEmail
154
+ totalRedemptions
155
+ createdAt
156
+ `;function uo(){if(!d())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}function S(o,i){let t=o[i];if(!t)throw Error(`--${i} es requerido.`);try{return JSON.parse(t)}catch{throw Error(`--${i} debe ser un JSON válido.`)}}function I(o,i){let t=o[i];if(!t)return;let r=Number.parseInt(t,10);if(Number.isNaN(r))throw Error(`--${i} debe ser un número entero.`);return r}function Mo(o,i){let t=o[i];if(!t)return;if(t==="true")return!0;if(t==="false")return!1;throw Error(`--${i} debe ser true o false.`)}async function f(o){if(uo(),!o)throw Error("Debes indicar <websiteId|domain>.");return O(o)}async function U(o,i){let t=await c({service:"main",query:`query ($couponId: ID) {
157
+ coupon(couponId: $couponId) {
158
+ _id
159
+ websiteId
160
+ }
161
+ }`,variables:{couponId:o}});if(!t.coupon)throw Error(`No se encontró el cupón "${o}"`);if(t.coupon.websiteId!==i)throw Error(`El cupón "${o}" no pertenece al website seleccionado.`);return t.coupon}async function Xo(o,i){uo();let t=o[2]??i.filter;if(!t)throw Error("Debes indicar un término de búsqueda. Uso: team-cli admin search <texto>");let r=I(i,"limit"),e=I(i,"page"),s=Mo(i,"only-active"),n=await c({service:"main",query:`query ($filter: String, $limit: BigInt, $page: BigInt, $onlyActiveWebsites: Boolean) {
162
+ websites(filter: $filter, limit: $limit, page: $page, onlyActiveWebsites: $onlyActiveWebsites) {
163
+ items {
164
+ _id
165
+ name
166
+ active
167
+ baseURL
168
+ domain
169
+ countryCode
170
+ timezone
171
+ }
172
+ totalCount
173
+ totalPages
174
+ hasNextPage
175
+ hasPreviousPage
176
+ }
177
+ }`,variables:{filter:t,limit:r,page:e,onlyActiveWebsites:s}});return{searchTerm:t,websites:n.websites.items??[],pagination:{totalCount:n.websites.totalCount??0,totalPages:n.websites.totalPages??0,hasNextPage:Boolean(n.websites.hasNextPage),hasPreviousPage:Boolean(n.websites.hasPreviousPage),page:e??1,limit:r??null}}}function Yo(){return`team-cli admin search
178
+
179
+ Buscar websites en admin.
180
+
181
+ Uso:
182
+ team-cli admin search <texto> [--limit <n>] [--page <n>] [--only-active true|false]
183
+
184
+ Opciones:
185
+ --limit <n>
186
+ Límite de resultados.
187
+
188
+ --page <n>
189
+ Página a consultar.
190
+
191
+ --only-active true|false
192
+ Filtrar solo websites activos.
193
+
194
+ Ejemplos:
195
+ team-cli admin search milas
196
+ team-cli admin search buffalo --limit 5
197
+ team-cli admin search pizza --only-active true`}function at(){if(!d())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}function ct(o){let i=[o.address?.streetAddress,o.address?.extendedAddress,o.address?.locality].filter(Boolean);if(!i.length)return null;return i.join(", ")}async function Zo(o){if(at(),!o)throw Error("Uso: team-cli admin <websiteId|domain> stores list");let i=await O(o),r=((await c({service:"main",query:`query ($websiteId: ID) {
198
+ stores(websiteId: $websiteId) {
199
+ items {
200
+ _id
201
+ name
202
+ address {
203
+ streetAddress
204
+ extendedAddress
205
+ locality
206
+ }
207
+ }
208
+ }
209
+ }`,variables:{websiteId:i.websiteId}})).stores.items??[]).map((e)=>({_id:e._id,name:e.name,address:ct(e)})).sort((e,s)=>e.name.localeCompare(s.name,"es",{sensitivity:"base"}));return{context:i,stores:r,totalCount:r.length}}var vo={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 mt(o){let i=Object.entries(o).filter(([,s])=>s!==void 0),t=i.map(([s])=>s).filter((s)=>!vo[s]);if(t.length)throw Error(`Campos no soportados para create: ${t.join(", ")}`);let r=i.map(([s])=>`$${s}: ${vo[s]}`).join(", "),e=i.map(([s])=>`${s}: $${s}`).join(", ");return`mutation (${r}) {
210
+ createCoupon(${e}) {
211
+ ${D}
212
+ }
213
+ }`}async function zo(o,i){let t=await f(o),r=I(i,"limit"),e=I(i,"page"),s=i.filter,n=await c({service:"main",query:`query ($websiteId: ID, $filter: String, $limit: BigInt, $page: BigInt) {
214
+ coupons(websiteId: $websiteId, filter: $filter, limit: $limit, page: $page) {
215
+ items {
216
+ _id
217
+ name
218
+ code
219
+ active
220
+ type
221
+ totalRedemptions
222
+ percentageOff
223
+ discountAmount
224
+ fixedAmount
225
+ fromDate
226
+ endDate
227
+ }
228
+ totalCount
229
+ totalPages
230
+ hasNextPage
231
+ hasPreviousPage
232
+ }
233
+ }`,variables:{websiteId:t.websiteId,filter:s,limit:r,page:e}});return{context:t,coupons:n.coupons.items??[],pagination:{totalCount:n.coupons.totalCount??0,totalPages:n.coupons.totalPages??0,hasNextPage:Boolean(n.coupons.hasNextPage),hasPreviousPage:Boolean(n.coupons.hasPreviousPage),page:e??1,limit:r??null}}}async function Ho(o,i){let t=await f(o);await U(i,t.websiteId);let r=await c({service:"main",query:`query ($couponId: ID) {
234
+ coupon(couponId: $couponId) {
235
+ ${D}
236
+ }
237
+ }`,variables:{couponId:i}});return{context:t,coupon:r.coupon}}async function Do(o,i){let t=await f(o),r=S(i,"input");if(r.websiteId&&r.websiteId!==t.websiteId)throw Error("El websiteId del input no coincide con el website seleccionado.");let e={...r,websiteId:t.websiteId},s=mt(e),n=await c({service:"main",query:s,variables:e});return{context:t,coupon:n.createCoupon}}async function Ko(o,i,t){let r=await f(o);await U(i,r.websiteId);let e=S(t,"input"),s=await c({service:"main",query:`mutation ($couponId: ID, $coupon: UpdateCouponInput) {
238
+ updateCoupon(couponId: $couponId, coupon: $coupon) {
239
+ ${D}
240
+ }
241
+ }`,variables:{couponId:i,coupon:e}});return{context:r,coupon:s.updateCoupon}}async function ko(o,i){let t=await f(o);await U(i,t.websiteId);let r=await c({service:"main",query:`mutation ($couponsIds: [ID]) {
242
+ deleteCoupons(couponsIds: $couponsIds, globalCoupon: false)
243
+ }`,variables:{couponsIds:[i]}});return{context:t,couponId:i,deleted:r.deleteCoupons}}function X(){return`team-cli admin coupons
244
+
245
+ Administracion de cupones para el website seleccionado.
246
+
247
+ Uso:
248
+ team-cli admin <websiteId|domain> coupons <accion> [opciones]
249
+
250
+ Acciones:
251
+ list
252
+ Listar cupones.
253
+ Uso: team-cli admin <web> coupons list [--filter <text>] [--limit <n>] [--page <n>]
254
+
255
+ show
256
+ Ver detalle de un cupón.
257
+ Uso: team-cli admin <web> coupons show <couponId>
258
+
259
+ create
260
+ Crear un cupón usando --input con JSON.
261
+ Uso: team-cli admin <web> coupons create --input '<json>'
262
+ Ayuda detallada: team-cli admin <web> coupons create --help
263
+
264
+ update
265
+ Actualizar un cupón usando --input con JSON.
266
+ Uso: team-cli admin <web> coupons update <couponId> --input '<json>'
267
+ Ayuda detallada: team-cli admin <web> coupons update <couponId> --help
268
+
269
+ delete
270
+ Eliminar un cupón.
271
+ Uso: team-cli admin <web> coupons delete <couponId>
272
+
273
+ codes list
274
+ Listar códigos de un cupón.
275
+ Uso: team-cli admin <web> coupons codes list <couponId> [--filter <text>] [--limit <n>] [--page <n>]
276
+
277
+ codes create
278
+ Crear códigos explícitos para un cupón.
279
+ Uso: team-cli admin <web> coupons codes create <couponId> --input '<json>'
280
+ Ayuda detallada: team-cli admin <web> coupons codes create <couponId> --help
281
+
282
+ codes create-random
283
+ Crear códigos aleatorios para un cupón.
284
+ Uso: team-cli admin <web> coupons codes create-random <couponId> --quantity <n> [--prefix <text>]
285
+
286
+ codes delete
287
+ Eliminar códigos por id.
288
+ Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1","id2"]'
289
+
290
+ Nota:
291
+ El schema actual no expone update para coupon codes.`}function Vo(){return`team-cli admin coupons create
292
+
293
+ Crea un cupón para el website seleccionado.
294
+
295
+ Uso:
296
+ team-cli admin <websiteId|domain> coupons create --input '<json>'
297
+
298
+ Como funciona:
299
+ --input recibe un objeto JSON con los campos de createCoupon.
300
+ team-cli agrega automaticamente websiteId usando el contexto seleccionado.
301
+ Si mandas websiteId dentro del JSON y no coincide con el website seleccionado, el comando falla.
302
+
303
+ Campos comunes:
304
+ name
305
+ code
306
+ type
307
+ active
308
+ description
309
+ percentageOff
310
+ discountAmount
311
+ fixedAmount
312
+ maxRedemptions
313
+ maxRedemptionsPerUser
314
+ minimumOrderPrice
315
+ maximumOrderPrice
316
+ fromDate
317
+ endDate
318
+ requiresStoresIds
319
+ requireChannels
320
+ requiresPaymentTypes
321
+ requiredBINs
322
+ schedule
323
+ scheduleAtUse
324
+
325
+ Ejemplo porcentaje:
326
+ team-cli admin <web> coupons create --input '{"name":"Promo 20","code":"PROMO20","type":"percentage","percentageOff":20,"active":true}'
327
+
328
+ Ejemplo monto fijo:
329
+ team-cli admin <web> coupons create --input '{"name":"Descuento 5000","code":"MENOS5K","type":"fixed","discountAmount":5000,"active":true}'
330
+
331
+ Ejemplo con restricciones:
332
+ team-cli admin <web> coupons create --input '{"name":"Solo retiro","code":"GOONLY","type":"fixed","discountAmount":3000,"active":true,"requiresStoresIds":["store1","store2"],"requireChannels":["web"]}'
333
+
334
+ Ejemplo con schedule:
335
+ team-cli admin <web> coupons create --input '{"name":"Happy Hour","code":"HAPPY","type":"percentage","percentageOff":15,"schedule":{"timezone":"America/Santiago","isAvailableNow":true,"openPeriods":[{"daysOfWeek":[1,2,3,4,5],"fromMinute":720,"toMinute":900}]}}'
336
+
337
+ Tips:
338
+ Usa comillas simples afuera del JSON en shell.
339
+ Usa arrays JSON reales para ids o listas.
340
+ Si necesitas el shape exacto de un cupón existente, parte con: team-cli admin <web> coupons show <couponId>`}function Lo(){return`team-cli admin coupons update
341
+
342
+ Actualiza un cupón existente.
343
+
344
+ Uso:
345
+ team-cli admin <websiteId|domain> coupons update <couponId> --input '<json>'
346
+
347
+ Como funciona:
348
+ --input recibe un objeto JSON compatible con UpdateCouponInput.
349
+ Solo envía los campos que quieras cambiar.
350
+ couponId se valida contra el website seleccionado antes de ejecutar la mutation.
351
+
352
+ Campos comunes:
353
+ name
354
+ active
355
+ description
356
+ percentageOff
357
+ discountAmount
358
+ fixedAmount
359
+ maxRedemptions
360
+ maxRedemptionsPerUser
361
+ minimumOrderPrice
362
+ maximumOrderPrice
363
+ fromDate
364
+ endDate
365
+ requiresStoresIds
366
+ requireChannels
367
+ requiresPaymentTypes
368
+ requiredBINs
369
+ schedule
370
+ scheduleAtUse
371
+
372
+ Ejemplo simple:
373
+ team-cli admin <web> coupons update <couponId> --input '{"active":false}'
374
+
375
+ Ejemplo cambiando descuento:
376
+ team-cli admin <web> coupons update <couponId> --input '{"percentageOff":25,"maxRedemptions":100}'
377
+
378
+ Ejemplo reemplazando restricciones:
379
+ team-cli admin <web> coupons update <couponId> --input '{"requiresStoresIds":["store1"],"requiresPaymentTypes":["card"]}'
380
+
381
+ Tip:
382
+ Primero mira el cupón actual con: team-cli admin <web> coupons show <couponId>`}function ut(o){if(!Array.isArray(o))throw Error("--input debe ser un arreglo JSON.");return o.map((i)=>{if(!i||typeof i!=="object"||typeof i.code!=="string")throw Error('Cada item de --input debe tener al menos { "code": "..." }.');if(i.userEmail!=null&&typeof i.userEmail!=="string")throw Error("userEmail debe ser string cuando viene informado.");return{code:i.code,userEmail:i.userEmail}})}function gt(o){if(!Array.isArray(o)||o.some((i)=>typeof i!=="string"))throw Error("--ids debe ser un arreglo JSON de strings.");return o}async function oi(o,i,t){let r=await f(o);await U(i,r.websiteId);let e=I(t,"limit"),s=I(t,"page"),n=t.filter,a=await c({service:"main",query:`query ($couponId: ID, $filter: String, $limit: BigInt, $page: BigInt) {
383
+ couponCodes(couponId: $couponId, filter: $filter, limit: $limit, page: $page) {
384
+ items {
385
+ ${To}
386
+ }
387
+ totalCount
388
+ totalPages
389
+ hasNextPage
390
+ hasPreviousPage
391
+ }
392
+ }`,variables:{couponId:i,filter:n,limit:e,page:s}});return{context:r,couponId:i,codes:a.couponCodes.items??[],pagination:{totalCount:a.couponCodes.totalCount??0,totalPages:a.couponCodes.totalPages??0,hasNextPage:Boolean(a.couponCodes.hasNextPage),hasPreviousPage:Boolean(a.couponCodes.hasPreviousPage),page:s??1,limit:e??null}}}async function ii(o,i,t){let r=await f(o);await U(i,r.websiteId);let e=ut(S(t,"input")),s=e.some((a)=>a.userEmail),n=await c({service:"main",query:`mutation ($couponId: ID, $codesWithEmail: [CodeWithEmailInput], $useCodeWithEmail: Boolean) {
393
+ createCouponCodes(couponId: $couponId, codesWithEmail: $codesWithEmail, useCodeWithEmail: $useCodeWithEmail)
394
+ }`,variables:{couponId:i,codesWithEmail:e,useCodeWithEmail:s}});return{context:r,couponId:i,requestedCount:e.length,result:n.createCouponCodes}}async function ti(o,i,t){let r=await f(o);await U(i,r.websiteId);let e=I(t,"quantity");if(!e)throw Error("--quantity es requerido.");let s=await c({service:"main",query:`mutation ($couponId: ID, $couponQuantity: Float, $couponCodePrefix: String) {
395
+ createRandomCouponCodes(couponId: $couponId, couponQuantity: $couponQuantity, couponCodePrefix: $couponCodePrefix)
396
+ }`,variables:{couponId:i,couponQuantity:e,couponCodePrefix:t.prefix}});return{context:r,couponId:i,quantity:e,prefix:t.prefix??null,result:s.createRandomCouponCodes}}async function ri(o,i,t){let r=await f(o);await U(i,r.websiteId);let e=gt(S(t,"ids")),s=await c({service:"main",query:`mutation ($couponId: ID, $couponCodesIds: [ID]) {
397
+ deleteCouponCodes(couponId: $couponId, couponCodesIds: $couponCodesIds, globalCoupon: false)
398
+ }`,variables:{couponId:i,couponCodesIds:e}});return{context:r,couponId:i,deleted:s.deleteCouponCodes,couponCodesIds:e}}function ei(){return`team-cli admin coupons codes create
399
+
400
+ Crea códigos explícitos para un cupón.
401
+
402
+ Uso:
403
+ team-cli admin <websiteId|domain> coupons codes create <couponId> --input '<json>'
404
+
405
+ Como funciona:
406
+ --input recibe un arreglo JSON.
407
+ Cada item debe tener al menos el campo code.
408
+ Opcionalmente puede incluir userEmail.
409
+
410
+ Formato esperado:
411
+ [
412
+ {"code":"BIENVENIDA1"},
413
+ {"code":"BIENVENIDA2","userEmail":"persona@ejemplo.com"}
414
+ ]
415
+
416
+ Ejemplo:
417
+ team-cli admin <web> coupons codes create <couponId> --input '[{"code":"PROMO001"},{"code":"PROMO002","userEmail":"ana@ejemplo.com"}]'
418
+
419
+ Notas:
420
+ Si algún item trae userEmail, team-cli activa useCodeWithEmail automáticamente.
421
+ couponId se valida contra el website seleccionado antes de ejecutar la mutation.`}import{writeFileSync as dt}from"node:fs";function K(){if(!d())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}function k(o,i){let t=o[3];if(!t)throw Error(`Uso: ${i}`);return t}function si(o){if(!o.params)return{};try{return JSON.parse(o.params)}catch{throw Error("--params debe ser un JSON válido.")}}function lt(o){if(typeof o!=="string")return o;try{return JSON.parse(o)}catch{return{value:o}}}async function ni(o){K();let i=k(o,"team-cli data queries view <queryId>");return(await c({service:"data",query:`query ($aggregationQueryId: String) {
39
422
  aggregationQuery(aggregationQueryId: $aggregationQueryId) {
40
423
  _id
41
424
  name
@@ -48,15 +431,17 @@ var sg={main:{local:"http://localhost:3000",develop:"https://api.bejusto.com",pr
48
431
  fieldParams
49
432
  }
50
433
  }
51
- }`,variables:{aggregationQueryId:q}});Bg($.aggregationQuery,m)}async function Tg(g,m){i();let q=k(g,"team-cli data queries view-pipeline <queryId>"),$=await N({service:"data",query:`query ($aggregationQueryId: String) {
434
+ }`,variables:{aggregationQueryId:i}})).aggregationQuery}async function ai(o){K();let i=k(o,"team-cli data queries view-pipeline <queryId>"),t=await c({service:"data",query:`query ($aggregationQueryId: String) {
52
435
  aggregationQuery(aggregationQueryId: $aggregationQueryId) {
53
436
  pipeline
54
437
  }
55
- }`,variables:{aggregationQueryId:q}});console.log($.aggregationQuery.pipeline)}async function Og(g,m){i();let q=k(g,"team-cli data queries preview <queryId> --params '<json>'"),$=Ag(m),j=await N({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
438
+ }`,variables:{aggregationQueryId:i}});return{queryId:i,pipeline:t.aggregationQuery.pipeline}}async function ci(o,i){K();let t=k(o,"team-cli data queries preview <queryId> --params '<json>'"),r=si(i),e=await c({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
56
439
  testAggregationQuery(aggregationQueryId: $aggregationQueryId, params: $params)
57
- }`,variables:{aggregationQueryId:q,params:$}});Bg(j.testAggregationQuery,m)}function Am(g){return new Promise((m)=>setTimeout(m,g))}async function Fg(g,m){i();let q=k(g,"team-cli data queries download <queryId> --params '<json>'"),$=Ag(m);if(!m.path)throw Error("--path es requerido. Ejemplo: --path resultado.xlsx");let j=m.path;console.log("Iniciando descarga...");let f=(await N({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
440
+ }`,variables:{aggregationQueryId:t,params:r}});return lt(e.testAggregationQuery)}function pt(o){return new Promise((i)=>setTimeout(i,o))}async function mi(o,i){K();let t=k(o,"team-cli data queries download <queryId> --params '<json>'"),r=si(i);if(!i.path)throw Error("--path es requerido. Ejemplo: --path resultado.xlsx");let e=i.path;$(`Iniciando descarga...
441
+ `);let n=(await c({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
58
442
  downloadAggregationQueryData(aggregationQueryId: $aggregationQueryId, params: $params)
59
- }`,variables:{aggregationQueryId:q,params:$}})).downloadAggregationQueryData;console.log(`Reporte en proceso (${f})...`);let C=null;while(!C){await Am(1000);let r=await N({service:"data",query:`query ($id: String) {
443
+ }`,variables:{aggregationQueryId:t,params:r}})).downloadAggregationQueryData;$(`Reporte en proceso (${n})...
444
+ `);let a=null;while(!a){await pt(1000);let b=await c({service:"data",query:`query ($id: String) {
60
445
  getAsyncReport(id: $id) {
61
446
  _id
62
447
  status
@@ -64,30 +449,42 @@ var sg={main:{local:"http://localhost:3000",develop:"https://api.bejusto.com",pr
64
449
  fileUrl
65
450
  }
66
451
  getAsyncReportRecordsCount(id: $id)
67
- }`,variables:{id:f}}),X=r.getAsyncReport,J=r.getAsyncReportRecordsCount;if(X.status==="error")throw Error("El reporte falló al generarse.");if(X.fileUrl)C=X.fileUrl;else{let F=X.estimatedRecordsCount?` (~${X.estimatedRecordsCount} registros)`:"",M=J!=null?` ${J} procesados`:"";process.stdout.write(`\rGenerando...${F}${M}`)}}process.stdout.write(`
68
- `),console.log("Descargando archivo...");let G=await fetch(C);if(!G.ok)throw Error(`Error descargando archivo: ${G.status}`);let Y=Buffer.from(await G.arrayBuffer());Mm(j,Y),console.log(`Archivo guardado en ${j}`)}function gg(){console.log(`
69
- team-cli data - Comandos de datos y reportes
70
-
71
- Uso:
72
- team-cli data queries <subcomando> [opciones]
73
-
74
- Subcomandos:
75
- view <queryId> Ver información de un query
76
- view-pipeline <queryId> Ver el pipeline de un query
77
- preview <queryId> Ejecutar un query de prueba (max 100 filas)
78
- download <queryId> Descargar resultado completo como Excel
79
-
80
- Opciones:
81
- --params '<json>' Parámetros del query (default: {})
82
- --format toon|json Formato de salida para view/preview (default: toon)
83
- --path <filepath> Ruta del archivo de descarga (requerido para download)
84
-
85
- Ejemplos:
86
- team-cli data queries view abc123
87
- team-cli data queries view-pipeline abc123
88
- team-cli data queries preview abc123 --params '{"startDate": "2026-01-01"}'
89
- team-cli data queries download abc123 --params '{"startDate": "2026-01-01"}' --path resultado.xlsx
90
- `)}function bg(){console.log(`# @getjusto/team-cli
452
+ }`,variables:{id:n}}),q=b.getAsyncReport,y=b.getAsyncReportRecordsCount;if(q.status==="error")throw Error("El reporte falló al generarse.");if(q.fileUrl)a=q.fileUrl;else{let B=q.estimatedRecordsCount?` (~${q.estimatedRecordsCount} registros)`:"",x=y!=null?` ${y} procesados`:"";$(`\rGenerando...${B}${x}`)}}$(`
453
+ `),$(`Descargando archivo...
454
+ `);let u=await fetch(a);if(!u.ok)throw Error(`Error descargando archivo: ${u.status}`);let j=Buffer.from(await u.arrayBuffer());return dt(e,j),{ok:!0,queryId:t,asyncReportId:n,outputPath:e,fileUrl:a}}function go(){return`team-cli data
455
+
456
+ Comandos de datos y reportes.
457
+
458
+ Uso:
459
+ team-cli data queries <subcomando> [opciones]
460
+
461
+ Subcomandos:
462
+ view <queryId>
463
+ Ver informacion de un query.
464
+
465
+ view-pipeline <queryId>
466
+ Ver el pipeline de un query.
467
+
468
+ preview <queryId>
469
+ Ejecutar un query de prueba.
470
+ Uso: team-cli data queries preview <queryId> --params '<json>' [--format toon|json]
471
+
472
+ download <queryId>
473
+ Descargar resultado completo como Excel.
474
+ Uso: team-cli data queries download <queryId> --path <filepath> [--params '<json>'] [--format toon|json]
475
+
476
+ Opciones:
477
+ --params '<json>' Parametros del query. Default: {}
478
+ --format <toon|json>
479
+ --path <filepath> Requerido para download
480
+
481
+ Ejemplos:
482
+ team-cli data queries view abc123
483
+ team-cli data queries view-pipeline abc123
484
+ team-cli data queries preview abc123 --params '{"startDate": "2026-01-01"}'
485
+ team-cli data queries download abc123 --params '{"startDate": "2026-01-01"}' --path resultado.xlsx`}var wt=["local","develop","prod"];function ui(){return Object.keys(Y)}function ft(){return ui().map((o)=>{return[`- \`${o}\``,...wt.map((t)=>{let r=Y[o][t];return` - ${t}: \`${r}/graphql\``})].join(`
486
+ `)}).join(`
487
+ `)}function bt(){let i=ui().join(", "),t=ft();return`# @getjusto/team-cli
91
488
 
92
489
  CLI tool for Justo team members. Authenticated access to Justo's GraphQL services and data queries.
93
490
 
@@ -116,7 +513,7 @@ npx @getjusto/team-cli auth login
116
513
  npx @getjusto/team-cli graphql <service> '<query>' [--variables '<json>'] [--format toon|json]
117
514
  \`\`\`
118
515
 
119
- Available services: 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.
516
+ Available services: ${i}.
120
517
 
121
518
  Examples:
122
519
  \`\`\`bash
@@ -125,6 +522,64 @@ npx @getjusto/team-cli graphql main 'query($id: ID) { user(userId: $id) { _id }
125
522
  npx @getjusto/team-cli graphql tabs 'query { tab(tabId: "t123") { _id status } }' --format json
126
523
  \`\`\`
127
524
 
525
+ ### GraphQL Service Map
526
+
527
+ Use this when someone shares a GraphQL \`curl\` and you need to map the URL to the correct \`team-cli graphql <service>\` value.
528
+
529
+ Rule:
530
+ - If the curl points to \`https://something/.../graphql\`, match that URL against the list below and use the corresponding service name.
531
+ - In \`team-cli\`, you pass the service name only, not the full URL.
532
+
533
+ Service name to endpoint map:
534
+ ${t}
535
+
536
+ Example conversion:
537
+ \`\`\`bash
538
+ # curl
539
+ curl 'https://tabs.service.getjusto.com/graphql' \\
540
+ -H 'content-type: application/json' \\
541
+ --data-raw '{"query":"query { tab(tabId: \\"t123\\") { _id status } }"}'
542
+
543
+ # team-cli
544
+ npx @getjusto/team-cli graphql tabs 'query { tab(tabId: "t123") { _id status } }'
545
+ \`\`\`
546
+
547
+ ### admin search — Search websites/brands in admin
548
+
549
+ Use this when you need to find a website first before calling other admin commands.
550
+
551
+ \`\`\`bash
552
+ npx @getjusto/team-cli admin search <text> [--limit <n>] [--page <n>] [--only-active true|false]
553
+ \`\`\`
554
+
555
+ What it returns:
556
+ - \`_id\`
557
+ - \`name\`
558
+ - \`active\`
559
+ - \`baseURL\`
560
+ - \`domain\`
561
+ - \`countryCode\`
562
+ - \`timezone\`
563
+
564
+ Typical use:
565
+ 1. Search the brand/site by name fragment.
566
+ 2. Take either the returned \`_id\` or a known domain/baseURL.
567
+ 3. Use that value in \`team-cli admin <websiteId|domain> ...\`.
568
+
569
+ Examples:
570
+ \`\`\`bash
571
+ # find the website
572
+ npx @getjusto/team-cli admin search milas --limit 5
573
+
574
+ # then use the returned website id
575
+ npx @getjusto/team-cli admin YRZjQ7L6whxfkezmF show
576
+ npx @getjusto/team-cli admin YRZjQ7L6whxfkezmF stores list
577
+ npx @getjusto/team-cli admin YRZjQ7L6whxfkezmF coupons list
578
+
579
+ # or use a domain directly
580
+ npx @getjusto/team-cli admin www.masmilas.com show
581
+ \`\`\`
582
+
128
583
  ### data queries view — View query metadata and required variables
129
584
 
130
585
  \`\`\`bash
@@ -166,22 +621,33 @@ Default output is TOON (Token-Oriented Object Notation), a compact human-readabl
166
621
  1. View a query to understand its variables: \`data queries view <id>\`
167
622
  2. Preview with params: \`data queries preview <id> --params '{"startDate": "2026-01-01"}'\`
168
623
  3. Download full data: \`data queries download <id> --params '{"startDate": "2026-01-01"}' --path output.xlsx\`
169
- `)}var{positional:c,flags:R}=$g(process.argv.slice(2));if(R.env)mg(R.env);var s=c[0],B=c[1];function zg(){let g=W(),m=g?`Sesión: ${g.email}`:"Sesión: no iniciada";console.log(`
170
- team-cli - Herramienta CLI para el equipo Justo
624
+ `}function gi(){return{skill:bt()}}var{positional:l,flags:m}=wo(process.argv.slice(2));if(m.env)lo(m.env);var Q=l[0],P=l[1];function di(){let o=d();return`team-cli
625
+
626
+ Herramienta CLI para el equipo Justo.
627
+
628
+ ${o?`Sesión: ${o.email}`:"Sesión: no iniciada"}
629
+
630
+ Uso:
631
+ team-cli <comando> [opciones]
632
+
633
+ Comandos:
634
+ auth
635
+ Gestión de sesión.
636
+
637
+ admin
638
+ Comandos administrativos con contexto de website.
171
639
 
172
- ${m}
640
+ graphql
641
+ Ejecutar queries y mutations GraphQL.
173
642
 
174
- Uso:
175
- team-cli <comando> [opciones]
643
+ data
644
+ Datos y reportes.
176
645
 
177
- Comandos:
178
- auth Gestión de sesión
179
- graphql Ejecutar queries/mutations GraphQL
180
- data Datos y reportes
181
- get-skill Obtener skill para usar con Claude
646
+ get-skill
647
+ Obtener skill para usar con Claude.
182
648
 
183
- Opciones globales:
184
- --env <local|develop|prod> Seleccionar ambiente (default: prod)
185
- --version Muestra la versión
186
- --help Muestra la ayuda
187
- `)}async function Bm(){try{if(R.version)console.log("0.0.2");else if(R.help&&!s)zg();else if(s==="auth")if(B==="--help"||R.help)p();else if(B==="login")await Ng();else if(B==="login-with-token")await Wg(R);else if(B==="request-code")await Ug(R);else if(B==="logout")await rg();else if(B==="status")await Xg();else p();else if(s==="graphql")if(B==="--help"||R.help)e();else await Mg(c,R);else if(s==="get-skill")bg();else if(s==="data"){let g=c[1],m=c[2];if(R.help||B==="--help")gg();else if(g==="queries"&&m==="view")await Sg(c,R);else if(g==="queries"&&m==="view-pipeline")await Tg(c,R);else if(g==="queries"&&m==="preview")await Og(c,R);else if(g==="queries"&&m==="download")await Fg(c,R);else gg()}else zg()}catch(g){console.error(`Error: ${g instanceof Error?g.message:g}`),process.exit(1)}}Bm();
649
+ Opciones globales:
650
+ --env <local|develop|prod>
651
+ --version
652
+ --help
653
+ --format <toon|json>`}async function qt(){try{let o;if(m.version)o={version:"0.0.3"};else if(m.help&&!Q){g(di());return}else if(Q==="auth")if(P==="--help"||m.help){g(co());return}else if(P==="login")o=await No();else if(P==="login-with-token")o=await Ao(m);else if(P==="request-code")o=await Oo(m);else if(P==="logout")o=await So();else if(P==="status")o=await Qo();else{g(co());return}else if(Q==="admin"){let i=l[1],t=l[2],r=l[3],e=l[4];if(!i||i==="--help"){g(H());return}else if(i==="search"&&m.help){g(Yo());return}else if(i==="search")o=await Xo(l,m);else if(!t||t==="--help"){g(H());return}else if(t==="show")o=await _o(i);else if(t==="stores"&&r==="list")o=await Zo(i);else if(t==="coupons"&&(!r||r==="--help")){g(X());return}else if(t==="coupons"&&r==="create"&&m.help){g(Vo());return}else if(t==="coupons"&&r==="update"&&m.help){g(Lo());return}else if(t==="coupons"&&r==="codes"&&l[4]==="create"&&m.help){g(ei());return}else if(t==="coupons"&&m.help){g(X());return}else if(t==="coupons"&&r==="list")o=await zo(i,m);else if(t==="coupons"&&r==="show"){if(!e)throw Error("Uso: team-cli admin <web> coupons show <couponId>");o=await Ho(i,e)}else if(t==="coupons"&&r==="create")o=await Do(i,m);else if(t==="coupons"&&r==="update"){if(!e)throw Error("Uso: team-cli admin <web> coupons update <couponId> --input '<json>'");o=await Ko(i,e,m)}else if(t==="coupons"&&r==="delete"){if(!e)throw Error("Uso: team-cli admin <web> coupons delete <couponId>");o=await ko(i,e)}else if(t==="coupons"&&r==="codes"){let s=l[4],n=l[5];if(!s||s==="--help"){g(X());return}else if(s==="list"){if(!n)throw Error("Uso: team-cli admin <web> coupons codes list <couponId>");o=await oi(i,n,m)}else if(s==="create"){if(!n)throw Error("Uso: team-cli admin <web> coupons codes create <couponId> --input '<json>'");o=await ii(i,n,m)}else if(s==="create-random"){if(!n)throw Error("Uso: team-cli admin <web> coupons codes create-random <couponId> --quantity <n>");o=await ti(i,n,m)}else if(s==="delete"){if(!n)throw Error(`Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1"]'`);o=await ri(i,n,m)}else{g(X());return}}else{g(H());return}}else if(Q==="graphql")if(P==="--help"||m.help){g(Go());return}else o=await Bo(l,m);else if(Q==="get-skill")o=gi();else if(Q==="data"){let i=l[1],t=l[2];if(m.help||P==="--help"){g(go());return}else if(i==="queries"&&t==="view")o=await ni(l);else if(i==="queries"&&t==="view-pipeline")o=await ai(l);else if(i==="queries"&&t==="preview")o=await ci(l,m);else if(i==="queries"&&t==="download")o=await mi(l,m);else{g(go());return}}else{g(di());return}if(o!==void 0)xo(o,m)}catch(o){Eo(o,m),process.exit(1)}}qt();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getjusto/team-cli",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "CLI tool for Justo team members",
5
5
  "type": "module",
6
6
  "bin": {