@aloma.io/integration-sdk 3.8.70 → 3.8.71

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 (118) hide show
  1. package/README.md +15 -2
  2. package/build/internal/connector/server/on-connect/make-oauth.mjs +27 -6
  3. package/build/internal/fetcher/fetcher.d.mts +14 -1
  4. package/build/internal/fetcher/fetcher.mjs +52 -11
  5. package/build/internal/fetcher/oauth-fetcher.d.mts +15 -2
  6. package/build/internal/fetcher/oauth-fetcher.mjs +72 -27
  7. package/build/internal/util/index.d.mts +8 -0
  8. package/build/internal/util/index.mjs +13 -1
  9. package/build/internal/util/jwe/index.mjs +3 -1
  10. package/package.json +8 -3
  11. package/.prettierrc.cjs +0 -8
  12. package/FINDINGS-PLAT-47.md +0 -253
  13. package/MULTI_RESOURCE_GUIDE.md +0 -220
  14. package/OPENAPI_TO_CONNECTOR.md +0 -349
  15. package/examples/hello-world/package.json +0 -25
  16. package/examples/hello-world/src/controller/index.mts +0 -12
  17. package/examples/hello-world/src/index.mts +0 -6
  18. package/examples/hello-world/tsconfig.json +0 -27
  19. package/examples/sample-api.json +0 -325
  20. package/examples/sample-api.yaml +0 -222
  21. package/examples/simple-api.json +0 -39
  22. package/index.js +0 -4
  23. package/src/builder/index.mts +0 -274
  24. package/src/builder/runtime-context.mts +0 -129
  25. package/src/cli.mts +0 -533
  26. package/src/controller/index.mts +0 -278
  27. package/src/index.mts +0 -2
  28. package/src/internal/connector/config.mts +0 -59
  29. package/src/internal/connector/index.mts +0 -53
  30. package/src/internal/connector/metrics.mts +0 -34
  31. package/src/internal/connector/server/index.mts +0 -51
  32. package/src/internal/connector/server/on-connect/decrypt-config.mts +0 -27
  33. package/src/internal/connector/server/on-connect/finish-oauth.mts +0 -109
  34. package/src/internal/connector/server/on-connect/index.mts +0 -162
  35. package/src/internal/connector/server/on-connect/make-oauth.mts +0 -97
  36. package/src/internal/connector/server/on-connect/start-oauth.mts +0 -24
  37. package/src/internal/connector/server/on-message.mts +0 -13
  38. package/src/internal/dispatcher/index.mts +0 -231
  39. package/src/internal/fetcher/fetcher.mts +0 -215
  40. package/src/internal/fetcher/oauth-fetcher.mts +0 -153
  41. package/src/internal/index.mts +0 -3
  42. package/src/internal/util/index.mts +0 -52
  43. package/src/internal/util/jwe/cli.mts +0 -12
  44. package/src/internal/util/jwe/index.mts +0 -72
  45. package/src/internal/websocket/config.mjs +0 -109
  46. package/src/internal/websocket/connection/constants.mjs +0 -25
  47. package/src/internal/websocket/connection/index.mjs +0 -71
  48. package/src/internal/websocket/connection/registration.mjs +0 -42
  49. package/src/internal/websocket/index.mjs +0 -46
  50. package/src/internal/websocket/transport/durable.mjs +0 -71
  51. package/src/internal/websocket/transport/index.mjs +0 -194
  52. package/src/internal/websocket/transport/packet.mjs +0 -54
  53. package/src/internal/websocket/transport/processor.mjs +0 -66
  54. package/src/openapi-to-connector.mts +0 -1648
  55. package/src/testing/fake-aloma.mts +0 -306
  56. package/src/testing/harness.mts +0 -172
  57. package/src/testing/index.mts +0 -15
  58. package/src/testing/keys.mts +0 -19
  59. package/src/testing/network-guard.mts +0 -57
  60. package/src/testing/runtime-connector.mts +0 -50
  61. package/src/testing/vendor-mock.mts +0 -166
  62. package/src/transform/index.mts +0 -544
  63. package/test/MUTATION-entry.md +0 -21
  64. package/test/MUTATION.md +0 -43
  65. package/test/dispatcher-ctx-forwarding.test.mjs +0 -161
  66. package/test/fetcher-query-params.test.mjs +0 -294
  67. package/test/fixtures/transform/basic/expected.json +0 -9
  68. package/test/fixtures/transform/basic/src/controller/abstract.mts +0 -5
  69. package/test/fixtures/transform/basic/src/controller/index.mts +0 -30
  70. package/test/fixtures/transform/basic/tsconfig.json +0 -1
  71. package/test/fixtures/transform/interface-param/src/controller/abstract.mts +0 -5
  72. package/test/fixtures/transform/interface-param/src/controller/index.mts +0 -12
  73. package/test/fixtures/transform/interface-param/tsconfig.json +0 -1
  74. package/test/fixtures/transform/overloads/expected.json +0 -6
  75. package/test/fixtures/transform/overloads/src/controller/abstract.mts +0 -5
  76. package/test/fixtures/transform/overloads/src/controller/index.mts +0 -11
  77. package/test/fixtures/transform/overloads/tsconfig.json +0 -1
  78. package/test/fixtures/transform/tdd-stub/expected.json +0 -8
  79. package/test/fixtures/transform/tdd-stub/src/controller/abstract.mts +0 -6
  80. package/test/fixtures/transform/tdd-stub/src/controller/index.mts +0 -204
  81. package/test/fixtures/transform/tdd-stub/tsconfig.json +0 -1
  82. package/test/fixtures/transform/two-exports/src/controller/abstract.mts +0 -5
  83. package/test/fixtures/transform/two-exports/src/controller/index.mts +0 -9
  84. package/test/fixtures/transform/two-exports/tsconfig.json +0 -1
  85. package/test/fixtures/transform/type-error/src/controller/abstract.mts +0 -5
  86. package/test/fixtures/transform/type-error/src/controller/index.mts +0 -7
  87. package/test/fixtures/transform/type-error/tsconfig.json +0 -1
  88. package/test/fixtures/transform/typed/expected.json +0 -8
  89. package/test/fixtures/transform/typed/src/controller/abstract.mts +0 -5
  90. package/test/fixtures/transform/typed/src/controller/index.mts +0 -13
  91. package/test/fixtures/transform/typed/tsconfig.json +0 -1
  92. package/test/fixtures/transform/visibility/expected.json +0 -9
  93. package/test/fixtures/transform/visibility/src/controller/abstract.mts +0 -5
  94. package/test/fixtures/transform/visibility/src/controller/index.mts +0 -19
  95. package/test/fixtures/transform/visibility/tsconfig.json +0 -1
  96. package/test/harness-connector-smoke.test.mjs +0 -72
  97. package/test/harness.test.mjs +0 -375
  98. package/test/nested-resolver.test.mjs +0 -184
  99. package/test/openapi-generator-bugs.test.mjs +0 -248
  100. package/test/openapi-identifier-sanitise.test.mjs +0 -69
  101. package/test/openapi-nested-paths.test.mjs +0 -100
  102. package/test/openapi-to-connector.test.mts +0 -232
  103. package/test/openapi-ts-compilation.test.mjs +0 -178
  104. package/test/scenarios/README.md +0 -148
  105. package/test/scenarios/complex/expected/controller.mts +0 -271
  106. package/test/scenarios/complex/expected/orders-resource.mts +0 -262
  107. package/test/scenarios/complex/expected/products-resource.mts +0 -237
  108. package/test/scenarios/complex/specs/orders.json +0 -362
  109. package/test/scenarios/complex/specs/products.json +0 -308
  110. package/test/scenarios/simple/expected-controller.mts +0 -60
  111. package/test/scenarios/simple/simple-api.json +0 -39
  112. package/test/scenarios.test.mts +0 -294
  113. package/test/transform.test.mjs +0 -68
  114. package/test/verify-scenarios.mjs +0 -298
  115. package/tools/mutation-run-entry.mjs +0 -52
  116. package/tools/mutation-run.mjs +0 -138
  117. package/tools/run-tests.mjs +0 -64
  118. package/tsconfig.json +0 -27
