@thymian/plugin-sampler 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +11 -0
  2. package/dist/cli/commands/sampler/hooks/generate.d.ts +9 -0
  3. package/dist/cli/commands/sampler/hooks/generate.d.ts.map +1 -0
  4. package/dist/cli/commands/sampler/hooks/generate.js +18 -0
  5. package/dist/cli/commands/sampler/hooks/generate.js.map +1 -0
  6. package/dist/cli/commands/sampler/init.d.ts +9 -0
  7. package/dist/cli/commands/sampler/init.d.ts.map +1 -0
  8. package/dist/cli/commands/sampler/init.js +55 -0
  9. package/dist/cli/commands/sampler/init.js.map +1 -0
  10. package/dist/cli/create-context.d.ts +3 -0
  11. package/dist/cli/create-context.d.ts.map +1 -0
  12. package/dist/cli/create-context.js +21 -0
  13. package/dist/cli/create-context.js.map +1 -0
  14. package/dist/cli/generate-hook.d.ts +4 -0
  15. package/dist/cli/generate-hook.d.ts.map +1 -0
  16. package/dist/cli/generate-hook.js +92 -0
  17. package/dist/cli/generate-hook.js.map +1 -0
  18. package/dist/cli/templates.d.ts +4 -0
  19. package/dist/cli/templates.d.ts.map +1 -0
  20. package/dist/cli/templates.js +28 -0
  21. package/dist/cli/templates.js.map +1 -0
  22. package/dist/constants.d.ts +5 -0
  23. package/dist/constants.d.ts.map +1 -0
  24. package/dist/constants.js +5 -0
  25. package/dist/constants.js.map +1 -0
  26. package/dist/generation/content-source-generator.d.ts +10 -0
  27. package/dist/generation/content-source-generator.d.ts.map +1 -0
  28. package/dist/generation/content-source-generator.js +15 -0
  29. package/dist/generation/content-source-generator.js.map +1 -0
  30. package/dist/generation/content-type-strategies/content-type-strategy.d.ts +7 -0
  31. package/dist/generation/content-type-strategies/content-type-strategy.d.ts.map +1 -0
  32. package/dist/generation/content-type-strategies/content-type-strategy.js +2 -0
  33. package/dist/generation/content-type-strategies/content-type-strategy.js.map +1 -0
  34. package/dist/generation/content-type-strategies/error.content-type-strategy.d.ts +7 -0
  35. package/dist/generation/content-type-strategies/error.content-type-strategy.d.ts.map +1 -0
  36. package/dist/generation/content-type-strategies/error.content-type-strategy.js +13 -0
  37. package/dist/generation/content-type-strategies/error.content-type-strategy.js.map +1 -0
  38. package/dist/generation/content-type-strategies/hook.content-type-strategy.d.ts +10 -0
  39. package/dist/generation/content-type-strategies/hook.content-type-strategy.d.ts.map +1 -0
  40. package/dist/generation/content-type-strategies/hook.content-type-strategy.js +27 -0
  41. package/dist/generation/content-type-strategies/hook.content-type-strategy.js.map +1 -0
  42. package/dist/generation/content-type-strategies/image.content-type-strategy.d.ts +15 -0
  43. package/dist/generation/content-type-strategies/image.content-type-strategy.d.ts.map +1 -0
  44. package/dist/generation/content-type-strategies/image.content-type-strategy.js +40 -0
  45. package/dist/generation/content-type-strategies/image.content-type-strategy.js.map +1 -0
  46. package/dist/generation/content-type-strategies/json.content-type-strategy.d.ts +8 -0
  47. package/dist/generation/content-type-strategies/json.content-type-strategy.d.ts.map +1 -0
  48. package/dist/generation/content-type-strategies/json.content-type-strategy.js +12 -0
  49. package/dist/generation/content-type-strategies/json.content-type-strategy.js.map +1 -0
  50. package/dist/generation/content-type-strategies/text.content-type-strategy.d.ts +8 -0
  51. package/dist/generation/content-type-strategies/text.content-type-strategy.d.ts.map +1 -0
  52. package/dist/generation/content-type-strategies/text.content-type-strategy.js +13 -0
  53. package/dist/generation/content-type-strategies/text.content-type-strategy.js.map +1 -0
  54. package/dist/generation/content-type-strategies/xml.content-type-strategy.d.ts +8 -0
  55. package/dist/generation/content-type-strategies/xml.content-type-strategy.d.ts.map +1 -0
  56. package/dist/generation/content-type-strategies/xml.content-type-strategy.js +14 -0
  57. package/dist/generation/content-type-strategies/xml.content-type-strategy.js.map +1 -0
  58. package/dist/generation/generate-samples-for-thymian-format.d.ts +4 -0
  59. package/dist/generation/generate-samples-for-thymian-format.d.ts.map +1 -0
  60. package/dist/generation/generate-samples-for-thymian-format.js +18 -0
  61. package/dist/generation/generate-samples-for-thymian-format.js.map +1 -0
  62. package/dist/generation/generate-samples.d.ts +4 -0
  63. package/dist/generation/generate-samples.d.ts.map +1 -0
  64. package/dist/generation/generate-samples.js +26 -0
  65. package/dist/generation/generate-samples.js.map +1 -0
  66. package/dist/generation/request-generators/default-request-generator.d.ts +22 -0
  67. package/dist/generation/request-generators/default-request-generator.d.ts.map +1 -0
  68. package/dist/generation/request-generators/default-request-generator.js +80 -0
  69. package/dist/generation/request-generators/default-request-generator.js.map +1 -0
  70. package/dist/generation/request-generators/range-request-generator.d.ts +8 -0
  71. package/dist/generation/request-generators/range-request-generator.d.ts.map +1 -0
  72. package/dist/generation/request-generators/range-request-generator.js +22 -0
  73. package/dist/generation/request-generators/range-request-generator.js.map +1 -0
  74. package/dist/generation/request-generators/unauthorized-request-generator.d.ts +6 -0
  75. package/dist/generation/request-generators/unauthorized-request-generator.d.ts.map +1 -0
  76. package/dist/generation/request-generators/unauthorized-request-generator.js +10 -0
  77. package/dist/generation/request-generators/unauthorized-request-generator.js.map +1 -0
  78. package/dist/hooks/create-hook-utils.d.ts +8 -0
  79. package/dist/hooks/create-hook-utils.d.ts.map +1 -0
  80. package/dist/hooks/create-hook-utils.js +137 -0
  81. package/dist/hooks/create-hook-utils.js.map +1 -0
  82. package/dist/hooks/generate-request-types.d.ts +30 -0
  83. package/dist/hooks/generate-request-types.d.ts.map +1 -0
  84. package/dist/hooks/generate-request-types.js +424 -0
  85. package/dist/hooks/generate-request-types.js.map +1 -0
  86. package/dist/hooks/hook-errors.d.ts +5 -0
  87. package/dist/hooks/hook-errors.d.ts.map +1 -0
  88. package/dist/hooks/hook-errors.js +5 -0
  89. package/dist/hooks/hook-errors.js.map +1 -0
  90. package/dist/hooks/hook-runner.d.ts +18 -0
  91. package/dist/hooks/hook-runner.d.ts.map +1 -0
  92. package/dist/hooks/hook-runner.js +172 -0
  93. package/dist/hooks/hook-runner.js.map +1 -0
  94. package/dist/hooks/hook-types.d.ts +7 -0
  95. package/dist/hooks/hook-types.d.ts.map +1 -0
  96. package/dist/hooks/hook-types.js +2 -0
  97. package/dist/hooks/hook-types.js.map +1 -0
  98. package/dist/hooks/hook-utils.d.ts +36 -0
  99. package/dist/hooks/hook-utils.d.ts.map +1 -0
  100. package/dist/hooks/hook-utils.js +2 -0
  101. package/dist/hooks/hook-utils.js.map +1 -0
  102. package/dist/hooks/load-hooks-from-samples.d.ts +3 -0
  103. package/dist/hooks/load-hooks-from-samples.d.ts.map +1 -0
  104. package/dist/hooks/load-hooks-from-samples.js +22 -0
  105. package/dist/hooks/load-hooks-from-samples.js.map +1 -0
  106. package/dist/hooks/ts-config.d.ts +10 -0
  107. package/dist/hooks/ts-config.d.ts.map +1 -0
  108. package/dist/hooks/ts-config.js +10 -0
  109. package/dist/hooks/ts-config.js.map +1 -0
  110. package/dist/http-request-sample.d.ts +24 -0
  111. package/dist/http-request-sample.d.ts.map +1 -0
  112. package/dist/http-request-sample.js +11 -0
  113. package/dist/http-request-sample.js.map +1 -0
  114. package/dist/index.d.ts +41 -0
  115. package/dist/index.d.ts.map +1 -0
  116. package/dist/index.js +145 -0
  117. package/dist/index.js.map +1 -0
  118. package/dist/request-sample-to-request-template.d.ts +6 -0
  119. package/dist/request-sample-to-request-template.d.ts.map +1 -0
  120. package/dist/request-sample-to-request-template.js +35 -0
  121. package/dist/request-sample-to-request-template.js.map +1 -0
  122. package/dist/request-sampler.d.ts +15 -0
  123. package/dist/request-sampler.d.ts.map +1 -0
  124. package/dist/request-sampler.js +82 -0
  125. package/dist/request-sampler.js.map +1 -0
  126. package/dist/samples-structure/file-request-sample.d.ts +20 -0
  127. package/dist/samples-structure/file-request-sample.d.ts.map +1 -0
  128. package/dist/samples-structure/file-request-sample.js +5 -0
  129. package/dist/samples-structure/file-request-sample.js.map +1 -0
  130. package/dist/samples-structure/get-path-transaction-id.d.ts +3 -0
  131. package/dist/samples-structure/get-path-transaction-id.d.ts.map +1 -0
  132. package/dist/samples-structure/get-path-transaction-id.js +22 -0
  133. package/dist/samples-structure/get-path-transaction-id.js.map +1 -0
  134. package/dist/samples-structure/merge-tree.d.ts +5 -0
  135. package/dist/samples-structure/merge-tree.d.ts.map +1 -0
  136. package/dist/samples-structure/merge-tree.js +118 -0
  137. package/dist/samples-structure/merge-tree.js.map +1 -0
  138. package/dist/samples-structure/read-samples-from-dir.d.ts +13 -0
  139. package/dist/samples-structure/read-samples-from-dir.d.ts.map +1 -0
  140. package/dist/samples-structure/read-samples-from-dir.js +204 -0
  141. package/dist/samples-structure/read-samples-from-dir.js.map +1 -0
  142. package/dist/samples-structure/samples-from-transactions.d.ts +5 -0
  143. package/dist/samples-structure/samples-from-transactions.d.ts.map +1 -0
  144. package/dist/samples-structure/samples-from-transactions.js +120 -0
  145. package/dist/samples-structure/samples-from-transactions.js.map +1 -0
  146. package/dist/samples-structure/samples-tree-structure.d.ts +106 -0
  147. package/dist/samples-structure/samples-tree-structure.d.ts.map +1 -0
  148. package/dist/samples-structure/samples-tree-structure.js +26 -0
  149. package/dist/samples-structure/samples-tree-structure.js.map +1 -0
  150. package/dist/samples-structure/structure-meta-on-disc.d.ts +11 -0
  151. package/dist/samples-structure/structure-meta-on-disc.d.ts.map +1 -0
  152. package/dist/samples-structure/structure-meta-on-disc.js +2 -0
  153. package/dist/samples-structure/structure-meta-on-disc.js.map +1 -0
  154. package/dist/samples-structure/traverse.d.ts +4 -0
  155. package/dist/samples-structure/traverse.d.ts.map +1 -0
  156. package/dist/samples-structure/traverse.js +13 -0
  157. package/dist/samples-structure/traverse.js.map +1 -0
  158. package/dist/samples-structure/write-samples-to-dir.d.ts +25 -0
  159. package/dist/samples-structure/write-samples-to-dir.d.ts.map +1 -0
  160. package/dist/samples-structure/write-samples-to-dir.js +173 -0
  161. package/dist/samples-structure/write-samples-to-dir.js.map +1 -0
  162. package/dist/utils.d.ts +4 -0
  163. package/dist/utils.d.ts.map +1 -0
  164. package/dist/utils.js +26 -0
  165. package/dist/utils.js.map +1 -0
  166. package/package.json +51 -0
