@aderis-erp/cli 1.0.2 → 1.0.4

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