package/src/cli.mts DELETED
@@ -1,533 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import {Command} from 'commander';
4
- import ChildProcess from 'node:child_process';
5
- import fs from 'node:fs';
6
- import path from 'node:path';
7
- import {fileURLToPath} from 'node:url';
8
- import util from 'node:util';
9
- import {TARGET_DIR} from './builder/index.mjs';
10
- import {notEmpty} from './internal/util/index.mjs';
11
- import JWE from './internal/util/jwe/index.mjs';
12
- import parseTypes from './transform/index.mjs';
13
- import {OpenAPIToConnector} from './openapi-to-connector.mjs';
14
-
15
- const exec = util.promisify(ChildProcess.exec);
16
-
17
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
18
-
19
- const files = [
20
- {name: 'index.mts', dir: 'src/controller'},
21
- {name: 'index.mts', dir: 'src'},
22
- {name: 'package.json', dir: ''},
23
- {name: 'Containerfile', dir: ''},
24
- {name: 'entrypoint.sh', dir: ''},
25
- {name: 'tsconfig.json', dir: ''},
26
- ];
27
-
28
- const extract = ({target, name, connectorId}) => {
29
- const source = `${__dirname}/../template/connector/`;
30
-
31
- if (!fs.existsSync(source)) {
32
- throw new Error(`source ${source} does not exist`);
33
- }
34
-
35
- files.forEach(({name, dir}) => {
36
- if (dir) {
37
- fs.mkdirSync(`${target}/${dir}`, {recursive: true});
38
- }
39
-
40
- const content = fs.readFileSync(`${source}/${dir}/${name}`, {
41
- encoding: 'utf-8',
42
- });
43
- fs.writeFileSync(`${target}/${dir}/${name}`, content);
44
- });
45
-
46
- const content = JSON.parse(fs.readFileSync(`${target}/package.json`, {encoding: 'utf-8'}));
47
-
48
- content.name = name;
49
- content.connectorId = connectorId;
50
-
51
- fs.writeFileSync(`${target}/package.json`, JSON.stringify(content, null, 2));
52
- fs.writeFileSync(
53
- `${target}/.gitignore`,
54
- `.DS_Store
55
- node_modules
56
- build
57
- .env
58
- yarn-error.log`
59
- );
60
- };
61
-
62
- const generateKeys = async ({target}) => {
63
- const jwe = new JWE({});
64
- await jwe.newPair();
65
-
66
- const priv = await jwe.exportPrivateAsBase64();
67
- const pub = await jwe.exportPublicAsBase64();
68
-
69
- const content = `REGISTRATION_TOKEN=
70
- PRIVATE_KEY=${priv}
71
- PUBLIC_KEY=${pub}
72
- `;
73
-
74
- fs.writeFileSync(`${target}/.env`, content);
75
- };
76
-
77
- const program = new Command();
78
-
79
- program
80
- .name('npx @aloma.io/integration-sdk')
81
- .description('aloma.io integration sdk')
82
- .version('0.8.0')
83
- .showHelpAfterError();
84
-
85
- program
86
- .command('create')
87
- .description('Create a new connector project')
88
- .argument('<name>', 'name of the project')
89
- .requiredOption('--connector-id <id>', 'id of the connector')
90
- .action(async (name, options) => {
91
- name = name.replace(/[\/\.]/gi, '');
92
- if (!name) throw new Error('name is empty');
93
-
94
- const target = `${process.cwd()}/${name}`;
95
-
96
- fs.mkdirSync(target);
97
-
98
- console.log('Creating connector ...');
99
- extract({...options, target, name});
100
-
101
- console.log('Generating keys ...');
102
- await generateKeys({target});
103
-
104
- console.log('Installing dependencies ...');
105
- await exec(`cd ${target}; yarn --ignore-engines`);
106
-
107
- console.log('Building ...');
108
- await exec(`cd ${target}; yarn build`);
109
-
110
- console.log(`
111
- Success!
112
-
113
- 1.) Add the connector to a workspace
114
- 2.) Edit ./${name}/.env and insert the registration token
115
- 3.) Start the connector with cd ./${name}/; yarn start`);
116
- });
117
-
118
- program
119
- .command('build')
120
- .description('Build the current connector project')
121
- .action(async (str, options) => {
122
- const {stdout, stderr} = await exec(`rm -rf build; mkdir -p build; `);
123
-
124
- try {
125
- fs.copyFileSync(`${TARGET_DIR}/logo.png`, `${TARGET_DIR}/build/logo.png`);
126
- } catch (e) {
127
- // blank
128
- }
129
-
130
- if (stdout) console.log(stdout);
131
-
132
- new Extractor().extract('./src/controller/index.mts', './build/.controller.json');
133
- });
134
-
135
- program
136
- .command('from-openapi')
137
- .description('Generate a connector controller from an OpenAPI specification')
138
- .argument('<name>', 'name of the connector project')
139
- .requiredOption('--connector-id <id>', 'id of the connector')
140
- .requiredOption('--spec <file>', 'OpenAPI specification file (JSON or YAML)')
141
- .option('--out <file>', 'output file path for the controller', 'src/controller/index.mts')
142
- .option(
143
- '--resource <className>',
144
- 'Generate as a resource class with the specified class name (e.g., CompaniesResource)'
145
- )
146
- .option('--multi-resource', 'Generate multiple resource files + main controller (requires multiple --spec files)')
147
- .option('--controller-only', 'Generate only the controller file, do not create full project structure')
148
- .option('--nested-paths', 'Use dotted namespace paths derived from URL structure (e.g., crm.contacts.getPage)')
149
- .option('--no-build', 'Skip installing dependencies and building the project')
150
- .action(async (name, options) => {
151
- name = name.replace(/[\/\.]/gi, '');
152
- if (!name) throw new Error('name is empty');
153
-
154
- try {
155
- // Read and parse the OpenAPI spec
156
- const specContent = fs.readFileSync(options.spec, 'utf-8');
157
- const spec = OpenAPIToConnector.parseSpec(specContent);
158
-
159
- // Generate the controller from OpenAPI spec
160
- const generatorOptions = {nestedPaths: !!options.nestedPaths};
161
- const generator = new OpenAPIToConnector(spec, name, generatorOptions);
162
- let controllerCode: string;
163
-
164
- if (options.resource) {
165
- console.log(`Generating resource class '${options.resource}' from OpenAPI specification...`);
166
- controllerCode = generator.generateResourceClass(options.resource);
167
- } else {
168
- console.log('Generating controller from OpenAPI specification...');
169
- controllerCode = generator.generateController();
170
- }
171
-
172
- if (options.controllerOnly) {
173
- // Controller-only mode: just generate the controller file
174
- const controllerPath = path.resolve(options.out);
175
- fs.mkdirSync(path.dirname(controllerPath), {recursive: true});
176
- fs.writeFileSync(controllerPath, controllerCode);
177
-
178
- console.log(`\nāœ… Success! Generated controller from OpenAPI specification
179
- šŸ“ Connector name: ${name}
180
- šŸ“Š Found ${generator.getOperationsCount()} operations
181
- šŸ“„ Controller file: ${controllerPath}
182
-
183
- Controller file generated successfully! You can now use it in your existing project.`);
184
- } else {
185
- // Full project mode: create complete project structure
186
- const target = `${process.cwd()}/${name}`;
187
-
188
- // Create the connector project structure
189
- fs.mkdirSync(target);
190
- console.log('Creating connector project...');
191
- extract({...options, target, name});
192
-
193
- // Write the generated controller
194
- const controllerPath = `${target}/${options.out}`;
195
- fs.mkdirSync(path.dirname(controllerPath), {recursive: true});
196
- fs.writeFileSync(controllerPath, controllerCode);
197
-
198
- console.log('Generating keys...');
199
- await generateKeys({target});
200
-
201
- if (options.build !== false) {
202
- console.log('Installing dependencies...');
203
- await exec(`cd ${target}; yarn --ignore-engines`);
204
-
205
- console.log('Building...');
206
- await exec(`cd ${target}; yarn build`);
207
- }
208
-
209
- const nextSteps =
210
- options.build !== false
211
- ? `Next steps:
212
- 1.) Add the connector to a workspace
213
- 2.) Edit ./${name}/.env and insert the registration token
214
- 3.) Implement the actual API calls in each method in ${options.out}
215
- 4.) Start the connector with cd ./${name}/; yarn start`
216
- : `Next steps:
217
- 1.) Install dependencies: cd ./${name}/ && yarn --ignore-engines
218
- 2.) Implement the actual API calls in each method in ${options.out}
219
- 3.) Build the project: yarn build
220
- 4.) Add the connector to a workspace
221
- 5.) Edit ./${name}/.env and insert the registration token
222
- 6.) Start the connector: yarn start`;
223
-
224
- console.log(`\nāœ… Success! Generated connector from OpenAPI specification
225
- šŸ“ Connector name: ${name}
226
- šŸ“Š Found ${generator.getOperationsCount()} operations
227
- šŸ“„ Controller generated: ${options.out}
228
-
229
- ${nextSteps}`);
230
- }
231
- } catch (error) {
232
- console.error('āŒ Error:', error instanceof Error ? error.message : 'Unknown error');
233
-
234
- // Clean up on error (only if we created a project directory)
235
- if (!options.controllerOnly) {
236
- const target = `${process.cwd()}/${name}`;
237
- if (fs.existsSync(target)) {
238
- fs.rmSync(target, {recursive: true, force: true});
239
- }
240
- }
241
-
242
- process.exit(1);
243
- }
244
- });
245
-
246
- class Extractor {
247
- async extract(source, target) {
248
- notEmpty(source, 'source');
249
-
250
- fs.readFileSync(source);
251
- const {text, methods} = await parseTypes(source);
252
-
253
- const packageJson = JSON.parse(
254
- fs.readFileSync(TARGET_DIR + 'package.json', {
255
- encoding: 'utf-8',
256
- })
257
- );
258
-
259
- fs.writeFileSync(
260
- target,
261
- JSON.stringify({
262
- text,
263
- methods,
264
- connectorId: packageJson.connectorId,
265
- version: packageJson.version,
266
- }),
267
- {encoding: 'utf-8'}
268
- );
269
- }
270
- }
271
-
272
- // Multi-resource connector creation
273
- program
274
- .command('create-multi-resource')
275
- .description('Create a multi-resource connector project with multiple OpenAPI specifications')
276
- .argument('<name>', 'name of the connector project')
277
- .requiredOption('--connector-id <id>', 'id of the connector')
278
- .requiredOption(
279
- '--resources <specs>',
280
- 'comma-separated list of "className:specFile" pairs (e.g., "CompaniesResource:companies.json,ContactsResource:contacts.json")'
281
- )
282
- .option('--base-url <url>', 'base URL for the API (if not specified, will be extracted from first OpenAPI spec)')
283
- .option('--nested-paths', 'Use dotted namespace paths derived from URL structure (e.g., crm.contacts.getPage)')
284
- .option('--no-build', 'Skip installing dependencies and building the project')
285
- .action(async (name, options) => {
286
- name = name.replace(/[\/\.]/gi, '');
287
- if (!name) throw new Error('name is empty');
288
-
289
- const target = `${process.cwd()}/${name}`;
290
- const generatorOptions = {nestedPaths: !!options.nestedPaths};
291
-
292
- try {
293
- // Parse resources specification
294
- const resourceSpecs = options.resources.split(',').map((spec) => {
295
- const [className, specFile] = spec.split(':');
296
- if (!className || !specFile) {
297
- throw new Error(`Invalid resource specification: ${spec}. Expected format: "ClassName:specFile"`);
298
- }
299
- return {className: className.trim(), specFile: specFile.trim()};
300
- });
301
-
302
- console.log(`Creating multi-resource connector '${name}' with ${resourceSpecs.length} resources...`);
303
-
304
- // Create the connector project structure
305
- fs.mkdirSync(target);
306
- extract({...options, target, name});
307
-
308
- // Generate each resource
309
- const resources: Array<{className: string; fileName: string}> = [];
310
- const parsedResourceSpecs: Array<{fileName: string; spec: any}> = [];
311
- let baseUrl = options.baseUrl;
312
-
313
- for (const {className, specFile} of resourceSpecs) {
314
- console.log(`Generating ${className} from ${specFile}...`);
315
-
316
- // Read and parse the OpenAPI spec
317
- const specContent = fs.readFileSync(specFile, 'utf-8');
318
- const spec = OpenAPIToConnector.parseSpec(specContent);
319
-
320
- // Extract base URL from first spec if not provided
321
- if (!baseUrl && spec.servers && spec.servers.length > 0) {
322
- baseUrl = spec.servers[0].url;
323
- }
324
-
325
- // Generate the resource class
326
- const generator = new OpenAPIToConnector(spec, name, generatorOptions);
327
- const resourceCode = generator.generateResourceClass(className);
328
-
329
- // Write the resource file
330
- const fileName = className.toLowerCase().replace('resource', '');
331
- const resourcePath = `${target}/src/resources/${fileName}.mts`;
332
- fs.mkdirSync(path.dirname(resourcePath), {recursive: true});
333
- fs.writeFileSync(resourcePath, resourceCode);
334
-
335
- resources.push({className, fileName});
336
- parsedResourceSpecs.push({fileName, spec});
337
- }
338
-
339
- // Generate the main controller
340
- console.log('Generating main controller...');
341
- const firstSpec = OpenAPIToConnector.parseSpec(fs.readFileSync(resourceSpecs[0].specFile, 'utf-8'));
342
- const mainGenerator = new OpenAPIToConnector(firstSpec, name, generatorOptions);
343
- const mainControllerCode = mainGenerator.generateMainController(resources, parsedResourceSpecs);
344
-
345
- // Write the main controller
346
- const controllerPath = `${target}/src/controller/index.mts`;
347
- fs.writeFileSync(controllerPath, mainControllerCode);
348
-
349
- console.log('Generating keys...');
350
- await generateKeys({target});
351
-
352
- if (options.build !== false) {
353
- console.log('Installing dependencies...');
354
- await exec(`cd "${target}"; yarn --ignore-engines`);
355
-
356
- console.log('Building...');
357
- await exec(`cd "${target}"; yarn build`);
358
- }
359
-
360
- const nextSteps =
361
- options.build !== false
362
- ? `Next steps:
363
- 1.) Add the connector to a workspace
364
- 2.) Edit ./${name}/.env and insert the registration token
365
- 3.) Start the connector with cd ./${name}/; yarn start`
366
- : `Next steps:
367
- 1.) Install dependencies: cd ./${name}/ && yarn --ignore-engines
368
- 2.) Build the project: yarn build
369
- 3.) Add the connector to a workspace
370
- 4.) Edit ./${name}/.env and insert the registration token
371
- 5.) Start the connector with yarn start`;
372
-
373
- console.log(`\nāœ… Multi-resource connector created successfully!
374
-
375
- Generated resources:
376
- ${resources.map((r) => `- ${r.className} (${r.fileName}.mts)`).join('\n')}
377
-
378
- Main controller: src/controller/index.mts
379
- ${nextSteps}`);
380
- } catch (error) {
381
- console.error('Error creating multi-resource connector:', (error as Error).message);
382
- process.exit(1);
383
- }
384
- });
385
-
386
- // Add resource to existing project
387
- program
388
- .command('add-resource')
389
- .description('Add a new resource to an existing multi-resource connector')
390
- .argument('<projectPath>', 'path to the existing connector project')
391
- .requiredOption('--className <name>', 'class name for the resource (e.g., DealsResource)')
392
- .requiredOption('--spec <file>', 'OpenAPI specification file for the new resource')
393
- .option('--nested-paths', 'Use dotted namespace paths derived from URL structure (e.g., crm.contacts.getPage)')
394
- .option('--no-build', 'Skip building the project after adding the resource')
395
- .action(async (projectPath, options) => {
396
- const target = path.resolve(projectPath);
397
-
398
- if (!fs.existsSync(target)) {
399
- throw new Error(`Project path does not exist: ${target}`);
400
- }
401
-
402
- const controllerPath = `${target}/src/controller/index.mts`;
403
- if (!fs.existsSync(controllerPath)) {
404
- throw new Error(
405
- `Controller file not found: ${controllerPath}. This might not be a multi-resource connector project.`
406
- );
407
- }
408
-
409
- try {
410
- console.log(`Adding ${options.className} resource to existing project...`);
411
-
412
- // Read and parse the OpenAPI spec
413
- const specContent = fs.readFileSync(options.spec, 'utf-8');
414
- const spec = OpenAPIToConnector.parseSpec(specContent);
415
-
416
- // Generate the resource functions file (new function-based pattern)
417
- const generatorOptions = {nestedPaths: !!options.nestedPaths};
418
- const generator = new OpenAPIToConnector(spec, 'Resource', generatorOptions);
419
- const resourceCode = generator.generateResourceClass(options.className);
420
-
421
- // Write the resource file
422
- const fileName = options.className.toLowerCase().replace('resource', '');
423
- const resourcePath = `${target}/src/resources/${fileName}.mts`;
424
- fs.mkdirSync(path.dirname(resourcePath), {recursive: true});
425
- fs.writeFileSync(resourcePath, resourceCode);
426
-
427
- // Update the main controller to include the new resource
428
- console.log('Updating main controller...');
429
- let controllerContent = fs.readFileSync(controllerPath, 'utf-8');
430
-
431
- // Add import
432
- const importStatement = `import * as ${fileName}Functions from '../resources/${fileName}.mjs';`;
433
- if (!controllerContent.includes(importStatement)) {
434
- // Find the last import and add after it
435
- const importRegex = /^import.*from.*?;$/gm;
436
- const imports = controllerContent.match(importRegex);
437
- if (imports && imports.length > 0) {
438
- const lastImport = imports[imports.length - 1];
439
- controllerContent = controllerContent.replace(lastImport, `${lastImport}\n${importStatement}`);
440
- } else {
441
- // If no imports found, add at the beginning
442
- controllerContent = `${importStatement}\n\n${controllerContent}`;
443
- }
444
- }
445
-
446
- // Add property declaration
447
- const propertyDeclaration = ` ${fileName}: any = {};`;
448
- if (!controllerContent.includes(propertyDeclaration)) {
449
- // Find the existing properties and add the new one
450
- const propertyRegex = /^ \w+: any = \{\};$/gm;
451
- const properties = controllerContent.match(propertyRegex);
452
- if (properties && properties.length > 0) {
453
- const lastProperty = properties[properties.length - 1];
454
- controllerContent = controllerContent.replace(lastProperty, `${lastProperty}\n${propertyDeclaration}`);
455
- } else {
456
- // Add after class declaration
457
- controllerContent = controllerContent.replace(
458
- /^export default class Controller extends AbstractController \{$/gm,
459
- `export default class Controller extends AbstractController {\n${propertyDeclaration}`
460
- );
461
- }
462
- }
463
-
464
- // Add binding in start() method
465
- const bindingStatement = ` this.bindResourceFunctions('${fileName}', ${fileName}Functions);`;
466
- if (!controllerContent.includes(bindingStatement)) {
467
- // Find the existing bindings and add the new one
468
- const bindingRegex = /^ this\.bindResourceFunctions\(.*?\);$/gm;
469
- const bindings = controllerContent.match(bindingRegex);
470
- if (bindings && bindings.length > 0) {
471
- const lastBinding = bindings[bindings.length - 1];
472
- controllerContent = controllerContent.replace(lastBinding, `${lastBinding}\n${bindingStatement}`);
473
- }
474
- }
475
-
476
- // Write the updated controller
477
- fs.writeFileSync(controllerPath, controllerContent);
478
-
479
- // Generate exposed methods for the new resource
480
- console.log('Generating exposed methods for the new resource...');
481
- const resources = [{className: options.className, fileName}];
482
- const resourceSpecs = [{fileName, spec}];
483
-
484
- // Create a temporary generator to generate just the exposed methods for this resource
485
- const tempGenerator = new OpenAPIToConnector(spec, 'temp', generatorOptions);
486
- const exposedMethods = tempGenerator.generateExposedResourceMethods(resources, resourceSpecs);
487
-
488
- // Add the exposed methods to the controller, deduplicating by method name
489
- if (exposedMethods.trim()) {
490
- controllerContent = fs.readFileSync(controllerPath, 'utf-8');
491
-
492
- // Extract existing method names from controller (async 'method.name' pattern)
493
- const existingNames = new Set(
494
- (controllerContent.match(/async\s+['"]([^'"]+)['"]\s*\(/g) || [])
495
- .map(m => m.match(/['"]([^'"]+)['"]/)?.[1])
496
- .filter(Boolean)
497
- );
498
-
499
- // Filter exposed methods to only include new ones
500
- const methodBlocks = exposedMethods.split(/(?=\n async ['"])/);
501
- const newMethods = methodBlocks.filter(block => {
502
- const nameMatch = block.match(/async\s+['"]([^'"]+)['"]\s*\(/);
503
- return !nameMatch || !existingNames.has(nameMatch[1]);
504
- }).join('');
505
-
506
- if (newMethods.trim()) {
507
- const lastBrace = controllerContent.lastIndexOf('}');
508
- if (lastBrace !== -1) {
509
- const beforeBrace = controllerContent.substring(0, lastBrace);
510
- const afterBrace = controllerContent.substring(lastBrace);
511
- const updatedContent = `${beforeBrace}\n${newMethods}\n${afterBrace}`;
512
- fs.writeFileSync(controllerPath, updatedContent);
513
- }
514
- }
515
- }
516
-
517
- console.log(`āœ… Resource ${options.className} added successfully!`);
518
- console.log(`šŸ“„ Resource functions: ${resourcePath}`);
519
- console.log(`šŸŽ›ļø Controller updated: ${controllerPath}`);
520
- console.log(`\nšŸŽ‰ The new resource is fully integrated and ready to use!`);
521
-
522
- if (options.build !== false) {
523
- console.log('\nšŸ”Ø Building project...');
524
- await exec(`cd "${target}"; yarn build`);
525
- console.log('āœ… Build complete!');
526
- }
527
- } catch (error) {
528
- console.error('āŒ Error adding resource:', (error as Error).message);
529
- process.exit(1);
530
- }
531
- });
532
-
533
- program.parse();