@@ -0,0 +1,424 @@
1
+ import { isEdgeType, thymianHttpRequestToUrl, } from '@thymian/core';
2
+ import CodeBlockWriter from 'code-block-writer';
3
+ import { compile } from 'json-schema-to-typescript';
4
+ export async function generateTypeForSchema(schema, mediaType) {
5
+ if (!(mediaType === 'application/json' || mediaType.includes('+json'))) {
6
+ return 'unknown';
7
+ }
8
+ const type = await compile(schema, 'Type', {
9
+ bannerComment: '',
10
+ additionalProperties: true,
11
+ style: {
12
+ semi: false,
13
+ },
14
+ });
15
+ return type.replace(/export (interface|type) Type =?/, '');
16
+ }
17
+ export async function generateTypeForParameters2(parameters) {
18
+ const schema = {
19
+ type: 'object',
20
+ properties: {},
21
+ required: [],
22
+ };
23
+ for (const [name, param] of Object.entries(parameters)) {
24
+ schema.properties[name] = param.schema;
25
+ if (param.required) {
26
+ schema.required.push(name);
27
+ }
28
+ }
29
+ return {
30
+ type: await generateTypeForSchema(schema, "'application/json'"),
31
+ required: schema.required.length > 0,
32
+ };
33
+ }
34
+ export async function generateTypeForParameters(parameters) {
35
+ const result = {
36
+ required: false,
37
+ types: {},
38
+ };
39
+ for (const [name, param] of Object.entries(parameters)) {
40
+ result.required ||= param.required;
41
+ result.types[name] = await generateTypeForSchema(param.schema, param.contentType ?? 'application/json');
42
+ }
43
+ const writer = new CodeBlockWriter({
44
+ indentNumberOfSpaces: 2,
45
+ });
46
+ writer.block(() => {
47
+ for (const [name, type] of Object.entries(result.types)) {
48
+ writer.quote(name).write(': ').write(type).writeLine(';');
49
+ }
50
+ });
51
+ return {
52
+ type: writer.toString(),
53
+ required: result.required,
54
+ };
55
+ }
56
+ export const staticCode = `
57
+ export type HttpRequestTemplate = {
58
+ origin: string;
59
+ path: string;
60
+ pathParameters: Record<string, unknown>;
61
+ method: string;
62
+ query: Record<string, unknown>;
63
+ authorize: boolean;
64
+ bodyEncoding?: string;
65
+ body?: unknown;
66
+ headers: Record<string, unknown>;
67
+ cookies: Record<string, unknown>;
68
+ };
69
+
70
+ export type ThymianHttpTransaction = {
71
+ thymianReq: ThymianHttpRequest;
72
+ thymianReqId: string;
73
+ thymianRes: ThymianHttpResponse;
74
+ thymianResId: string;
75
+ transactionId: string;
76
+ transaction: HttpTransaction;
77
+ };
78
+
79
+ export interface ThymianHttpRequest {
80
+ host: string;
81
+ port: number;
82
+ protocol: 'http' | 'https';
83
+ path: string;
84
+ method: string;
85
+ headers: Record<string, Parameter>;
86
+ queryParameters: Record<string, Parameter>;
87
+ cookies: Record<string, Parameter>;
88
+ pathParameters: Record<string, Parameter>;
89
+ description?: string;
90
+ bodyRequired?: boolean;
91
+ body?: ThymianSchema;
92
+ mediaType: string;
93
+ encoding?: Encoding;
94
+ }
95
+
96
+ export type Encoding = {
97
+ [propertyName: string]: {
98
+ contentType?: string;
99
+ headers: Record<string, Parameter>;
100
+ serializationStyle: SerializationStyle;
101
+ };
102
+ };
103
+
104
+ export interface ThymianHttpResponse {
105
+ description?: string;
106
+ headers: Record<string, Parameter>;
107
+ mediaType: string;
108
+ statusCode: number;
109
+ schema?: ThymianSchema;
110
+ }
111
+
112
+ export interface HttpTransaction {
113
+ }
114
+
115
+ export type HttpResponse = {
116
+ statusCode: number;
117
+ headers: Record<string, string | string[] | undefined>;
118
+ body?: string;
119
+ bodyEncoding?: string;
120
+ trailers: Record<string, string>;
121
+ duration: number;
122
+ };
123
+
124
+ export type HttpRequest = {
125
+ origin: string;
126
+ path: string;
127
+ method: string;
128
+ bodyEncoding?: string;
129
+ body?: string;
130
+ headers?: Record<string, string | string[] | undefined>;
131
+ };
132
+
133
+
134
+ export interface Parameter {
135
+ description?: string;
136
+ required: boolean;
137
+ schema: ThymianSchema;
138
+ contentType?: string;
139
+ style: SerializationStyle;
140
+ }
141
+
142
+ export type Style =
143
+ | 'matrix'
144
+ | 'label'
145
+ | 'form'
146
+ | 'simple'
147
+ | 'spaceDelimited'
148
+ | 'pipeDelimited'
149
+ | 'deepObject';
150
+
151
+ export interface SerializationStyle {
152
+ explode: boolean;
153
+
154
+ style: Style;
155
+ }
156
+
157
+ export type ThymianSchemaType =
158
+ | 'null'
159
+ | 'boolean'
160
+ | 'object'
161
+ | 'array'
162
+ | 'number'
163
+ | 'string'
164
+ | 'integer';
165
+
166
+ export type ThymianSchema = {
167
+ // Type
168
+ type?: ThymianSchemaType | ThymianSchemaType[];
169
+ const?: unknown;
170
+ enum?: unknown[];
171
+
172
+ examples?: unknown[];
173
+ description?: string;
174
+ default?: unknown;
175
+
176
+ // Numbers
177
+ multipleOf?: number;
178
+ maximum?: number;
179
+ exclusiveMaximum?: number;
180
+ minimum?: number;
181
+ exclusiveMinimum?: number;
182
+
183
+ // Strings
184
+ maxLength?: number;
185
+ minLength?: number;
186
+ pattern?: string;
187
+ format?: string;
188
+ contentEncoding?: string;
189
+ contentMediaType?: string;
190
+
191
+ // Arrays
192
+ prefixItems?: ThymianSchema[];
193
+ items?: ThymianSchema;
194
+ contains?: ThymianSchema;
195
+ minItems?: number;
196
+ maxItems?: number;
197
+ uniqueItems?: boolean;
198
+ minContains?: number;
199
+ maxContains?: number;
200
+
201
+ // Objects
202
+ properties?: Record<string, ThymianSchema>;
203
+ patternProperties?: Record<string, ThymianSchema>;
204
+ additionalProperties?: ThymianSchema | boolean;
205
+ propertyNames?: ThymianSchema;
206
+ required?: string[];
207
+ minProperties?: number;
208
+ maxProperties?: number;
209
+ dependentSchemas?: Record<string, ThymianSchema>;
210
+ dependentRequired?: Record<string, string[]>;
211
+
212
+ allOf?: ThymianSchema[];
213
+ anyOf?: ThymianSchema[];
214
+ oneOf?: ThymianSchema[];
215
+ not?: ThymianSchema;
216
+ if?: ThymianSchema;
217
+ then?: ThymianSchema;
218
+ else?: ThymianSchema;
219
+
220
+ unevaluatedProperties?: ThymianSchema | boolean;
221
+ unevaluatedItems?: ThymianSchema | boolean;
222
+
223
+ $ref?: string;
224
+ $anchor?: string;
225
+
226
+ xml?: {
227
+ name?: string;
228
+ namespace?: string;
229
+ prefix?: string;
230
+ attribute?: string;
231
+ wrapped?: boolean;
232
+ };
233
+ };
234
+
235
+
236
+ export type BeforeEachRequestHook = (request: HttpRequestTemplate, context: ThymianHttpTransaction | undefined, utils: HookUtils) => HttpRequestTemplate | Promise<HttpRequestTemplate>;
237
+
238
+ export type AfterEachRequestHookContext = {
239
+ requestTemplate: HttpRequestTemplate;
240
+ request: HttpRequest;
241
+ thymianTransaction?: ThymianHttpTransaction;
242
+ }
243
+
244
+ export type AfterEachRequestHook = (response: HttpResponse, context: AfterEachRequestHookContext, utils: HookUtils) => HttpResponse | Promise<HttpResponse>;
245
+
246
+ export type AuthorizeHook = (response: HttpRequestTemplate, context: ThymianHttpTransaction | undefined, utils: HookUtils) => HttpRequestTemplate | Promise<HttpRequestTemplate>;
247
+
248
+ export interface HookUtils {
249
+ skip(message: string): never;
250
+
251
+ fail(message: string): never;
252
+
253
+ info(message: string): void;
254
+
255
+ warn(message: string, details?: string): void;
256
+
257
+ assertionSuccess(message: string, assertion?: string): void;
258
+
259
+ assertionFailure(
260
+ message: string,
261
+ details?: { assertion?: string; expected?: unknown; actual?: unknown },
262
+ ): void;
263
+
264
+ timeout(message: string, durationMs: number): void;
265
+
266
+ request<R extends keyof Endpoints>(
267
+ req: R,
268
+ args: Endpoints[R]['req'],
269
+ options?: {
270
+ runHooks?: boolean;
271
+ authorize?: boolean;
272
+ forStatusCode?: number;
273
+ }
274
+ ): Promise<Endpoints[R]['res']>;
275
+
276
+ randomString(length?: number): string;
277
+ }
278
+ `;
279
+ export const infoText = `
280
+ /*
281
+ * ========================================================================
282
+ *
283
+ * WARNING: THIS FILE IS AUTO-GENERATED. DO NOT EDIT.
284
+ *
285
+ * Any changes made to this file will be lost if the code is regenerated.
286
+ *
287
+ * ========================================================================
288
+ */
289
+ `;
290
+ export function generatedTypesToString(types) {
291
+ const writer = new CodeBlockWriter({
292
+ indentNumberOfSpaces: 2,
293
+ });
294
+ writer.writeLine(infoText).write(staticCode);
295
+ writer.writeLine(`export type Endpoints = `).block(() => {
296
+ for (const [key, { req, res }] of Object.entries(types)) {
297
+ writer
298
+ .quote(key)
299
+ .write(':')
300
+ .block(() => {
301
+ writer
302
+ .writeLine(`req:`)
303
+ .block(() => {
304
+ // body
305
+ if (typeof req.body === 'string') {
306
+ writer.writeLine(`body:`).writeLine(req.body);
307
+ }
308
+ writer
309
+ // query params
310
+ .writeLine(`query${req.query.required ? '' : '?'}:`)
311
+ .writeLine(req.query.type)
312
+ .writeLine(' & { [query: string]: string | number | boolean }')
313
+ // path params
314
+ .writeLine(`path${req.path.required ? '' : '?'}:`)
315
+ .writeLine(req.path.type)
316
+ .writeLine(' & { [param: string]: string | number | boolean }')
317
+ // headers
318
+ .writeLine(`headers${req.headers.required ? '' : '?'}:`)
319
+ .writeLine(req.headers.type)
320
+ .writeLine(' & { [param: string]: string | string[] | undefined }');
321
+ })
322
+ .write(',')
323
+ .writeLine(`res:`);
324
+ if (res.length === 0) {
325
+ writer.write('never;');
326
+ }
327
+ for (const { statusCode, body, headers } of res) {
328
+ writer.writeLine(`|`);
329
+ writer.block(() => {
330
+ writer
331
+ .writeLine(`statusCode: ${statusCode};`)
332
+ .writeLine(`headers${headers.required ? '' : '?'}:`)
333
+ .writeLine(headers.type)
334
+ .writeLine(' & { [param: string]: string | string[] | undefined }');
335
+ if (body) {
336
+ writer.writeLine(`body:`).writeLine(body);
337
+ }
338
+ });
339
+ }
340
+ });
341
+ }
342
+ });
343
+ return writer.toString();
344
+ }
345
+ const mediaTypeParameter = (mediaType) => ({
346
+ schema: {
347
+ type: 'string',
348
+ const: mediaType,
349
+ },
350
+ required: true,
351
+ style: { style: 'simple', explode: false },
352
+ });
353
+ export async function generateTypesForThymianFormat(format) {
354
+ const generated = {
355
+ types: {},
356
+ keyToTransactionId: {},
357
+ };
358
+ for (const [req, responses, reqId, responseIds,] of format.getThymianHttpRequestsWithResponses()) {
359
+ const allHeaders = {
360
+ ...req.headers,
361
+ };
362
+ if (req.mediaType) {
363
+ allHeaders['content-type'] = mediaTypeParameter(req.mediaType);
364
+ }
365
+ const key = `${req.method.toUpperCase()} ${thymianHttpRequestToUrl(req)}`;
366
+ const query = await generateTypeForParameters(req.queryParameters);
367
+ const path = await generateTypeForParameters(req.pathParameters);
368
+ const headers = await generateTypeForParameters(allHeaders);
369
+ const body = req.body
370
+ ? await generateTypeForSchema(req.body, req.mediaType)
371
+ : undefined;
372
+ const res = await Promise.all(responses.map(async (res) => {
373
+ const headers = {
374
+ ...res.headers,
375
+ };
376
+ if (res.mediaType) {
377
+ headers['content-type'] = mediaTypeParameter(res.mediaType);
378
+ }
379
+ const result = {
380
+ statusCode: res.statusCode,
381
+ headers: await generateTypeForParameters(headers),
382
+ };
383
+ if (res.schema) {
384
+ result.body = await generateTypeForSchema(res.schema, res.mediaType);
385
+ }
386
+ return result;
387
+ }));
388
+ const default2xxResponse = res
389
+ .filter((r) => r.statusCode >= 200 && r.statusCode < 300)
390
+ .sort((a, b) => a.statusCode - b.statusCode)[0];
391
+ if (default2xxResponse) {
392
+ const idx = res.indexOf(default2xxResponse);
393
+ // this should never happen, but just in case
394
+ if (idx < 0) {
395
+ throw new Error('Could not find default 2xx response');
396
+ }
397
+ const transactionId = format.graph.findEdge(reqId, responseIds[idx], (edgeId, edge) => isEdgeType(edge, 'http-transaction'));
398
+ if (!transactionId) {
399
+ throw new Error('Could not find transaction ID for default 2xx response');
400
+ }
401
+ generated.keyToTransactionId[key] = transactionId;
402
+ }
403
+ for (const [idx, response] of res.entries()) {
404
+ const transactionId = format.graph.findEdge(reqId, responseIds[idx], (edgeId, edge) => isEdgeType(edge, 'http-transaction'));
405
+ // should never happen, but just in case
406
+ if (!transactionId) {
407
+ throw new Error('Could not find transaction ID for default 2xx response');
408
+ }
409
+ generated.keyToTransactionId[`${key}->${response.statusCode}`] =
410
+ transactionId;
411
+ }
412
+ generated.types[key] = {
413
+ req: {
414
+ query,
415
+ headers,
416
+ path,
417
+ body,
418
+ },
419
+ res,
420
+ };
421
+ }
422
+ return generated;
423
+ }
424
+ //# sourceMappingURL=generate-request-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-request-types.js","sourceRoot":"","sources":["../../src/hooks/generate-request-types.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EAGV,uBAAuB,GACxB,MAAM,eAAe,CAAC;AACvB,OAAO,eAAe,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAmB,MAAM,2BAA2B,CAAC;AAErE,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,MAAe,EACf,SAAiB;IAEjB,IAAI,CAAC,CAAC,SAAS,KAAK,kBAAkB,IAAI,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;QACvE,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,MAAoB,EAAE,MAAM,EAAE;QACvD,aAAa,EAAE,EAAE;QACjB,oBAAoB,EAAE,IAAI;QAC1B,KAAK,EAAE;YACL,IAAI,EAAE,KAAK;SACZ;KACF,CAAC,CAAC;IAEH,OAAO,IAAI,CAAC,OAAO,CAAC,iCAAiC,EAAE,EAAE,CAAC,CAAC;AAC7D,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,UAAqC;IAErC,MAAM,MAAM,GAIR;QACF,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,EAAE;QACd,QAAQ,EAAE,EAAE;KACb,CAAC;IAEF,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC;QACvD,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC;QAEvC,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;YACnB,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC;IAED,OAAO;QACL,IAAI,EAAE,MAAM,qBAAqB,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,MAAM,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC,QAAQ,CACzC,KAAK,EACL,WAAW,CAAC,GAAG,CAAE,EACjB,CAAC,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,EAAE,kBAAkB,CAAC,CACvD,CAAC;YAEF,IAAI,CAAC,aAAa,EAAE,CAAC;gBACnB,MAAM,IAAI,KAAK,CACb,wDAAwD,CACzD,CAAC;YACJ,CAAC;YAED,SAAS,CAAC,kBAAkB,CAAC,GAAG,CAAC,GAAG,aAAa,CAAC;QACpD,CAAC;QAED,KAAK,MAAM,CAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC;YAC5C,MAAM,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC,QAAQ,CACzC,KAAK,EACL,WAAW,CAAC,GAAG,CAAE,EACjB,CAAC,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,EAAE,kBAAkB,CAAC,CACvD,CAAC;YAEF,wCAAwC;YACxC,IAAI,CAAC,aAAa,EAAE,CAAC;gBACnB,MAAM,IAAI,KAAK,CACb,wDAAwD,CACzD,CAAC;YACJ,CAAC;YAED,SAAS,CAAC,kBAAkB,CAAC,GAAG,GAAG,KAAK,QAAQ,CAAC,UAAU,EAAE,CAAC;gBAC5D,aAAa,CAAC;QAClB,CAAC;QAED,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG;YACrB,GAAG,EAAE;gBACH,KAAK;gBACL,OAAO;gBACP,IAAI;gBACJ,IAAI;aACL;YACD,GAAG;SACJ,CAAC;IACJ,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC"}
@@ -0,0 +1,5 @@
1
+ export declare class SkipError extends Error {
2
+ }
3
+ export declare class FailError extends Error {
4
+ }
5
+ //# sourceMappingURL=hook-errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-errors.d.ts","sourceRoot":"","sources":["../../src/hooks/hook-errors.ts"],"names":[],"mappings":"AAAA,qBAAa,SAAU,SAAQ,KAAK;CAAG;AAEvC,qBAAa,SAAU,SAAQ,KAAK;CAAG"}
@@ -0,0 +1,5 @@
1
+ export class SkipError extends Error {
2
+ }
3
+ export class FailError extends Error {
4
+ }
5
+ //# sourceMappingURL=hook-errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-errors.js","sourceRoot":"","sources":["../../src/hooks/hook-errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,SAAU,SAAQ,KAAK;CAAG;AAEvC,MAAM,OAAO,SAAU,SAAQ,KAAK;CAAG"}
@@ -0,0 +1,18 @@
1
+ import type { HttpTestHooks } from '@thymian/core';
2
+ import { type HttpRequest, type HttpResponse, type Logger, type ThymianFormat } from '@thymian/core';
3
+ import type { SamplesStructure } from '../samples-structure/samples-tree-structure.js';
4
+ export declare class HookRunner {
5
+ private readonly path;
6
+ private readonly runRequest;
7
+ private readonly logger;
8
+ private initialized;
9
+ private hooks;
10
+ private urlToTransactionId;
11
+ private format;
12
+ constructor(path: string, runRequest: (req: HttpRequest) => Promise<HttpResponse>, logger: Logger);
13
+ init(format: ThymianFormat, samplesStructure?: SamplesStructure): Promise<void>;
14
+ afterEachResponse(hook: HttpTestHooks['afterResponse']['arg']): Promise<HttpTestHooks['afterResponse']['return']>;
15
+ authorize(hook: HttpTestHooks['authorize']['arg']): Promise<HttpTestHooks['authorize']['return']>;
16
+ beforeEachRequest(hook: HttpTestHooks['beforeRequest']['arg']): Promise<HttpTestHooks['beforeRequest']['return']>;
17
+ }
18
+ //# sourceMappingURL=hook-runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-runner.d.ts","sourceRoot":"","sources":["../../src/hooks/hook-runner.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAsB,aAAa,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,MAAM,EAEX,KAAK,aAAa,EAEnB,MAAM,eAAe,CAAC;AAGvB,OAAO,KAAK,EAEV,gBAAgB,EACjB,MAAM,gDAAgD,CAAC;AAOxD,qBAAa,UAAU;IAOnB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM;IARzB,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,KAAK,CAAiC;IAC9C,OAAO,CAAC,kBAAkB,CAA8B;IACxD,OAAO,CAAC,MAAM,CAAiB;gBAGZ,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,CAAC,GAAG,EAAE,WAAW,KAAK,OAAO,CAAC,YAAY,CAAC,EACvD,MAAM,EAAE,MAAM;IAG3B,IAAI,CACR,MAAM,EAAE,aAAa,EACrB,gBAAgB,CAAC,EAAE,gBAAgB,GAClC,OAAO,CAAC,IAAI,CAAC;IAqBV,iBAAiB,CACrB,IAAI,EAAE,aAAa,CAAC,eAAe,CAAC,CAAC,KAAK,CAAC,GAC1C,OAAO,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC,QAAQ,CAAC,CAAC;IAgE9C,SAAS,CACb,IAAI,EAAE,aAAa,CAAC,WAAW,CAAC,CAAC,KAAK,CAAC,GACtC,OAAO,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC,QAAQ,CAAC,CAAC;IAoE1C,iBAAiB,CACrB,IAAI,EAAE,aAAa,CAAC,eAAe,CAAC,CAAC,KAAK,CAAC,GAC1C,OAAO,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC,QAAQ,CAAC,CAAC;CA+DrD"}
@@ -0,0 +1,172 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { ThymianBaseError, thymianHttpTransactionToString, } from '@thymian/core';
4
+ import { readSamplesFromDir } from '../samples-structure/read-samples-from-dir.js';
5
+ import { entryExists } from '../utils.js';
6
+ import { createHookUtils } from './create-hook-utils.js';
7
+ import { FailError, SkipError } from './hook-errors.js';
8
+ import { loadHooksFromSamples } from './load-hooks-from-samples.js';
9
+ export class HookRunner {
10
+ path;
11
+ runRequest;
12
+ logger;
13
+ initialized = false;
14
+ hooks = new Map();
15
+ urlToTransactionId = {};
16
+ format;
17
+ constructor(path, runRequest, logger) {
18
+ this.path = path;
19
+ this.runRequest = runRequest;
20
+ this.logger = logger;
21
+ }
22
+ async init(format, samplesStructure) {
23
+ if (this.initialized) {
24
+ return;
25
+ }
26
+ if (!(await entryExists(this.path))) {
27
+ return;
28
+ }
29
+ const samples = samplesStructure ?? (await readSamplesFromDir(this.path));
30
+ const meta = JSON.parse(await readFile(join(this.path, 'meta.json'), 'utf-8'));
31
+ this.urlToTransactionId = meta.transactions;
32
+ this.hooks = loadHooksFromSamples(samples);
33
+ this.format = format;
34
+ this.initialized = true;
35
+ }
36
+ async afterEachResponse(hook) {
37
+ if (!this.initialized) {
38
+ throw new ThymianBaseError('Cannot run hooks before @thymian/plugin-sampler is initialized.', {
39
+ name: 'HookRunnerNotInitialized',
40
+ suggestions: ['Did you run "thymian sampler:init"?'],
41
+ });
42
+ }
43
+ const { value, ctx } = hook;
44
+ const hooks = ctx.thymianTransaction
45
+ ? this.hooks.get(ctx.thymianTransaction.transactionId)
46
+ : undefined;
47
+ let result = value;
48
+ const testResults = [];
49
+ const utils = createHookUtils(this.format, this.runRequest, this, this.urlToTransactionId, testResults, this.logger);
50
+ for (const afterEach of hooks?.afterEachResponse ?? []) {
51
+ try {
52
+ result = await afterEach(result, ctx, utils);
53
+ }
54
+ catch (e) {
55
+ if (e instanceof SkipError) {
56
+ return {
57
+ result,
58
+ skip: e.message,
59
+ testResults,
60
+ };
61
+ }
62
+ if (e instanceof FailError) {
63
+ return {
64
+ result,
65
+ fail: e.message,
66
+ testResults,
67
+ };
68
+ }
69
+ throw new ThymianBaseError(`Error while running afterEach hook${hook.ctx && hook.ctx.thymianTransaction ? ' for transaction: ' + thymianHttpTransactionToString(hook.ctx.thymianTransaction.thymianReq, hook.ctx.thymianTransaction.thymianRes) : ''}.`, {
70
+ cause: e,
71
+ name: 'HookError',
72
+ });
73
+ }
74
+ }
75
+ return {
76
+ result,
77
+ testResults,
78
+ };
79
+ }
80
+ async authorize(hook) {
81
+ if (!this.initialized) {
82
+ throw new ThymianBaseError('Cannot run hooks before @thymian/plugin-sampler is initialized.', {
83
+ name: 'HookRunnerNotInitialized',
84
+ suggestions: ['Did you run "thymian sampler:init"?'],
85
+ });
86
+ }
87
+ const { value, ctx } = hook;
88
+ const hooks = ctx?.transactionId
89
+ ? this.hooks.get(ctx.transactionId)
90
+ : undefined;
91
+ const authorize = hooks?.authorize?.at(-1);
92
+ if (!authorize) {
93
+ return {
94
+ result: value,
95
+ };
96
+ }
97
+ const testResults = [];
98
+ const utils = createHookUtils(this.format, this.runRequest, this, this.urlToTransactionId, testResults, this.logger);
99
+ try {
100
+ const result = await authorize(value, ctx, utils);
101
+ return {
102
+ result,
103
+ testResults,
104
+ };
105
+ }
106
+ catch (e) {
107
+ if (e instanceof SkipError) {
108
+ return {
109
+ result: value,
110
+ skip: e.message,
111
+ testResults,
112
+ };
113
+ }
114
+ if (e instanceof FailError) {
115
+ return {
116
+ result: value,
117
+ fail: e.message,
118
+ testResults,
119
+ };
120
+ }
121
+ throw new ThymianBaseError(`Error while running authorize hook${hook.ctx ? ' for transaction: ' + thymianHttpTransactionToString(hook.ctx.thymianReq, hook.ctx.thymianRes) : ''}.`, {
122
+ cause: e,
123
+ name: 'HookError',
124
+ });
125
+ }
126
+ }
127
+ async beforeEachRequest(hook) {
128
+ if (!this.initialized) {
129
+ throw new ThymianBaseError('Cannot run hooks before @thymian/plugin-sampler is initialized.', {
130
+ name: 'HookRunnerNotInitialized',
131
+ suggestions: ['Did you run "thymian sampler:init"?'],
132
+ });
133
+ }
134
+ const { value, ctx } = hook;
135
+ const hooks = ctx?.transactionId
136
+ ? this.hooks.get(ctx.transactionId)
137
+ : undefined;
138
+ let result = value;
139
+ const testResults = [];
140
+ const utils = createHookUtils(this.format, this.runRequest, this, this.urlToTransactionId, testResults, this.logger);
141
+ for (const beforeEach of hooks?.beforeEachRequest ?? []) {
142
+ try {
143
+ result = await beforeEach(result, ctx, utils);
144
+ }
145
+ catch (e) {
146
+ if (e instanceof SkipError) {
147
+ return {
148
+ result,
149
+ skip: e.message,
150
+ testResults,
151
+ };
152
+ }
153
+ if (e instanceof FailError) {
154
+ return {
155
+ result,
156
+ fail: e.message,
157
+ testResults,
158
+ };
159
+ }
160
+ throw new ThymianBaseError(`Error while running beforeEach hook${hook.ctx ? ' for transaction: ' + thymianHttpTransactionToString(hook.ctx.thymianReq, hook.ctx.thymianRes) : ''}.`, {
161
+ cause: e,
162
+ name: 'HookError',
163
+ });
164
+ }
165
+ }
166
+ return {
167
+ result,
168
+ testResults,
169
+ };
170
+ }
171
+ }
172
+ //# sourceMappingURL=hook-runner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-runner.js","sourceRoot":"","sources":["../../src/hooks/hook-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAIL,gBAAgB,EAEhB,8BAA8B,GAC/B,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,kBAAkB,EAAE,MAAM,+CAA+C,CAAC;AAMnF,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAEpE,MAAM,OAAO,UAAU;IAOF;IACA;IACA;IARX,WAAW,GAAG,KAAK,CAAC;IACpB,KAAK,GAAuB,IAAI,GAAG,EAAE,CAA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G,MAAM,UAAU,CAAC,MAAM,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;YAChD,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC;gBACX,IAAI,CAAC,YAAY,SAAS,EAAE,CAAC;oBAC3B,OAAO;wBACL,MAAM;wBACN,IAAI,EAAE,CAAC,CAAC,OAAO;wBACf,WAAW;qBACZ,CAAC;gBACJ,CAAC;gBACD,IAAI,CAAC,YAAY,SAAS,EAAE,CAAC;oBAC3B,OAAO;wBACL,MAAM;wBACN,IAAI,EAAE,CAAC,CAAC,OAAO;wBACf,WAAW;qBACZ,CAAC;gBACJ,CAAC;gBAED,MAAM,IAAI,gBAAgB,CACxB,sCAAsC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,oBAAoB,GAAG,8BAA8B,CAAC,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,EACxJ;oBACE,KAAK,EAAE,CAAC;oBACR,IAAI,EAAE,WAAW;iBAClB,CACF,CAAC;YACJ,CAAC;QACH,CAAC;QAED,OAAO;YACL,MAAM;YACN,WAAW;SACZ,CAAC;IACJ,CAAC;CACF"}
@@ -0,0 +1,7 @@
1
+ import type { HttpTestHooks } from '@thymian/core';
2
+ import type { Endpoints, HookUtils } from './hook-utils.js';
3
+ export type SampleHttpTestHook<Hook extends keyof HttpTestHooks, E extends Endpoints> = (value: HttpTestHooks[Hook]['arg']['value'], ctx: HttpTestHooks[Hook]['arg']['ctx'], utils: HookUtils<E>) => Promise<HttpTestHooks[Hook]['return']['result']>;
4
+ export type BeforeEachRequestHook<E extends Endpoints = Record<string, any>> = SampleHttpTestHook<'beforeRequest', E>;
5
+ export type AfterEachResponseHook<E extends Endpoints = Record<string, any>> = SampleHttpTestHook<'afterResponse', E>;
6
+ export type AuthorizeHook<E extends Endpoints = Record<string, any>> = SampleHttpTestHook<'authorize', E>;
7
+ //# sourceMappingURL=hook-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-types.d.ts","sourceRoot":"","sources":["../../src/hooks/hook-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEnD,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5D,MAAM,MAAM,kBAAkB,CAC5B,IAAI,SAAS,MAAM,aAAa,EAChC,CAAC,SAAS,SAAS,IACjB,CACF,KAAK,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,EAC1C,GAAG,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,EACtC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,KAChB,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;AAEtD,MAAM,MAAM,qBAAqB,CAAC,CAAC,SAAS,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IACzE,kBAAkB,CAAC,eAAe,EAAE,CAAC,CAAC,CAAC;AACzC,MAAM,MAAM,qBAAqB,CAAC,CAAC,SAAS,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IACzE,kBAAkB,CAAC,eAAe,EAAE,CAAC,CAAC,CAAC;AACzC,MAAM,MAAM,aAAa,CAAC,CAAC,SAAS,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IACjE,kBAAkB,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC"}