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