@scalar/mock-server 0.18.0 → 0.19.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.
- package/CHANGELOG.md +10 -0
- package/dist/create-asyncapi-mock-server.d.ts +4 -55
- package/dist/create-asyncapi-mock-server.d.ts.map +1 -1
- package/dist/create-asyncapi-mock-server.js +16 -22
- package/dist/create-mock-server.d.ts +4 -3
- package/dist/create-mock-server.d.ts.map +1 -1
- package/dist/create-mock-server.js +11 -227
- package/dist/create-openapi-mock-server.d.ts +10 -0
- package/dist/create-openapi-mock-server.d.ts.map +1 -0
- package/dist/create-openapi-mock-server.js +227 -0
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -2
- package/dist/routes/respond-with-openapi-document.d.ts +1 -1
- package/dist/transports/types.d.ts +2 -2
- package/dist/types.d.ts +20 -8
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/get-asyncapi-document.d.ts +4 -0
- package/dist/utils/get-asyncapi-document.d.ts.map +1 -0
- package/dist/utils/get-asyncapi-document.js +47 -0
- package/dist/utils/get-asyncapi-security-schemes.d.ts +4 -0
- package/dist/utils/get-asyncapi-security-schemes.d.ts.map +1 -0
- package/dist/utils/get-asyncapi-security-schemes.js +17 -0
- package/dist/utils/process-document.d.ts +13 -0
- package/dist/utils/process-document.d.ts.map +1 -0
- package/dist/utils/{process-openapi-document.js → process-document.js} +18 -26
- package/dist/utils/resolve-channels.d.ts.map +1 -1
- package/dist/utils/resolve-channels.js +32 -19
- package/dist/utils/resolve-server-pathnames.d.ts +4 -0
- package/dist/utils/resolve-server-pathnames.d.ts.map +1 -0
- package/dist/utils/resolve-server-pathnames.js +14 -0
- package/dist/utils/set-up-asyncapi-authentication-routes.d.ts.map +1 -1
- package/dist/utils/set-up-asyncapi-authentication-routes.js +2 -14
- package/package.json +7 -7
- package/dist/utils/process-asyncapi-document.d.ts +0 -24
- package/dist/utils/process-asyncapi-document.d.ts.map +0 -1
- package/dist/utils/process-asyncapi-document.js +0 -64
- package/dist/utils/process-openapi-document.d.ts +0 -19
- package/dist/utils/process-openapi-document.d.ts.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# @scalar/mock-server
|
|
2
2
|
|
|
3
|
+
## 0.19.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#10683](https://github.com/scalar/scalar/pull/10683): Unify OpenAPI and AsyncAPI mocking in createMockServer, detecting the document format after loading it. The factory returns a Hono app for either format. WebSocket channels now require a runtime-specific upgradeWebSocket adapter; Node hosts create their own WebSocketServer. This replaces the exported createAsyncApiMockServer factory and its result/options types.
|
|
8
|
+
|
|
9
|
+
Serve sample Galaxy events on connection in the existing Cloudflare Pages deployment.
|
|
10
|
+
|
|
11
|
+
Expand AsyncAPI server pathname enums and serve deployment-specific AsyncAPI JSON and YAML documents automatically.
|
|
12
|
+
|
|
3
13
|
## 0.18.0
|
|
4
14
|
|
|
5
15
|
### Minor Changes
|
|
@@ -1,57 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { AsyncApiDocument } from '@scalar/types/asyncapi/3.1';
|
|
2
2
|
import { Hono } from 'hono';
|
|
3
|
-
import type {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
export type AsyncApiMockServerOptions = {
|
|
7
|
-
/**
|
|
8
|
-
* The AsyncAPI 3.1 document to mock. Can be a string (URL or file path), a raw JSON/YAML
|
|
9
|
-
* string, or an already-parsed object.
|
|
10
|
-
*/
|
|
11
|
-
document?: string | Record<string, any>;
|
|
12
|
-
/** Source file path or URL for resolving references in an already loaded document. */
|
|
13
|
-
origin?: string;
|
|
14
|
-
/**
|
|
15
|
-
* Additional transports appended after the built-in WebSocket and SSE transports. Use this to
|
|
16
|
-
* support extra protocols (for example SignalR) without changing the core. The first transport
|
|
17
|
-
* whose `supports()` returns `true` for a channel owns it.
|
|
18
|
-
*/
|
|
19
|
-
transports?: MockTransport[];
|
|
20
|
-
/** Called for every message flowing in or out of the mock, for logging or inspection. */
|
|
21
|
-
onMessage?: (event: {
|
|
22
|
-
channel: string;
|
|
23
|
-
direction: MessageDirection;
|
|
24
|
-
payload: unknown;
|
|
25
|
-
}) => void;
|
|
26
|
-
/**
|
|
27
|
-
* Control the transport lifecycle log lines the server prints. Pass `true` to log them to the
|
|
28
|
-
* console, a `(line) => void` sink to route them elsewhere, or `false` (the default) to stay silent.
|
|
29
|
-
*
|
|
30
|
-
* Diagnostics such as a channel with no matching transport are printed either way.
|
|
31
|
-
*/
|
|
32
|
-
logger?: boolean | MockServerLogger;
|
|
33
|
-
};
|
|
34
|
-
/** The result of {@link createAsyncApiMockServer}. */
|
|
35
|
-
export type AsyncApiMockServer = {
|
|
36
|
-
/** The Hono app serving SSE channels and WebSocket upgrade routes. */
|
|
37
|
-
app: Hono;
|
|
38
|
-
/** Pass this option to `@hono/node-server`'s `serve()` to enable WebSocket channels. */
|
|
39
|
-
websocket: {
|
|
40
|
-
server: WebSocketServerLike;
|
|
41
|
-
};
|
|
42
|
-
};
|
|
43
|
-
/**
|
|
44
|
-
* Create a mock server for an AsyncAPI 3.1 document — the event-driven counterpart of
|
|
45
|
-
* {@link createMockServer}. Each channel is registered on a transport (WebSocket or SSE by
|
|
46
|
-
* default) that emits realistic mock messages generated from the channel's message payload
|
|
47
|
-
* schemas, the same way the REST mocker generates HTTP response bodies.
|
|
48
|
-
*
|
|
49
|
-
* Pass the returned WebSocket option to `serve()`:
|
|
50
|
-
*
|
|
51
|
-
* ```ts
|
|
52
|
-
* const { app, websocket } = await createAsyncApiMockServer({ document })
|
|
53
|
-
* serve({ fetch: app.fetch, port: 3000, websocket })
|
|
54
|
-
* ```
|
|
55
|
-
*/
|
|
56
|
-
export declare function createAsyncApiMockServer(options: AsyncApiMockServerOptions): Promise<AsyncApiMockServer>;
|
|
3
|
+
import type { MockServerOptions } from './types.js';
|
|
4
|
+
/** Register the AsyncAPI channels on the selected runtime's adapter. */
|
|
5
|
+
export declare const createAsyncApiMockServer: (options: MockServerOptions, document: AsyncApiDocument) => Hono;
|
|
57
6
|
//# sourceMappingURL=create-asyncapi-mock-server.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-asyncapi-mock-server.d.ts","sourceRoot":"","sources":["../src/create-asyncapi-mock-server.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"create-asyncapi-mock-server.d.ts","sourceRoot":"","sources":["../src/create-asyncapi-mock-server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAM3B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA;AAQhD,wEAAwE;AACxE,eAAO,MAAM,wBAAwB,GAAI,SAAS,iBAAiB,EAAE,UAAU,gBAAgB,KAAG,IA2DjG,CAAA"}
|
|
@@ -1,39 +1,33 @@
|
|
|
1
|
-
import { upgradeWebSocket } from '@hono/node-server';
|
|
2
1
|
import { Hono } from 'hono';
|
|
3
2
|
import { cors } from 'hono/cors';
|
|
4
|
-
import {
|
|
3
|
+
import { stringify } from 'yaml';
|
|
5
4
|
import { defaultTransports } from './transports/index.js';
|
|
6
5
|
import { authenticateAsyncApiChannel, warnUnsupportedAsyncApiSecurity } from './utils/authenticate-asyncapi-channel.js';
|
|
7
6
|
import { generateMessage } from './utils/generate-message.js';
|
|
8
|
-
import {
|
|
7
|
+
import { getAsyncApiDocument } from './utils/get-asyncapi-document.js';
|
|
9
8
|
import { resolveChannels } from './utils/resolve-channels.js';
|
|
10
9
|
import { resolveLogger } from './utils/resolve-logger.js';
|
|
11
10
|
import { setUpAsyncApiAuthenticationRoutes } from './utils/set-up-asyncapi-authentication-routes.js';
|
|
12
|
-
/**
|
|
13
|
-
|
|
14
|
-
* {@link createMockServer}. Each channel is registered on a transport (WebSocket or SSE by
|
|
15
|
-
* default) that emits realistic mock messages generated from the channel's message payload
|
|
16
|
-
* schemas, the same way the REST mocker generates HTTP response bodies.
|
|
17
|
-
*
|
|
18
|
-
* Pass the returned WebSocket option to `serve()`:
|
|
19
|
-
*
|
|
20
|
-
* ```ts
|
|
21
|
-
* const { app, websocket } = await createAsyncApiMockServer({ document })
|
|
22
|
-
* serve({ fetch: app.fetch, port: 3000, websocket })
|
|
23
|
-
* ```
|
|
24
|
-
*/
|
|
25
|
-
export async function createAsyncApiMockServer(options) {
|
|
11
|
+
/** Register the AsyncAPI channels on the selected runtime's adapter. */
|
|
12
|
+
export const createAsyncApiMockServer = (options, document) => {
|
|
26
13
|
const app = new Hono();
|
|
27
|
-
const document = await processAsyncApiDocument(options.document, options.origin);
|
|
28
14
|
const channels = resolveChannels(document);
|
|
29
15
|
const transports = [...defaultTransports, ...(options.transports ?? [])];
|
|
30
16
|
const log = resolveLogger(options.logger, false);
|
|
31
17
|
// CORS for the SSE/HTTP routes (WebSocket upgrades are not subject to CORS).
|
|
32
|
-
|
|
18
|
+
const corsMiddleware = cors();
|
|
19
|
+
app.use((c, next) => (c.req.header('Upgrade')?.toLowerCase() === 'websocket' ? next() : corsMiddleware(c, next)));
|
|
20
|
+
app.get('/asyncapi.json', (c) => c.json(getAsyncApiDocument(document, c.req.url)));
|
|
21
|
+
app.get('/asyncapi.yaml', (c) => c.text(stringify(getAsyncApiDocument(document, c.req.url)), 200, {
|
|
22
|
+
'Content-Type': 'application/yaml; charset=UTF-8',
|
|
23
|
+
}));
|
|
33
24
|
setUpAsyncApiAuthenticationRoutes(app, document);
|
|
34
25
|
const context = {
|
|
35
26
|
app,
|
|
36
|
-
upgradeWebSocket
|
|
27
|
+
upgradeWebSocket: options.upgradeWebSocket ??
|
|
28
|
+
(() => {
|
|
29
|
+
throw new Error('AsyncAPI WebSocket channels require an upgradeWebSocket adapter. Pass the adapter for your runtime to createMockServer().');
|
|
30
|
+
}),
|
|
37
31
|
generateMessage,
|
|
38
32
|
onMessage: options.onMessage,
|
|
39
33
|
log,
|
|
@@ -54,5 +48,5 @@ export async function createAsyncApiMockServer(options) {
|
|
|
54
48
|
transport.register(channel, context);
|
|
55
49
|
log(`[asyncapi] ${transport.name} -> ${channel.route} (channel "${channel.id}")`);
|
|
56
50
|
}
|
|
57
|
-
return
|
|
58
|
-
}
|
|
51
|
+
return app;
|
|
52
|
+
};
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { Hono } from 'hono';
|
|
1
|
+
import type { Hono } from 'hono';
|
|
2
2
|
import type { MockServerOptions } from './types.js';
|
|
3
3
|
/**
|
|
4
|
-
* Create a mock
|
|
4
|
+
* Create a Hono mock app from an OpenAPI or AsyncAPI document, detected after loading it.
|
|
5
|
+
* WebSocket channels require a runtime-specific upgradeWebSocket adapter; HTTP and SSE do not.
|
|
5
6
|
*/
|
|
6
|
-
export declare
|
|
7
|
+
export declare const createMockServer: (configuration: MockServerOptions) => Promise<Hono>;
|
|
7
8
|
//# sourceMappingURL=create-mock-server.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-mock-server.d.ts","sourceRoot":"","sources":["../src/create-mock-server.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"create-mock-server.d.ts","sourceRoot":"","sources":["../src/create-mock-server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAIhC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA;AAGhD;;;GAGG;AACH,eAAO,MAAM,gBAAgB,GAAU,eAAe,iBAAiB,KAAG,OAAO,CAAC,IAAI,CAQrF,CAAA"}
|
|
@@ -1,229 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { Hono } from 'hono';
|
|
5
|
-
import { every } from 'hono/combine';
|
|
6
|
-
import { cors } from 'hono/cors';
|
|
7
|
-
import { buildSeedContext } from './utils/build-seed-context.js';
|
|
8
|
-
import { executeSeed } from './utils/execute-seed.js';
|
|
9
|
-
import { getOperations } from './utils/get-operation.js';
|
|
10
|
-
import { handleAuthentication } from './utils/handle-authentication.js';
|
|
11
|
-
import { honoRouteFromPath } from './utils/hono-route-from-path.js';
|
|
12
|
-
import { isAuthenticationRequired } from './utils/is-authentication-required.js';
|
|
13
|
-
import { logAuthenticationInstructions } from './utils/log-authentication-instructions.js';
|
|
14
|
-
import { processOpenApiDocument } from './utils/process-openapi-document.js';
|
|
15
|
-
import { requestMatchesPinnedQuery } from './utils/request-matches-pinned-query.js';
|
|
16
|
-
import { resolveLogger } from './utils/resolve-logger.js';
|
|
17
|
-
import { setUpAuthenticationRoutes } from './utils/set-up-authentication-routes.js';
|
|
18
|
-
import { splitPathKey } from './utils/split-path-key.js';
|
|
19
|
-
import { validateRequest } from './utils/validate-request.js';
|
|
20
|
-
import { store } from './libs/store.js';
|
|
21
|
-
import { mockAnyResponse } from './routes/mock-any-response.js';
|
|
22
|
-
import { mockHandlerResponse } from './routes/mock-handler-response.js';
|
|
23
|
-
import { respondWithOpenApiDocument } from './routes/respond-with-openapi-document.js';
|
|
24
|
-
/** Record which operation a request matched, so an error escaping it can be named */
|
|
25
|
-
const setMockedOperation = (c, operation) => {
|
|
26
|
-
;
|
|
27
|
-
c.set('mockedOperation', operation);
|
|
28
|
-
};
|
|
29
|
-
/** Read back the operation a request matched, or `undefined` when it reached no mocked route */
|
|
30
|
-
const getMockedOperation = (c) => c.get('mockedOperation');
|
|
31
|
-
/**
|
|
32
|
-
* Whether an error carries its own response, the way Hono's `HTTPException` does.
|
|
33
|
-
*
|
|
34
|
-
* Checked structurally rather than with `instanceof`, exactly like Hono's own default handler, so an
|
|
35
|
-
* `HTTPException` thrown from a second copy of Hono is still recognized.
|
|
36
|
-
*/
|
|
37
|
-
const carriesResponse = (error) => 'getResponse' in error && typeof error.getResponse === 'function';
|
|
1
|
+
import { createAsyncApiMockServer } from './create-asyncapi-mock-server.js';
|
|
2
|
+
import { createOpenApiMockServer } from './create-openapi-mock-server.js';
|
|
3
|
+
import { processDocument } from './utils/process-document.js';
|
|
38
4
|
/**
|
|
39
|
-
* Create a mock
|
|
5
|
+
* Create a Hono mock app from an OpenAPI or AsyncAPI document, detected after loading it.
|
|
6
|
+
* WebSocket channels require a runtime-specific upgradeWebSocket adapter; HTTP and SSE do not.
|
|
40
7
|
*/
|
|
41
|
-
export async
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
// which makes the failure readable in the response instead of something to go reproduce.
|
|
48
|
-
app.onError((error, c) => {
|
|
49
|
-
// The status and body such an error chose are deliberate, not an internal failure, so answer
|
|
50
|
-
// with them. Unlike Hono's default handler, which returns the response directly, it is rebuilt
|
|
51
|
-
// through the context so headers already staged on the response — those from the CORS
|
|
52
|
-
// middleware, most of all — still apply.
|
|
53
|
-
if (carriesResponse(error)) {
|
|
54
|
-
const response = error.getResponse();
|
|
55
|
-
return c.newResponse(response.body, response);
|
|
56
|
-
}
|
|
57
|
-
const operation = getMockedOperation(c);
|
|
58
|
-
// Keep logging the error, as Hono's default handler does, so the stack trace is not lost. Routes
|
|
59
|
-
// added to the returned app are not mocked operations, so name the concrete request instead —
|
|
60
|
-
// the log always points somewhere.
|
|
61
|
-
console.error(operation
|
|
62
|
-
? `Error while mocking ${operation.method} ${operation.path}:`
|
|
63
|
-
: `Error handling ${c.req.method} ${c.req.path}:`, error);
|
|
64
|
-
return c.json({
|
|
65
|
-
error: 'Internal Server Error',
|
|
66
|
-
message: error.message,
|
|
67
|
-
// Left out entirely rather than sent as `null`, so a client can test for the key.
|
|
68
|
-
...(operation ? { operation } : {}),
|
|
69
|
-
}, 500);
|
|
70
|
-
});
|
|
71
|
-
const input = configuration?.document ?? configuration?.specification;
|
|
72
|
-
const schema = await processOpenApiDocument(input, configuration?.origin);
|
|
73
|
-
const sourceDocument = typeof input === 'string' ? normalize(input) : input;
|
|
74
|
-
// Source locations need a bundled export so relative references remain usable outside the server.
|
|
75
|
-
const exportDocument = configuration?.origin ||
|
|
76
|
-
(typeof input === 'string' && (sourceDocument === null || typeof sourceDocument !== 'object'))
|
|
77
|
-
? getRaw(schema)
|
|
78
|
-
: input;
|
|
79
|
-
// Seed data from schemas with x-seed extension
|
|
80
|
-
// This happens before routes are set up so data is available immediately
|
|
81
|
-
const schemas = schema?.components?.schemas;
|
|
82
|
-
if (schemas) {
|
|
83
|
-
for (const [schemaName, schemaObject] of Object.entries(schemas)) {
|
|
84
|
-
// Merge `$ref` siblings so an `x-seed` placed next to a `$ref` is preserved (OpenAPI 3.1 semantics)
|
|
85
|
-
const seedCode = getResolvedRef(schemaObject, mergeSiblingReferences)?.['x-seed'];
|
|
86
|
-
if (seedCode && typeof seedCode === 'string') {
|
|
87
|
-
try {
|
|
88
|
-
// Check if collection is empty (idempotent seeding)
|
|
89
|
-
// Use the schema key directly as the collection name
|
|
90
|
-
const existingItems = store.list(schemaName);
|
|
91
|
-
if (existingItems.length === 0) {
|
|
92
|
-
// Build seed context with schema key (used as collection name)
|
|
93
|
-
const seedContext = buildSeedContext(schemaName);
|
|
94
|
-
// Execute seed code
|
|
95
|
-
await executeSeed(seedCode, seedContext);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
catch (error) {
|
|
99
|
-
// Log error but don't fail server startup
|
|
100
|
-
console.error(`Error seeding schema "${schemaName}":`, error);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
// CORS headers
|
|
106
|
-
const allowedMethods = new Set(['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY']);
|
|
107
|
-
for (const pathItem of Object.values(schema?.paths ?? {})) {
|
|
108
|
-
for (const method of Object.keys(getOperations(getResolvedRef(pathItem)))) {
|
|
109
|
-
allowedMethods.add(method);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
app.use(cors({ origin: '*', allowMethods: [...allowedMethods], exposeHeaders: ['X-Scalar-XML-Error'] }));
|
|
113
|
-
/** Authentication methods defined in the OpenAPI document */
|
|
114
|
-
setUpAuthenticationRoutes(app, schema);
|
|
115
|
-
// Only the instructions honor `logger` (on by default); the util still prints warnings and errors
|
|
116
|
-
// about security schemes the mock server cannot handle, which a silenced startup should surface.
|
|
117
|
-
logAuthenticationInstructions(schema?.components?.securitySchemes || {}, resolveLogger(configuration.logger, true));
|
|
118
|
-
/** Paths specified in the OpenAPI document */
|
|
119
|
-
const paths = schema?.paths ?? {};
|
|
120
|
-
// A path key may pin query parameters to describe a variant of an operation, for example
|
|
121
|
-
// `/v1/messages?beta=true` next to `/v1/messages`. Hono runs every matching route in registration
|
|
122
|
-
// order, so a variant has to come before the sibling it shares a path with — otherwise the sibling
|
|
123
|
-
// answers its requests too, and the more pinned parameters a key has the more specific it is.
|
|
124
|
-
const pathKeys = Object.keys(paths).map((path) => {
|
|
125
|
-
const { path: pathname, query } = splitPathKey(path);
|
|
126
|
-
return { path, pathname, query };
|
|
127
|
-
});
|
|
128
|
-
/** Where each path first shows up in the document, so its variants stay with it */
|
|
129
|
-
const documentOrder = new Map();
|
|
130
|
-
pathKeys.forEach(({ pathname }, index) => {
|
|
131
|
-
if (!documentOrder.has(pathname)) {
|
|
132
|
-
documentOrder.set(pathname, index);
|
|
133
|
-
}
|
|
134
|
-
});
|
|
135
|
-
// Keys that share a path are grouped where the first of them appears and the most specific one
|
|
136
|
-
// leads the group; a key with a path of its own never moves. So the only keys that change places
|
|
137
|
-
// with anything unrelated are the variants of a path that is described more than once. When two
|
|
138
|
-
// distinct paths overlap — a literal and a parameterized one that pins a query — neither is moved,
|
|
139
|
-
// so whichever the document declares first is matched first, the same as any pair of overlapping
|
|
140
|
-
// Hono routes.
|
|
141
|
-
const orderedPathKeys = [...pathKeys].sort((a, b) => (documentOrder.get(a.pathname) ?? 0) - (documentOrder.get(b.pathname) ?? 0) || b.query.length - a.query.length);
|
|
142
|
-
orderedPathKeys.forEach(({ path, query }) => {
|
|
143
|
-
// A path item may itself be a `$ref`, so resolve it before reading its operations.
|
|
144
|
-
const pathItem = getResolvedRef(paths[path]);
|
|
145
|
-
const operations = getOperations(pathItem);
|
|
146
|
-
/** Keys for all operations of a specified path */
|
|
147
|
-
Object.entries(operations).forEach(([method, operation]) => {
|
|
148
|
-
const route = honoRouteFromPath(path);
|
|
149
|
-
// Remember which operation this route mocks, so the error handler can name it when something
|
|
150
|
-
// fails downstream. Recorded on the context rather than mapped back from the request path,
|
|
151
|
-
// which would not survive the app being mounted under a base path. Registered before the rest
|
|
152
|
-
// of the route so a failure in request validation is named too. The OpenAPI path key is kept
|
|
153
|
-
// (rather than the Hono route) because that is what the document author reads.
|
|
154
|
-
const mockedOperation = {
|
|
155
|
-
method,
|
|
156
|
-
path,
|
|
157
|
-
...(operation?.operationId ? { operationId: operation.operationId } : {}),
|
|
158
|
-
};
|
|
159
|
-
/** Middleware chain answering this operation, in the order it runs */
|
|
160
|
-
const handlers = [];
|
|
161
|
-
// Runs first, so the error handler can name the operation even when validation fails. For a
|
|
162
|
-
// path key that pins a query it is part of the guarded chain below, so it only fires once the
|
|
163
|
-
// request actually matches the variant rather than for one that is handed on to the sibling.
|
|
164
|
-
handlers.push(async (c, next) => {
|
|
165
|
-
setMockedOperation(c, mockedOperation);
|
|
166
|
-
await next();
|
|
167
|
-
});
|
|
168
|
-
// Operation-level security overrides the global requirement, so fall back to the
|
|
169
|
-
// document-wide `security` when the operation does not define its own.
|
|
170
|
-
const effectiveSecurity = operation.security ?? schema?.security;
|
|
171
|
-
// Check if authentication is required for this operation
|
|
172
|
-
if (isAuthenticationRequired(effectiveSecurity)) {
|
|
173
|
-
handlers.push(handleAuthentication(schema, operation));
|
|
174
|
-
}
|
|
175
|
-
// Notify the `onRequest` callback before validation runs, so it fires for every request —
|
|
176
|
-
// including ones the validation middleware rejects with a `422`.
|
|
177
|
-
if (configuration.onRequest) {
|
|
178
|
-
handlers.push(async (c, next) => {
|
|
179
|
-
configuration.onRequest?.({ context: c, operation });
|
|
180
|
-
await next();
|
|
181
|
-
});
|
|
182
|
-
}
|
|
183
|
-
// Validate the incoming request against the operation contract (on by default;
|
|
184
|
-
// opt out with `validateRequest: false`). Runs after authentication but before the
|
|
185
|
-
// mock handler. Validators are compiled once here, so there is no per-request recompilation.
|
|
186
|
-
if (configuration.validateRequest !== false) {
|
|
187
|
-
handlers.push(validateRequest(operation, pathItem?.parameters));
|
|
188
|
-
}
|
|
189
|
-
// Check if operation has x-handler extension
|
|
190
|
-
// Validate that it's a non-empty string (consistent with x-seed validation)
|
|
191
|
-
const handlerCode = operation?.['x-handler'];
|
|
192
|
-
const hasHandler = handlerCode && typeof handlerCode === 'string' && handlerCode.trim().length > 0;
|
|
193
|
-
// Route to appropriate handler
|
|
194
|
-
if (hasHandler) {
|
|
195
|
-
handlers.push(async (c) => await mockHandlerResponse(c, operation, pathItem?.parameters, schema.openapi));
|
|
196
|
-
}
|
|
197
|
-
else {
|
|
198
|
-
handlers.push(async (c) => await mockAnyResponse(c, operation, schema.openapi));
|
|
199
|
-
}
|
|
200
|
-
// The pinned query parameters are not part of the route, so they are checked here. A request
|
|
201
|
-
// that does not carry them is handed on to the next matching route — usually the sibling path
|
|
202
|
-
// key without the query string.
|
|
203
|
-
const operationChain = every(...handlers);
|
|
204
|
-
// Hono uppercases methods during registration. Match the original method ourselves so
|
|
205
|
-
// additional operations such as COPY and copy remain distinct.
|
|
206
|
-
const register = (handler) => {
|
|
207
|
-
if (method === method.toUpperCase()) {
|
|
208
|
-
app.on(method, route, handler);
|
|
209
|
-
}
|
|
210
|
-
else {
|
|
211
|
-
app.all(route, handler);
|
|
212
|
-
}
|
|
213
|
-
};
|
|
214
|
-
register(async (c, next) => {
|
|
215
|
-
if ((c.req.method !== method && !(method === 'GET' && c.req.method === 'HEAD')) ||
|
|
216
|
-
!requestMatchesPinnedQuery(c, query)) {
|
|
217
|
-
await next();
|
|
218
|
-
return;
|
|
219
|
-
}
|
|
220
|
-
await operationChain(c, next);
|
|
221
|
-
});
|
|
222
|
-
});
|
|
223
|
-
});
|
|
224
|
-
// OpenAPI JSON file
|
|
225
|
-
app.get('/openapi.json', (c) => respondWithOpenApiDocument(c, exportDocument, 'json'));
|
|
226
|
-
// OpenAPI YAML file
|
|
227
|
-
app.get('/openapi.yaml', (c) => respondWithOpenApiDocument(c, exportDocument, 'yaml'));
|
|
228
|
-
return app;
|
|
229
|
-
}
|
|
8
|
+
export const createMockServer = async (configuration) => {
|
|
9
|
+
const processed = await processDocument(configuration?.document ?? configuration?.specification, configuration?.origin);
|
|
10
|
+
return processed.type === 'asyncapi'
|
|
11
|
+
? createAsyncApiMockServer(configuration, processed.document)
|
|
12
|
+
: createOpenApiMockServer(configuration, processed.document);
|
|
13
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import type { MockServerOptions } from './types.js';
|
|
3
|
+
import type { ProcessedDocument } from './utils/process-document.js';
|
|
4
|
+
/**
|
|
5
|
+
* Create a mock server instance
|
|
6
|
+
*/
|
|
7
|
+
export declare const createOpenApiMockServer: (configuration: MockServerOptions, schema: Extract<ProcessedDocument, {
|
|
8
|
+
type: "openapi";
|
|
9
|
+
}>["document"]) => Promise<Hono>;
|
|
10
|
+
//# sourceMappingURL=create-openapi-mock-server.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-openapi-mock-server.d.ts","sourceRoot":"","sources":["../src/create-openapi-mock-server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAgB,IAAI,EAA0B,MAAM,MAAM,CAAA;AAIjE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA;AAQhD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAA;AAgDjE;;GAEG;AACH,eAAO,MAAM,uBAAuB,GAClC,eAAe,iBAAiB,EAChC,QAAQ,OAAO,CAAC,iBAAiB,EAAE;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC,CAAC,UAAU,CAAC,KAClE,OAAO,CAAC,IAAI,CAuOd,CAAA"}
|