@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
@@ -1,298 +0,0 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { fileURLToPath } from 'url';
4
- import { OpenAPIToConnector } from '../build/openapi-to-connector.mjs';
5
-
6
- const __filename = fileURLToPath(import.meta.url);
7
- const __dirname = path.dirname(__filename);
8
-
9
- // Colors for output
10
- const colors = {
11
- green: '\x1b[32m',
12
- red: '\x1b[31m',
13
- yellow: '\x1b[33m',
14
- reset: '\x1b[0m',
15
- cyan: '\x1b[36m'
16
- };
17
-
18
- let passed = 0;
19
- let failed = 0;
20
-
21
- function test(name, fn) {
22
- try {
23
- console.log(`${colors.cyan}Running: ${name}${colors.reset}`);
24
- fn();
25
- console.log(`${colors.green}✓ PASS: ${name}${colors.reset}\n`);
26
- passed++;
27
- } catch (error) {
28
- console.log(`${colors.red}✗ FAIL: ${name}${colors.reset}`);
29
- console.log(`${colors.red} Error: ${error.message}${colors.reset}\n`);
30
- failed++;
31
- }
32
- }
33
-
34
- function expect(actual) {
35
- return {
36
- toEqual: (expected) => {
37
- if (actual !== expected) {
38
- throw new Error(`Expected:\n${expected.slice(0, 200)}...\n\nActual:\n${actual.slice(0, 200)}...`);
39
- }
40
- },
41
- toInclude: (expected) => {
42
- if (!actual.includes(expected)) {
43
- throw new Error(`Expected output to include: "${expected}"\n\nActual output snippet: "${actual.slice(0, 500)}..."`);
44
- }
45
- },
46
- toNotInclude: (expected) => {
47
- if (actual.includes(expected)) {
48
- throw new Error(`Expected output to NOT include: "${expected}"\n\nBut it was found in the output.`);
49
- }
50
- }
51
- };
52
- }
53
-
54
- // Helper function to normalize output
55
- const normalizeOutput = (output) => output
56
- .replace(/\r\n/g, '\n')
57
- .trim();
58
-
59
- console.log(`${colors.yellow}🧪 Running Scenario Fixture Tests${colors.reset}\n`);
60
-
61
- // Test 1: Simple Scenario
62
- test('Simple Scenario - should generate expected output', () => {
63
- // Read input spec
64
- const specPath = path.join(__dirname, 'scenarios/simple/simple-api.json');
65
- const specContent = fs.readFileSync(specPath, 'utf-8');
66
- const spec = OpenAPIToConnector.parseSpec(specContent);
67
-
68
- // Read expected output
69
- const expectedPath = path.join(__dirname, 'scenarios/simple/expected-controller.mts');
70
- const expectedOutput = fs.readFileSync(expectedPath, 'utf-8');
71
-
72
- // Generate actual output
73
- const generator = new OpenAPIToConnector(spec, 'simple-test');
74
- const actualOutput = generator.generateController();
75
-
76
- // Compare outputs
77
- expect(normalizeOutput(actualOutput)).toEqual(normalizeOutput(expectedOutput));
78
- });
79
-
80
- // Test 2: Simple Scenario - Methods without options
81
- test('Simple Scenario - methods without options should be clean', () => {
82
- const specPath = path.join(__dirname, 'scenarios/simple/simple-api.json');
83
- const specContent = fs.readFileSync(specPath, 'utf-8');
84
- const spec = OpenAPIToConnector.parseSpec(specContent);
85
-
86
- const generator = new OpenAPIToConnector(spec, 'simple-test');
87
- const actualOutput = generator.generateController();
88
-
89
- expect(actualOutput).toInclude('async getProducts(options?: {headers?: Record<string, string>}) {');
90
- expect(actualOutput).toInclude('async createProduct(options:');
91
- });
92
-
93
- // Test 3: Complex Scenario - Main Controller
94
- test('Complex Scenario - main controller should generate expected output', () => {
95
- const productsSpecPath = path.join(__dirname, 'scenarios/complex/specs/products.json');
96
- const ordersSpecPath = path.join(__dirname, 'scenarios/complex/specs/orders.json');
97
- const productsSpecContent = fs.readFileSync(productsSpecPath, 'utf-8');
98
- const ordersSpecContent = fs.readFileSync(ordersSpecPath, 'utf-8');
99
-
100
- const productsSpec = OpenAPIToConnector.parseSpec(productsSpecContent);
101
- const ordersSpec = OpenAPIToConnector.parseSpec(ordersSpecContent);
102
-
103
- const expectedPath = path.join(__dirname, 'scenarios/complex/expected/controller.mts');
104
- const expectedOutput = fs.readFileSync(expectedPath, 'utf-8');
105
-
106
- const resources = [
107
- { className: 'ProductsResource', fileName: 'products' },
108
- { className: 'OrdersResource', fileName: 'orders' }
109
- ];
110
- const resourceSpecs = [
111
- { fileName: 'products', spec: productsSpec },
112
- { fileName: 'orders', spec: ordersSpec }
113
- ];
114
-
115
- const mainGenerator = new OpenAPIToConnector(productsSpec, 'test-shop-temp');
116
- const actualOutput = mainGenerator.generateMainController(resources, resourceSpecs);
117
-
118
- expect(normalizeOutput(actualOutput)).toEqual(normalizeOutput(expectedOutput));
119
- });
120
-
121
- // Test 4: Complex Scenario - Products Resource
122
- test('Complex Scenario - products resource should generate expected output', () => {
123
- const specPath = path.join(__dirname, 'scenarios/complex/specs/products.json');
124
- const specContent = fs.readFileSync(specPath, 'utf-8');
125
- const spec = OpenAPIToConnector.parseSpec(specContent);
126
-
127
- const expectedPath = path.join(__dirname, 'scenarios/complex/expected/products-resource.mts');
128
- const expectedOutput = fs.readFileSync(expectedPath, 'utf-8');
129
-
130
- const generator = new OpenAPIToConnector(spec, 'test-shop');
131
- const actualOutput = generator.generateResourceClass('ProductsResource');
132
-
133
- expect(normalizeOutput(actualOutput)).toEqual(normalizeOutput(expectedOutput));
134
- });
135
-
136
- // Test 5: Complex Scenario - Orders Resource
137
- test('Complex Scenario - orders resource should generate expected output', () => {
138
- const specPath = path.join(__dirname, 'scenarios/complex/specs/orders.json');
139
- const specContent = fs.readFileSync(specPath, 'utf-8');
140
- const spec = OpenAPIToConnector.parseSpec(specContent);
141
-
142
- const expectedPath = path.join(__dirname, 'scenarios/complex/expected/orders-resource.mts');
143
- const expectedOutput = fs.readFileSync(expectedPath, 'utf-8');
144
-
145
- const generator = new OpenAPIToConnector(spec, 'test-shop');
146
- const actualOutput = generator.generateResourceClass('OrdersResource');
147
-
148
- expect(normalizeOutput(actualOutput)).toEqual(normalizeOutput(expectedOutput));
149
- });
150
-
151
- // Test 6: TypeScript Interface Generation
152
- test('TypeScript interfaces should be generated correctly', () => {
153
- const specPath = path.join(__dirname, 'scenarios/complex/specs/products.json');
154
- const specContent = fs.readFileSync(specPath, 'utf-8');
155
- const spec = OpenAPIToConnector.parseSpec(specContent);
156
-
157
- const generator = new OpenAPIToConnector(spec, 'test-shop');
158
- const actualOutput = generator.generateResourceClass('ProductsResource');
159
-
160
- expect(actualOutput).toInclude('export interface Product {');
161
- expect(actualOutput).toInclude('export interface ProductList {');
162
- expect(actualOutput).toInclude('export interface CreateProductRequest {');
163
- expect(actualOutput).toInclude('Promise<ProductList>');
164
- expect(actualOutput).toInclude('Promise<Product>');
165
- });
166
-
167
- // Test 7: Path Parameters and Options
168
- test('Path parameters and options should be handled correctly', () => {
169
- const specPath = path.join(__dirname, 'scenarios/complex/specs/orders.json');
170
- const specContent = fs.readFileSync(specPath, 'utf-8');
171
- const spec = OpenAPIToConnector.parseSpec(specContent);
172
-
173
- const generator = new OpenAPIToConnector(spec, 'test-shop');
174
- const actualOutput = generator.generateResourceClass('OrdersResource');
175
-
176
- expect(actualOutput).toInclude('export function getOrder(this: any, orderId: string, options?: {headers?: Record<string, string>})');
177
- expect(actualOutput).toInclude('export function updateOrderStatus(this: any, orderId: string, options');
178
- expect(actualOutput).toInclude('export function cancelOrder(this: any, orderId: string, options?: {headers?: Record<string, string>})');
179
- });
180
-
181
- // Test 8: Exposed Methods in Main Controller
182
- test('Exposed methods should be present in main controller', () => {
183
- const productsSpecPath = path.join(__dirname, 'scenarios/complex/specs/products.json');
184
- const ordersSpecPath = path.join(__dirname, 'scenarios/complex/specs/orders.json');
185
- const productsSpecContent = fs.readFileSync(productsSpecPath, 'utf-8');
186
- const ordersSpecContent = fs.readFileSync(ordersSpecPath, 'utf-8');
187
-
188
- const productsSpec = OpenAPIToConnector.parseSpec(productsSpecContent);
189
- const ordersSpec = OpenAPIToConnector.parseSpec(ordersSpecContent);
190
-
191
- const resources = [
192
- { className: 'ProductsResource', fileName: 'products' },
193
- { className: 'OrdersResource', fileName: 'orders' }
194
- ];
195
- const resourceSpecs = [
196
- { fileName: 'products', spec: productsSpec },
197
- { fileName: 'orders', spec: ordersSpec }
198
- ];
199
-
200
- const mainGenerator = new OpenAPIToConnector(productsSpec, 'test-shop');
201
- const actualOutput = mainGenerator.generateMainController(resources, resourceSpecs);
202
-
203
- expect(actualOutput).toInclude('async productsGetProducts(');
204
- expect(actualOutput).toInclude('async productsCreateProduct(');
205
- expect(actualOutput).toInclude('async productsGetProduct(');
206
- expect(actualOutput).toInclude('async productsUpdateProduct(');
207
- expect(actualOutput).toInclude('async productsDeleteProduct(');
208
-
209
- expect(actualOutput).toInclude('async ordersGetOrders(');
210
- expect(actualOutput).toInclude('async ordersCreateOrder(');
211
- expect(actualOutput).toInclude('async ordersGetOrder(');
212
- expect(actualOutput).toInclude('async ordersUpdateOrderStatus(');
213
- expect(actualOutput).toInclude('async ordersCancelOrder(');
214
-
215
- expect(actualOutput).toInclude('this.bindResourceFunctions(\'products\', productsFunctions);');
216
- expect(actualOutput).toInclude('this.bindResourceFunctions(\'orders\', ordersFunctions);');
217
- });
218
-
219
- // Test 9: Schema Name Sanitization
220
- test('Schema names should be sanitized correctly', () => {
221
- const testSpec = {
222
- openapi: '3.0.0',
223
- info: { title: 'Test API', version: '1.0.0' },
224
- paths: {
225
- '/test': {
226
- get: {
227
- operationId: 'testOperation',
228
- responses: {
229
- '200': {
230
- description: 'Success',
231
- content: {
232
- 'application/json': {
233
- schema: {
234
- '$ref': '#/components/schemas/Complex.Name.With.Dots'
235
- }
236
- }
237
- }
238
- }
239
- }
240
- }
241
- }
242
- },
243
- components: {
244
- schemas: {
245
- 'Complex.Name.With.Dots': {
246
- type: 'object',
247
- properties: {
248
- id: { type: 'string' },
249
- name: { type: 'string' }
250
- }
251
- }
252
- }
253
- }
254
- };
255
-
256
- const generator = new OpenAPIToConnector(testSpec, 'test');
257
- const output = generator.generateController();
258
-
259
- expect(output).toInclude('export interface Complex_Name_With_Dots {');
260
- expect(output).toNotInclude('export interface Complex.Name.With.Dots {');
261
- expect(output).toInclude('Promise<Complex_Name_With_Dots>');
262
- });
263
-
264
- // Test 10: No Options Parameter for Simple Methods
265
- test('Simple methods should not have options parameter', () => {
266
- const simpleSpec = {
267
- openapi: '3.0.0',
268
- info: { title: 'Simple API', version: '1.0.0' },
269
- paths: {
270
- '/simple': {
271
- get: {
272
- operationId: 'getSimple',
273
- responses: { '200': { description: 'Success' } }
274
- }
275
- }
276
- }
277
- };
278
-
279
- const generator = new OpenAPIToConnector(simpleSpec, 'test');
280
- const output = generator.generateController();
281
-
282
- expect(output).toInclude('async getSimple(options?: {headers?: Record<string, string>}) {');
283
- expect(output).toNotInclude('options = options || {}');
284
- expect(output).toNotInclude('headers: options');
285
- });
286
-
287
- // Print final results
288
- console.log(`${colors.yellow}📊 Test Results:${colors.reset}`);
289
- console.log(`${colors.green}✓ Passed: ${passed}${colors.reset}`);
290
- console.log(`${colors.red}✗ Failed: ${failed}${colors.reset}`);
291
-
292
- if (failed === 0) {
293
- console.log(`\n${colors.green}🎉 All tests passed!${colors.reset}`);
294
- process.exit(0);
295
- } else {
296
- console.log(`\n${colors.red}❌ Some tests failed!${colors.reset}`);
297
- process.exit(1);
298
- }
@@ -1,52 +0,0 @@
1
- // Mutation check for the SDK tests that `yarn test` now runs (openapi-to-connector generator tests, scenarios).
2
- //
3
- // yarn build && node tools/mutation-run-entry.mjs
4
- //
5
- // Applies each single-point bug to src/openapi-to-connector.mts, rebuilds, runs `yarn test` and expects it to FAIL.
6
- // The source file is restored after every mutant (and on exit). Prints a markdown table.
7
- import {spawnSync} from 'node:child_process';
8
- import fs from 'node:fs';
9
- import path from 'node:path';
10
- import {fileURLToPath} from 'node:url';
11
-
12
- const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
13
- const file = path.join(root, 'src/openapi-to-connector.mts');
14
- const original = fs.readFileSync(file, 'utf8');
15
- const restore = () => fs.writeFileSync(file, original);
16
- process.on('exit', restore);
17
- process.on('SIGINT', () => process.exit(130));
18
-
19
- // [id, exact text (must occur once), replacement, bug]
20
- const MUTANTS = [
21
- ['E01', "method: method.toUpperCase(),\n path,", "method: method.toLowerCase(),\n path,", 'the HTTP verb is taken in lower case'],
22
- ['E02', "lines.push(` if (${paramName}) {`);\n lines.push(` url = url.replace('{${paramName}}', ${paramName});`);\n lines.push(` }`);\n }", "lines.push(` if (!${paramName}) {`);\n lines.push(` url = url.replace('{${paramName}}', ${paramName});`);\n lines.push(` }`);\n }", 'path parameter substitution is guarded by the wrong condition'],
23
- ['E03', "return `${methodPrefix}_${pathSuffix}`;", "return `${methodPrefix}${pathSuffix}`;", 'fallback method name drops the separator'],
24
- ['E04', "const requiredText = propRequired ? '(required)' : '(optional)';", "const requiredText = propRequired ? '(optional)' : '(required)';", 'body properties are documented with the wrong required flag'],
25
- ['E05', " // Always include headers in options type (generated code references options.headers)\n optionProps.push('headers?: Record<string, string>');", " // Always include headers in options type (generated code references options.headers)", 'headers are dropped from the generated options type'],
26
- ['E06', "lines.push(` options = options || {};`);", "lines.push(` // no options default`);", 'options is not defaulted in generated methods'],
27
- ['E07', "if (criticalErrors.length > 0) {", "if (false) {", 'invalid specs are no longer rejected'],
28
- ['E08', "const propRequired = (schema.required && schema.required.includes(propName)) || requestBody.required;", "const propRequired = (schema.required && schema.required.includes(propName)) && requestBody.required;", 'a property is required only if both the schema and the body say so'],
29
- ];
30
-
31
- const sh = (args) => spawnSync('npx', ['--yes', 'yarn@1.22.22', '-s', ...args], {cwd: root, encoding: 'utf8'});
32
- const rows = [];
33
- let survived = 0;
34
- for (const [id, find, repl, bug] of MUTANTS) {
35
- const n = original.split(find).length - 1;
36
- if (n !== 1) { console.error(`${id}: pattern occurs ${n} times, expected 1`); process.exit(2); }
37
- fs.writeFileSync(file, original.replace(find, repl));
38
- const b = sh(['build']);
39
- let result;
40
- if (b.status !== 0) result = 'build failed (not counted)';
41
- else {
42
- const t = sh(['test']);
43
- result = t.status !== 0 ? 'killed' : 'SURVIVED';
44
- if (t.status === 0) survived++;
45
- }
46
- restore();
47
- rows.push(`| ${id} | ${bug} | ${result} |`);
48
- console.log(rows.at(-1));
49
- }
50
- sh(['build']);
51
- console.log(`\n${MUTANTS.length - survived}/${MUTANTS.length} killed`);
52
- process.exit(survived ? 1 : 0);
@@ -1,138 +0,0 @@
1
- // Mutation check for the connector test harness.
2
- //
3
- // yarn build && yarn test:mutation
4
- //
5
- // Applies each deliberate single-point bug below to src/, rebuilds, runs the harness tests (or, for the F mutants,
6
- // test/fetcher-query-params.test.mjs) and expects them to FAIL. The original file is restored after every mutant (and on Ctrl-C). Writes test/MUTATION.md.
7
- // Not part of CI: it rebuilds the SDK ~30 times. Run it when the harness or the SDK paths it covers change.
8
- import {spawnSync} from 'node:child_process';
9
- import fs from 'node:fs';
10
- import path from 'node:path';
11
- import {fileURLToPath} from 'node:url';
12
-
13
- const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
14
- const src = (p) => path.join(root, 'src', p);
15
-
16
- // [id, area, file (under src/), exact text to find (must occur once), replacement, what the bug is]
17
- const MUTANTS = [
18
- ['M01', 'sdk handshake', 'internal/websocket/connection/index.mjs', 'response.status === 401', 'response.status === 403', 'a 401 from /connect no longer triggers registration'],
19
- ['M02', 'sdk handshake', 'internal/websocket/connection/index.mjs', 'config.setToken(await new Registration(local.config).run());', 'await new Registration(local.config).run();', 'the token from registration is not stored'],
20
- ['M03', 'sdk handshake', 'internal/websocket/connection/registration.mjs', 'return (await response.json()).key;', 'return (await response.json()).token;', 'registration reads the wrong field of the answer'],
21
- ['M04', 'sdk handshake', 'internal/websocket/connection/registration.mjs', 'id: config.id(),', 'id: config.name(),', 'registration sends the name as the connector id'],
22
- ['M05', 'sdk handshake', 'internal/websocket/connection/registration.mjs', 'publicKey: config.publicKey(),', 'publicKey: undefined,', 'registration omits the public key'],
23
- ['M06', 'sdk handshake', 'internal/websocket/connection/constants.mjs', "'User-Agent': config.id() + '/' + config.version(),\n };\n\n what.headers[AUTHORIZATION] = `Connector ${config.token()}`;", "'User-Agent': config.id(),\n };\n\n what.headers[AUTHORIZATION] = `Connector ${config.token()}`;", 'authenticated requests drop the version from the User-Agent'],
24
- ['M07', 'sdk handshake', 'internal/websocket/connection/constants.mjs', 'what.headers[AUTHORIZATION] = `Connector ${config.token()}`;', 'what.headers[AUTHORIZATION] = `Bearer ${config.token()}`;', 'wrong authorization scheme for the session token'],
25
- ['M08', 'sdk handshake', 'internal/websocket/transport/index.mjs', "config.wsUrl(), ['connector']", 'config.wsUrl(), []', 'websocket opened without the "connector" subprotocol'],
26
- ['M09', 'sdk transport', 'internal/websocket/transport/index.mjs', 'msgs.p?.forEach((item) => {', 'msgs.p?.slice(1).forEach((item) => {', 'the first packet of every incoming frame is dropped'],
27
- ['M10', 'sdk transport', 'internal/websocket/transport/index.mjs', 'local.ws.send(JSON.stringify({p: packets}));', 'local.ws.send(JSON.stringify({packets}));', 'outgoing frames use the wrong envelope'],
28
- ['M11', 'sdk transport', 'internal/websocket/transport/index.mjs', 'if (packet.cb() && this.callbacks[packet.cb()]) {', 'if (false && packet.cb() && this.callbacks[packet.cb()]) {', 'answers to connector-initiated requests are never routed to their callback'],
29
- ['M12', 'sdk dispatch', 'internal/dispatcher/index.mts', 'case \'connector.set-config\':\n await local.onConfig({...packet.args().secrets});', 'case \'connector.set-config\':\n await local.onConfig({});', 'configuration secrets are dropped before onConfig'],
30
- ['M13', 'sdk dispatch', 'internal/dispatcher/index.mts', 'const ctx = {taskId, namespace, sticky};', 'const ctx = {taskId, namespace};', 'sticky is not forwarded to the method'],
31
- ['M14', 'sdk dispatch', 'internal/dispatcher/index.mts', 'if (!method && !_resolvers.__default) throw new Error(`${originalQuery} not found`);', 'if (false) throw new Error(`${originalQuery} not found`);', 'unknown methods are no longer reported as "not found"'],
32
- ['M15', 'sdk result return', 'internal/dispatcher/index.mts', 'return typeof ret === \'object\' && !Array.isArray(ret) ? ret : {[packet.args().query]: ret};', 'return typeof ret === \'object\' && !Array.isArray(ret) ? ret : {result: ret};', 'scalar results are wrapped under the wrong key'],
33
- ['M16', 'sdk result return', 'internal/util/index.mts', 'transport.send(transport.newPacket({c: packet.cb(), a: {...arg}}));', 'transport.send(transport.newPacket({c: packet.cb(), a: {}}));', 'successful results are replied empty'],
34
- ['M17', 'sdk result return', 'internal/util/index.mts', "a: {error: '' + e}", "a: {error: 'failed'}", 'errors lose their message'],
35
- ['M18', 'sdk result return', 'internal/connector/server/on-message.mts', 'if (ret) reply(ret, packet, transport);', 'if (false) reply(ret, packet, transport);', 'results are never sent back'],
36
- ['M19', 'sdk config', 'internal/connector/server/on-connect/decrypt-config.mts', 'jwe.decrypt(value, config.id())', "jwe.decrypt(value, 'other-audience')", 'config is decrypted for the wrong audience'],
37
- ['M20', 'sdk config', 'internal/connector/server/on-connect/decrypt-config.mts', 'if (fields[key]?.plain ||', 'if (false ||', 'plain fields are decrypted like secrets'],
38
- ['M21', 'sdk config', 'internal/connector/server/on-connect/index.mts', 'config: decrypted,\n oauth: theOAuth,', 'config: {},\n oauth: theOAuth,', 'main() receives an empty config'],
39
- ['M22', 'harness vendor mock', 'testing/vendor-mock.mts', 'error.alomaHarnessUnmocked = true;\n throw error;', 'error.alomaHarnessUnmocked = true;\n return new Response(\'{}\');', 'an unmocked request is answered instead of rejected'],
40
- ['M23', 'harness vendor mock', 'testing/vendor-mock.mts', 'if (this.unmocked.length) {', 'if (false) {', 'verify() never fails'],
41
- ['M24', 'harness vendor mock', 'testing/vendor-mock.mts', 'const status = spec.status ?? 200;', 'const status = 200;', 'mocked status codes are ignored'],
42
- ['M25', 'harness vendor mock', 'testing/vendor-mock.mts', 'r.used < r.times && ', '', 'the times limit on a route is ignored'],
43
- ['M26', 'harness network guard', 'testing/network-guard.mts', 'if (!local && !LOOPBACK.has(host)) {', 'if (false) {', 'the network guard lets everything through (the mutant may try one TCP connect to the TEST-NET-3 documentation address 203.0.113.9)'],
44
- ['M27', 'harness fake ALOMA', 'testing/fake-aloma.mts', 'const authorized = auth === `Connector ${this.sessionToken}`;', 'const authorized = true;', 'the fake accepts a connect without registration'],
45
- ['M28', 'harness fake ALOMA', 'testing/fake-aloma.mts', '.setAudience(this.id)', ".setAudience('wrong')", 'the fake encrypts config for the wrong audience'],
46
- ['M29', 'harness fake ALOMA', 'testing/fake-aloma.mts', ' done(packet.a);', ' done(undefined);', 'the fake drops the connector\'s answer'],
47
- ['M30', 'harness fake ALOMA', 'testing/fake-aloma.mts', "{query: method, variables, ...ctx}", "{query: method, variables}", 'call() drops the ctx fields'],
48
- ['M31', 'harness', 'testing/harness.mts', 'this.vendor.verify();', '', 'stop() no longer fails on unmocked requests'],
49
- ['M32', 'harness', 'testing/harness.mts', "await aloma.setConfig(options.config || {});", "", 'the harness never sends configuration'],
50
- // PLAT-47: Fetcher query parameters, checked by test/fetcher-query-params.test.mjs
51
- ['F01', 'sdk fetcher', 'internal/fetcher/fetcher.mts', 'const fullURL = withQuery(theURL, toQuery(options0.params));', 'const fullURL = theURL;', 'params are not sent at all (the PLAT-47 bug)'],
52
- ['F02', 'sdk fetcher', 'internal/fetcher/fetcher.mts', 'if (Array.isArray(value)) value.forEach((item) => add(key, item));\n else add(key, value);', 'add(key, value);', 'array handling dropped (arrays are refused as objects)'],
53
- ['F03', 'sdk fetcher', 'internal/fetcher/fetcher.mts', 'if (Array.isArray(value)) value.forEach((item) => add(key, item));', "if (Array.isArray(value)) add(key, value.join(','));", 'arrays are comma-joined instead of repeated keys'],
54
- ['F04', 'sdk fetcher', 'internal/fetcher/fetcher.mts', 'if (value == null) return;', 'if (value === null) return;', 'undefined values are not skipped'],
55
- ['F05', 'sdk fetcher', 'internal/fetcher/fetcher.mts', 'if (value == null) return;', 'if (value === undefined) return;', 'null values are not skipped'],
56
- ['F06', 'sdk fetcher', 'internal/fetcher/fetcher.mts', " if (typeof value === 'object') {", ' if (false) {', 'nested objects are sent instead of refused'],
57
- ['F07', 'sdk fetcher', 'internal/fetcher/fetcher.mts', 'if (e instanceof ParamsError) throw e;', '', 'a refused params object is retried'],
58
- ['F08', 'sdk fetcher', 'internal/fetcher/fetcher.mts', "const sep = !base.includes('?') ? '?'", "const sep = true ? '?'", 'a query already in the url gets a second "?"'],
59
- ['F09', 'sdk fetcher', 'internal/fetcher/fetcher.mts', ' ...init,\n', ' ...options0,\n', 'params is passed on to native fetch'],
60
- ['F10', 'sdk fetcher', 'internal/fetcher/fetcher.mts', 'const {params, ...init} = options0;', 'const {params, ...init} = options0;\n delete options0.params;', 'params are dropped from options0, so a retry loses the query'],
61
- ['F11', 'sdk fetcher', 'internal/fetcher/fetcher.mts', "console.log(theURL.split('?')[0], e);", 'console.log(theURL, e);', 'a failed attempt logs query values'],
62
- ['F12', 'sdk fetcher', 'internal/fetcher/fetcher.mts', 'if (params instanceof URLSearchParams) return params.toString();', '', 'a URLSearchParams instance is silently dropped'],
63
- ];
64
-
65
- const run = (cmd, args, timeout) =>
66
- spawnSync(cmd, args, {cwd: root, encoding: 'utf8', timeout, env: {...process.env, FORCE_COLOR: '0'}});
67
-
68
- const build = () => {
69
- const r = run('node', ['./node_modules/typescript/bin/tsc'], 120000);
70
- if (r.status !== 0) throw new Error('build failed:\n' + r.stdout + r.stderr);
71
- };
72
- const mocha = () => run('node', ['./node_modules/mocha/bin/_mocha', '--bail', '--exit', 'test/harness.test.mjs', 'test/harness-connector-smoke.test.mjs'], 150000);
73
- const fetcherTests = () => run('node', ['test/fetcher-query-params.test.mjs'], 150000);
74
- const testsFor = (id) => (id.startsWith('F') ? fetcherTests() : mocha());
75
-
76
- let current = null;
77
- const restore = () => {
78
- if (current) fs.writeFileSync(current.file, current.original);
79
- current = null;
80
- };
81
- process.on('SIGINT', () => {
82
- restore();
83
- process.exit(130);
84
- });
85
-
86
- const results = [];
87
- try {
88
- build();
89
- const baseline = mocha();
90
- if (baseline.status !== 0) throw new Error('baseline run must pass before mutating:\n' + baseline.stdout.slice(-2000));
91
- const fetcherBaseline = fetcherTests();
92
- if (fetcherBaseline.status !== 0) throw new Error('fetcher baseline must pass:\n' + fetcherBaseline.stdout.slice(-2000));
93
-
94
- for (const [id, area, rel, find, replace, bug] of MUTANTS) {
95
- const file = src(rel);
96
- const original = fs.readFileSync(file, 'utf8');
97
- const count = original.split(find).length - 1;
98
- if (count !== 1) throw new Error(`${id}: expected exactly one match in ${rel}, found ${count}`);
99
-
100
- current = {file, original};
101
- let outcome;
102
- try {
103
- fs.writeFileSync(file, original.replace(find, () => replace));
104
- build();
105
- const r = testsFor(id);
106
- const failing = (r.stdout.match(/^\s+\d+\) .+$|FAIL: .+$/gm) || [])[0]?.trim() || '';
107
- outcome = r.error?.code === 'ETIMEDOUT' ? 'killed (timeout)' : r.status !== 0 ? 'killed' : 'SURVIVED';
108
- results.push({id, area, rel, bug, outcome, by: failing});
109
- } finally {
110
- restore();
111
- }
112
- console.log(id, results[results.length - 1].outcome, '-', bug);
113
- }
114
- } finally {
115
- restore();
116
- build();
117
- }
118
-
119
- const killed = results.filter((r) => r.outcome.startsWith('killed')).length;
120
- const md = [
121
- '# Mutation check for the connector test harness',
122
- '',
123
- `Result: **${killed}/${results.length} mutants killed**${killed === results.length ? '' : ' (survivors listed below)'}.`,
124
- '',
125
- 'Each row is one deliberate single-point bug in the SDK code paths the harness exercises (handshake, transport,',
126
- 'dispatch, result return, config) or in the harness itself. `tools/mutation-run.mjs` applies it to `src/`, rebuilds,',
127
- 'runs `test/harness.test.mjs` with `--bail` (F rows: `test/fetcher-query-params.test.mjs`), expects a failure, and',
128
- 'restores the file. Re-run with',
129
- '`yarn build && yarn test:mutation` after changing the harness or those SDK paths.',
130
- '',
131
- '| # | Area | File | Bug | Result |',
132
- '|---|------|------|-----|--------|',
133
- ...results.map((r) => `| ${r.id} | ${r.area} | \`src/${r.rel}\` | ${r.bug} | ${r.outcome} |`),
134
- '',
135
- ].join('\n');
136
- fs.writeFileSync(path.join(root, 'test', 'MUTATION.md'), md);
137
- console.log(`\n${killed}/${results.length} killed`);
138
- process.exit(killed === results.length ? 0 : 1);
@@ -1,64 +0,0 @@
1
- // `yarn test`: runs every test file in test/.
2
- //
3
- // Two kinds of test file live in test/:
4
- // - mocha files (describe/it): files that import from 'mocha'. They run together in ONE mocha process.
5
- // - standalone scripts (their own tiny test() helper, finish with process.exit): every other test/*.test.mjs, plus
6
- // test/verify-scenarios.mjs. Each runs in its own node process, because process.exit() inside a mocha process
7
- // ends the whole run while mocha is still loading files, so none of the describe/it tests would run.
8
- // A new test file is picked up by name (test/*.test.mjs|mts). Exit code is non-zero if anything fails.
9
- import {createRequire} from 'node:module';
10
- import {spawnSync} from 'node:child_process';
11
- import fs from 'node:fs';
12
- import path from 'node:path';
13
- import {fileURLToPath} from 'node:url';
14
-
15
- const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
16
- const testDir = path.join(root, 'test');
17
-
18
- const files = fs.readdirSync(testDir).filter((f) => /\.test\.m[jt]s$/.test(f)).sort();
19
- const isMocha = (f) => /from ['"]mocha['"]/.test(fs.readFileSync(path.join(testDir, f), 'utf8'));
20
- // .mts test files are transpiled (type-stripped) to sibling .mjs files and run by plain mocha. The ts-node/esm loader
21
- // cannot be used: it fails on Node 18 (ERR_UNKNOWN_FILE_EXTENSION) and Node 20 (ERR_INTERNAL_ASSERTION). The sibling
22
- // location keeps relative imports and import.meta.url paths identical to the source file.
23
- const require = createRequire(import.meta.url);
24
- const ts = require('typescript');
25
- const generated = [];
26
- const compile = (f) => {
27
- if (!f.endsWith('.mts')) return path.join('test', f);
28
- const out = path.join('test', `.compiled-${f.replace(/\.mts$/, '.mjs')}`);
29
- const src = fs.readFileSync(path.join(testDir, f), 'utf8');
30
- const js = ts.transpileModule(src, {
31
- compilerOptions: {module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022},
32
- fileName: f,
33
- }).outputText;
34
- fs.writeFileSync(path.join(root, out), js);
35
- generated.push(path.join(root, out));
36
- return out;
37
- };
38
- const mochaFiles = files.filter(isMocha).map(compile);
39
- const scripts = files.filter((f) => !isMocha(f)).map((f) => path.join('test', f));
40
- scripts.push(path.join('test', 'verify-scenarios.mjs'));
41
-
42
- const failures = [];
43
- const run = (label, cmd, args) => {
44
- console.log(`\n=== ${label}`);
45
- const r = spawnSync(cmd, args, {cwd: root, stdio: 'inherit'});
46
- if (r.status !== 0) failures.push(label);
47
- };
48
-
49
- if (mochaFiles.length) {
50
- run(`mocha (${mochaFiles.length} files)`, process.execPath, [
51
- path.join(root, 'node_modules/mocha/bin/_mocha'),
52
- '--exit',
53
- ...mochaFiles,
54
- ]);
55
- }
56
- for (const s of scripts) run(s, process.execPath, [s]);
57
-
58
- for (const g of generated) fs.rmSync(g, {force: true});
59
-
60
- console.log(`\n${mochaFiles.length} mocha files, ${scripts.length} standalone scripts, ${failures.length} failed`);
61
- if (failures.length) {
62
- console.log(`FAILED: ${failures.join(', ')}`);
63
- process.exit(1);
64
- }
package/tsconfig.json DELETED
@@ -1,27 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "es2022",
4
- "skipLibCheck": true,
5
- "module": "node16",
6
- "moduleResolution": "node16",
7
- "lib": ["es2015", "es6", "esnext"],
8
- "declaration": true,
9
- "allowJs": true,
10
- "outDir": "build",
11
- "rootDir": "src/",
12
- "strict": true,
13
- "noImplicitAny": false,
14
- "esModuleInterop": true,
15
- "resolveJsonModule": true,
16
- "experimentalDecorators": true,
17
- "emitDecoratorMetadata": true,
18
- "allowSyntheticDefaultImports": true
19
- },
20
- "include": [
21
- "src/**/*"
22
- ],
23
- "exclude": [
24
- "node_modules/**/*",
25
- "dist/**/*"
26
- ]
27
- }