@aderis-erp/cli 1.0.0

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