@aderis-erp/cli 1.1.0 → 1.1.1

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.
@@ -1,1155 +0,0 @@
1
- import { Command, Args, Flags } from '@oclif/core';
2
- import { apiRequest, ApiError, isTextualMediaType, normalizeSortBy } from '../lib/api-client.js';
3
- import { getCurrentContext, getContext, getBaseUrls, hasCredentials, missingCredentialsMessage } from '../lib/config.js';
4
- // Add 'import' action if both create and update exist
5
- const HAS_IMPORT = true;
6
- const HAS_EXPORT = true;
7
- const HAS_CAMT053 = false;
8
- const NESTED_IMPORTS = [];
9
- const SUBCOMMANDS = [...["list", "create", "get", "update", "delete", "journal-coverage"], ...(HAS_IMPORT ? ['import'] : []), ...(HAS_EXPORT ? ['export'] : []), ...NESTED_IMPORTS.map(n => `import-${n}`)];
10
- const ENDPOINTS = {
11
- 'list': { method: 'GET', path: '/v1/tag-configurations', summary: 'Get all tag configurations with pagination', pathParams: [], hasBody: false, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: [] },
12
- 'create': { method: 'POST', path: '/v1/tag-configurations', summary: 'Create a new tag configuration', pathParams: [], hasBody: true, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: ['resourceTypes', 'accountTypes', 'tagIds', 'tagCodes'] },
13
- 'get': { method: 'GET', path: '/v1/tag-configurations/{id}', summary: 'Get a tag configuration by ID', pathParams: ['id'], hasBody: false, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: [] },
14
- 'update': { method: 'PATCH', path: '/v1/tag-configurations/{id}', summary: 'Update a tag configuration', pathParams: ['id'], hasBody: true, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: ['resourceTypes', 'accountTypes', 'tagIds', 'tagCodes'] },
15
- 'delete': { method: 'DELETE', path: '/v1/tag-configurations/{id}', summary: 'Delete a tag configuration', pathParams: ['id'], hasBody: false, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: [] },
16
- 'journal-coverage': { method: 'GET', path: '/v1/tag-configurations/{id}/journal-coverage', summary: 'How much of the journal-line amount in scope carries one of this configuration\'s tags', pathParams: ['id'], hasBody: false, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: [] },
17
- };
18
- export default class TagConfigurations extends Command {
19
- static description = 'Manage tag configurations';
20
- static examples = [
21
- '<%= config.bin %> tag-configurations list',
22
- '<%= config.bin %> tag-configurations get <id>',
23
- '<%= config.bin %> tag-configurations create --data \'{...}\'',
24
- '<%= config.bin %> tag-configurations update <id> --set field=value',
25
- '<%= config.bin %> tag-configurations import --file data.json',
26
- '<%= config.bin %> tag-configurations export --csv > tag-configurations.csv',
27
- ];
28
- static args = {
29
- action: Args.string({ description: 'Action: ' + SUBCOMMANDS.join(', '), required: true }),
30
- id: Args.string({ description: 'Resource ID (for get, update, delete operations)', required: false }),
31
- };
32
- static flags = {
33
- context: Flags.string({ char: 'c', aliases: ['config'], env: 'ADERIS_CONTEXT', description: 'Context to use for this command, overriding the current context (alias: --config)' }),
34
- output: Flags.string({ char: 'o', description: 'Output format (default: table for import, json for other commands)', options: ['json', 'table', 'csv'] }),
35
- table: Flags.boolean({ char: 't', description: 'Output as table (shortcut for --output table)' }),
36
- csv: Flags.boolean({ description: 'Output as CSV (shortcut for --output csv)' }),
37
- data: Flags.string({ char: 'd', description: 'JSON data for request body' }),
38
- file: Flags.string({ char: 'f', description: 'Read request body from file' }),
39
- set: Flags.string({ char: 's', description: 'Set individual field (e.g. --set firstName=John)', multiple: true }),
40
- page: Flags.string({ description: 'Page number' }),
41
- limit: Flags.string({ description: 'Items per page' }),
42
- include: Flags.string({ description: 'Relations to include' }),
43
- search: Flags.string({ description: 'Search term' }),
44
- 'sort-by': Flags.string({ description: 'Sort field(s), comma-separated. Direction (:ASC/:DESC) is optional; date-like fields default to DESC, others to ASC.' }),
45
- filter: Flags.string({ description: 'Filter (e.g. --filter status=ACTIVE). Operators: in:A,B, like:%, gt:, lt:, null:', multiple: true }),
46
- query: Flags.string({ description: 'Additional query params as JSON' }),
47
- fields: Flags.string({ description: 'Comma-separated list of fields to return, applied by the API (e.g. --fields=id,name,status)' }),
48
- sanitize: Flags.boolean({ description: 'Remove null values, audit fields, and duplicate UUIDs from output' }),
49
- 'show-http-request': Flags.boolean({ description: 'Show HTTP request details (method, URL, body)' }),
50
- };
51
- async run() {
52
- const { args, flags } = await this.parse(TagConfigurations);
53
- // Handle import action specially
54
- if (args.action === 'import') {
55
- if (!HAS_IMPORT)
56
- this.error('Import not available for this resource');
57
- await this.runImport(flags);
58
- return;
59
- }
60
- // Handle export action specially
61
- if (args.action === 'export') {
62
- if (!HAS_EXPORT)
63
- this.error('Export not available for this resource');
64
- await this.runExport(flags);
65
- return;
66
- }
67
- // Handle CAMT.053 import specially - sends raw XML
68
- if (args.action === 'import-camt053') {
69
- if (!HAS_CAMT053)
70
- this.error('CAMT.053 import not available for this resource');
71
- await this.runCamt053Import(flags);
72
- return;
73
- }
74
- // Handle nested resource imports (e.g., import-prices)
75
- if (args.action.startsWith('import-')) {
76
- const suffix = args.action.replace('import-', '');
77
- if (NESTED_IMPORTS.includes(suffix)) {
78
- await this.runNestedImport(suffix, args.id, flags);
79
- return;
80
- }
81
- }
82
- const endpoint = ENDPOINTS[args.action];
83
- if (!endpoint)
84
- this.error(`Unknown action: ${args.action}. Available: ${SUBCOMMANDS.join(', ')}`);
85
- let apiPath = endpoint.path;
86
- for (let i = 0; i < endpoint.pathParams.length; i++) {
87
- const param = endpoint.pathParams[i];
88
- let value;
89
- if (i === 0) {
90
- // First path param always comes from positional argument
91
- value = args.id;
92
- if (!value)
93
- this.error('Missing required argument: id. Usage: aderis tag-configurations <action> <id>');
94
- }
95
- else {
96
- const flagName = param.replace(/\./g, '-').replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, '');
97
- value = flags[flagName];
98
- if (!value)
99
- this.error(`Missing required parameter: --${flagName}`);
100
- }
101
- apiPath = apiPath.replace(`{${param}}`, String(value));
102
- }
103
- const context = flags.context ? getContext(flags.context) : getCurrentContext();
104
- if (!context)
105
- this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
106
- if (!hasCredentials(context))
107
- this.error(missingCredentialsMessage(context));
108
- const queryParams = {};
109
- if (flags.page)
110
- queryParams.page = flags.page;
111
- if (flags.limit)
112
- queryParams.limit = flags.limit;
113
- if (flags.include)
114
- queryParams.include = flags.include;
115
- if (flags.search)
116
- queryParams.search = flags.search;
117
- if (flags['sort-by'])
118
- queryParams.sortBy = normalizeSortBy(flags['sort-by']);
119
- if (flags.fields)
120
- queryParams.fields = flags.fields;
121
- if (flags.query) {
122
- try {
123
- Object.assign(queryParams, JSON.parse(flags.query));
124
- }
125
- catch {
126
- this.error('Invalid JSON in --query');
127
- }
128
- }
129
- // Parse --filter flags (e.g., --filter status=ACTIVE becomes filter.status=$eq:ACTIVE)
130
- if (flags.filter && flags.filter.length > 0) {
131
- for (const f of flags.filter) {
132
- const eqIndex = f.indexOf('=');
133
- if (eqIndex === -1)
134
- this.error(`Invalid --filter format: ${f}. Use: --filter key=value`);
135
- const key = f.slice(0, eqIndex);
136
- const value = this.parseFilterValue(f.slice(eqIndex + 1));
137
- const filterKey = `filter.${key}`;
138
- if (filterKey in queryParams) {
139
- // Multiple filters on same field: collect as array
140
- const existing = queryParams[filterKey];
141
- queryParams[filterKey] = Array.isArray(existing) ? [...existing, value] : [existing, value];
142
- }
143
- else {
144
- queryParams[filterKey] = value;
145
- }
146
- }
147
- }
148
- let data;
149
- if (endpoint.isMultipart) {
150
- if (!flags.file)
151
- this.error('Missing required --file flag for file upload');
152
- const fsModule = await import('node:fs');
153
- const pathModule = await import('node:path');
154
- const FormDataLib = (await import('form-data')).default;
155
- const form = new FormDataLib();
156
- form.append('file', fsModule.createReadStream(flags.file), pathModule.basename(flags.file));
157
- // Append --set fields as extra form fields (e.g. --set type=CREDIT_CARD_STATEMENT)
158
- if (flags.set && flags.set.length > 0) {
159
- for (const pair of flags.set) {
160
- const eqIndex = pair.indexOf('=');
161
- if (eqIndex === -1)
162
- this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
163
- form.append(pair.slice(0, eqIndex), pair.slice(eqIndex + 1));
164
- }
165
- }
166
- data = form;
167
- }
168
- else if (endpoint.hasBody) {
169
- // For binary-response endpoints, --file is the output path, not a JSON
170
- // input file — skip the read-as-body branch.
171
- if (flags.file && !endpoint.isBinaryResponse) {
172
- const fsModule = await import('node:fs');
173
- try {
174
- data = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
175
- }
176
- catch {
177
- this.error(`Failed to read file: ${flags.file}`);
178
- }
179
- }
180
- else if (flags.data) {
181
- try {
182
- data = JSON.parse(flags.data);
183
- }
184
- catch {
185
- this.error('Invalid JSON in --data');
186
- }
187
- }
188
- // Apply --set flags (can be combined with --data or --file)
189
- if (flags.set && flags.set.length > 0) {
190
- if (!data)
191
- data = {};
192
- const body = data;
193
- const arrayFields = new Set(endpoint.bodyArrayFields);
194
- for (const pair of flags.set) {
195
- const eqIndex = pair.indexOf('=');
196
- if (eqIndex === -1)
197
- this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
198
- const key = pair.slice(0, eqIndex);
199
- let value = pair.slice(eqIndex + 1);
200
- // Try to parse as JSON for numbers, booleans, arrays, objects
201
- try {
202
- value = JSON.parse(value);
203
- }
204
- catch { /* keep as string */ }
205
- // For top-level keys typed as array in the API schema, split bare
206
- // comma-separated input (e.g. "1171,1170" -> ["1171","1170"]) and
207
- // wrap a lone scalar in a single-element array. Skips when --set
208
- // already provided a JSON array.
209
- const isArrayField = !key.includes('.') && arrayFields.has(key);
210
- if (isArrayField && !Array.isArray(value)) {
211
- if (typeof value === 'string') {
212
- value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
213
- }
214
- else if (value !== undefined && value !== null) {
215
- value = [value];
216
- }
217
- }
218
- // Support nested keys like "address.city"
219
- const keys = key.split('.');
220
- if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
221
- this.error(`Invalid --set key: ${key}`);
222
- }
223
- let obj = body;
224
- for (let i = 0; i < keys.length - 1; i++) {
225
- if (!(keys[i] in obj) || typeof obj[keys[i]] !== 'object') {
226
- obj[keys[i]] = {};
227
- }
228
- obj = obj[keys[i]];
229
- }
230
- obj[keys[keys.length - 1]] = value;
231
- }
232
- }
233
- }
234
- else if (flags.set && flags.set.length > 0) {
235
- // For GET endpoints, --set adds query params
236
- for (const pair of flags.set) {
237
- const eqIndex = pair.indexOf('=');
238
- if (eqIndex === -1)
239
- this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
240
- const key = pair.slice(0, eqIndex);
241
- let value = pair.slice(eqIndex + 1);
242
- try {
243
- value = JSON.parse(value);
244
- }
245
- catch { /* keep as string */ }
246
- queryParams[key] = value;
247
- }
248
- }
249
- // Show HTTP request details if --show-http-request flag is set
250
- if (flags['show-http-request']) {
251
- const baseUrls = getBaseUrls(context.environment);
252
- const queryString = Object.keys(queryParams).length > 0
253
- ? '?' + Object.entries(queryParams).flatMap(([k, v]) => {
254
- const vals = Array.isArray(v) ? v : [v];
255
- return vals.map(val => `${encodeURIComponent(k)}=${encodeURIComponent(String(val))}`);
256
- }).join('&')
257
- : '';
258
- process.stderr.write(`\n${endpoint.method.toUpperCase()} ${baseUrls.api}${apiPath}${queryString}\n`);
259
- if (endpoint.isMultipart) {
260
- process.stderr.write(`Body: [multipart/form-data file upload]\n`);
261
- }
262
- else if (data) {
263
- process.stderr.write(`Body: ${JSON.stringify(data, null, 2)}\n`);
264
- }
265
- process.stderr.write('\n');
266
- }
267
- try {
268
- // Binary response: to -f / --file, or to stdout when it is redirected.
269
- if (endpoint.isBinaryResponse) {
270
- const toStdout = !flags.file;
271
- if (toStdout && process.stdout.isTTY) {
272
- this.error(`Endpoint returns a binary file. Specify the output path with -f / --file (e.g. -f report.xlsx), or redirect stdout to a file.`);
273
- }
274
- const binResponse = await apiRequest(endpoint.method, apiPath, {
275
- params: Object.keys(queryParams).length > 0 ? queryParams : undefined,
276
- data,
277
- contextName: flags.context,
278
- binary: true,
279
- });
280
- const binData = binResponse.data;
281
- const buffer = Buffer.isBuffer(binData)
282
- ? binData
283
- : Buffer.from(binData);
284
- if (toStdout) {
285
- // Nothing else may reach stdout here — it is the file.
286
- process.stdout.write(buffer);
287
- return;
288
- }
289
- const fsModule = await import('node:fs');
290
- fsModule.writeFileSync(flags.file, buffer);
291
- this.log(`Saved ${buffer.length} bytes to ${flags.file}`);
292
- return;
293
- }
294
- let response;
295
- if (endpoint.hasBinaryVariant) {
296
- // This route answers JSON or a file depending on the request body, so the
297
- // bytes are read first and the response's own content-type decides. Asking
298
- // for text here would corrupt an xlsx/pdf before anything could inspect it.
299
- const raw = await apiRequest(endpoint.method, apiPath, {
300
- params: Object.keys(queryParams).length > 0 ? queryParams : undefined,
301
- data,
302
- contextName: flags.context,
303
- binary: true,
304
- });
305
- const rawType = String(raw.headers['content-type'] || '').toLowerCase();
306
- const rawData = raw.data;
307
- const buffer = Buffer.isBuffer(rawData) ? rawData : Buffer.from(rawData);
308
- if (!isTextualMediaType(rawType)) {
309
- if (process.stdout.isTTY) {
310
- this.error(`The API returned ${rawType || 'binary data'}. Redirect stdout to a file, e.g. ... > report.xlsx`);
311
- }
312
- // Nothing else may reach stdout here — it is the file.
313
- process.stdout.write(buffer);
314
- return;
315
- }
316
- response = { data: buffer.toString('utf8'), headers: raw.headers, status: raw.status };
317
- }
318
- else {
319
- response = await apiRequest(endpoint.method, apiPath, {
320
- params: Object.keys(queryParams).length > 0 ? queryParams : undefined,
321
- data,
322
- contextName: flags.context,
323
- acceptAny: true,
324
- });
325
- }
326
- // Check content-type for non-JSON responses (XML, text, etc.)
327
- const contentType = (response.headers['content-type'] || '').toLowerCase();
328
- if (isTextualMediaType(contentType) && !contentType.startsWith('application/json')) {
329
- // Output raw content for XML/text responses (CSV, plain, HTML, etc.)
330
- this.log(String(response.data));
331
- return;
332
- }
333
- // Parse JSON if response came as string (due to acceptAny)
334
- let output = response.data;
335
- if (typeof output === 'string') {
336
- try {
337
- output = JSON.parse(output);
338
- }
339
- catch { /* keep as string */ }
340
- }
341
- // Extract data array from paginated wrapper (e.g., { data: [...], total: 3 })
342
- if (output && typeof output === 'object' && !Array.isArray(output) && 'data' in output && Array.isArray(output.data)) {
343
- output = output.data;
344
- }
345
- // For table/csv on non-array responses, auto-extract the primary array
346
- // e.g., { payments: [...], total: 3 } → extract payments array
347
- if ((flags.table || flags.output === 'table' || flags.csv || flags.output === 'csv')
348
- && output && typeof output === 'object' && !Array.isArray(output)) {
349
- const obj = output;
350
- const arrayKeys = Object.keys(obj).filter(k => Array.isArray(obj[k]));
351
- if (arrayKeys.length === 1) {
352
- output = obj[arrayKeys[0]];
353
- }
354
- }
355
- // Sanitize output if requested
356
- if (flags.sanitize) {
357
- output = this.sanitizeOutput(output);
358
- }
359
- const fieldList = flags.fields?.split(',').map(f => f.trim());
360
- if (flags.csv || flags.output === 'csv')
361
- this.printCsv(output, fieldList);
362
- else if (flags.table || flags.output === 'table')
363
- this.printTable(output, fieldList);
364
- else
365
- this.log(JSON.stringify(output, null, 2));
366
- }
367
- catch (error) {
368
- if (error instanceof ApiError) {
369
- if (error.status === 404)
370
- this.error(error.message);
371
- this.error(`API Error (${error.status}): ${error.message}`);
372
- }
373
- throw error;
374
- }
375
- }
376
- async runImport(flags) {
377
- const context = flags.context ? getContext(flags.context) : getCurrentContext();
378
- if (!context)
379
- this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
380
- if (!hasCredentials(context))
381
- this.error(missingCredentialsMessage(context));
382
- // Get data from file, --data, or --set flags
383
- let items = [];
384
- if (flags.file) {
385
- const fsModule = await import('node:fs');
386
- try {
387
- const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
388
- items = Array.isArray(content) ? content : [content];
389
- }
390
- catch {
391
- this.error(`Failed to read file: ${flags.file}`);
392
- }
393
- }
394
- else if (flags.data) {
395
- try {
396
- const content = JSON.parse(flags.data);
397
- items = Array.isArray(content) ? content : [content];
398
- }
399
- catch {
400
- this.error('Invalid JSON in --data');
401
- }
402
- }
403
- else if (flags.set && flags.set.length > 0) {
404
- const item = {};
405
- const arrayFields = new Set(ENDPOINTS['create']?.bodyArrayFields ?? []);
406
- for (const pair of flags.set) {
407
- const eqIndex = pair.indexOf('=');
408
- if (eqIndex === -1)
409
- this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
410
- const key = pair.slice(0, eqIndex);
411
- let value = pair.slice(eqIndex + 1);
412
- try {
413
- value = JSON.parse(value);
414
- }
415
- catch { /* keep as string */ }
416
- const isArrayField = !key.includes('.') && arrayFields.has(key);
417
- if (isArrayField && !Array.isArray(value)) {
418
- if (typeof value === 'string') {
419
- value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
420
- }
421
- else if (value !== undefined && value !== null) {
422
- value = [value];
423
- }
424
- }
425
- const keys = key.split('.');
426
- if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
427
- this.error(`Invalid --set key: ${key}`);
428
- }
429
- let obj = item;
430
- for (let i = 0; i < keys.length - 1; i++) {
431
- if (!(keys[i] in obj))
432
- obj[keys[i]] = {};
433
- obj = obj[keys[i]];
434
- }
435
- obj[keys[keys.length - 1]] = value;
436
- }
437
- items = [item];
438
- }
439
- else {
440
- this.error('Import requires --file, --data, or --set flags');
441
- }
442
- const createEndpoint = ENDPOINTS['create'];
443
- const updateEndpoint = ENDPOINTS['update'];
444
- if (!createEndpoint || !updateEndpoint) {
445
- this.error('Import requires both create and update endpoints');
446
- }
447
- // Helper to extract identifier from item (id, code, or xxxCode)
448
- const getItemIdentifier = (item) => {
449
- if (item.id)
450
- return String(item.id);
451
- if (item.code)
452
- return String(item.code);
453
- // Look for xxxCode fields (e.g., ledgerCode, accountCode)
454
- for (const key of Object.keys(item)) {
455
- if (key.endsWith('Code') && item[key])
456
- return String(item[key]);
457
- }
458
- // Look for name as fallback
459
- if (item.name)
460
- return String(item.name).slice(0, 30);
461
- return '';
462
- };
463
- const results = [];
464
- // Stream output row-by-row so progress is visible during long imports.
465
- // Pre-compute the identifier column width from the input items so the
466
- // table stays aligned without buffering all rows.
467
- // When stdout is piped (IDE terminals, tee, CI), Node switches to async-buffered
468
- // mode and rows accumulate in the pipe buffer until it fills. Force blocking
469
- // mode so each \n-terminated write flushes immediately.
470
- const stdoutHandle = process.stdout._handle;
471
- if (stdoutHandle?.setBlocking)
472
- stdoutHandle.setBlocking(true);
473
- const outputFormat = flags.output || 'table';
474
- const useCsv = outputFormat === 'csv' || Boolean(flags.csv);
475
- const useJson = outputFormat === 'json';
476
- const statusWidth = 8;
477
- const identifierWidth = Math.max(10, ...items.map(i => getItemIdentifier(i).length));
478
- if (useCsv) {
479
- this.log('status,identifier,id,error');
480
- }
481
- else if (!useJson) {
482
- this.log(`${'status'.padEnd(statusWidth)} ${'identifier'.padEnd(identifierWidth)} error`);
483
- this.log(`${'-'.repeat(statusWidth)} ${'-'.repeat(identifierWidth)} ${'-'.repeat(50)}`);
484
- }
485
- const emitRow = (r) => {
486
- if (useJson)
487
- return;
488
- if (useCsv) {
489
- const err = (r.error || '').replace(/"/g, '""');
490
- this.log(`${r.status},${r.identifier || ''},${r.id || ''},"${err}"`);
491
- }
492
- else {
493
- this.log(`${r.status.padEnd(statusWidth)} ${(r.identifier || '').padEnd(identifierWidth)} ${r.error || ''}`);
494
- }
495
- };
496
- // Server-managed fields the API rejects in create/update bodies. Stripped
497
- // before every request so re-importing a previously-exported payload Just Works.
498
- const STRIP_FIELDS = new Set(['id', '_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy']);
499
- const stripServerFields = (item) => {
500
- const out = {};
501
- for (const [k, v] of Object.entries(item)) {
502
- if (!STRIP_FIELDS.has(k))
503
- out[k] = v;
504
- }
505
- return out;
506
- };
507
- const processItem = async (item) => {
508
- const identifier = getItemIdentifier(item);
509
- const body = stripServerFields(item);
510
- // If the payload carries an id (e.g. re-importing an export), PATCH directly.
511
- // Fall through to POST only on 404 (so a missing record still gets created).
512
- const itemId = typeof item.id === 'string' ? item.id : undefined;
513
- if (itemId) {
514
- try {
515
- const updatePath = updateEndpoint.path.replace('{id}', itemId);
516
- await apiRequest('PATCH', updatePath, {
517
- data: body,
518
- contextName: flags.context,
519
- });
520
- return { status: 'updated', id: itemId, identifier };
521
- }
522
- catch (error) {
523
- if (!(error instanceof ApiError && error.status === 404)) {
524
- const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
525
- return { status: 'error', id: itemId, identifier, error: msg };
526
- }
527
- // 404 → record gone, try create below
528
- }
529
- }
530
- try {
531
- const response = await apiRequest('POST', createEndpoint.path, {
532
- data: body,
533
- contextName: flags.context,
534
- });
535
- const id = response.data?.id;
536
- return { status: 'created', id: id ? String(id) : undefined, identifier };
537
- }
538
- catch (error) {
539
- if (error instanceof ApiError && error.status === 409) {
540
- const errorData = error.data;
541
- const existingId = errorData?.existingId;
542
- if (existingId) {
543
- try {
544
- const updatePath = updateEndpoint.path.replace('{id}', existingId);
545
- await apiRequest('PATCH', updatePath, {
546
- data: body,
547
- contextName: flags.context,
548
- });
549
- return { status: 'updated', id: existingId, identifier };
550
- }
551
- catch (updateError) {
552
- const msg = updateError instanceof ApiError ? updateError.message : String(updateError);
553
- return { status: 'error', id: existingId, identifier, error: `Update failed: ${msg}` };
554
- }
555
- }
556
- return { status: 'error', identifier, error: 'Conflict but no existingId returned' };
557
- }
558
- const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
559
- return { status: 'error', identifier, error: msg };
560
- }
561
- };
562
- // Worker pool: keep N requests in flight at all times. Rows are emitted as
563
- // each request resolves (so output order may differ from input order). The
564
- // summary at the end remains accurate regardless.
565
- const concurrency = 4;
566
- const queue = [...items];
567
- await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
568
- for (;;) {
569
- const item = queue.shift();
570
- if (!item)
571
- return;
572
- const r = await processItem(item);
573
- results.push(r);
574
- emitRow(r);
575
- }
576
- }));
577
- // Summary counts
578
- const created = results.filter(r => r.status === 'created').length;
579
- const updated = results.filter(r => r.status === 'updated').length;
580
- const errors = results.filter(r => r.status === 'error');
581
- if (useJson) {
582
- this.log(JSON.stringify(results, null, 2));
583
- }
584
- // Always show summary at the end
585
- this.log('');
586
- this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
587
- }
588
- async runExport(flags) {
589
- const context = flags.context ? getContext(flags.context) : getCurrentContext();
590
- if (!context)
591
- this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
592
- if (!hasCredentials(context))
593
- this.error(missingCredentialsMessage(context));
594
- const listEndpoint = ENDPOINTS['list'];
595
- if (!listEndpoint)
596
- this.error('Export requires a list endpoint');
597
- const allItems = [];
598
- let page = 1;
599
- const limit = 100;
600
- let hasMore = true;
601
- // Build base query params
602
- const baseParams = {};
603
- if (flags.search)
604
- baseParams.search = flags.search;
605
- if (flags['sort-by'])
606
- baseParams.sortBy = normalizeSortBy(flags['sort-by']);
607
- if (flags.include)
608
- baseParams.include = flags.include;
609
- if (flags.fields)
610
- baseParams.fields = flags.fields;
611
- if (flags.query) {
612
- try {
613
- Object.assign(baseParams, JSON.parse(flags.query));
614
- }
615
- catch {
616
- this.error('Invalid JSON in --query');
617
- }
618
- }
619
- // Parse --filter flags (auto-prepend $eq: if no operator specified)
620
- if (flags.filter && flags.filter.length > 0) {
621
- for (const f of flags.filter) {
622
- const eqIndex = f.indexOf('=');
623
- if (eqIndex === -1)
624
- this.error(`Invalid --filter format: ${f}. Use: --filter key=value`);
625
- const key = f.slice(0, eqIndex);
626
- const value = this.parseFilterValue(f.slice(eqIndex + 1));
627
- const filterKey = `filter.${key}`;
628
- if (filterKey in baseParams) {
629
- const existing = baseParams[filterKey];
630
- baseParams[filterKey] = Array.isArray(existing) ? [...existing, value] : [existing, value];
631
- }
632
- else {
633
- baseParams[filterKey] = value;
634
- }
635
- }
636
- }
637
- // Fetch all pages
638
- process.stderr.write('Exporting...');
639
- while (hasMore) {
640
- const params = { ...baseParams, page, limit };
641
- const response = await apiRequest('GET', listEndpoint.path, {
642
- params,
643
- contextName: flags.context,
644
- });
645
- let items = [];
646
- const data = response.data;
647
- // Handle paginated response format
648
- if (data && typeof data === 'object' && 'data' in data && Array.isArray(data.data)) {
649
- items = data.data;
650
- }
651
- else if (Array.isArray(response.data)) {
652
- items = response.data;
653
- }
654
- allItems.push(...items);
655
- process.stderr.write(` ${allItems.length}`);
656
- // Check if there are more pages
657
- if (items.length < limit) {
658
- hasMore = false;
659
- }
660
- else {
661
- page++;
662
- }
663
- }
664
- process.stderr.write(' done\n');
665
- let output = allItems;
666
- // Sanitize output if requested
667
- if (flags.sanitize) {
668
- output = this.sanitizeOutput(output);
669
- }
670
- // Output in requested format
671
- const fieldList = flags.fields ? flags.fields.split(',').map(f => f.trim()) : undefined;
672
- if (flags.csv || flags.output === 'csv') {
673
- this.printCsv(output, fieldList);
674
- }
675
- else {
676
- this.log(JSON.stringify(output, null, 2));
677
- }
678
- }
679
- async runCamt053Import(flags) {
680
- const context = flags.context ? getContext(flags.context) : getCurrentContext();
681
- if (!context)
682
- this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
683
- if (!hasCredentials(context))
684
- this.error(missingCredentialsMessage(context));
685
- if (!flags.file) {
686
- this.error('CAMT.053 import requires --file (-f) flag with path to XML file');
687
- }
688
- const fsModule = await import('node:fs');
689
- let xmlContent;
690
- try {
691
- xmlContent = fsModule.readFileSync(flags.file, 'utf-8');
692
- }
693
- catch {
694
- this.error(`Failed to read file: ${flags.file}`);
695
- }
696
- const endpoint = ENDPOINTS['import-camt053'];
697
- try {
698
- const response = await apiRequest(endpoint.method, endpoint.path, {
699
- data: xmlContent,
700
- contextName: flags.context,
701
- contentType: 'application/xml',
702
- });
703
- // Extract transactions array and counts from response
704
- let transactions = [];
705
- let imported = 0;
706
- let skipped = 0;
707
- if (response.data && typeof response.data === 'object') {
708
- const data = response.data;
709
- if ('data' in data && Array.isArray(data.data)) {
710
- transactions = data.data;
711
- }
712
- else if ('transactions' in data && Array.isArray(data.transactions)) {
713
- transactions = data.transactions;
714
- }
715
- else if (Array.isArray(response.data)) {
716
- transactions = response.data;
717
- }
718
- if (typeof data.imported === 'number')
719
- imported = data.imported;
720
- if (typeof data.skipped === 'number')
721
- skipped = data.skipped;
722
- }
723
- else if (Array.isArray(response.data)) {
724
- transactions = response.data;
725
- }
726
- if (imported === 0 && skipped === 0 && transactions.length > 0) {
727
- for (const tx of transactions) {
728
- const t = tx;
729
- if (t.status === 'skipped' || t.skipped === true) {
730
- skipped++;
731
- }
732
- else {
733
- imported++;
734
- }
735
- }
736
- if (imported === 0 && skipped === 0) {
737
- imported = transactions.length;
738
- }
739
- }
740
- let output = transactions;
741
- if (flags.sanitize) {
742
- output = this.sanitizeOutput(transactions);
743
- }
744
- const fieldList = flags.fields ? flags.fields.split(',').map(f => f.trim()) : undefined;
745
- if (flags.csv || flags.output === 'csv') {
746
- this.printCsv(output, fieldList);
747
- }
748
- else if (flags.table || flags.output === 'table') {
749
- this.printTable(output, fieldList);
750
- }
751
- else {
752
- this.log(JSON.stringify(output, null, 2));
753
- }
754
- this.log('');
755
- this.log(`Summary: ${imported} imported, ${skipped} skipped`);
756
- }
757
- catch (error) {
758
- if (error instanceof ApiError) {
759
- if (error.status === 404)
760
- this.error(error.message);
761
- this.error(`API Error (${error.status}): ${error.message}`);
762
- }
763
- throw error;
764
- }
765
- }
766
- async runNestedImport(suffix, parentId, flags) {
767
- if (!parentId) {
768
- this.error(`Missing required argument: id. Usage: aderis tag-configurations import-${suffix} <parent-id> --file data.json`);
769
- }
770
- const context = flags.context ? getContext(flags.context) : getCurrentContext();
771
- if (!context)
772
- this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
773
- if (!hasCredentials(context))
774
- this.error(missingCredentialsMessage(context));
775
- // Get data from file, --data, or --set flags
776
- let items = [];
777
- if (flags.file) {
778
- const fsModule = await import('node:fs');
779
- try {
780
- const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
781
- items = Array.isArray(content) ? content : [content];
782
- }
783
- catch {
784
- this.error(`Failed to read file: ${flags.file}`);
785
- }
786
- }
787
- else if (flags.data) {
788
- try {
789
- const content = JSON.parse(flags.data);
790
- items = Array.isArray(content) ? content : [content];
791
- }
792
- catch {
793
- this.error('Invalid JSON in --data');
794
- }
795
- }
796
- else if (flags.set && flags.set.length > 0) {
797
- const item = {};
798
- const arrayFields = new Set(ENDPOINTS[`create-${suffix}`]?.bodyArrayFields ?? []);
799
- for (const pair of flags.set) {
800
- const eqIndex = pair.indexOf('=');
801
- if (eqIndex === -1)
802
- this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
803
- const key = pair.slice(0, eqIndex);
804
- let value = pair.slice(eqIndex + 1);
805
- try {
806
- value = JSON.parse(value);
807
- }
808
- catch { /* keep as string */ }
809
- const isArrayField = !key.includes('.') && arrayFields.has(key);
810
- if (isArrayField && !Array.isArray(value)) {
811
- if (typeof value === 'string') {
812
- value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
813
- }
814
- else if (value !== undefined && value !== null) {
815
- value = [value];
816
- }
817
- }
818
- const keys = key.split('.');
819
- if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
820
- this.error(`Invalid --set key: ${key}`);
821
- }
822
- let obj = item;
823
- for (let i = 0; i < keys.length - 1; i++) {
824
- if (!(keys[i] in obj))
825
- obj[keys[i]] = {};
826
- obj = obj[keys[i]];
827
- }
828
- obj[keys[keys.length - 1]] = value;
829
- }
830
- items = [item];
831
- }
832
- else {
833
- this.error(`Import requires --file, --data, or --set flags`);
834
- }
835
- const createEndpoint = ENDPOINTS[`create-${suffix}`];
836
- const updateEndpoint = ENDPOINTS[`update-${suffix}`];
837
- if (!createEndpoint || !updateEndpoint) {
838
- this.error(`Import requires both create-${suffix} and update-${suffix} endpoints`);
839
- }
840
- // Build the base path with parent ID (first path param)
841
- const firstParam = createEndpoint.pathParams[0];
842
- const basePath = createEndpoint.path.replace(`{${firstParam}}`, parentId);
843
- // Helper to extract identifier from item
844
- const getItemIdentifier = (item) => {
845
- if (item.id)
846
- return String(item.id);
847
- if (item.itemId)
848
- return String(item.itemId);
849
- if (item.code)
850
- return String(item.code);
851
- for (const key of Object.keys(item)) {
852
- if (key.endsWith('Id') && item[key])
853
- return String(item[key]);
854
- if (key.endsWith('Code') && item[key])
855
- return String(item[key]);
856
- }
857
- return '';
858
- };
859
- const results = [];
860
- const stdoutHandle = process.stdout._handle;
861
- if (stdoutHandle?.setBlocking)
862
- stdoutHandle.setBlocking(true);
863
- const outputFormat = flags.output || 'table';
864
- const useCsv = outputFormat === 'csv' || Boolean(flags.csv);
865
- const useJson = outputFormat === 'json';
866
- const statusWidth = 8;
867
- const identifierWidth = Math.max(10, ...items.map(i => getItemIdentifier(i).length));
868
- if (useCsv) {
869
- this.log('status,identifier,id,error');
870
- }
871
- else if (!useJson) {
872
- this.log(`${'status'.padEnd(statusWidth)} ${'identifier'.padEnd(identifierWidth)} error`);
873
- this.log(`${'-'.repeat(statusWidth)} ${'-'.repeat(identifierWidth)} ${'-'.repeat(50)}`);
874
- }
875
- const emitRow = (r) => {
876
- if (useJson)
877
- return;
878
- if (useCsv) {
879
- const err = (r.error || '').replace(/"/g, '""');
880
- this.log(`${r.status},${r.identifier || ''},${r.id || ''},"${err}"`);
881
- }
882
- else {
883
- this.log(`${r.status.padEnd(statusWidth)} ${(r.identifier || '').padEnd(identifierWidth)} ${r.error || ''}`);
884
- }
885
- };
886
- const STRIP_FIELDS = new Set(['id', '_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy']);
887
- const stripServerFields = (item) => {
888
- const out = {};
889
- for (const [k, v] of Object.entries(item)) {
890
- if (!STRIP_FIELDS.has(k))
891
- out[k] = v;
892
- }
893
- return out;
894
- };
895
- const buildUpdatePath = (existingId) => {
896
- const firstUpdateParam = updateEndpoint.pathParams[0];
897
- const nestedIdParam = updateEndpoint.pathParams.find((p, i) => i > 0);
898
- let updatePath = updateEndpoint.path.replace(`{${firstUpdateParam}}`, parentId);
899
- if (nestedIdParam) {
900
- updatePath = updatePath.replace(`{${nestedIdParam}}`, existingId);
901
- }
902
- return updatePath;
903
- };
904
- const processItem = async (item) => {
905
- const identifier = getItemIdentifier(item);
906
- const body = stripServerFields(item);
907
- const itemId = typeof item.id === 'string' ? item.id : undefined;
908
- if (itemId) {
909
- try {
910
- await apiRequest('PATCH', buildUpdatePath(itemId), {
911
- data: body,
912
- contextName: flags.context,
913
- });
914
- return { status: 'updated', id: itemId, identifier };
915
- }
916
- catch (error) {
917
- if (!(error instanceof ApiError && error.status === 404)) {
918
- const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
919
- return { status: 'error', id: itemId, identifier, error: msg };
920
- }
921
- // 404 → fall through and try create
922
- }
923
- }
924
- try {
925
- const response = await apiRequest('POST', basePath, {
926
- data: body,
927
- contextName: flags.context,
928
- });
929
- const id = response.data?.id;
930
- return { status: 'created', id: id ? String(id) : undefined, identifier };
931
- }
932
- catch (error) {
933
- if (error instanceof ApiError && error.status === 409) {
934
- const errorData = error.data;
935
- const existingId = errorData?.existingId || item.id;
936
- if (existingId) {
937
- try {
938
- await apiRequest('PATCH', buildUpdatePath(existingId), {
939
- data: body,
940
- contextName: flags.context,
941
- });
942
- return { status: 'updated', id: existingId, identifier };
943
- }
944
- catch (updateError) {
945
- const msg = updateError instanceof ApiError ? updateError.message : String(updateError);
946
- return { status: 'error', id: existingId, identifier, error: `Update failed: ${msg}` };
947
- }
948
- }
949
- return { status: 'error', identifier, error: 'Conflict but no existingId returned' };
950
- }
951
- const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
952
- return { status: 'error', identifier, error: msg };
953
- }
954
- };
955
- // Worker pool: 4 requests in flight at a time. Rows are emitted as each
956
- // request resolves so output order may differ from input order.
957
- const concurrency = 4;
958
- const queue = [...items];
959
- await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
960
- for (;;) {
961
- const item = queue.shift();
962
- if (!item)
963
- return;
964
- const r = await processItem(item);
965
- results.push(r);
966
- emitRow(r);
967
- }
968
- }));
969
- // Summary counts
970
- const created = results.filter(r => r.status === 'created').length;
971
- const updated = results.filter(r => r.status === 'updated').length;
972
- const errors = results.filter(r => r.status === 'error');
973
- if (useJson) {
974
- this.log(JSON.stringify(results, null, 2));
975
- }
976
- this.log('');
977
- this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
978
- }
979
- parseFilterValue(value) {
980
- // Recognises the nestjs-paginate operator set (with or without the leading $)
981
- // and recursively unwraps chained operators like 'not:null' -> '$not:$null'
982
- // or 'not:like:John' -> '$not:$like:John'. Falls back to '$eq:<value>' when
983
- // no operator prefix is present.
984
- const opRe = /^\$?(and|or|not|eq|gt|gte|in|null|lt|lte|btw|ne|ilike|like|sw|contains)(?::|$)/;
985
- const m = value.match(opRe);
986
- if (!m)
987
- return `\$eq:${value}`;
988
- const op = m[1];
989
- const rest = value.slice(m[0].length);
990
- if (rest === '')
991
- return `\$${op}`;
992
- return opRe.test(rest) ? `\$${op}:${this.parseFilterValue(rest)}` : `\$${op}:${rest}`;
993
- }
994
- sanitizeOutput(data) {
995
- const auditFields = ['_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy'];
996
- const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
997
- const sanitize = (obj, parentUuids = new Set()) => {
998
- if (obj === null || obj === undefined)
999
- return undefined;
1000
- if (Array.isArray(obj)) {
1001
- const result = obj.map(item => sanitize(item, new Set(parentUuids))).filter(item => item !== undefined);
1002
- return result.length > 0 ? result : undefined;
1003
- }
1004
- if (typeof obj === 'object') {
1005
- const input = obj;
1006
- // Use a Map to avoid any prototype-pollution risk on the result object
1007
- const collected = new Map();
1008
- // Collect UUIDs from this level to pass to children
1009
- const currentUuids = new Set(parentUuids);
1010
- for (const [, value] of Object.entries(input)) {
1011
- if (typeof value === 'string' && uuidRegex.test(value)) {
1012
- currentUuids.add(value);
1013
- }
1014
- }
1015
- for (const [key, value] of Object.entries(input)) {
1016
- // Skip prototype-pollution keys
1017
- if (key === '__proto__' || key === 'constructor' || key === 'prototype')
1018
- continue;
1019
- // Skip audit fields
1020
- if (auditFields.includes(key))
1021
- continue;
1022
- // Skip null/undefined values
1023
- if (value === null || value === undefined)
1024
- continue;
1025
- // Skip UUID values that exist in parent
1026
- if (typeof value === 'string' && uuidRegex.test(value) && parentUuids.has(value))
1027
- continue;
1028
- // Recursively sanitize nested objects/arrays
1029
- const sanitized = sanitize(value, currentUuids);
1030
- if (sanitized !== undefined) {
1031
- collected.set(key, sanitized);
1032
- }
1033
- }
1034
- if (collected.size === 0)
1035
- return undefined;
1036
- return Object.fromEntries(collected);
1037
- }
1038
- return obj;
1039
- };
1040
- return sanitize(data) ?? (Array.isArray(data) ? [] : {});
1041
- }
1042
- getColumns(data, fields, flatten = false) {
1043
- const items = Array.isArray(data) ? data : [data];
1044
- if (items.length === 0)
1045
- return { cols: [], items: [] };
1046
- const first = items[0];
1047
- const hiddenFields = ['tenantId', '_type'];
1048
- if (fields) {
1049
- return { cols: fields, items: items };
1050
- }
1051
- // Recursively collect all column paths, flattening objects (but not arrays)
1052
- const collectPaths = (obj, prefix = '') => {
1053
- const paths = [];
1054
- for (const key of Object.keys(obj)) {
1055
- const fullKey = prefix ? `${prefix}.${key}` : key;
1056
- if (hiddenFields.includes(key))
1057
- continue;
1058
- const val = obj[key];
1059
- if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
1060
- // Flatten nested objects (but not arrays)
1061
- if (flatten) {
1062
- paths.push(...collectPaths(val, fullKey));
1063
- }
1064
- // Skip objects when not flattening
1065
- }
1066
- else if (!Array.isArray(val)) {
1067
- // Include primitives (and null)
1068
- paths.push(fullKey);
1069
- }
1070
- // Skip arrays entirely
1071
- }
1072
- return paths;
1073
- };
1074
- // Scan multiple items to discover all columns (handles fields absent/null in first item)
1075
- const cols = collectPaths(first);
1076
- const colSet = new Set(cols);
1077
- const scanCount = Math.min(items.length, 50);
1078
- for (let i = 1; i < scanCount; i++) {
1079
- for (const p of collectPaths(items[i])) {
1080
- if (!colSet.has(p)) {
1081
- cols.push(p);
1082
- colSet.add(p);
1083
- }
1084
- }
1085
- }
1086
- return { cols: flatten ? cols : cols.slice(0, 8), items: items };
1087
- }
1088
- getValue(row, col) {
1089
- if (!col.includes('.'))
1090
- return String(row[col] ?? '');
1091
- const parts = col.split('.');
1092
- // Walk the dot-path; descending through an array branches into every
1093
- // element so leaf values get collected from each one. Multiple leaves are
1094
- // joined with ';' (e.g. dunningReminders.id -> "uuid1;uuid2").
1095
- const walk = (o, idx) => {
1096
- if (idx >= parts.length)
1097
- return [o];
1098
- if (o == null)
1099
- return [];
1100
- if (Array.isArray(o))
1101
- return o.flatMap(item => walk(item, idx));
1102
- if (typeof o === 'object')
1103
- return walk(o[parts[idx]], idx + 1);
1104
- return [];
1105
- };
1106
- return walk(row, 0).filter(v => v !== undefined && v !== null).map(v => String(v)).join(';');
1107
- }
1108
- printTable(data, fields) {
1109
- const { cols, items } = this.getColumns(data, fields);
1110
- if (items.length === 0) {
1111
- this.log('No results');
1112
- return;
1113
- }
1114
- // Calculate column widths
1115
- const widths = cols.map(c => c.length);
1116
- for (const item of items) {
1117
- cols.forEach((col, i) => {
1118
- const val = this.getValue(item, col).slice(0, 40);
1119
- widths[i] = Math.max(widths[i], val.length);
1120
- });
1121
- }
1122
- // Print header
1123
- const header = cols.map((c, i) => c.padEnd(widths[i])).join(' ');
1124
- this.log(header);
1125
- this.log(widths.map(w => '-'.repeat(w)).join(' '));
1126
- // Print rows
1127
- for (const item of items) {
1128
- const row = cols.map((col, i) => {
1129
- const val = this.getValue(item, col).slice(0, 40);
1130
- return val.padEnd(widths[i]);
1131
- }).join(' ');
1132
- this.log(row);
1133
- }
1134
- }
1135
- printCsv(data, fields) {
1136
- const { cols, items } = this.getColumns(data, fields, true); // flatten=true for CSV
1137
- if (items.length === 0) {
1138
- this.log('No results');
1139
- return;
1140
- }
1141
- const escape = (val) => {
1142
- if (val.includes(',') || val.includes('"') || val.includes('\n')) {
1143
- return '"' + val.replace(/"/g, '""') + '"';
1144
- }
1145
- return val;
1146
- };
1147
- // Print header
1148
- this.log(cols.map(escape).join(','));
1149
- // Print rows
1150
- for (const item of items) {
1151
- const row = cols.map(col => escape(this.getValue(item, col)));
1152
- this.log(row.join(','));
1153
- }
1154
- }
1155
- }