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