@aderis-erp/cli 1.0.4 → 1.0.7

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