awilixify 3.1.2 → 3.1.3

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,211 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
3
+ import { basename, dirname, extname, resolve } from "node:path";
4
+ const httpMethods = new Set([
5
+ "delete",
6
+ "get",
7
+ "head",
8
+ "options",
9
+ "patch",
10
+ "post",
11
+ "put",
12
+ "trace",
13
+ ]);
14
+ export async function generateOrvalApiClient(options) {
15
+ const document = await resolveOpenApiDocument(options.openApi);
16
+ const operationIds = collectOperationIds(document, options.tags);
17
+ const getOperationFunctionName = options.getOperationFunctionName ?? ((operationId) => operationId);
18
+ assertIdentifier(options.apiClientClassName, "API client class name");
19
+ assertIdentifier(options.operationsConstName, "operations constant name");
20
+ const operations = operationIds.map((operationId) => {
21
+ assertIdentifier(operationId, "operation ID");
22
+ const functionName = getOperationFunctionName(operationId);
23
+ assertIdentifier(functionName, `function name for operation "${operationId}"`);
24
+ return { functionName, operationId };
25
+ });
26
+ const apiClientFileName = options.apiClientFileName ?? "generated-api-client.ts";
27
+ const operationsFileName = options.operationsFileName ?? "generated.operations.ts";
28
+ const outputDirectory = resolve(options.outputDirectory);
29
+ const apiClientPath = resolve(outputDirectory, apiClientFileName);
30
+ const operationsPath = resolve(outputDirectory, operationsFileName);
31
+ const moduleOptions = options.module;
32
+ const modulePath = moduleOptions
33
+ ? resolve(moduleOptions.outputPath)
34
+ : undefined;
35
+ await mkdir(outputDirectory, { recursive: true });
36
+ await Promise.all([
37
+ replaceFile(apiClientPath, renderApiClient({
38
+ ...options,
39
+ operations,
40
+ operationsImport: toJavaScriptImport(operationsFileName),
41
+ })),
42
+ replaceFile(operationsPath, renderOperations(options.serviceName, options.operationsConstName, operationIds)),
43
+ ]);
44
+ const moduleCreated = moduleOptions && modulePath
45
+ ? await createModuleIfMissing(modulePath, renderModule(options.apiClientClassName, moduleOptions))
46
+ : undefined;
47
+ return {
48
+ operationIds,
49
+ apiClientPath,
50
+ operationsPath,
51
+ modulePath,
52
+ moduleCreated,
53
+ };
54
+ }
55
+ async function replaceFile(filePath, source) {
56
+ const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
57
+ try {
58
+ await writeFile(temporaryPath, source);
59
+ await rename(temporaryPath, filePath);
60
+ }
61
+ finally {
62
+ await rm(temporaryPath, { force: true });
63
+ }
64
+ }
65
+ async function createModuleIfMissing(modulePath, source) {
66
+ await mkdir(dirname(modulePath), { recursive: true });
67
+ try {
68
+ await writeFile(modulePath, source, { flag: "wx" });
69
+ return true;
70
+ }
71
+ catch (error) {
72
+ if (typeof error === "object" &&
73
+ error !== null &&
74
+ "code" in error &&
75
+ error.code === "EEXIST") {
76
+ return false;
77
+ }
78
+ throw error;
79
+ }
80
+ }
81
+ async function resolveOpenApiDocument(input) {
82
+ if (typeof input !== "string")
83
+ return input;
84
+ const response = await fetch(input);
85
+ if (!response.ok) {
86
+ throw new Error(`Failed to fetch OpenAPI document from ${input}: ${response.status} ${response.statusText}`);
87
+ }
88
+ return (await response.json());
89
+ }
90
+ function collectOperationIds(document, tags) {
91
+ const operationIds = new Set();
92
+ for (const pathItem of Object.values(document.paths ?? {})) {
93
+ for (const [method, operation] of Object.entries(pathItem)) {
94
+ if (!httpMethods.has(method.toLowerCase()))
95
+ continue;
96
+ if (typeof operation.operationId !== "string")
97
+ continue;
98
+ const operationTags = Array.isArray(operation.tags)
99
+ ? operation.tags.filter((tag) => typeof tag === "string")
100
+ : [];
101
+ if (tags?.length && !tags.some((tag) => operationTags.includes(tag))) {
102
+ continue;
103
+ }
104
+ operationIds.add(operation.operationId);
105
+ }
106
+ }
107
+ return [...operationIds];
108
+ }
109
+ function renderApiClient({ apiClientClassName, generatedClientImport, operations, operationsConstName, operationsImport, }) {
110
+ const imports = operations
111
+ .map(({ functionName, operationId }) => `\t${functionName} as ${operationId}Request,`)
112
+ .join("\n");
113
+ const methods = operations
114
+ .map(({ operationId, }) => `\t@callsOperation(${operationsConstName}.${operationId})
115
+ \t${operationId}(
116
+ \t\t...args: Parameters<typeof ${operationId}Request>
117
+ \t): ReturnType<typeof ${operationId}Request> {
118
+ \t\treturn ${operationId}Request(
119
+ \t\t\t...(withTracePropagation(args, ${operationId}Request.length - 1) as Parameters<
120
+ \t\t\t\ttypeof ${operationId}Request
121
+ \t\t\t>),
122
+ \t\t);
123
+ \t}`)
124
+ .join("\n\n");
125
+ return `// Generated from OpenAPI. Do not edit.
126
+ import { callsOperation } from "awilixify";
127
+ import { getTracePropagationHeaders } from "awilixify/devtools";
128
+
129
+ import {
130
+ ${imports}
131
+ } from ${JSON.stringify(generatedClientImport)};
132
+ import { ${operationsConstName} } from ${JSON.stringify(operationsImport)};
133
+
134
+ function withTracePropagation(args: unknown[], optionsIndex: number): unknown[] {
135
+ \tconst tracedArgs = [...args];
136
+ \tconst options = (tracedArgs[optionsIndex] ?? {}) as {
137
+ \t\theaders?: Record<string, string>;
138
+ \t};
139
+
140
+ \ttracedArgs[optionsIndex] = {
141
+ \t\t...options,
142
+ \t\theaders: {
143
+ \t\t\t...options.headers,
144
+ \t\t\t...getTracePropagationHeaders(),
145
+ \t\t},
146
+ \t};
147
+
148
+ \treturn tracedArgs;
149
+ }
150
+
151
+ export class ${apiClientClassName} {
152
+ ${methods}
153
+ }
154
+ `;
155
+ }
156
+ function renderOperations(serviceName, operationsConstName, operationIds) {
157
+ const operations = Object.fromEntries(operationIds.map((operationId) => [
158
+ operationId,
159
+ {
160
+ serviceName,
161
+ operationId,
162
+ transport: "http",
163
+ },
164
+ ]));
165
+ return `// Generated from OpenAPI. Do not edit.
166
+ export const ${operationsConstName} = ${JSON.stringify(operations, null, 2)} as const;
167
+ `;
168
+ }
169
+ function renderModule(apiClientClassName, options) {
170
+ assertIdentifier(options.moduleName, "module name");
171
+ assertIdentifier(options.apiClientProviderName, "API client provider name");
172
+ const exportNames = options.exports ?? [options.apiClientProviderName];
173
+ for (const providerName of exportNames) {
174
+ if (providerName !== options.apiClientProviderName) {
175
+ throw new Error(`Initial module export "${providerName}" is not the generated API client provider`);
176
+ }
177
+ }
178
+ const imports = `import { createModule, type ModuleDef } from "awilixify";
179
+
180
+ import { ${apiClientClassName} } from ${JSON.stringify(options.apiClientImport)};`;
181
+ const exportKeys = exportNames.map((name) => JSON.stringify(name)).join(", ");
182
+ const moduleDefName = `${options.moduleName}Def`;
183
+ return `// Generated once by Awilixify codegen. Safe to customize.
184
+ ${imports}
185
+
186
+ export type ${moduleDefName} = ModuleDef<{
187
+ \tproviders: {
188
+ \t\t${options.apiClientProviderName}: ${apiClientClassName};
189
+ \t};
190
+ \texportKeys: [${exportKeys}];
191
+ }>;
192
+
193
+ export type Deps = ${moduleDefName}["deps"];
194
+
195
+ export const ${options.moduleName} = createModule<${moduleDefName}>({
196
+ \tname: "${options.moduleName}",
197
+ \tproviders: {
198
+ \t\t${options.apiClientProviderName}: ${apiClientClassName},
199
+ \t},
200
+ \texports: [${exportKeys}],
201
+ });
202
+ `;
203
+ }
204
+ function assertIdentifier(value, label) {
205
+ if (!/^[$A-Z_a-z][$\w]*$/.test(value)) {
206
+ throw new Error(`${label} "${value}" is not a valid TypeScript identifier`);
207
+ }
208
+ }
209
+ function toJavaScriptImport(fileName) {
210
+ return `./${basename(fileName, extname(fileName))}.js`;
211
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./config.js";
2
+ export * from "./generate-asyncapi-client.js";
3
+ export * from "./generate-orval-api-client.js";
@@ -0,0 +1,3 @@
1
+ export * from "./config.js";
2
+ export * from "./generate-asyncapi-client.js";
3
+ export * from "./generate-orval-api-client.js";
@@ -2,3 +2,4 @@ export type { InternalModuleLike } from "../di/modules/runtime-module.types.js";
2
2
  export { hasInitAfter, hasUseClass, isCostructorProvider, isCostructorProvider as isConstructorProvider, isEagerProvider, isFactoryProvider, isPromiseLike, isResultLike, } from "../di/type-guards.js";
3
3
  export * from "./devtools.types.js";
4
4
  export { getControllerMethodNames } from "./helpers.js";
5
+ export * from "./trace-context.js";
@@ -1,3 +1,4 @@
1
1
  export { hasInitAfter, hasUseClass, isCostructorProvider, isCostructorProvider as isConstructorProvider, isEagerProvider, isFactoryProvider, isPromiseLike, isResultLike, } from "../di/type-guards.js";
2
2
  export * from "./devtools.types.js";
3
3
  export { getControllerMethodNames } from "./helpers.js";
4
+ export * from "./trace-context.js";
@@ -0,0 +1,12 @@
1
+ export declare const TRACEPARENT_HEADER = "traceparent";
2
+ export type TracePropagationContext = {
3
+ traceId: string;
4
+ spanId: string;
5
+ traceFlags: string;
6
+ };
7
+ export declare function getTracePropagationContext(): TracePropagationContext | undefined;
8
+ export declare function runWithTracePropagationContext<T>(context: TracePropagationContext, callback: () => T | Promise<T>): T | Promise<T>;
9
+ export declare function parseTraceparent(value: string | string[] | undefined): TracePropagationContext | undefined;
10
+ export declare function formatTraceparent(context: TracePropagationContext): string;
11
+ export declare function getTracePropagationHeaders(): Record<string, string>;
12
+ export declare function runWithTraceparent<T>(value: string | string[] | undefined, callback: () => T | Promise<T>): T | Promise<T>;
@@ -0,0 +1,46 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ export const TRACEPARENT_HEADER = "traceparent";
3
+ const TRACEPARENT_PATTERN = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i;
4
+ const propagationStorage = new AsyncLocalStorage();
5
+ export function getTracePropagationContext() {
6
+ return propagationStorage.getStore();
7
+ }
8
+ export function runWithTracePropagationContext(context, callback) {
9
+ return propagationStorage.run(context, callback);
10
+ }
11
+ export function parseTraceparent(value) {
12
+ const candidate = Array.isArray(value) ? value[0] : value;
13
+ if (!candidate)
14
+ return undefined;
15
+ const match = TRACEPARENT_PATTERN.exec(candidate.trim());
16
+ if (!match)
17
+ return undefined;
18
+ const traceId = match[1];
19
+ const spanId = match[2];
20
+ const traceFlags = match[3];
21
+ if (!traceId || !spanId || !traceFlags)
22
+ return undefined;
23
+ if (isAllZeros(traceId) || isAllZeros(spanId))
24
+ return undefined;
25
+ return {
26
+ traceId: traceId.toLowerCase(),
27
+ spanId: spanId.toLowerCase(),
28
+ traceFlags: traceFlags.toLowerCase(),
29
+ };
30
+ }
31
+ export function formatTraceparent(context) {
32
+ return `00-${context.traceId}-${context.spanId}-${context.traceFlags}`;
33
+ }
34
+ export function getTracePropagationHeaders() {
35
+ const context = getTracePropagationContext();
36
+ return context ? { [TRACEPARENT_HEADER]: formatTraceparent(context) } : {};
37
+ }
38
+ export function runWithTraceparent(value, callback) {
39
+ const context = parseTraceparent(value);
40
+ return context
41
+ ? runWithTracePropagationContext(context, callback)
42
+ : callback();
43
+ }
44
+ function isAllZeros(value) {
45
+ return /^0+$/.test(value);
46
+ }
@@ -1,5 +1,6 @@
1
1
  export interface RouteRegistration {
2
2
  method: string;
3
+ operationId: string;
3
4
  path: string;
4
5
  schema: RouteSchema;
5
6
  }
@@ -12,13 +13,12 @@ export interface RouteSchema {
12
13
  description?: string;
13
14
  summary?: string;
14
15
  tags?: string[];
15
- operationId?: string;
16
16
  deprecated?: boolean;
17
17
  }
18
18
  export declare function hasValidationSchema(schema: RouteSchema): boolean;
19
19
  export declare class OpenAPIBuilder {
20
20
  private routes;
21
- registerRoute(method: string, path: string, schema: RouteSchema): void;
21
+ registerRoute(method: string, path: string, handlerName: string, schema: RouteSchema): void;
22
22
  buildPaths(): Record<string, any>;
23
23
  private buildOperation;
24
24
  private buildParameters;
@@ -6,17 +6,22 @@ export function hasValidationSchema(schema) {
6
6
  }
7
7
  export class OpenAPIBuilder {
8
8
  routes = [];
9
- registerRoute(method, path, schema) {
10
- this.routes.push({ method: method.toLowerCase(), path, schema });
9
+ registerRoute(method, path, handlerName, schema) {
10
+ this.routes.push({
11
+ method: method.toLowerCase(),
12
+ operationId: handlerName,
13
+ path,
14
+ schema,
15
+ });
11
16
  }
12
17
  buildPaths() {
13
18
  return this.routes.reduce((paths, route) => {
14
19
  paths[route.path] ??= {};
15
- paths[route.path][route.method] = this.buildOperation(route.schema);
20
+ paths[route.path][route.method] = this.buildOperation(route.operationId, route.schema);
16
21
  return paths;
17
22
  }, {});
18
23
  }
19
- buildOperation(schema) {
24
+ buildOperation(operationId, schema) {
20
25
  const parameters = this.buildParameters(schema);
21
26
  const requestBody = this.buildRequestBody(schema);
22
27
  const responses = this.buildResponses(schema);
@@ -24,7 +29,7 @@ export class OpenAPIBuilder {
24
29
  ...(schema.summary && { summary: schema.summary }),
25
30
  ...(schema.description && { description: schema.description }),
26
31
  ...(schema.tags && { tags: schema.tags }),
27
- ...(schema.operationId && { operationId: schema.operationId }),
32
+ operationId,
28
33
  ...(schema.deprecated && { deprecated: schema.deprecated }),
29
34
  ...(parameters.length > 0 && { parameters }),
30
35
  ...(requestBody && { requestBody }),
@@ -0,0 +1,23 @@
1
+ import type { DecoratorState, DecoratorToken } from "../decorators/decorator-state.types.js";
2
+ export type HttpOperationRef = {
3
+ operationId: string;
4
+ serviceName: string;
5
+ transport: "http";
6
+ };
7
+ export type MessagingOperationRef = {
8
+ serviceName: string;
9
+ transport: "messaging";
10
+ type: string;
11
+ };
12
+ export type OperationRef = HttpOperationRef | MessagingOperationRef;
13
+ export type MessagingOperationInput = Omit<MessagingOperationRef, "transport">;
14
+ export type LocalMessagingOperationRef = Omit<MessagingOperationRef, "serviceName">;
15
+ export type LocalMessagingOperationInput = Pick<MessagingOperationRef, "type">;
16
+ export interface OperationCallDecoratorState extends DecoratorState<OperationRef[]> {
17
+ }
18
+ export interface OperationPublishDecoratorState extends DecoratorState<LocalMessagingOperationRef[]> {
19
+ }
20
+ export declare const OPERATION_CALL_DECORATOR_STATE_TOKEN: DecoratorToken<OperationCallDecoratorState>;
21
+ export declare const OPERATION_PUBLISH_DECORATOR_STATE_TOKEN: DecoratorToken<OperationPublishDecoratorState>;
22
+ export declare function callsOperation(operation: HttpOperationRef | MessagingOperationInput): <This, Args extends unknown[], Result>(_target: (this: This, ...args: Args) => Result, context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Result>) => void;
23
+ export declare function publishesOperation(operation: LocalMessagingOperationInput): <This, Args extends unknown[], Result>(_target: (this: This, ...args: Args) => Result, context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Result>) => void;
@@ -0,0 +1,30 @@
1
+ import { createDecoratorStateUpdater } from "../decorators/decorator-state.js";
2
+ const callState = createDecoratorStateUpdater("operation-calls", {
3
+ method: () => [],
4
+ });
5
+ const publishState = createDecoratorStateUpdater("operation-publications", {
6
+ method: () => [],
7
+ });
8
+ export const OPERATION_CALL_DECORATOR_STATE_TOKEN = callState.token;
9
+ export const OPERATION_PUBLISH_DECORATOR_STATE_TOKEN = publishState.token;
10
+ export function callsOperation(operation) {
11
+ const operationRef = "operationId" in operation
12
+ ? operation
13
+ : { ...operation, transport: "messaging" };
14
+ return (_target, context) => {
15
+ callState.update(context, {
16
+ method: (operations) => [...operations, operationRef],
17
+ }, callsOperation.name);
18
+ };
19
+ }
20
+ export function publishesOperation(operation) {
21
+ const operationRef = {
22
+ ...operation,
23
+ transport: "messaging",
24
+ };
25
+ return (_target, context) => {
26
+ publishState.update(context, {
27
+ method: (operations) => [...operations, operationRef],
28
+ }, publishesOperation.name);
29
+ };
30
+ }