@winning-sales/nexo 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -1
- package/assets/skills/nexo-api/SKILL.md +2 -1
- package/assets/skills/nexo-connect/SKILL.md +20 -5
- package/dist/commands/connect-access.js +279 -0
- package/dist/commands/connect-agents.js +132 -0
- package/dist/commands/connect-build.js +172 -0
- package/dist/commands/connect-execute.js +85 -0
- package/dist/commands/connect-files.js +23 -7
- package/dist/commands/connect-hosts.js +177 -0
- package/dist/commands/connect-retained.js +134 -0
- package/dist/commands/connect-runs.js +70 -14
- package/dist/commands/connect-versions.js +143 -0
- package/dist/commands/erp.js +225 -0
- package/dist/commands/login.js +1 -5
- package/dist/commands/mcp.js +2 -1
- package/dist/commands/platform.js +98 -0
- package/dist/commands/whoami.js +9 -1
- package/dist/config/environments.js +10 -0
- package/dist/connect/access.js +117 -0
- package/dist/connect/agents.js +71 -0
- package/dist/connect/changes.js +68 -7
- package/dist/connect/operation-args.js +30 -0
- package/dist/connect/retained.js +106 -0
- package/dist/connect/runs.js +65 -10
- package/dist/connect/schedule.js +38 -0
- package/dist/connect/template.js +23 -0
- package/dist/connect/versions.js +60 -0
- package/dist/erp/operations.js +87 -0
- package/dist/http/problem.js +22 -1
- package/dist/program-connect-access.js +134 -0
- package/dist/program-connect.js +256 -4
- package/dist/program-erp.js +44 -0
- package/dist/program.js +22 -1
- package/dist/tools/tool-manifest.js +65 -0
- package/package.json +1 -1
- package/reference.json +1394 -54
|
@@ -8,6 +8,7 @@ export const DEFAULT_ENVIRONMENT = {
|
|
|
8
8
|
appUrl: 'https://app.nexo.winningsales.com.br'
|
|
9
9
|
};
|
|
10
10
|
export const TOKENS_PAGE = '/settings/api-tokens';
|
|
11
|
+
export const AGENT_PAIRING_PAGE = '/settings/connections/connectors?tab=agent&foco=parear';
|
|
11
12
|
export function environmentNamed(name) {
|
|
12
13
|
const environment = ENVIRONMENTS[name];
|
|
13
14
|
if (environment === undefined) {
|
|
@@ -31,3 +32,12 @@ export function normalizedApiUrl(raw) {
|
|
|
31
32
|
function isLoopback(hostname) {
|
|
32
33
|
return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]';
|
|
33
34
|
}
|
|
35
|
+
/** O app do ambiente da API, ou `null` quando a API não é de nenhum ambiente conhecido (localhost, staging). */
|
|
36
|
+
export function knownAppUrl(apiUrl) {
|
|
37
|
+
const known = Object.values(ENVIRONMENTS).find((environment) => environment.apiUrl === apiUrl);
|
|
38
|
+
return known?.appUrl ?? null;
|
|
39
|
+
}
|
|
40
|
+
/** O endereço do app para o `nexo login`; um ambiente desconhecido cai no de produção. */
|
|
41
|
+
export function appUrlOf(apiUrl) {
|
|
42
|
+
return knownAppUrl(apiUrl) ?? DEFAULT_ENVIRONMENT.appUrl;
|
|
43
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { CliError } from '../errors.js';
|
|
2
|
+
import { EXIT_CODES } from '../exit-codes.types.js';
|
|
3
|
+
export const DEFAULT_PATIENCE = { intervalMs: 3000, timeoutMs: 10 * 60_000 };
|
|
4
|
+
/**
|
|
5
|
+
* Confere `check` de tempos em tempos até ele devolver algo, ou o limite passar.
|
|
6
|
+
* O relógio só mede a espera: o que vale é o estado lido, nunca a hora da máquina contra a do servidor.
|
|
7
|
+
*/
|
|
8
|
+
export async function pollUntil(check, pause, patience, onTimeout) {
|
|
9
|
+
const now = patience.now ?? Date.now;
|
|
10
|
+
const deadline = now() + patience.timeoutMs;
|
|
11
|
+
for (;;) {
|
|
12
|
+
const found = await check();
|
|
13
|
+
if (found !== null) {
|
|
14
|
+
return found;
|
|
15
|
+
}
|
|
16
|
+
if (now() >= deadline) {
|
|
17
|
+
throw onTimeout();
|
|
18
|
+
}
|
|
19
|
+
await pause(patience.intervalMs);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export function timedOut(message, hint) {
|
|
23
|
+
return () => new CliError(message, EXIT_CODES.failure, hint);
|
|
24
|
+
}
|
|
25
|
+
function fieldsOf(value) {
|
|
26
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : null;
|
|
27
|
+
}
|
|
28
|
+
function strings(value) {
|
|
29
|
+
return Array.isArray(value) && value.every((item) => typeof item === 'string');
|
|
30
|
+
}
|
|
31
|
+
export function isSecretList(value) {
|
|
32
|
+
return (Array.isArray(value) &&
|
|
33
|
+
value.every((item) => {
|
|
34
|
+
const fields = fieldsOf(item);
|
|
35
|
+
return fields !== null && typeof fields.name === 'string' && typeof fields.filled === 'boolean';
|
|
36
|
+
}));
|
|
37
|
+
}
|
|
38
|
+
export function isWebhook(value) {
|
|
39
|
+
const fields = fieldsOf(value);
|
|
40
|
+
return fields !== null && typeof fields.url === 'string' && typeof fields.secretSet === 'boolean';
|
|
41
|
+
}
|
|
42
|
+
export function isOAuthStatus(value) {
|
|
43
|
+
const fields = fieldsOf(value);
|
|
44
|
+
return fields !== null && typeof fields.required === 'boolean' && typeof fields.status === 'string' && typeof fields.app === 'string';
|
|
45
|
+
}
|
|
46
|
+
export function isOAuthAuthorization(value) {
|
|
47
|
+
const fields = fieldsOf(value);
|
|
48
|
+
return fields !== null && typeof fields.authorizeUrl === 'string';
|
|
49
|
+
}
|
|
50
|
+
function isSftpKey(value) {
|
|
51
|
+
const fields = fieldsOf(value);
|
|
52
|
+
return fields !== null && typeof fields.host === 'string' && typeof fields.port === 'number' && typeof fields.fingerprint === 'string';
|
|
53
|
+
}
|
|
54
|
+
export function isSftpKeyList(value) {
|
|
55
|
+
return Array.isArray(value) && value.every(isSftpKey);
|
|
56
|
+
}
|
|
57
|
+
export function isMailAddress(value) {
|
|
58
|
+
const fields = fieldsOf(value);
|
|
59
|
+
return fields !== null && (fields.address === null || typeof fields.address === 'string') && strings(fields.senders);
|
|
60
|
+
}
|
|
61
|
+
export function isMailFileList(value) {
|
|
62
|
+
return (Array.isArray(value) &&
|
|
63
|
+
value.every((item) => {
|
|
64
|
+
const fields = fieldsOf(item);
|
|
65
|
+
return fields !== null && typeof fields.name === 'string' && typeof fields.status === 'string';
|
|
66
|
+
}));
|
|
67
|
+
}
|
|
68
|
+
export function describeSecret(slot) {
|
|
69
|
+
return `${slot.name.padEnd(28)} ${slot.filled ? `preenchido${slot.setAt === null ? '' : ` desde ${slot.setAt}`}` : 'faltando'}`;
|
|
70
|
+
}
|
|
71
|
+
export function describeWebhook(webhook) {
|
|
72
|
+
return [
|
|
73
|
+
`URL: ${webhook.url} (POST com corpo JSON)`,
|
|
74
|
+
`Assinatura: o cabeçalho ${webhook.signatureHeader} leva sha256= e o HMAC-SHA256 de "<timestamp>.<corpo>" com o segredo; o cabeçalho ${webhook.timestampHeader} leva a hora da chamada, em segundos (5 minutos de tolerância).`,
|
|
75
|
+
webhook.secretSet ? 'Segredo: definido.' : 'Segredo: ainda não definido. Defina com `nexo connect webhook secret set --generate`.'
|
|
76
|
+
];
|
|
77
|
+
}
|
|
78
|
+
const APP_NAMES = {
|
|
79
|
+
nexo: 'o app do Nexo',
|
|
80
|
+
own: 'o app da própria empresa',
|
|
81
|
+
none: 'nenhum (a empresa precisa trazer o app dela)'
|
|
82
|
+
};
|
|
83
|
+
const STATUS_NAMES = {
|
|
84
|
+
unauthorized: 'não autorizado',
|
|
85
|
+
authorized: 'autorizado',
|
|
86
|
+
revoked: 'revogado pelo outro sistema'
|
|
87
|
+
};
|
|
88
|
+
export function describeOAuth(oauth) {
|
|
89
|
+
return [
|
|
90
|
+
oauth.required ? 'A versão em edição pede OAuth.' : 'A versão em edição não pede OAuth.',
|
|
91
|
+
`Sistema: ${oauth.systemName ?? 'fora do catálogo'}. App: ${APP_NAMES[oauth.app]}${oauth.clientId === null ? '' : ` (client id ${oauth.clientId})`}.`,
|
|
92
|
+
`Estado: ${STATUS_NAMES[oauth.status]}${oauth.authorizedAt === null ? '' : `, autorizado em ${oauth.authorizedAt}`}${oauth.expiresAt === null ? '' : `, o token vale até ${oauth.expiresAt} e o Nexo o renova`}.`,
|
|
93
|
+
...(oauth.revokedReason === null
|
|
94
|
+
? []
|
|
95
|
+
: [`Motivo da revogação: ${oauth.revokedReason}. Autorize de novo com \`nexo connect oauth authorize\`.`])
|
|
96
|
+
];
|
|
97
|
+
}
|
|
98
|
+
export function describeSftpKey(key) {
|
|
99
|
+
return `${key.host}:${String(key.port)} ${key.fingerprint} guardada em ${key.pinnedAt}`;
|
|
100
|
+
}
|
|
101
|
+
export function describeMail(mail) {
|
|
102
|
+
return [
|
|
103
|
+
mail.address === null ? 'Endereço: ainda não gerado. Gere com `nexo connect email renew`.' : `Endereço: ${mail.address}`,
|
|
104
|
+
mail.senders.length === 0 ? 'Quem pode mandar: ninguém declarado no manifesto.' : `Quem pode mandar: ${mail.senders.join(', ')}`
|
|
105
|
+
];
|
|
106
|
+
}
|
|
107
|
+
const IGNORED_REASONS = {
|
|
108
|
+
not_spreadsheet: 'não é planilha (.csv, .tsv, .txt ou .xlsx)',
|
|
109
|
+
too_large: 'passou do limite de tamanho',
|
|
110
|
+
empty: 'sem conteúdo'
|
|
111
|
+
};
|
|
112
|
+
export function describeMailFile(file) {
|
|
113
|
+
const left = file.status === 'received'
|
|
114
|
+
? 'recebido'
|
|
115
|
+
: `deixado de fora: ${IGNORED_REASONS[file.ignoredReason ?? ''] ?? file.ignoredReason ?? '?'}`;
|
|
116
|
+
return `${file.receivedAt} ${file.name} ${String(file.sizeBytes)} bytes ${left}`;
|
|
117
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
export function isAgent(value) {
|
|
2
|
+
if (typeof value !== 'object' || value === null) {
|
|
3
|
+
return false;
|
|
4
|
+
}
|
|
5
|
+
const fields = value;
|
|
6
|
+
return (typeof fields.id === 'string' &&
|
|
7
|
+
typeof fields.name === 'string' &&
|
|
8
|
+
typeof fields.status === 'string' &&
|
|
9
|
+
typeof fields.pairedAt === 'string' &&
|
|
10
|
+
Array.isArray(fields.connectors) &&
|
|
11
|
+
Array.isArray(fields.reach));
|
|
12
|
+
}
|
|
13
|
+
export function isAgentList(value) {
|
|
14
|
+
return Array.isArray(value) && value.every(isAgent);
|
|
15
|
+
}
|
|
16
|
+
export function isPairingCode(value) {
|
|
17
|
+
if (typeof value !== 'object' || value === null) {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
const fields = value;
|
|
21
|
+
return typeof fields.code === 'string' && typeof fields.expiresAt === 'string';
|
|
22
|
+
}
|
|
23
|
+
function connectionOf(agent) {
|
|
24
|
+
if (agent.status === 'revoked') {
|
|
25
|
+
return 'revogado';
|
|
26
|
+
}
|
|
27
|
+
return agent.connected ? 'conectado' : 'desconectado';
|
|
28
|
+
}
|
|
29
|
+
function connectorNames(agent) {
|
|
30
|
+
return agent.connectors.length === 0
|
|
31
|
+
? 'nenhum conector'
|
|
32
|
+
: agent.connectors.map((connector) => connector.name).join(', ');
|
|
33
|
+
}
|
|
34
|
+
export function describeAgentRow(agent) {
|
|
35
|
+
return `${agent.id} ${connectionOf(agent).padEnd(12)} v${agent.agentVersion} último contato ${agent.lastSeenAt ?? '-'} ${agent.name} (${connectorNames(agent)})`;
|
|
36
|
+
}
|
|
37
|
+
function describeReach(reach) {
|
|
38
|
+
const where = reach.port === undefined ? reach.host : `${reach.host}:${String(reach.port)}`;
|
|
39
|
+
const extra = [reach.engine, reach.database].filter((part) => part !== undefined).join('/');
|
|
40
|
+
return `${reach.kind} ${where}${extra === '' ? '' : ` (${extra})`}`;
|
|
41
|
+
}
|
|
42
|
+
export function describeAgent(agent) {
|
|
43
|
+
return [
|
|
44
|
+
`${agent.name} ${agent.id}`,
|
|
45
|
+
` Estado: ${connectionOf(agent)}, versão ${agent.agentVersion}, último contato ${agent.lastSeenAt ?? '-'}`,
|
|
46
|
+
` Máquina: ${agent.hostname} (${agent.os}, ${agent.arch}), pareada em ${agent.pairedAt}`,
|
|
47
|
+
...(agent.revokedAt === null ? [] : [` Revogado em ${agent.revokedAt}`]),
|
|
48
|
+
` Conectores: ${connectorNames(agent)}`,
|
|
49
|
+
agent.reach.length === 0 ? ' A lista local dele não alcança nada que ele tenha informado.' : ' A lista local dele alcança:',
|
|
50
|
+
...agent.reach.map((reach) => ` - ${describeReach(reach)}`)
|
|
51
|
+
];
|
|
52
|
+
}
|
|
53
|
+
export function revokePreview(agent) {
|
|
54
|
+
return {
|
|
55
|
+
title: `Revogar o agente local ${agent.name}`,
|
|
56
|
+
changes: [
|
|
57
|
+
`A máquina é ${agent.hostname} (${agent.os}, ${agent.arch}); o programa instalado nela fica parado até alguém desinstalá-lo.`,
|
|
58
|
+
agent.connectors.length === 0
|
|
59
|
+
? 'Nenhum conector usa este agente agora.'
|
|
60
|
+
: `Os conectores que passam por ele deixam de alcançar o ERP até o manifesto apontar para outro agente: ${connectorNames(agent)}.`,
|
|
61
|
+
'O túnel é cortado na hora e sem volta: não há como reativá-lo. Para ter um agente de novo, instale outro com um código novo.'
|
|
62
|
+
]
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** O agente ativo que não estava na lista de antes do pedido (o mais novo), sem depender de relógio; ou `null`. */
|
|
66
|
+
export function newlyPaired(agents, known) {
|
|
67
|
+
const paired = agents
|
|
68
|
+
.filter((agent) => agent.status === 'active' && !known.has(agent.id))
|
|
69
|
+
.sort((a, b) => b.pairedAt.localeCompare(a.pairedAt));
|
|
70
|
+
return paired[0] ?? null;
|
|
71
|
+
}
|
package/dist/connect/changes.js
CHANGED
|
@@ -7,7 +7,7 @@ function isPreview(value) {
|
|
|
7
7
|
const fields = value;
|
|
8
8
|
return typeof fields.title === 'string' && Array.isArray(fields.changes) && typeof fields.confirmation === 'object';
|
|
9
9
|
}
|
|
10
|
-
async function ask(context, question) {
|
|
10
|
+
export async function ask(context, question) {
|
|
11
11
|
const reader = createInterface({ input: context.stdin, output: context.stderr, terminal: true });
|
|
12
12
|
try {
|
|
13
13
|
const answer = await new Promise((resolve) => {
|
|
@@ -21,23 +21,51 @@ async function ask(context, question) {
|
|
|
21
21
|
}
|
|
22
22
|
async function apply(context, session, request, token) {
|
|
23
23
|
const response = await clientOf(context, session).request({
|
|
24
|
-
method: 'POST',
|
|
25
|
-
path: `/v1/connect/connectors/${request.connectorId}
|
|
26
|
-
body: { confirmationToken: token }
|
|
24
|
+
method: request.applyAs?.method ?? 'POST',
|
|
25
|
+
path: `/v1/connect/connectors/${request.connectorId}${request.applyAs === undefined ? `/${request.path}` : request.applyAs.path}`,
|
|
26
|
+
body: { ...request.body, confirmationToken: token }
|
|
27
27
|
});
|
|
28
28
|
if (request.json) {
|
|
29
29
|
printJson(context, response.body);
|
|
30
30
|
return;
|
|
31
31
|
}
|
|
32
32
|
printLine(context, 'Feito.');
|
|
33
|
+
for (const line of request.summarize?.(response.body) ?? []) {
|
|
34
|
+
printLine(context, line);
|
|
35
|
+
}
|
|
33
36
|
}
|
|
34
|
-
function showPreview(context, preview) {
|
|
37
|
+
export function showPreview(context, preview) {
|
|
35
38
|
printLine(context, preview.title);
|
|
36
39
|
for (const change of preview.changes) {
|
|
37
40
|
printLine(context, ` - ${change}`);
|
|
38
41
|
}
|
|
39
42
|
}
|
|
43
|
+
async function typedName(context, expected) {
|
|
44
|
+
const reader = createInterface({ input: context.stdin, output: context.stderr, terminal: true });
|
|
45
|
+
try {
|
|
46
|
+
const answer = await new Promise((resolve) => {
|
|
47
|
+
reader.question(`Para apagar, digite o nome do conector (${expected}): `, resolve);
|
|
48
|
+
});
|
|
49
|
+
return answer.trim() === expected;
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
reader.close();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
40
55
|
async function decide(context, session, request, preview) {
|
|
56
|
+
if (request.typeToConfirm !== undefined) {
|
|
57
|
+
if (context.stdin.isTTY === true && (await typedName(context, request.typeToConfirm))) {
|
|
58
|
+
await apply(context, session, request, preview.confirmation.token);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (context.stdin.isTTY === true) {
|
|
62
|
+
printNotice(context, 'O nome não confere. Nada mudou.');
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
printNotice(context, 'Mostre isto à pessoa. Depois do sim dela, aplique uma vez (-y sozinho não basta):');
|
|
66
|
+
printNotice(context, ` ${request.command} --confirm ${preview.confirmation.token}`);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
41
69
|
if (request.yes || (context.stdin.isTTY === true && (await ask(context, 'Confirma? (s/N) ')))) {
|
|
42
70
|
await apply(context, session, request, preview.confirmation.token);
|
|
43
71
|
return;
|
|
@@ -47,7 +75,7 @@ async function decide(context, session, request, preview) {
|
|
|
47
75
|
return;
|
|
48
76
|
}
|
|
49
77
|
printNotice(context, 'Mostre isto à pessoa. Depois do sim dela, aplique uma vez:');
|
|
50
|
-
printNotice(context, `
|
|
78
|
+
printNotice(context, ` ${request.command} --confirm ${preview.confirmation.token}`);
|
|
51
79
|
}
|
|
52
80
|
export async function requestChange(context, session, request) {
|
|
53
81
|
if (request.confirm !== undefined) {
|
|
@@ -56,7 +84,8 @@ export async function requestChange(context, session, request) {
|
|
|
56
84
|
}
|
|
57
85
|
const response = await clientOf(context, session).request({
|
|
58
86
|
method: 'POST',
|
|
59
|
-
path: `/v1/connect/connectors/${request.connectorId}/${request.
|
|
87
|
+
path: `/v1/connect/connectors/${request.connectorId}/${request.path}/preview`,
|
|
88
|
+
...(request.body === undefined ? {} : { body: request.body })
|
|
60
89
|
});
|
|
61
90
|
if (!isPreview(response.body)) {
|
|
62
91
|
throw new Error('Prévia em formato inesperado.');
|
|
@@ -68,3 +97,35 @@ export async function requestChange(context, session, request) {
|
|
|
68
97
|
showPreview(context, response.body);
|
|
69
98
|
await decide(context, session, request, response.body);
|
|
70
99
|
}
|
|
100
|
+
function reportApplied(context, change, response) {
|
|
101
|
+
if (change.json) {
|
|
102
|
+
printJson(context, response.body);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (change.report === undefined) {
|
|
106
|
+
printLine(context, 'Feito.');
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
change.report(response.body);
|
|
110
|
+
}
|
|
111
|
+
/** Mudança sem prévia no `/v1`: a prévia é montada aqui e o sim é local (`--confirm` sem token). */
|
|
112
|
+
export async function requestLocalChange(context, change) {
|
|
113
|
+
const approved = change.yes || change.confirmed;
|
|
114
|
+
if (change.json && !approved) {
|
|
115
|
+
printJson(context, change.preview);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (!change.json) {
|
|
119
|
+
showPreview(context, change.preview);
|
|
120
|
+
}
|
|
121
|
+
if (approved || (context.stdin.isTTY === true && (await ask(context, 'Confirma? (s/N) ')))) {
|
|
122
|
+
reportApplied(context, change, await change.apply());
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (context.stdin.isTTY === true) {
|
|
126
|
+
printNotice(context, 'Nada mudou.');
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
printNotice(context, 'Mostre isto à pessoa. Depois do sim dela, aplique uma vez:');
|
|
130
|
+
printNotice(context, ` ${change.command} --confirm`);
|
|
131
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { usageError } from '../errors.js';
|
|
3
|
+
function parsed(text, origin) {
|
|
4
|
+
let value;
|
|
5
|
+
try {
|
|
6
|
+
value = JSON.parse(text);
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
throw usageError(`${origin} não é JSON válido.`, 'Passe um objeto, como --args \'{"cnpj":"123"}\' ou --args @args.json.');
|
|
10
|
+
}
|
|
11
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
12
|
+
throw usageError(`${origin} precisa ser um objeto JSON.`);
|
|
13
|
+
}
|
|
14
|
+
return { ...value };
|
|
15
|
+
}
|
|
16
|
+
/** O valor de `--args`: um JSON na linha, ou `@arquivo`. Recusa antes de chamar o Nexo. */
|
|
17
|
+
export function readArgs(raw) {
|
|
18
|
+
if (!raw.startsWith('@')) {
|
|
19
|
+
return parsed(raw, '--args');
|
|
20
|
+
}
|
|
21
|
+
const path = raw.slice(1);
|
|
22
|
+
let text;
|
|
23
|
+
try {
|
|
24
|
+
text = readFileSync(path, 'utf8');
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
throw usageError(`Não consegui ler ${path}.`);
|
|
28
|
+
}
|
|
29
|
+
return parsed(text, path);
|
|
30
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { usageError } from '../errors.js';
|
|
3
|
+
const PROPERTIES_PREFIX = 'properties.';
|
|
4
|
+
export function isQuarantineList(value) {
|
|
5
|
+
return Array.isArray(value);
|
|
6
|
+
}
|
|
7
|
+
export function isExternalWrites(value) {
|
|
8
|
+
return typeof value === 'object' && value !== null && typeof value.externalWrites === 'boolean';
|
|
9
|
+
}
|
|
10
|
+
function isProperty(key) {
|
|
11
|
+
return key.startsWith(PROPERTIES_PREFIX) && key.length > PROPERTIES_PREFIX.length;
|
|
12
|
+
}
|
|
13
|
+
function scalar(text) {
|
|
14
|
+
if (text === 'true') {
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
if (text === 'false') {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
return text;
|
|
21
|
+
}
|
|
22
|
+
function fileSection(file, name) {
|
|
23
|
+
const section = file[name];
|
|
24
|
+
if (section === undefined) {
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
if (typeof section !== 'object' || section === null || Array.isArray(section)) {
|
|
28
|
+
throw usageError(`"${name}" no arquivo precisa ser um objeto.`);
|
|
29
|
+
}
|
|
30
|
+
return { ...section };
|
|
31
|
+
}
|
|
32
|
+
export function readFixFile(path) {
|
|
33
|
+
let parsed;
|
|
34
|
+
try {
|
|
35
|
+
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
throw usageError(`Não consegui ler o JSON de ${path}.`, 'O arquivo tem o formato do PATCH: { "values": {...}, "properties": {...} }.');
|
|
39
|
+
}
|
|
40
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
41
|
+
throw usageError('O arquivo precisa ser um objeto JSON.', 'Formato: { "values": {...}, "properties": {...} }.');
|
|
42
|
+
}
|
|
43
|
+
const file = parsed;
|
|
44
|
+
return { values: fileSection(file, 'values'), properties: fileSection(file, 'properties') };
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* `campo=valor` vai para os campos nativos (`values`); `properties.chave=valor` para as propriedades.
|
|
48
|
+
* `true` e `false` viram booleano; o resto é texto (para outro tipo, use `--file`).
|
|
49
|
+
*/
|
|
50
|
+
export function fixFrom(sets, file) {
|
|
51
|
+
const values = { ...file?.values };
|
|
52
|
+
const properties = { ...file?.properties };
|
|
53
|
+
for (const entry of sets) {
|
|
54
|
+
const at = entry.indexOf('=');
|
|
55
|
+
if (at <= 0) {
|
|
56
|
+
throw usageError(`"${entry}" não está no formato campo=valor.`, 'Exemplo: --set cnpj=12345678000190');
|
|
57
|
+
}
|
|
58
|
+
const key = entry.slice(0, at);
|
|
59
|
+
const value = scalar(entry.slice(at + 1));
|
|
60
|
+
const target = isProperty(key) ? properties : values;
|
|
61
|
+
target[isProperty(key) ? key.slice(PROPERTIES_PREFIX.length) : key] = value;
|
|
62
|
+
}
|
|
63
|
+
if (Object.keys(values).length === 0 && Object.keys(properties).length === 0) {
|
|
64
|
+
throw usageError('Nada para corrigir.', 'Use --set campo=valor ou --file <json>.');
|
|
65
|
+
}
|
|
66
|
+
return { values, properties };
|
|
67
|
+
}
|
|
68
|
+
function show(value) {
|
|
69
|
+
return typeof value === 'string' ? value : JSON.stringify(value);
|
|
70
|
+
}
|
|
71
|
+
export function describeItem(item) {
|
|
72
|
+
const fields = [
|
|
73
|
+
...Object.entries(item.record.values).map(([key, value]) => ` ${key}: ${show(value)}`),
|
|
74
|
+
...Object.entries(item.record.properties).map(([key, value]) => ` ${PROPERTIES_PREFIX}${key}: ${show(value)}`)
|
|
75
|
+
];
|
|
76
|
+
return [
|
|
77
|
+
`${item.id} ${item.objectType} execução ${item.runId}`,
|
|
78
|
+
` motivo: ${item.reason}`,
|
|
79
|
+
...(fields.length === 0 ? [] : [' valores:', ...fields])
|
|
80
|
+
];
|
|
81
|
+
}
|
|
82
|
+
export function fixPreview(item, fix) {
|
|
83
|
+
const lines = (kind, prefix) => Object.entries(fix[kind]).map(([key, value]) => `${prefix}${key}: ${show(item.record[kind][key] ?? '(vazio)')} → ${show(value)}`);
|
|
84
|
+
return {
|
|
85
|
+
title: `Corrigir o registro ${item.id} (${item.objectType}) da quarentena`,
|
|
86
|
+
changes: [...lines('values', ''), ...lines('properties', PROPERTIES_PREFIX), 'O registro volta ao Nexo no próximo reprocessamento.']
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
export function describeWrites(writes) {
|
|
90
|
+
const lines = [`Escreve no outro sistema: ${writes.externalWrites ? 'sim' : 'não'}`];
|
|
91
|
+
lines.push(`Hosts confirmados: ${(writes.confirmed?.hosts ?? []).join(', ') || 'nenhum'}`);
|
|
92
|
+
if (writes.needsConfirmation) {
|
|
93
|
+
lines.push('Uma escrita espera a confirmação de uma pessoa.');
|
|
94
|
+
}
|
|
95
|
+
const held = writes.held;
|
|
96
|
+
if (held !== null) {
|
|
97
|
+
lines.push(`Escrita retida ${held.id} (${held.status}), execução ${held.runId}:`, ` ${held.method} ${held.url}`);
|
|
98
|
+
if (held.body !== null) {
|
|
99
|
+
lines.push(` corpo: ${held.body}`);
|
|
100
|
+
}
|
|
101
|
+
if (held.failureNotice !== null) {
|
|
102
|
+
lines.push(` ${held.failureNotice}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return lines;
|
|
106
|
+
}
|
package/dist/connect/runs.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { clientOf, printLine } from '../context.js';
|
|
2
2
|
import { CliError } from '../errors.js';
|
|
3
3
|
import { EXIT_CODES } from '../exit-codes.types.js';
|
|
4
|
+
/** O que se corta na tela; o `--json` traz tudo. */
|
|
5
|
+
export const MAX_OUTPUT_LINES = 20;
|
|
6
|
+
export const MAX_QUARANTINE_ITEMS = 10;
|
|
4
7
|
export const DEFAULT_WAIT = { intervalMs: 2000, timeoutMs: 10 * 60_000 };
|
|
5
8
|
function isRun(value) {
|
|
6
9
|
return typeof value === 'object' && value !== null && typeof value.status === 'string';
|
|
@@ -23,7 +26,7 @@ export async function waitForRun(context, session, ids, wait) {
|
|
|
23
26
|
let run = await fetchRun(context, session, ids.connectorId, ids.runId);
|
|
24
27
|
while (run.status === 'running') {
|
|
25
28
|
if (Date.now() > deadline) {
|
|
26
|
-
throw new CliError('
|
|
29
|
+
throw new CliError('A execução ainda está rodando.', EXIT_CODES.failure, `Acompanhe com \`nexo connect run ${ids.runId}\`.`);
|
|
27
30
|
}
|
|
28
31
|
await pause(wait.intervalMs);
|
|
29
32
|
run = await fetchRun(context, session, ids.connectorId, ids.runId);
|
|
@@ -45,7 +48,46 @@ function failedSteps(steps) {
|
|
|
45
48
|
.slice(0, 10)
|
|
46
49
|
.map((step) => ` ${step.kind} ${step.target ?? ''} → ${step.errorCode ?? String(step.status)}: ${step.message ?? ''}`.trimEnd());
|
|
47
50
|
}
|
|
48
|
-
export function
|
|
51
|
+
export function cut(lines, max, what) {
|
|
52
|
+
return lines.length <= max ? lines : [...lines.slice(0, max), ` … mais ${String(lines.length - max)} ${what} (veja com --json)`];
|
|
53
|
+
}
|
|
54
|
+
function compact(value) {
|
|
55
|
+
return JSON.stringify(value);
|
|
56
|
+
}
|
|
57
|
+
function timeOf(at) {
|
|
58
|
+
return at === undefined || at === null ? '' : `${at.slice(11, 19)} `;
|
|
59
|
+
}
|
|
60
|
+
function logLines(steps) {
|
|
61
|
+
const logs = (steps ?? []).filter((step) => step.kind === 'log');
|
|
62
|
+
if (logs.length === 0) {
|
|
63
|
+
return [];
|
|
64
|
+
}
|
|
65
|
+
const lines = logs.map((log) => ` ${timeOf(log.at)}${log.message ?? ''}${log.data === undefined || log.data === null ? '' : ` ${compact(log.data)}`}`.trimEnd());
|
|
66
|
+
return ['Logs do script:', ...cut(lines, MAX_OUTPUT_LINES, 'logs')];
|
|
67
|
+
}
|
|
68
|
+
function outputLines(output) {
|
|
69
|
+
if (output === undefined || output === null || Object.keys(output).length === 0) {
|
|
70
|
+
return [];
|
|
71
|
+
}
|
|
72
|
+
const lines = JSON.stringify(output, null, 2)
|
|
73
|
+
.split('\n')
|
|
74
|
+
.map((line) => ` ${line}`);
|
|
75
|
+
return ['Resultado da operação:', ...cut(lines, MAX_OUTPUT_LINES, 'linhas')];
|
|
76
|
+
}
|
|
77
|
+
function quarantineLines(planned) {
|
|
78
|
+
if (planned === undefined || planned === null || (planned.total === 0 && planned.items.length === 0)) {
|
|
79
|
+
return [];
|
|
80
|
+
}
|
|
81
|
+
const shown = planned.items.slice(0, MAX_QUARANTINE_ITEMS);
|
|
82
|
+
const lines = shown.map((item) => ` ${item.object} ${item.externalId ?? '-'}: ${item.reason} (${item.code}) ${compact({ ...item.values, ...(item.properties === undefined ? {} : { properties: item.properties }) })}`);
|
|
83
|
+
const total = Math.max(planned.total, planned.items.length);
|
|
84
|
+
return [
|
|
85
|
+
`Iriam para a quarentena (${String(total)}):`,
|
|
86
|
+
...lines,
|
|
87
|
+
...(total > shown.length ? [` … mais ${String(total - shown.length)} (veja com --json)`] : [])
|
|
88
|
+
];
|
|
89
|
+
}
|
|
90
|
+
function headLines(run) {
|
|
49
91
|
const lines = [`Execução ${run.id}: ${run.status}${run.mode === 'dry_run' ? ' (ensaio)' : ''}`];
|
|
50
92
|
if (run.failureReason !== null) {
|
|
51
93
|
lines.push(`Motivo: ${run.failureReason}`);
|
|
@@ -53,18 +95,31 @@ export function describeRun(run) {
|
|
|
53
95
|
if (run.counters !== null && Object.keys(run.counters).length > 0) {
|
|
54
96
|
lines.push(`Contadores: ${JSON.stringify(run.counters)}`);
|
|
55
97
|
}
|
|
56
|
-
lines
|
|
98
|
+
return lines;
|
|
99
|
+
}
|
|
100
|
+
function errorLines(run) {
|
|
57
101
|
const failed = failedSteps(run.steps);
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
102
|
+
return [
|
|
103
|
+
...(failed.length > 0 ? ['Passos com erro:', ...failed] : []),
|
|
104
|
+
...(run.error === null
|
|
105
|
+
? []
|
|
106
|
+
: [`Erro: ${run.error.name ?? 'Error'}: ${run.error.message ?? ''}`, ...(run.error.stack === null ? [] : [run.error.stack])])
|
|
107
|
+
];
|
|
108
|
+
}
|
|
109
|
+
export function describeRun(run, options = {}) {
|
|
110
|
+
const lines = [
|
|
111
|
+
...headLines(run),
|
|
112
|
+
...plannedLines('Escreveria no Nexo:', run.plannedNexoWrites),
|
|
113
|
+
...plannedLines('Escreveria no outro sistema:', run.plannedWrites),
|
|
114
|
+
...errorLines(run)
|
|
115
|
+
];
|
|
116
|
+
if (options.quiet !== true) {
|
|
117
|
+
lines.push(...logLines(run.steps), ...outputLines(run.output), ...quarantineLines(run.plannedQuarantine));
|
|
63
118
|
}
|
|
64
119
|
return lines;
|
|
65
120
|
}
|
|
66
|
-
export function printRun(context, run) {
|
|
67
|
-
for (const line of describeRun(run)) {
|
|
121
|
+
export function printRun(context, run, options = {}) {
|
|
122
|
+
for (const line of describeRun(run, options)) {
|
|
68
123
|
printLine(context, line);
|
|
69
124
|
}
|
|
70
125
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { fetchMe } from '../commands/whoami.js';
|
|
2
|
+
/** O fuso da empresa (`/v1/me`); só se pergunta quando há uma próxima execução para mostrar. */
|
|
3
|
+
export async function companyTimeZone(context, session) {
|
|
4
|
+
return (await fetchMe(context, session)).company.timezone;
|
|
5
|
+
}
|
|
6
|
+
export function formatNextRun(iso, timeZone) {
|
|
7
|
+
const parts = {};
|
|
8
|
+
for (const part of new Intl.DateTimeFormat('pt-BR', {
|
|
9
|
+
timeZone,
|
|
10
|
+
day: '2-digit',
|
|
11
|
+
month: '2-digit',
|
|
12
|
+
hour: '2-digit',
|
|
13
|
+
minute: '2-digit',
|
|
14
|
+
hourCycle: 'h23'
|
|
15
|
+
}).formatToParts(new Date(iso))) {
|
|
16
|
+
parts[part.type] = part.value;
|
|
17
|
+
}
|
|
18
|
+
return `${parts.day ?? ''}/${parts.month ?? ''} ${parts.hour ?? ''}:${parts.minute ?? ''}`;
|
|
19
|
+
}
|
|
20
|
+
export function hasNextRun(rows) {
|
|
21
|
+
return rows.some((row) => typeof row.nextRunAt === 'string');
|
|
22
|
+
}
|
|
23
|
+
/** A linha "Agenda" do `status`; nada quando a resposta é antiga e não traz a agenda. */
|
|
24
|
+
export function scheduleLine(fields, timeZone) {
|
|
25
|
+
if (fields.schedule === undefined) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
if (fields.schedule === null) {
|
|
29
|
+
return 'Agenda: sem agenda.';
|
|
30
|
+
}
|
|
31
|
+
if (typeof fields.nextRunAt === 'string') {
|
|
32
|
+
return `Agenda: ${fields.schedule}. Próxima: ${formatNextRun(fields.nextRunAt, timeZone ?? 'UTC')}${timeZone === null ? ' UTC' : ''}.`;
|
|
33
|
+
}
|
|
34
|
+
if (fields.status === 'paused') {
|
|
35
|
+
return `Agenda: ${fields.schedule} (pausado).`;
|
|
36
|
+
}
|
|
37
|
+
return `Agenda: ${fields.schedule} (não está ligado).`;
|
|
38
|
+
}
|
package/dist/connect/template.js
CHANGED
|
@@ -29,3 +29,26 @@ export const TEMPLATE_TSCONFIG = `${JSON.stringify({
|
|
|
29
29
|
},
|
|
30
30
|
include: ['connector.ts', 'connect-sdk.d.ts']
|
|
31
31
|
}, null, 2)}\n`;
|
|
32
|
+
export const TEMPLATE_README = `# Conector
|
|
33
|
+
|
|
34
|
+
\`connector.ts\` é o código e \`manifest.json\` diz no que ele mexe. Suba com \`nexo connect push -m "o que mudou"\`.
|
|
35
|
+
|
|
36
|
+
## Quando ele roda
|
|
37
|
+
|
|
38
|
+
O gatilho \`cron\` do manifesto tem duas formas. Use uma por gatilho.
|
|
39
|
+
|
|
40
|
+
A cada tanto tempo:
|
|
41
|
+
|
|
42
|
+
\`\`\`json
|
|
43
|
+
{ "type": "cron", "everyMinutes": 60 }
|
|
44
|
+
\`\`\`
|
|
45
|
+
|
|
46
|
+
Em horário fixo, no fuso da empresa (\`at\` aceita um horário ou uma lista; \`days\` é opcional e, sem ele, vale todo dia):
|
|
47
|
+
|
|
48
|
+
\`\`\`json
|
|
49
|
+
{ "type": "cron", "at": "22:00" }
|
|
50
|
+
{ "type": "cron", "at": ["08:00", "18:00"], "days": ["mon", "tue", "wed", "thu", "fri"] }
|
|
51
|
+
\`\`\`
|
|
52
|
+
|
|
53
|
+
A agenda muda no manifesto, com \`nexo connect push\` e \`nexo connect publish\`. \`nexo connect status\` mostra a agenda e a próxima execução.
|
|
54
|
+
`;
|