@waffo/pancake-cli 0.0.0-stage → 0.0.1-rc.2
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/CHANGELOG.md +49 -0
- package/CONTRIBUTING.md +38 -0
- package/LICENSE +21 -0
- package/README.md +230 -2
- package/SECURITY.md +23 -0
- package/SKILL.md +110 -0
- package/dist/adapters/browser-login.js +210 -0
- package/dist/adapters/config.js +180 -0
- package/dist/adapters/files.js +222 -0
- package/dist/adapters/loopback-forward.js +33 -0
- package/dist/adapters/operations.js +89 -0
- package/dist/adapters/pancake/client.js +235 -0
- package/dist/adapters/pancake/conflict-error.js +18 -0
- package/dist/adapters/pancake/graphql-errors.js +41 -0
- package/dist/adapters/pancake/http-error-reason.js +12 -0
- package/dist/adapters/pancake/queries.js +9 -0
- package/dist/adapters/pancake/safe-reason.js +23 -0
- package/dist/adapters/system-process.js +12 -0
- package/dist/application/action-auth.js +7 -0
- package/dist/application/action-result.js +40 -0
- package/dist/application/api-actions.js +80 -0
- package/dist/application/api-reads.js +56 -0
- package/dist/application/auth-context.js +34 -0
- package/dist/application/auth.js +115 -0
- package/dist/application/confirmation.js +14 -0
- package/dist/application/diagnostics.js +48 -0
- package/dist/application/dispatch.js +109 -0
- package/dist/application/idempotency.js +8 -0
- package/dist/application/listen.js +147 -0
- package/dist/application/local.js +35 -0
- package/dist/application/product-verification.js +96 -0
- package/dist/application/products.js +70 -0
- package/dist/application/queries.js +26 -0
- package/dist/application/read-handlers.js +30 -0
- package/dist/application/read-operation.js +30 -0
- package/dist/application/webhooks.js +56 -0
- package/dist/application/write-operation.js +26 -0
- package/dist/cli/guidance.js +29 -0
- package/dist/cli/human-output.js +44 -0
- package/dist/cli/input.js +62 -0
- package/dist/cli/listen-output.js +10 -0
- package/dist/cli/login-prompt.js +66 -0
- package/dist/cli/output.js +43 -0
- package/dist/cli/run.js +128 -0
- package/dist/commands/action-definitions.js +100 -0
- package/dist/commands/action-previews.js +12 -0
- package/dist/commands/action-schemas.js +47 -0
- package/dist/commands/action-values.js +11 -0
- package/dist/commands/api-coverage.js +25 -0
- package/dist/commands/checkout-action-schema.js +25 -0
- package/dist/commands/discount-definitions.js +47 -0
- package/dist/commands/discount-preview.js +17 -0
- package/dist/commands/discount-schemas.js +39 -0
- package/dist/commands/discount-validation.js +17 -0
- package/dist/commands/listen-input.js +12 -0
- package/dist/commands/operation-impact.js +16 -0
- package/dist/commands/product-action-schemas.js +26 -0
- package/dist/commands/product-preview.js +5 -0
- package/dist/commands/read-definitions.js +92 -0
- package/dist/commands/read-query.js +49 -0
- package/dist/commands/read-schemas.js +17 -0
- package/dist/commands/registry.js +45 -0
- package/dist/commands/schemas.js +94 -0
- package/dist/commands/webhook-preview.js +3 -0
- package/dist/contracts/action-routes.js +7 -0
- package/dist/contracts/command.js +1 -0
- package/dist/contracts/errors.js +26 -0
- package/dist/contracts/impact.js +1 -0
- package/dist/contracts/listen.js +1 -0
- package/dist/contracts/loopback-target.js +14 -0
- package/dist/contracts/types.js +1 -0
- package/dist/index.js +20 -0
- package/docs/api-coverage.md +154 -0
- package/docs/usage.md +458 -0
- package/package.json +60 -4
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
2
|
+
import { readdir, unlink } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { atomicJson, hasCode, readJson, protectDirectory, privateDirectory, withDirectoryLock } from "./files.js";
|
|
5
|
+
import { argumentError, CliError } from "../contracts/errors.js";
|
|
6
|
+
export function inputFingerprint(input) {
|
|
7
|
+
const canonical = (value) => {
|
|
8
|
+
if (Array.isArray(value))
|
|
9
|
+
return value.map(canonical);
|
|
10
|
+
if (value && typeof value === 'object')
|
|
11
|
+
return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, canonical(v)]));
|
|
12
|
+
return value;
|
|
13
|
+
};
|
|
14
|
+
return createHash('sha256').update(JSON.stringify(canonical(input))).digest('hex');
|
|
15
|
+
}
|
|
16
|
+
export class OperationStore {
|
|
17
|
+
directory;
|
|
18
|
+
root;
|
|
19
|
+
constructor(root) { this.root = root; this.directory = join(root, 'operations'); }
|
|
20
|
+
async show(id) {
|
|
21
|
+
await protectDirectory(this.root);
|
|
22
|
+
await protectDirectory(this.directory);
|
|
23
|
+
return this.readRecord(id);
|
|
24
|
+
}
|
|
25
|
+
async readRecord(id) {
|
|
26
|
+
if (!/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(id))
|
|
27
|
+
throw argumentError('Invalid operation ID.');
|
|
28
|
+
const record = await readJson(join(this.directory, `${id}.json`));
|
|
29
|
+
if (!record)
|
|
30
|
+
throw new CliError('NOT_FOUND', 'Operation not found.');
|
|
31
|
+
if (record.operationRecordVersion !== 1)
|
|
32
|
+
throw new CliError('OPERATION_VERSION_UNSUPPORTED', 'Unsupported operation record version; it will not be overwritten.');
|
|
33
|
+
if (record.operationId !== id || !Array.isArray(record.attempts) || typeof record.startedAt !== 'string')
|
|
34
|
+
throw new CliError('INVALID_CONFIG', 'Invalid operation record.');
|
|
35
|
+
return record;
|
|
36
|
+
}
|
|
37
|
+
async all() {
|
|
38
|
+
await protectDirectory(this.root);
|
|
39
|
+
await protectDirectory(this.directory);
|
|
40
|
+
let entries;
|
|
41
|
+
try {
|
|
42
|
+
entries = await readdir(this.directory);
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (hasCode(error, 'ENOENT'))
|
|
46
|
+
return [];
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
const records = [];
|
|
50
|
+
for (const file of entries.filter(name => /^[0-9a-f-]{36}\.json$/i.test(name)))
|
|
51
|
+
records.push(await this.readRecord(file.slice(0, -5)));
|
|
52
|
+
return records.sort((a, b) => b.startedAt.localeCompare(a.startedAt));
|
|
53
|
+
}
|
|
54
|
+
async list(limit = 20) { return (await this.all()).slice(0, limit); }
|
|
55
|
+
async begin(input) {
|
|
56
|
+
await privateDirectory(this.root);
|
|
57
|
+
return withDirectoryLock(this.directory, async () => {
|
|
58
|
+
const records = await this.all();
|
|
59
|
+
if (input.idempotencyKey) {
|
|
60
|
+
const existing = records.find(record => record.idempotencyKey === input.idempotencyKey);
|
|
61
|
+
if (existing)
|
|
62
|
+
throw new CliError('OPERATION_EXISTS', 'This idempotency key already has a local operation. It will not be replayed.', { details: { operationId: existing.operationId }, recovery: 'Inspect operations show, then query the remote resource. Do not create a new key to retry an unknown result.' });
|
|
63
|
+
}
|
|
64
|
+
const expired = records.filter(record => ['completed', 'rejected'].includes(record.outcome) && Date.now() - Date.parse(record.startedAt) > 30 * 86400000);
|
|
65
|
+
for (const record of expired)
|
|
66
|
+
await unlink(join(this.directory, `${record.operationId}.json`));
|
|
67
|
+
const retained = records.filter(record => !expired.includes(record));
|
|
68
|
+
const disposable = retained.filter(record => !record.idempotencyKey && ['completed', 'rejected'].includes(record.outcome)).reverse();
|
|
69
|
+
const removeCount = Math.max(0, retained.length - 999);
|
|
70
|
+
const rotated = disposable.slice(0, removeCount);
|
|
71
|
+
for (const record of rotated)
|
|
72
|
+
await unlink(join(this.directory, `${record.operationId}.json`));
|
|
73
|
+
if (retained.length - rotated.length >= 1000)
|
|
74
|
+
throw new CliError('OPERATION_STORAGE_FULL', 'Operation storage reached 1000 records; unresolved records are retained.', { recovery: 'Export needed diagnostics and resolve pending operations before explicitly archiving local records.' });
|
|
75
|
+
const record = { operationRecordVersion: 1, operationId: randomUUID(), ...input, startedAt: new Date().toISOString(), outcome: 'unknown', attempts: [] };
|
|
76
|
+
await atomicJson(join(this.directory, `${record.operationId}.json`), record);
|
|
77
|
+
return record;
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
async finish(id, patch) {
|
|
81
|
+
await protectDirectory(this.root);
|
|
82
|
+
return withDirectoryLock(this.directory, async () => {
|
|
83
|
+
const previous = await this.readRecord(id);
|
|
84
|
+
const record = { ...previous, outcome: patch.outcome, finishedAt: new Date().toISOString(), ...(patch.resourceId ? { resourceId: patch.resourceId } : {}), ...(patch.errorCode ? { errorCode: patch.errorCode } : {}), attempts: patch.attempts ?? previous.attempts };
|
|
85
|
+
await atomicJson(join(this.directory, `${id}.json`), record);
|
|
86
|
+
return record;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { createHash, createPrivateKey, randomUUID, sign } from 'node:crypto';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { DEFAULT_API_ORIGIN, productCreateEndpoint, webhookEndpoint } from "../../contracts/action-routes.js";
|
|
4
|
+
import { CliError } from "../../contracts/errors.js";
|
|
5
|
+
import { serviceOrigin } from "../browser-login.js";
|
|
6
|
+
import { readPrivateKey } from "../files.js";
|
|
7
|
+
import { ME_QUERY, PRODUCT_QUERIES, STORES_QUERY, WEBHOOKS_QUERY, WEBHOOK_SECRETS_QUERY } from "./queries.js";
|
|
8
|
+
import { graphqlValidationError } from "./graphql-errors.js";
|
|
9
|
+
import { conflictError } from "./conflict-error.js";
|
|
10
|
+
import { httpErrorReason } from "./http-error-reason.js";
|
|
11
|
+
export function parsePrivateKey(raw) {
|
|
12
|
+
let value = raw.trim().replace(/\\n/g, '\n');
|
|
13
|
+
if (!value.startsWith('-----BEGIN'))
|
|
14
|
+
value = `-----BEGIN PRIVATE KEY-----\n${value.replace(/\s/g, '')}\n-----END PRIVATE KEY-----`;
|
|
15
|
+
try {
|
|
16
|
+
const key = createPrivateKey(value);
|
|
17
|
+
if (key.asymmetricKeyType !== 'rsa')
|
|
18
|
+
throw new Error('RSA required');
|
|
19
|
+
return key;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
throw new CliError('INVALID_KEY', 'A valid RSA private key in PKCS#8 or PKCS#1 format is required.', { exitCode: 2, stage: 'credentials' });
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function apiError(status, write, reason, requestId, session = false) {
|
|
26
|
+
const codes = { 400: 'INVALID_REQUEST', 401: 'AUTH_FAILED', 403: 'PERMISSION_DENIED', 404: 'NOT_FOUND', 429: 'RATE_LIMITED' };
|
|
27
|
+
const unknown = write && (status >= 500 || status === 409 || (status >= 200 && status < 300));
|
|
28
|
+
const message = unknown ? 'The write result is unknown; do not create a new operation to retry it.' : status === 401 && session ? 'Your login was not accepted. Run login again.' : 'The API rejected or could not complete the request.';
|
|
29
|
+
return new CliError(unknown ? 'OUTCOME_UNKNOWN' : codes[status] ?? 'REMOTE_ERROR', reason ? `${message} Server reason: ${reason}` : message, {
|
|
30
|
+
stage: 'api', outcome: unknown ? 'unknown' : 'rejected', details: { status, ...(requestId ? { requestId } : {}) },
|
|
31
|
+
recovery: unknown ? 'Inspect the operation record and query the affected resource before taking further action.' : 'Check credentials, store access and command input. Run doctor for connection checks.',
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
async function responseJson(response, maximumBytes = 2 * 1024 * 1024) {
|
|
35
|
+
if (!response.body)
|
|
36
|
+
throw new Error('Empty response');
|
|
37
|
+
const reader = response.body.getReader();
|
|
38
|
+
const chunks = [];
|
|
39
|
+
let size = 0;
|
|
40
|
+
try {
|
|
41
|
+
for (;;) {
|
|
42
|
+
const { value, done } = await reader.read();
|
|
43
|
+
if (done)
|
|
44
|
+
break;
|
|
45
|
+
size += value.length;
|
|
46
|
+
if (size > maximumBytes)
|
|
47
|
+
throw new Error('Response too large');
|
|
48
|
+
chunks.push(value);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
await reader.cancel().catch(() => { });
|
|
53
|
+
}
|
|
54
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
55
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
56
|
+
throw new Error('Invalid response');
|
|
57
|
+
return parsed;
|
|
58
|
+
}
|
|
59
|
+
function requestId(response) {
|
|
60
|
+
const value = response.headers.get('x-request-id') ?? response.headers.get('x-context-request-id');
|
|
61
|
+
return value && /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : undefined;
|
|
62
|
+
}
|
|
63
|
+
export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
64
|
+
if (!/^MER_[A-Za-z0-9]+$/.test(credentials.merchantId))
|
|
65
|
+
throw new CliError('INVALID_CONFIG', 'Invalid Merchant ID.', { exitCode: 2 });
|
|
66
|
+
const apiUrl = serviceOrigin(credentials.apiUrl ?? DEFAULT_API_ORIGIN);
|
|
67
|
+
if (credentials.sessionToken && !['test', 'prod'].includes(credentials.environment ?? ''))
|
|
68
|
+
throw new CliError('INVALID_CONFIG', 'Select a valid session environment.', { exitCode: 2 });
|
|
69
|
+
const raw = credentials.privateKey ?? (credentials.privateKeyFile ? await readPrivateKey(credentials.privateKeyFile) : '');
|
|
70
|
+
const key = credentials.sessionToken ? undefined : parsePrivateKey(raw);
|
|
71
|
+
async function post(path, body, idempotencyKey, acknowledgementOnly = false, signal, singleAttempt = false) {
|
|
72
|
+
const serialized = JSON.stringify(body);
|
|
73
|
+
const write = idempotencyKey !== undefined || singleAttempt;
|
|
74
|
+
const deadline = Date.now() + 20000;
|
|
75
|
+
for (let index = 0;; index++) {
|
|
76
|
+
const started = Date.now(), timestamp = Math.floor(started / 1000).toString();
|
|
77
|
+
const canonical = `POST\n${path}\n${timestamp}\n${createHash('sha256').update(serialized).digest('base64')}`;
|
|
78
|
+
const headers = credentials.sessionToken ? { 'Content-Type': 'application/json', Authorization: `Bearer ${credentials.sessionToken}`, 'X-Environment': credentials.environment } : { 'Content-Type': 'application/json', 'X-Merchant-Id': credentials.merchantId, 'X-Timestamp': timestamp, 'X-Signature': sign('RSA-SHA256', Buffer.from(canonical), key).toString('base64') };
|
|
79
|
+
if (idempotencyKey)
|
|
80
|
+
headers['X-Idempotency-Key'] = idempotencyKey;
|
|
81
|
+
const attempt = { attemptId: randomUUID(), endpoint: path, durationMs: 0 };
|
|
82
|
+
let response;
|
|
83
|
+
let envelope;
|
|
84
|
+
try {
|
|
85
|
+
response = await fetchImpl(`${apiUrl}${path}`, { method: 'POST', headers, body: serialized, redirect: 'error', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15000)]) : AbortSignal.timeout(Math.max(1, Math.min(15000, deadline - Date.now()))) });
|
|
86
|
+
attempt.status = response.status;
|
|
87
|
+
attempt.requestId = requestId(response);
|
|
88
|
+
const environment = response.headers.get('x-waffo-environment');
|
|
89
|
+
if (environment === 'test' || environment === 'prod')
|
|
90
|
+
attempt.environment = environment;
|
|
91
|
+
if (response.status === 204 && acknowledgementOnly)
|
|
92
|
+
envelope = { data: {} };
|
|
93
|
+
else if (response.ok)
|
|
94
|
+
envelope = await responseJson(response);
|
|
95
|
+
else
|
|
96
|
+
envelope = await responseJson(response, 16384).catch(() => ({}));
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
attempt.durationMs = Date.now() - started;
|
|
100
|
+
observer(attempt);
|
|
101
|
+
if (!signal?.aborted && !write && index < 2 && Date.now() + 100 < deadline) {
|
|
102
|
+
await delay(50 * (index + 1));
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
throw new CliError(write ? 'OUTCOME_UNKNOWN' : 'NETWORK_ERROR', write ? 'No complete response was received; the write may have succeeded.' : 'No valid API response was received.', {
|
|
106
|
+
stage: 'api', outcome: write ? 'unknown' : 'rejected', recovery: write ? 'Keep this operation ID and inspect the remote resource. Do not retry with a new key.' : 'Check network access and try the read-only command again.',
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
attempt.durationMs = Date.now() - started;
|
|
110
|
+
observer(attempt);
|
|
111
|
+
if (!response.ok) {
|
|
112
|
+
const retryable = response.status === 429 || response.status >= 500;
|
|
113
|
+
const retryHeader = response.headers.get('retry-after');
|
|
114
|
+
const retryMs = retryHeader ? (/^\d+$/.test(retryHeader) ? Number(retryHeader) * 1000 : Math.max(0, Date.parse(retryHeader) - Date.now())) : 100 * (index + 1);
|
|
115
|
+
if (!signal?.aborted && !write && retryable && index < 2 && Number.isFinite(retryMs) && Date.now() + retryMs < deadline) {
|
|
116
|
+
await delay(retryMs);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (response.status === 409) {
|
|
120
|
+
const conflict = conflictError(envelope, [credentials.sessionToken ?? '', raw, headers['X-Signature'] ?? '']);
|
|
121
|
+
if (conflict)
|
|
122
|
+
throw conflict;
|
|
123
|
+
}
|
|
124
|
+
const reason = httpErrorReason(response.status, envelope, [credentials.sessionToken ?? '', raw, headers['X-Signature'] ?? '']);
|
|
125
|
+
throw apiError(response.status, write, reason, attempt.requestId, Boolean(credentials.sessionToken));
|
|
126
|
+
}
|
|
127
|
+
if (Array.isArray(envelope.errors) && envelope.errors.length > 0) {
|
|
128
|
+
if (!write && path === '/v1/graphql' && response.status === 200 && 'query' in body && typeof body.query === 'string') {
|
|
129
|
+
throw graphqlValidationError(envelope.errors, body.query) ?? apiError(response.status, write);
|
|
130
|
+
}
|
|
131
|
+
throw apiError(response.status, write);
|
|
132
|
+
}
|
|
133
|
+
if (idempotencyKey && credentials.sessionToken && attempt.environment !== credentials.environment) {
|
|
134
|
+
throw new CliError('OUTCOME_UNKNOWN', 'The write response did not verify the selected environment. Check the affected resource before taking further action.', {
|
|
135
|
+
stage: 'api', outcome: 'unknown', recovery: 'Do not repeat the write. Inspect the operation record and merchant dashboard.',
|
|
136
|
+
details: { selectedEnvironment: credentials.environment, actualEnvironment: attempt.environment ?? null },
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
if (acknowledgementOnly && envelope.data === null)
|
|
140
|
+
return { data: {}, environment: attempt.environment };
|
|
141
|
+
if (!envelope.data || typeof envelope.data !== 'object' || Array.isArray(envelope.data))
|
|
142
|
+
throw apiError(response.status, write);
|
|
143
|
+
return { data: envelope.data, environment: attempt.environment };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
async function query(query, variables = {}) { return (await post('/v1/graphql', { query, variables })).data; }
|
|
147
|
+
return {
|
|
148
|
+
query,
|
|
149
|
+
async revokeSession() {
|
|
150
|
+
if (!credentials.sessionToken)
|
|
151
|
+
return false;
|
|
152
|
+
let payload;
|
|
153
|
+
try {
|
|
154
|
+
payload = JSON.parse(Buffer.from(credentials.sessionToken.split('.')[1], 'base64url').toString('utf8'));
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
throw new CliError('INVALID_CONFIG', 'Saved session is invalid. Revoke it in Dashboard Security.');
|
|
158
|
+
}
|
|
159
|
+
if (typeof payload.jti !== 'string' || !/^mer_[A-Za-z0-9_-]{16}$/.test(payload.jti))
|
|
160
|
+
throw new CliError('INVALID_CONFIG', 'Saved session ID is invalid. Revoke it in Dashboard Security.');
|
|
161
|
+
try {
|
|
162
|
+
const result = await post('/v1/actions/merchant/sign-out-session', { jti: payload.jti }, undefined, false, undefined, true);
|
|
163
|
+
if (result.data.success !== true)
|
|
164
|
+
throw new Error('Revocation not confirmed');
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
if (error instanceof CliError && error.code === 'AUTH_FAILED')
|
|
169
|
+
return false;
|
|
170
|
+
throw new CliError('LOGOUT_UNCONFIRMED', 'Server logout could not be confirmed. Your saved login was retained. Revoke this CLI session in Dashboard Security, then run logout again.', { stage: 'credentials' });
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
async listen(action, body, signal) {
|
|
174
|
+
if (!['start', 'poll', 'ack', 'stop'].includes(action))
|
|
175
|
+
throw new CliError('INVALID_ARGUMENT', 'Invalid listener action.', { exitCode: 2 });
|
|
176
|
+
try {
|
|
177
|
+
return (await post(`/v1/actions/notification/cli-listen-${action}`, body, undefined, false, signal, true)).data;
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
if (error instanceof CliError && error.code === 'OUTCOME_UNKNOWN')
|
|
181
|
+
throw new CliError('OUTCOME_UNKNOWN', 'The temporary listener request result is unknown.', { stage: 'listen', outcome: 'unknown', recovery: 'The CLI attempts session cleanup when the session ID is known. Otherwise the session expires within 90 seconds without polling.' });
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
},
|
|
185
|
+
async action(path, body, key, acknowledgementOnly = false) {
|
|
186
|
+
if (!/^\/v1\/actions\/[a-z-]+\/[a-z-]+$/.test(path))
|
|
187
|
+
throw new CliError('INVALID_ARGUMENT', 'Invalid action endpoint.', { exitCode: 2 });
|
|
188
|
+
return (await post(path, body, key, acknowledgementOnly)).data;
|
|
189
|
+
},
|
|
190
|
+
async me(signal) {
|
|
191
|
+
const { data, environment } = await post('/v1/graphql', { query: ME_QUERY, variables: {} }, undefined, false, signal);
|
|
192
|
+
const me = data.me;
|
|
193
|
+
if (!me || me.id !== credentials.merchantId)
|
|
194
|
+
throw new CliError('AUTH_FAILED', 'The authenticated merchant could not be verified.', { stage: 'identity' });
|
|
195
|
+
return { id: me.id, ...(environment ? { environment } : {}) };
|
|
196
|
+
},
|
|
197
|
+
async stores(limit, offset) {
|
|
198
|
+
const data = await query(STORES_QUERY, { limit, offset });
|
|
199
|
+
if (!Array.isArray(data.stores))
|
|
200
|
+
throw apiError(200, false);
|
|
201
|
+
return data.stores;
|
|
202
|
+
},
|
|
203
|
+
async product(type, id) {
|
|
204
|
+
const data = await query(PRODUCT_QUERIES[type], { id });
|
|
205
|
+
if (data.product === null)
|
|
206
|
+
return null;
|
|
207
|
+
if (!data.product || typeof data.product !== 'object' || Array.isArray(data.product))
|
|
208
|
+
throw apiError(200, false);
|
|
209
|
+
return data.product;
|
|
210
|
+
},
|
|
211
|
+
async createProduct(type, body, idempotencyKey) {
|
|
212
|
+
const { data } = await post(productCreateEndpoint(type), body, idempotencyKey);
|
|
213
|
+
const product = data.product;
|
|
214
|
+
if (!product || typeof product !== 'object' || Array.isArray(product) || typeof product.id !== 'string' || !/^PROD_[A-Za-z0-9]+$/.test(product.id))
|
|
215
|
+
throw apiError(200, true);
|
|
216
|
+
return product;
|
|
217
|
+
},
|
|
218
|
+
async webhooks(storeId, includeSecret = false) {
|
|
219
|
+
const data = await query(includeSecret ? WEBHOOK_SECRETS_QUERY : WEBHOOKS_QUERY, { storeId });
|
|
220
|
+
const store = data.store;
|
|
221
|
+
if (!store)
|
|
222
|
+
throw new CliError('NOT_FOUND', 'Store not found or not accessible.');
|
|
223
|
+
if (store.id !== storeId || !Array.isArray(store.storeWebhooks))
|
|
224
|
+
throw apiError(200, false);
|
|
225
|
+
return store.storeWebhooks;
|
|
226
|
+
},
|
|
227
|
+
async mutateWebhook(action, body, idempotencyKey) {
|
|
228
|
+
const { data } = await post(webhookEndpoint(action), body, idempotencyKey);
|
|
229
|
+
const webhook = data.webhook;
|
|
230
|
+
if (!webhook || typeof webhook.id !== 'string' || typeof webhook.testMode !== 'boolean' || !Array.isArray(webhook.events))
|
|
231
|
+
throw apiError(200, true);
|
|
232
|
+
return webhook;
|
|
233
|
+
},
|
|
234
|
+
};
|
|
235
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { safeReason } from "./safe-reason.js";
|
|
2
|
+
import { CliError } from "../../contracts/errors.js";
|
|
3
|
+
/** Only a complete business rejection establishes that a write was rejected. */
|
|
4
|
+
export function conflictError(envelope, secrets) {
|
|
5
|
+
if (envelope.data !== null || !Array.isArray(envelope.errors) || !envelope.errors.length || envelope.errors.length > 10)
|
|
6
|
+
return;
|
|
7
|
+
const businessLayers = new Set(['user', 'store', 'product', 'order', 'ticket', 'resource']);
|
|
8
|
+
const errors = envelope.errors;
|
|
9
|
+
if (!errors.every(error => error && typeof error.message === 'string' && error.message.trim() && error.message.length <= 4096 && typeof error.layer === 'string' && businessLayers.has(error.layer)))
|
|
10
|
+
return;
|
|
11
|
+
const reason = safeReason(errors[0].message, secrets);
|
|
12
|
+
if (!reason)
|
|
13
|
+
return;
|
|
14
|
+
return new CliError('CONFLICT', `Operation conflict: ${reason}`, {
|
|
15
|
+
stage: 'api', outcome: 'rejected', details: { status: 409 },
|
|
16
|
+
recovery: 'Resolve the reported conflict in the command input or merchant dashboard before starting another operation.',
|
|
17
|
+
});
|
|
18
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { parse, visit } from 'graphql';
|
|
2
|
+
import { CliError } from "../../contracts/errors.js";
|
|
3
|
+
const name = '[_A-Za-z][_0-9A-Za-z]{0,63}';
|
|
4
|
+
const suggestion = `(?: Did you mean "${name}"\\?)?`;
|
|
5
|
+
const unsupportedField = new RegExp(`^Cannot query field "(${name})" on type "${name}"\\.${suggestion}$`);
|
|
6
|
+
const unsupportedFilter = new RegExp(`^Field "(${name})" is not defined by type "${name}"\\.${suggestion}$`);
|
|
7
|
+
/** Describe known schema mismatches without exposing raw server errors or values. */
|
|
8
|
+
export function graphqlValidationError(errors, query) {
|
|
9
|
+
if (!Array.isArray(errors))
|
|
10
|
+
return;
|
|
11
|
+
const queryFields = new Set();
|
|
12
|
+
const inputFields = new Set();
|
|
13
|
+
try {
|
|
14
|
+
visit(parse(query), {
|
|
15
|
+
Field: node => { queryFields.add(node.name.value); },
|
|
16
|
+
ObjectField: node => { inputFields.add(node.name.value); },
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
const issues = new Set();
|
|
23
|
+
for (const error of errors) {
|
|
24
|
+
if (!error || typeof error !== 'object' || typeof error.message !== 'string')
|
|
25
|
+
continue;
|
|
26
|
+
const field = unsupportedField.exec(error.message)?.[1];
|
|
27
|
+
const filter = unsupportedFilter.exec(error.message)?.[1];
|
|
28
|
+
if (field && queryFields.has(field))
|
|
29
|
+
issues.add(`Unsupported query field: ${field}.`);
|
|
30
|
+
if (filter && inputFields.has(filter))
|
|
31
|
+
issues.add(`Unsupported input field: ${filter}.`);
|
|
32
|
+
if (issues.size === 5)
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
if (!issues.size)
|
|
36
|
+
return;
|
|
37
|
+
return new CliError('INVALID_QUERY', [...issues].join(' '), {
|
|
38
|
+
stage: 'api', details: { status: 200 },
|
|
39
|
+
recovery: 'The query does not match the API schema. Update the CLI or correct a custom query.',
|
|
40
|
+
});
|
|
41
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { safeReason } from "./safe-reason.js";
|
|
2
|
+
const errorLayers = new Set(['gateway', 'user', 'store', 'product', 'order', 'ticket', 'resource']);
|
|
3
|
+
export function httpErrorReason(status, envelope, secrets) {
|
|
4
|
+
if (status === 409 || envelope.data !== null || !Array.isArray(envelope.errors) || envelope.errors.length > 10)
|
|
5
|
+
return;
|
|
6
|
+
const first = envelope.errors[0];
|
|
7
|
+
if (!first || !errorLayers.has(first.layer) || typeof first.message !== 'string' || first.message.length > 4096)
|
|
8
|
+
return;
|
|
9
|
+
if (status >= 500 && first.layer !== 'gateway')
|
|
10
|
+
return;
|
|
11
|
+
return safeReason(first.message, secrets) || undefined;
|
|
12
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export const ME_QUERY = 'query CliIdentity { me { id } }';
|
|
2
|
+
export const STORES_QUERY = 'query CliStores($limit: Int!, $offset: Int!) { stores(limit: $limit, offset: $offset) { id name status slug } }';
|
|
3
|
+
export const WEBHOOKS_QUERY = 'query CliWebhooks($storeId: String!) { store(id: $storeId) { id storeWebhooks { id channel url events testMode createdAt } } }';
|
|
4
|
+
export const WEBHOOK_SECRETS_QUERY = 'query CliWebhookSecrets($storeId: String!) { store(id: $storeId) { id storeWebhooks { id channel url events testMode createdAt secret } } }';
|
|
5
|
+
const productFields = 'id storeId name description status media { type url alt thumbnail } successUrl metadata createdAt updatedAt';
|
|
6
|
+
export const PRODUCT_QUERIES = {
|
|
7
|
+
onetime: `query CliOnetimeProduct($id: String!) { product: onetimeProduct(id: $id) { ${productFields} prices { currency priceInfo { amount taxCategory } } } }`,
|
|
8
|
+
subscription: `query CliSubscriptionProduct($id: String!) { product: subscriptionProduct(id: $id) { ${productFields} prices { currency priceInfo { amount taxCategory trialAmount } } billingPeriod } }`,
|
|
9
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export function safeReason(message, secrets) {
|
|
2
|
+
const clean = (value) => value.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '').replace(/[\r\n\t]/g, ' ').replace(/[\p{Cc}\p{Cf}]/gu, '');
|
|
3
|
+
let text = clean(message);
|
|
4
|
+
for (const secret of secrets.filter(Boolean)) {
|
|
5
|
+
const normalized = secret.replace(/\\n/g, '\n');
|
|
6
|
+
const body = normalized.replace(/-----[^-]+-----/g, '').replace(/\s/g, '');
|
|
7
|
+
for (const value of [secret, normalized, JSON.stringify(normalized).slice(1, -1), body].map(clean).filter(Boolean))
|
|
8
|
+
text = text.split(value).join('[redacted]');
|
|
9
|
+
}
|
|
10
|
+
if (/\b(?:stack trace|SQLSTATE|SELECT .+ FROM|INSERT INTO|Error:|at \S+ \()|[{}<>]/i.test(text))
|
|
11
|
+
return '';
|
|
12
|
+
return text
|
|
13
|
+
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, '[redacted]')
|
|
14
|
+
.replace(/\b(?:customer|buyer|billing|shipping)[_-]?(?:name|address|email|phone)\b\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^,;]+)/gi, '[redacted]')
|
|
15
|
+
.replace(/https?:\/\/[^\s]+/gi, '[redacted]')
|
|
16
|
+
.replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g, '[redacted]')
|
|
17
|
+
.replace(/\+?\d[\d ()-]{7,}\d/g, '[redacted]')
|
|
18
|
+
.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, '[redacted]')
|
|
19
|
+
.replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi, 'Bearer [redacted]')
|
|
20
|
+
.replace(/\b[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g, '[redacted]')
|
|
21
|
+
.replace(/\b(authorization|(?:session|access|refresh|api|private)[_-]?(?:token|key)|token|secret|signature|password)\b\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1=[redacted]')
|
|
22
|
+
.replace(/[\p{Cc}\p{Cf}]/gu, ' ').replace(/\s+/g, ' ').trim().slice(0, 512);
|
|
23
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { win32 } from 'node:path';
|
|
2
|
+
import { CliError } from "../contracts/errors.js";
|
|
3
|
+
export function windowsSystemTool(tool, environment = process.env) {
|
|
4
|
+
const root = environment.SystemRoot ?? environment.SYSTEMROOT;
|
|
5
|
+
if (!root || !/^[A-Za-z]:\\/.test(root) || root.includes('..'))
|
|
6
|
+
throw new CliError('LOCAL_ERROR', 'Windows system directory is unavailable.');
|
|
7
|
+
return win32.join(root, 'System32', tool === 'powershell' ? 'WindowsPowerShell\\v1.0\\powershell.exe' : 'rundll32.exe');
|
|
8
|
+
}
|
|
9
|
+
export function systemProcessEnvironment(environment = process.env) {
|
|
10
|
+
const allowed = new Set(['systemroot', 'windir', 'comspec', 'temp', 'tmp', 'userprofile', 'home', 'path', 'display', 'wayland_display', 'dbus_session_bus_address', 'xdg_runtime_dir', 'xdg_config_home', 'lang', 'lc_all']);
|
|
11
|
+
return Object.fromEntries(Object.entries(environment).filter(([key]) => allowed.has(key.toLowerCase())));
|
|
12
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { CliError } from "../contracts/errors.js";
|
|
2
|
+
export function requireActionAuthentication(authentication, hasSession) {
|
|
3
|
+
if (authentication === 'merchant-rsa' && hasSession)
|
|
4
|
+
throw new CliError('AUTH_METHOD_UNSUPPORTED', 'This command requires RSA API-key login; browser login cannot issue customer session tokens.', {
|
|
5
|
+
exitCode: 2, stage: 'credentials', recovery: 'Run login --key-login with a merchant RSA API key, then run sessions create again.',
|
|
6
|
+
});
|
|
7
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { operationImpact } from "../commands/operation-impact.js";
|
|
2
|
+
import { argumentError, CliError } from "../contracts/errors.js";
|
|
3
|
+
export function actionEndpoint(spec, input) {
|
|
4
|
+
if (typeof spec.endpoint === 'string')
|
|
5
|
+
return spec.endpoint;
|
|
6
|
+
if (input.type !== 'onetime' && input.type !== 'subscription')
|
|
7
|
+
throw argumentError('Provide --type onetime or --type subscription.');
|
|
8
|
+
return spec.endpoint[input.type];
|
|
9
|
+
}
|
|
10
|
+
const publicFields = ['id', 'storeId', 'name', 'status', 'slug', 'createdAt', 'updatedAt', 'billingPeriod', 'orderId', 'recipientId', 'removed', 'action', 'reasonCode', 'requestId', 'semanticStatus'];
|
|
11
|
+
function publicResult(value) {
|
|
12
|
+
const result = Object.fromEntries(publicFields.filter(key => ['string', 'number', 'boolean'].includes(typeof value[key])).map(key => [key, value[key]]));
|
|
13
|
+
if (Array.isArray(value.matchedCategories) && value.matchedCategories.every(item => typeof item === 'string'))
|
|
14
|
+
result.matchedCategories = value.matchedCategories;
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
export function actionResult(spec, data) {
|
|
18
|
+
if (spec.validateResponse && !spec.validateResponse(data))
|
|
19
|
+
throw new CliError('OUTCOME_UNKNOWN', 'The API returned an unexpected action response; the operation may have completed.', { outcome: 'unknown', stage: 'api' });
|
|
20
|
+
if (spec.sensitiveOutput)
|
|
21
|
+
return { exported: true };
|
|
22
|
+
if (spec.verification === 'acknowledgement_only')
|
|
23
|
+
return { acknowledged: true };
|
|
24
|
+
if (spec.projectResponse)
|
|
25
|
+
return spec.projectResponse(data);
|
|
26
|
+
return spec.responseKey ? { [spec.responseKey]: publicResult(data[spec.responseKey]) } : publicResult(data);
|
|
27
|
+
}
|
|
28
|
+
export function priceReplacementWarning(command, input) {
|
|
29
|
+
return command === 'products.update' && input.prices !== undefined
|
|
30
|
+
? 'Supplying prices replaces all existing currencies and their price settings. Omitted currencies are removed. Include every currency you want to keep.'
|
|
31
|
+
: undefined;
|
|
32
|
+
}
|
|
33
|
+
export function actionPreview(spec, input) {
|
|
34
|
+
return { executed: false, validation: 'local', command: spec.definition.id, endpoint: actionEndpoint(spec, input),
|
|
35
|
+
...operationImpact(spec.definition), targetEnvironment: operationImpact(spec.definition).impact === 'test-to-prod' ? 'prod' : null, environmentVerified: false,
|
|
36
|
+
input: spec.previewInput(input),
|
|
37
|
+
requiresPrivateOutput: spec.sensitiveOutput ?? false,
|
|
38
|
+
...(priceReplacementWarning(spec.definition.id, input) ? { warning: priceReplacementWarning(spec.definition.id, input) } : {}),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { requireActionAuthentication } from "./action-auth.js";
|
|
2
|
+
import { operationImpact } from "../commands/operation-impact.js";
|
|
3
|
+
import { requireImpactConfirmation } from "./confirmation.js";
|
|
4
|
+
import { DEFAULT_API_ORIGIN } from "../contracts/action-routes.js";
|
|
5
|
+
import { createIdempotencyKey } from "./idempotency.js";
|
|
6
|
+
import { beginWriteOperation } from "./write-operation.js";
|
|
7
|
+
import { argumentError, CliError } from "../contracts/errors.js";
|
|
8
|
+
import { productPriceMismatch } from "./product-verification.js";
|
|
9
|
+
import { requireWriteEnvironment, credentialContext, contextualError, writeWarning } from "./auth-context.js";
|
|
10
|
+
import { actionEndpoint, actionResult, priceReplacementWarning } from "./action-result.js";
|
|
11
|
+
export async function executeApiAction(spec, input, options, services) {
|
|
12
|
+
const endpoint = actionEndpoint(spec, input);
|
|
13
|
+
const replacementWarning = priceReplacementWarning(spec.definition.id, input);
|
|
14
|
+
const production = operationImpact(spec.definition).impact === 'test-to-prod';
|
|
15
|
+
if (!options.yes)
|
|
16
|
+
throw argumentError(production ? 'This publishes test data to PRODUCTION. Review --dry-run and pass --yes to confirm.' : [replacementWarning, 'Review --dry-run and pass --yes to confirm this API operation.'].filter(Boolean).join(' '));
|
|
17
|
+
if (spec.sensitiveOutput && !options.output)
|
|
18
|
+
throw argumentError('This response contains a token or checkout link. Provide --output with a new private file path.');
|
|
19
|
+
const credentials = await services.credentials(options);
|
|
20
|
+
requireActionAuthentication(spec.authentication, Boolean(credentials.sessionToken));
|
|
21
|
+
const attempts = [];
|
|
22
|
+
const storeId = typeof input.storeId === 'string' ? input.storeId
|
|
23
|
+
: spec.definition.id.startsWith('stores.') && typeof input.id === 'string' ? input.id : undefined;
|
|
24
|
+
const targetResourceId = spec.targetResourceId(input);
|
|
25
|
+
let impact = operationImpact(spec.definition);
|
|
26
|
+
const context = () => ({ ...impact, ...credentialContext(credentials, attempts), storeId, targetResourceId, targetEnvironment: production ? 'prod' : null, ...(replacementWarning ? { priceReplacementWarning: replacementWarning } : {}) });
|
|
27
|
+
const key = createIdempotencyKey(credentials.merchantId, options.idempotencyKey);
|
|
28
|
+
let output;
|
|
29
|
+
try {
|
|
30
|
+
const gateway = await services.gateway(credentials, event => { attempts.push(event); if (options.debug)
|
|
31
|
+
services.diagnostic({ stage: 'api', ...event }); });
|
|
32
|
+
const identity = await gateway.me();
|
|
33
|
+
requireWriteEnvironment(credentials, identity);
|
|
34
|
+
impact = operationImpact(spec.definition, identity.environment);
|
|
35
|
+
requireImpactConfirmation(impact, options);
|
|
36
|
+
if (options.output)
|
|
37
|
+
output = await services.prepareOutput(options.output);
|
|
38
|
+
const { type: _type, ...body } = input;
|
|
39
|
+
const operation = await beginWriteOperation(services.operations, { command: spec.definition.id, impact: impact.impact, cliVersion: services.cliVersion, merchantId: credentials.merchantId,
|
|
40
|
+
storeId, inputHash: services.fingerprint(input), idempotencyKey: key,
|
|
41
|
+
targetResourceId,
|
|
42
|
+
endpoint, apiOrigin: credentials.apiUrl ?? DEFAULT_API_ORIGIN, selectedEnvironment: credentials.sessionToken ? credentials.environment : undefined });
|
|
43
|
+
const meta = { ...context(), operationId: operation.operationId, idempotencyKey: key, verification: spec.verification };
|
|
44
|
+
services.diagnostic({ stage: 'confirmation', command: spec.definition.id, ...meta,
|
|
45
|
+
warning: [replacementWarning, production ? 'This operation publishes TEST data to PRODUCTION.' : writeWarning(attempts)].filter(Boolean).join(' ') });
|
|
46
|
+
let raw, displayed;
|
|
47
|
+
try {
|
|
48
|
+
raw = await gateway.action(endpoint, body, key, spec.verification === 'acknowledgement_only');
|
|
49
|
+
displayed = actionResult(spec, raw);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
throw await operation.failed(error, attempts, meta, 'Inspect operations show and query the affected resource or merchant dashboard before taking further action. Do not replay an unknown operation.');
|
|
53
|
+
}
|
|
54
|
+
const entity = spec.responseKey ? raw[spec.responseKey] : raw;
|
|
55
|
+
const resourceId = spec.resultResourceId(raw, input);
|
|
56
|
+
try {
|
|
57
|
+
await operation.accepted(resourceId, attempts);
|
|
58
|
+
if (spec.definition.id === 'products.update' && resourceId && productPriceMismatch(input, entity, resourceId))
|
|
59
|
+
throw new CliError('PRICE_MISMATCH', 'The API accepted the product update but returned prices different from those requested.');
|
|
60
|
+
if (output)
|
|
61
|
+
await output.commit(`${JSON.stringify(raw, null, 2)}\n`);
|
|
62
|
+
await operation.completed(resourceId, attempts);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
const mismatch = error instanceof CliError && error.code === 'PRICE_MISMATCH';
|
|
66
|
+
const errorCode = mismatch ? 'PRICE_MISMATCH' : 'VERIFICATION_PENDING';
|
|
67
|
+
await operation.accepted(resourceId, attempts, errorCode).catch(() => { });
|
|
68
|
+
throw new CliError(errorCode, mismatch ? error.message : 'The API accepted the operation, but exporting its result or updating the local record failed.', {
|
|
69
|
+
outcome: 'committed_unverified', stage: mismatch ? 'verification' : 'local-persistence', recovery: 'Inspect the output file if present, operation record and merchant dashboard. Do not repeat the operation to recover its response.', details: { ...meta, resourceId: resourceId ?? null },
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
return { data: options.output ? { output: options.output, exported: true } : displayed, meta: { ...meta, ...context(), resourceId: resourceId ?? null, requestId: attempts.at(-1)?.requestId ?? null } };
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
throw contextualError(error, { ...context(), requestId: attempts.at(-1)?.requestId ?? null });
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
await output?.discard().catch(() => { });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { argumentError, CliError } from "../contracts/errors.js";
|
|
2
|
+
import { readOperation } from "./read-operation.js";
|
|
3
|
+
import { Kind, parse } from 'graphql';
|
|
4
|
+
function projectResult(value, selected, scalarListFields) {
|
|
5
|
+
if (value === null)
|
|
6
|
+
return null;
|
|
7
|
+
if (Array.isArray(value))
|
|
8
|
+
return value.map(item => projectResult(item, selected, scalarListFields));
|
|
9
|
+
if (!value || typeof value !== 'object')
|
|
10
|
+
throw new CliError('REMOTE_ERROR', 'The API returned an invalid query object.');
|
|
11
|
+
const object = value;
|
|
12
|
+
return Object.fromEntries(selected.selections.flatMap(field => {
|
|
13
|
+
if (field.kind !== Kind.FIELD)
|
|
14
|
+
throw new CliError('LOCAL_ERROR', 'Named queries must use explicit field selections.');
|
|
15
|
+
const key = field.alias?.value ?? field.name.value;
|
|
16
|
+
if (!Object.hasOwn(object, key))
|
|
17
|
+
return [];
|
|
18
|
+
const current = object[key];
|
|
19
|
+
const scalarList = scalarListFields.includes(field.name.value) && Array.isArray(current) && current.every(item => item === null || ['string', 'number', 'boolean'].includes(typeof item));
|
|
20
|
+
if (!field.selectionSet && current !== null && typeof current === 'object' && !scalarList)
|
|
21
|
+
throw new CliError('REMOTE_ERROR', 'The API returned an unexpected nested value.');
|
|
22
|
+
return [[key, field.selectionSet ? projectResult(current, field.selectionSet, scalarListFields) : current]];
|
|
23
|
+
}));
|
|
24
|
+
}
|
|
25
|
+
export async function executeApiRead(spec, request, options, services) {
|
|
26
|
+
if (spec.sensitiveOutput && !options.output)
|
|
27
|
+
throw argumentError('Arbitrary GraphQL responses may contain secrets. Provide --output with a new private file path.');
|
|
28
|
+
const output = options.output ? await services.prepareOutput(options.output) : undefined;
|
|
29
|
+
try {
|
|
30
|
+
return await readOperation(spec.definition.id, options, services, async (gateway) => {
|
|
31
|
+
const response = await gateway.query(request.query, request.variables);
|
|
32
|
+
if (output) {
|
|
33
|
+
await output.commit(`${JSON.stringify(response, null, 2)}\n`);
|
|
34
|
+
return { output: options.output, exported: true };
|
|
35
|
+
}
|
|
36
|
+
const operation = parse(request.query).definitions.find(item => item.kind === Kind.OPERATION_DEFINITION);
|
|
37
|
+
const data = projectResult(response, operation.selectionSet, spec.scalarListFields ?? []);
|
|
38
|
+
if (spec.definition.id.endsWith('.get')) {
|
|
39
|
+
if (data.item === null)
|
|
40
|
+
throw new CliError('NOT_FOUND', 'The resource was not found or is not accessible.');
|
|
41
|
+
if (!data.item || typeof data.item !== 'object' || Array.isArray(data.item))
|
|
42
|
+
throw new CliError('REMOTE_ERROR', 'The API returned an invalid resource.');
|
|
43
|
+
return { item: data.item };
|
|
44
|
+
}
|
|
45
|
+
if (!Array.isArray(data.items))
|
|
46
|
+
throw new CliError('REMOTE_ERROR', 'The API returned an invalid resource list.');
|
|
47
|
+
if (!spec.definition.options?.some(([flag]) => flag.startsWith('--limit')))
|
|
48
|
+
return { items: data.items };
|
|
49
|
+
const limit = options.limit ?? 20, offset = options.offset ?? 0;
|
|
50
|
+
return { items: data.items, pagination: { limit, offset, hasMore: data.items.length < limit ? false : 'unknown', nextOffset: data.items.length < limit ? null : offset + limit } };
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
await output?.discard().catch(() => { });
|
|
55
|
+
}
|
|
56
|
+
}
|