@ankhorage/data-sources 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,533 @@
1
+ import type {
2
+ CredentialRef,
3
+ DataContractValue,
4
+ DataEndpointConfig,
5
+ DataOperationConfig,
6
+ DataOperationParameter,
7
+ DataSourceConfig,
8
+ DataSourceDiagnostic,
9
+ EndpointId,
10
+ OperationId,
11
+ } from '@ankhorage/contracts/data';
12
+
13
+ export type EndpointTestInputValues = Readonly<Record<string, DataContractValue>>;
14
+ export type EndpointTestHeaders = Readonly<Record<string, string>>;
15
+
16
+ export interface EndpointTestCredential {
17
+ readonly headers?: EndpointTestHeaders;
18
+ readonly query?: EndpointTestInputValues;
19
+ }
20
+
21
+ export type EndpointTestCredentialResolver = (
22
+ credential: CredentialRef,
23
+ ) => EndpointTestCredential | Promise<EndpointTestCredential | undefined> | undefined;
24
+
25
+ export interface EndpointTestFetchInit {
26
+ readonly method: string;
27
+ readonly headers: EndpointTestHeaders;
28
+ readonly body?: string;
29
+ }
30
+
31
+ export interface EndpointTestFetchResponse {
32
+ readonly status: number;
33
+ readonly headers?: EndpointTestHeaders;
34
+ text(): Promise<string>;
35
+ }
36
+
37
+ export type EndpointTestFetch = (
38
+ url: string,
39
+ init: EndpointTestFetchInit,
40
+ ) => Promise<EndpointTestFetchResponse>;
41
+
42
+ export interface EndpointTestInput {
43
+ readonly dataSource: DataSourceConfig;
44
+ readonly endpointId: EndpointId;
45
+ readonly operationId: OperationId;
46
+ readonly values?: EndpointTestInputValues;
47
+ readonly dryRun?: boolean;
48
+ readonly fetch?: EndpointTestFetch;
49
+ readonly credentialResolver?: EndpointTestCredentialResolver;
50
+ }
51
+
52
+ export interface EndpointTestRequestDiagnostic {
53
+ readonly dataSourceId: string;
54
+ readonly endpointId: EndpointId;
55
+ readonly operationId: OperationId;
56
+ readonly url: string;
57
+ readonly method: string;
58
+ readonly headers: EndpointTestHeaders;
59
+ readonly body?: string;
60
+ readonly dryRun: boolean;
61
+ }
62
+
63
+ export interface EndpointTestResponseDiagnostic {
64
+ readonly status: number;
65
+ readonly ok: boolean;
66
+ readonly headers?: EndpointTestHeaders;
67
+ readonly bodyText?: string;
68
+ readonly parsedBody?: DataContractValue;
69
+ }
70
+
71
+ export type EndpointTestResult =
72
+ | {
73
+ readonly ok: true;
74
+ readonly request: EndpointTestRequestDiagnostic;
75
+ readonly response?: EndpointTestResponseDiagnostic;
76
+ readonly data?: DataContractValue;
77
+ readonly diagnostics: readonly DataSourceDiagnostic[];
78
+ }
79
+ | {
80
+ readonly ok: false;
81
+ readonly request?: EndpointTestRequestDiagnostic;
82
+ readonly response?: EndpointTestResponseDiagnostic;
83
+ readonly diagnostics: readonly DataSourceDiagnostic[];
84
+ };
85
+
86
+ interface EndpointOperationSelection {
87
+ readonly endpoint: DataEndpointConfig;
88
+ readonly operation: DataOperationConfig;
89
+ }
90
+
91
+ export async function testEndpoint(input: EndpointTestInput): Promise<EndpointTestResult> {
92
+ const built = await buildEndpointTestRequest(input);
93
+
94
+ if (!built.ok) return built;
95
+ if (input.dryRun === true) return built;
96
+
97
+ if (input.fetch === undefined) {
98
+ return {
99
+ ok: false,
100
+ request: built.request,
101
+ diagnostics: [
102
+ ...built.diagnostics,
103
+ createDiagnostic(
104
+ input,
105
+ 'invalid-config',
106
+ 'Endpoint test runner requires an injected fetch function.',
107
+ ),
108
+ ],
109
+ };
110
+ }
111
+
112
+ try {
113
+ const response = await input.fetch(built.request.url, {
114
+ method: built.request.method,
115
+ headers: built.request.headers,
116
+ body: built.request.body,
117
+ });
118
+ const responseDiagnostic = await createResponseDiagnostic(response);
119
+ const diagnostics = [...built.diagnostics];
120
+
121
+ if (!responseDiagnostic.ok) {
122
+ diagnostics.push(
123
+ createDiagnostic(
124
+ input,
125
+ 'http-error',
126
+ `Endpoint test request returned HTTP status ${responseDiagnostic.status}.`,
127
+ ),
128
+ );
129
+ }
130
+
131
+ return responseDiagnostic.ok
132
+ ? {
133
+ ok: true,
134
+ request: built.request,
135
+ response: responseDiagnostic,
136
+ data: responseDiagnostic.parsedBody,
137
+ diagnostics,
138
+ }
139
+ : {
140
+ ok: false,
141
+ request: built.request,
142
+ response: responseDiagnostic,
143
+ diagnostics,
144
+ };
145
+ } catch (error) {
146
+ return {
147
+ ok: false,
148
+ request: built.request,
149
+ diagnostics: [
150
+ ...built.diagnostics,
151
+ createDiagnostic(input, 'network-error', createNetworkErrorMessage(error)),
152
+ ],
153
+ };
154
+ }
155
+ }
156
+
157
+ export async function buildEndpointTestRequest(
158
+ input: EndpointTestInput,
159
+ ): Promise<EndpointTestResult> {
160
+ const selection = selectEndpointOperation(input);
161
+ if (selection === undefined) {
162
+ return {
163
+ ok: false,
164
+ diagnostics: [
165
+ createDiagnostic(input, 'missing-operation', 'Endpoint or operation could not be found.'),
166
+ ],
167
+ };
168
+ }
169
+
170
+ const diagnostics: DataSourceDiagnostic[] = [];
171
+ const credential = await resolveEndpointCredential(input, selection, diagnostics);
172
+ const request =
173
+ selection.operation.protocol === 'graphql'
174
+ ? buildGraphQlRequest(input, selection, credential, diagnostics)
175
+ : buildHttpRequest(input, selection, credential, diagnostics);
176
+
177
+ if (request === undefined || diagnostics.some((diagnostic) => diagnostic.severity === 'error')) {
178
+ return {
179
+ ok: false,
180
+ request,
181
+ diagnostics,
182
+ };
183
+ }
184
+
185
+ return {
186
+ ok: true,
187
+ request,
188
+ diagnostics,
189
+ };
190
+ }
191
+
192
+ function selectEndpointOperation(input: EndpointTestInput): EndpointOperationSelection | undefined {
193
+ const endpoint = input.dataSource.endpoints[input.endpointId];
194
+ const operation = endpoint?.operations[input.operationId];
195
+
196
+ if (endpoint === undefined || operation === undefined) return undefined;
197
+
198
+ return { endpoint, operation };
199
+ }
200
+
201
+ async function resolveEndpointCredential(
202
+ input: EndpointTestInput,
203
+ selection: EndpointOperationSelection,
204
+ diagnostics: DataSourceDiagnostic[],
205
+ ): Promise<EndpointTestCredential | undefined> {
206
+ const credentialRef =
207
+ selection.operation.credential ?? selection.endpoint.credential ?? input.dataSource.credential;
208
+
209
+ if (credentialRef === undefined) return undefined;
210
+
211
+ if (input.credentialResolver === undefined) {
212
+ diagnostics.push(
213
+ createDiagnostic(
214
+ input,
215
+ 'missing-credential',
216
+ `Credential '${credentialRef.id}' requires a resolver.`,
217
+ ),
218
+ );
219
+ return undefined;
220
+ }
221
+
222
+ const credential = await input.credentialResolver(credentialRef);
223
+
224
+ if (credential === undefined) {
225
+ diagnostics.push(
226
+ createDiagnostic(
227
+ input,
228
+ 'missing-credential',
229
+ `Credential '${credentialRef.id}' could not be resolved.`,
230
+ ),
231
+ );
232
+ }
233
+
234
+ return credential;
235
+ }
236
+
237
+ function buildHttpRequest(
238
+ input: EndpointTestInput,
239
+ selection: EndpointOperationSelection,
240
+ credential: EndpointTestCredential | undefined,
241
+ diagnostics: DataSourceDiagnostic[],
242
+ ): EndpointTestRequestDiagnostic | undefined {
243
+ const baseUrl = getDataSourceBaseUrl(input.dataSource, selection.endpoint);
244
+ const path = selection.operation.path ?? selection.endpoint.path;
245
+
246
+ if (baseUrl === undefined || baseUrl.trim().length === 0) {
247
+ diagnostics.push(
248
+ createDiagnostic(input, 'invalid-config', 'HTTP endpoint requires a base URL.'),
249
+ );
250
+ return undefined;
251
+ }
252
+
253
+ if (path === undefined) {
254
+ diagnostics.push(createDiagnostic(input, 'invalid-config', 'HTTP operation requires a path.'));
255
+ return undefined;
256
+ }
257
+
258
+ const values = input.values ?? {};
259
+ const parameters = selection.operation.request?.parameters ?? [];
260
+ const pathResult = interpolatePath(path, parameters, values, input, diagnostics);
261
+ const query = collectQuery(parameters, values, credential?.query);
262
+ const url = appendQuery(joinUrl(baseUrl, pathResult), query);
263
+ const body = createHttpBody(selection.operation, values);
264
+ const headers: Record<string, string> = {
265
+ ...(credential?.headers ?? {}),
266
+ };
267
+
268
+ if (body !== undefined) {
269
+ headers['content-type'] = headers['content-type'] ?? 'application/json';
270
+ }
271
+
272
+ return {
273
+ dataSourceId: input.dataSource.id,
274
+ endpointId: input.endpointId,
275
+ operationId: input.operationId,
276
+ url,
277
+ method: selection.operation.method ?? 'GET',
278
+ headers,
279
+ body,
280
+ dryRun: input.dryRun === true,
281
+ };
282
+ }
283
+
284
+ function buildGraphQlRequest(
285
+ input: EndpointTestInput,
286
+ selection: EndpointOperationSelection,
287
+ credential: EndpointTestCredential | undefined,
288
+ diagnostics: DataSourceDiagnostic[],
289
+ ): EndpointTestRequestDiagnostic | undefined {
290
+ const endpointUrl = getGraphQlEndpointUrl(input.dataSource, selection.endpoint);
291
+
292
+ if (endpointUrl === undefined || endpointUrl.trim().length === 0) {
293
+ diagnostics.push(
294
+ createDiagnostic(input, 'invalid-config', 'GraphQL endpoint requires an endpoint URL.'),
295
+ );
296
+ return undefined;
297
+ }
298
+
299
+ const query =
300
+ getStringMetadataValue(selection.operation.metadata, 'document') ??
301
+ getStringValue(input.values, 'query');
302
+
303
+ if (query === undefined) {
304
+ diagnostics.push(
305
+ createDiagnostic(input, 'invalid-config', 'GraphQL operation requires a query document.'),
306
+ );
307
+ return undefined;
308
+ }
309
+
310
+ const variables = getRecordValue(input.values, 'variables');
311
+ const body = JSON.stringify({ query, variables: variables ?? {} });
312
+ const headers: Record<string, string> = {
313
+ ...(credential?.headers ?? {}),
314
+ 'content-type': 'application/json',
315
+ };
316
+
317
+ return {
318
+ dataSourceId: input.dataSource.id,
319
+ endpointId: input.endpointId,
320
+ operationId: input.operationId,
321
+ url: appendQuery(endpointUrl, credential?.query ?? {}),
322
+ method: 'POST',
323
+ headers,
324
+ body,
325
+ dryRun: input.dryRun === true,
326
+ };
327
+ }
328
+
329
+ function getDataSourceBaseUrl(
330
+ dataSource: DataSourceConfig,
331
+ endpoint: DataEndpointConfig,
332
+ ): string | undefined {
333
+ if (endpoint.baseUrl !== undefined) return endpoint.baseUrl;
334
+ if (dataSource.kind === 'rest' || dataSource.kind === 'openapi') return dataSource.baseUrl;
335
+ if (dataSource.kind === 'graphql') return dataSource.endpointUrl;
336
+ return undefined;
337
+ }
338
+
339
+ function getGraphQlEndpointUrl(
340
+ dataSource: DataSourceConfig,
341
+ endpoint: DataEndpointConfig,
342
+ ): string | undefined {
343
+ if (endpoint.baseUrl !== undefined) return endpoint.baseUrl;
344
+ if (dataSource.kind === 'graphql') return dataSource.endpointUrl;
345
+ return undefined;
346
+ }
347
+
348
+ function interpolatePath(
349
+ path: string,
350
+ parameters: readonly DataOperationParameter[],
351
+ values: EndpointTestInputValues,
352
+ input: EndpointTestInput,
353
+ diagnostics: DataSourceDiagnostic[],
354
+ ): string {
355
+ let nextPath = path;
356
+ const pathParameters = parameters.filter((parameter) => parameter.location === 'path');
357
+
358
+ for (const parameter of pathParameters) {
359
+ const value = values[parameter.name] ?? parameter.default;
360
+
361
+ if (value === undefined) {
362
+ diagnostics.push(
363
+ createDiagnostic(
364
+ input,
365
+ 'invalid-config',
366
+ `Missing required path parameter '${parameter.name}'.`,
367
+ ),
368
+ );
369
+ continue;
370
+ }
371
+
372
+ const encodedValue = encodeURIComponent(serializeEndpointUrlValue(value));
373
+ nextPath = nextPath.replaceAll(`{${parameter.name}}`, encodedValue);
374
+ nextPath = nextPath.replaceAll(`:${parameter.name}`, encodedValue);
375
+ }
376
+
377
+ return nextPath;
378
+ }
379
+
380
+ function collectQuery(
381
+ parameters: readonly DataOperationParameter[],
382
+ values: EndpointTestInputValues,
383
+ credentialQuery: EndpointTestInputValues | undefined,
384
+ ): EndpointTestInputValues {
385
+ const query: Record<string, DataContractValue> = { ...(credentialQuery ?? {}) };
386
+
387
+ for (const parameter of parameters) {
388
+ if (parameter.location !== 'query') continue;
389
+
390
+ const value = values[parameter.name] ?? parameter.default;
391
+ if (value !== undefined) query[parameter.name] = value;
392
+ }
393
+
394
+ return query;
395
+ }
396
+
397
+ function createHttpBody(
398
+ operation: DataOperationConfig,
399
+ values: EndpointTestInputValues,
400
+ ): string | undefined {
401
+ if (operation.method === 'GET' || operation.method === 'HEAD') return undefined;
402
+
403
+ const { body } = values;
404
+ if (body === undefined) return undefined;
405
+
406
+ return JSON.stringify(body);
407
+ }
408
+
409
+ async function createResponseDiagnostic(
410
+ response: EndpointTestFetchResponse,
411
+ ): Promise<EndpointTestResponseDiagnostic> {
412
+ const bodyText = await response.text();
413
+ const parsedBody = parseResponseBody(bodyText);
414
+
415
+ return {
416
+ status: response.status,
417
+ ok: response.status >= 200 && response.status < 300,
418
+ headers: response.headers,
419
+ bodyText,
420
+ parsedBody,
421
+ };
422
+ }
423
+
424
+ function parseResponseBody(bodyText: string): DataContractValue | undefined {
425
+ if (bodyText.trim().length === 0) return undefined;
426
+
427
+ try {
428
+ const parsed: unknown = JSON.parse(bodyText);
429
+ return isDataContractValue(parsed) ? parsed : { raw: bodyText };
430
+ } catch {
431
+ return { raw: bodyText };
432
+ }
433
+ }
434
+
435
+ function appendQuery(url: string, query: EndpointTestInputValues): string {
436
+ const entries = Object.entries(query);
437
+ if (entries.length === 0) return url;
438
+
439
+ const search = entries
440
+ .map(
441
+ ([key, value]) =>
442
+ `${encodeURIComponent(key)}=${encodeURIComponent(serializeEndpointUrlValue(value))}`,
443
+ )
444
+ .join('&');
445
+ const separator = url.includes('?') ? '&' : '?';
446
+
447
+ return `${url}${separator}${search}`;
448
+ }
449
+
450
+ function serializeEndpointUrlValue(value: DataContractValue): string {
451
+ if (typeof value === 'string') return value;
452
+ if (typeof value === 'number' || typeof value === 'boolean') return value.toString();
453
+ if (value === null) return '';
454
+
455
+ return JSON.stringify(value);
456
+ }
457
+
458
+ function joinUrl(baseUrl: string, path: string): string {
459
+ const normalizedBase = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
460
+ const normalizedPath = path.startsWith('/') ? path : `/${path}`;
461
+
462
+ return `${normalizedBase}${normalizedPath}`;
463
+ }
464
+
465
+ function getStringValue(
466
+ values: EndpointTestInputValues | undefined,
467
+ key: string,
468
+ ): string | undefined {
469
+ const value = values?.[key];
470
+ return typeof value === 'string' ? value : undefined;
471
+ }
472
+
473
+ function getRecordValue(
474
+ values: EndpointTestInputValues | undefined,
475
+ key: string,
476
+ ): DataContractValue | undefined {
477
+ const value = values?.[key];
478
+ return isDataContractValue(value) ? value : undefined;
479
+ }
480
+
481
+ function getStringMetadataValue(
482
+ metadata: DataContractValue | undefined,
483
+ key: string,
484
+ ): string | undefined {
485
+ if (!isDataContractRecord(metadata)) return undefined;
486
+
487
+ const value = metadata[key];
488
+ return typeof value === 'string' ? value : undefined;
489
+ }
490
+
491
+ function createDiagnostic(
492
+ input: EndpointTestInput,
493
+ code: string,
494
+ message: string,
495
+ ): DataSourceDiagnostic {
496
+ return {
497
+ code,
498
+ dataSourceId: input.dataSource.id,
499
+ endpointId: input.endpointId,
500
+ operationId: input.operationId,
501
+ message,
502
+ severity: code === 'missing-schema' ? 'info' : 'error',
503
+ };
504
+ }
505
+
506
+ function createNetworkErrorMessage(error: unknown): string {
507
+ if (error instanceof Error) return error.message;
508
+ return 'Endpoint test request failed.';
509
+ }
510
+
511
+ function isDataContractValue(value: unknown): value is DataContractValue {
512
+ if (
513
+ value === null ||
514
+ typeof value === 'string' ||
515
+ typeof value === 'number' ||
516
+ typeof value === 'boolean'
517
+ ) {
518
+ return true;
519
+ }
520
+
521
+ if (Array.isArray(value)) return value.every(isDataContractValue);
522
+ if (typeof value !== 'object') return false;
523
+
524
+ return Object.values(value).every(isDataContractValue);
525
+ }
526
+
527
+ function isDataContractRecord(
528
+ value: DataContractValue | undefined,
529
+ ): value is Record<string, DataContractValue> {
530
+ return (
531
+ value !== undefined && typeof value === 'object' && value !== null && !Array.isArray(value)
532
+ );
533
+ }