nestjs-cloudflare 0.1.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.
- package/README.md +270 -4
- package/dist/cloudflare.module.d.ts +1 -0
- package/dist/cloudflare.module.js +12 -2
- package/dist/durable-objects/client.d.ts +13 -0
- package/dist/durable-objects/client.js +67 -0
- package/dist/durable-objects/constants.d.ts +1 -0
- package/dist/durable-objects/constants.js +1 -0
- package/dist/durable-objects/context.d.ts +18 -0
- package/dist/durable-objects/context.js +53 -0
- package/dist/durable-objects/context.transport.d.ts +9 -0
- package/dist/durable-objects/context.transport.js +13 -0
- package/dist/durable-objects/durable-object.d.ts +11 -0
- package/dist/durable-objects/durable-object.js +21 -0
- package/dist/durable-objects/index.d.ts +9 -0
- package/dist/durable-objects/index.js +7 -0
- package/dist/durable-objects/interfaces/client-options.interface.d.ts +15 -0
- package/dist/durable-objects/interfaces/client-options.interface.js +1 -0
- package/dist/durable-objects/interfaces/server-options.interface.d.ts +14 -0
- package/dist/durable-objects/interfaces/server-options.interface.js +1 -0
- package/dist/durable-objects/record-builder.d.ts +16 -0
- package/dist/durable-objects/record-builder.js +28 -0
- package/dist/durable-objects/record.serializer.d.ts +10 -0
- package/dist/durable-objects/record.serializer.js +10 -0
- package/dist/durable-objects/server.d.ts +16 -0
- package/dist/durable-objects/server.js +101 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/interfaces/worker-options.interface.d.ts +32 -1
- package/dist/interfaces/worker.interface.d.ts +3 -1
- package/dist/queue/client.js +10 -2
- package/dist/queue/index.d.ts +2 -0
- package/dist/queue/index.js +2 -0
- package/dist/queue/record-builder.d.ts +19 -0
- package/dist/queue/record-builder.js +32 -0
- package/dist/queue/record.serializer.d.ts +10 -0
- package/dist/queue/record.serializer.js +14 -0
- package/dist/schedule/cron.explorer.d.ts +3 -0
- package/dist/schedule/cron.explorer.js +20 -4
- package/dist/websockets/adapter.d.ts +8 -1
- package/dist/websockets/adapter.js +30 -5
- package/dist/websockets/context.d.ts +12 -0
- package/dist/websockets/context.js +15 -0
- package/dist/websockets/durable-object.d.ts +3 -0
- package/dist/websockets/durable-object.js +7 -0
- package/dist/websockets/gateway-durable-object.d.ts +17 -0
- package/dist/websockets/gateway-durable-object.js +82 -0
- package/dist/websockets/index.d.ts +4 -0
- package/dist/websockets/index.js +2 -0
- package/dist/websockets/interfaces/adapter-options.interface.d.ts +4 -0
- package/dist/websockets/interfaces/gateway-options.interface.d.ts +11 -0
- package/dist/websockets/interfaces/gateway-options.interface.js +1 -0
- package/dist/websockets/message-dispatcher.d.ts +8 -0
- package/dist/websockets/message-dispatcher.js +26 -0
- package/dist/worker/create-worker.d.ts +1 -0
- package/dist/worker/create-worker.js +167 -43
- package/dist/worker/request-context.d.ts +19 -0
- package/dist/worker/request-context.js +38 -0
- package/dist/worker/websocket-routing.d.ts +3 -0
- package/dist/worker/websocket-routing.js +10 -0
- package/package.json +5 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { DurableObject } from 'cloudflare:workers';
|
|
2
|
+
import { attachDurableObjectContext, resolveForDurableObject, } from '../durable-objects/context.js';
|
|
2
3
|
import { InvalidWebSocketMessageException } from './invalid-message.exception.js';
|
|
3
4
|
/**
|
|
4
5
|
* Hosts a Nest gateway using the Durable Object WebSocket Hibernation API.
|
|
@@ -17,10 +18,15 @@ export class CloudflareWebSocketDurableObject extends DurableObject {
|
|
|
17
18
|
this.ready = (async () => {
|
|
18
19
|
await options.getApplication();
|
|
19
20
|
for (const socket of ctx.getWebSockets(tag)) {
|
|
21
|
+
attachDurableObjectContext(socket, ctx);
|
|
20
22
|
options.adapter.connect(options.path, socket);
|
|
21
23
|
}
|
|
22
24
|
})();
|
|
23
25
|
}
|
|
26
|
+
/** Resolves object-owned providers from fetch, alarm, and RPC handlers. */
|
|
27
|
+
async resolve(token) {
|
|
28
|
+
return resolveForDurableObject(await this.options.getApplication(), this.ctx, token);
|
|
29
|
+
}
|
|
24
30
|
/** Accepts upgrades and registers connections for hibernation. */
|
|
25
31
|
async fetch(request) {
|
|
26
32
|
await this.ready;
|
|
@@ -32,6 +38,7 @@ export class CloudflareWebSocketDurableObject extends DurableObject {
|
|
|
32
38
|
}
|
|
33
39
|
const pair = new WebSocketPair();
|
|
34
40
|
this.ctx.acceptWebSocket(pair[1], [this.tag]);
|
|
41
|
+
attachDurableObjectContext(pair[1], this.ctx);
|
|
35
42
|
this.options.adapter.connect(this.options.path, pair[1], request);
|
|
36
43
|
return new Response(null, { status: 101, webSocket: pair[0] });
|
|
37
44
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { InjectionToken } from '@nestjs/common';
|
|
2
|
+
import { DurableObject } from 'cloudflare:workers';
|
|
3
|
+
import type { CloudflareWebSocketGatewayOptions } from './interfaces/gateway-options.interface.js';
|
|
4
|
+
/** Hosts Nest gateways with the non-hibernating WebSocket API. */
|
|
5
|
+
export declare abstract class CloudflareWebSocketGatewayDurableObject<Env = Cloudflare.Env> extends DurableObject<Env> {
|
|
6
|
+
private readonly ready;
|
|
7
|
+
private readonly sockets;
|
|
8
|
+
private readonly options;
|
|
9
|
+
protected constructor(ctx: DurableObjectState, env: Env, options: CloudflareWebSocketGatewayOptions);
|
|
10
|
+
/** Resolves object-owned providers from fetch, alarm, and RPC handlers. */
|
|
11
|
+
protected resolve<T>(token: InjectionToken<T>): Promise<T>;
|
|
12
|
+
/** Accepts a matching upgrade with server.accept(). */
|
|
13
|
+
fetch(request: Request): Promise<Response>;
|
|
14
|
+
/** Handles requests that are not WebSocket upgrades. */
|
|
15
|
+
protected nonWebSocketFetch(_request: Request): Response | Promise<Response>;
|
|
16
|
+
private handleMessage;
|
|
17
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { DurableObject } from 'cloudflare:workers';
|
|
2
|
+
import { attachDurableObjectContext, resolveForDurableObject, } from '../durable-objects/context.js';
|
|
3
|
+
import { InvalidWebSocketMessageException } from './invalid-message.exception.js';
|
|
4
|
+
/** Hosts Nest gateways with the non-hibernating WebSocket API. */
|
|
5
|
+
export class CloudflareWebSocketGatewayDurableObject extends DurableObject {
|
|
6
|
+
ready;
|
|
7
|
+
sockets = new Set();
|
|
8
|
+
options;
|
|
9
|
+
constructor(ctx, env, options) {
|
|
10
|
+
super(ctx, env);
|
|
11
|
+
this.options = options;
|
|
12
|
+
for (const path of options.paths) {
|
|
13
|
+
if (!path.startsWith('/')) {
|
|
14
|
+
throw new Error(`WebSocket gateway path must start with /: ${path}`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
this.ready = options.getApplication().then(() => {
|
|
18
|
+
const firstPath = options.paths[0];
|
|
19
|
+
if (firstPath) {
|
|
20
|
+
for (const path of options.paths.slice(1)) {
|
|
21
|
+
options.adapter.registerPathAlias(path, firstPath);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/** Resolves object-owned providers from fetch, alarm, and RPC handlers. */
|
|
27
|
+
async resolve(token) {
|
|
28
|
+
return resolveForDurableObject(await this.options.getApplication(), this.ctx, token);
|
|
29
|
+
}
|
|
30
|
+
/** Accepts a matching upgrade with server.accept(). */
|
|
31
|
+
async fetch(request) {
|
|
32
|
+
await this.ready;
|
|
33
|
+
const path = new URL(request.url).pathname;
|
|
34
|
+
const isUpgrade = request.headers.get('Upgrade')?.toLowerCase() === 'websocket';
|
|
35
|
+
if (!isUpgrade) {
|
|
36
|
+
return this.nonWebSocketFetch(request);
|
|
37
|
+
}
|
|
38
|
+
if (request.method !== 'GET' || !this.options.paths.includes(path)) {
|
|
39
|
+
return new Response('Not found', { status: 404 });
|
|
40
|
+
}
|
|
41
|
+
const pair = new WebSocketPair();
|
|
42
|
+
const [client, server] = Object.values(pair);
|
|
43
|
+
server.accept();
|
|
44
|
+
const context = {
|
|
45
|
+
ctx: this.ctx,
|
|
46
|
+
env: this.env,
|
|
47
|
+
object: this,
|
|
48
|
+
storage: this.ctx.storage,
|
|
49
|
+
sockets: this.sockets,
|
|
50
|
+
};
|
|
51
|
+
this.sockets.add(server);
|
|
52
|
+
attachDurableObjectContext(server, this.ctx);
|
|
53
|
+
this.options.adapter.connect(path, server, request, context);
|
|
54
|
+
server.addEventListener('message', event => {
|
|
55
|
+
void this.handleMessage(server, event.data);
|
|
56
|
+
});
|
|
57
|
+
server.addEventListener('close', event => {
|
|
58
|
+
this.sockets.delete(server);
|
|
59
|
+
this.options.adapter.disconnect(server, event.reason);
|
|
60
|
+
});
|
|
61
|
+
server.addEventListener('error', event => {
|
|
62
|
+
this.options.adapter.error(server, event);
|
|
63
|
+
});
|
|
64
|
+
return new Response(null, { status: 101, webSocket: client });
|
|
65
|
+
}
|
|
66
|
+
/** Handles requests that are not WebSocket upgrades. */
|
|
67
|
+
nonWebSocketFetch(_request) {
|
|
68
|
+
return new Response('WebSocket upgrade required', { status: 426 });
|
|
69
|
+
}
|
|
70
|
+
async handleMessage(socket, data) {
|
|
71
|
+
try {
|
|
72
|
+
await this.options.adapter.message(socket, data);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error instanceof InvalidWebSocketMessageException) {
|
|
76
|
+
socket.close(1007, error.message);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
this.options.adapter.error(socket, error);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
export { CloudflareWebSocketAdapter } from './adapter.js';
|
|
2
|
+
export type { CloudflareWebSocketContext } from './context.js';
|
|
3
|
+
export { getCloudflareWebSocketContext } from './context.js';
|
|
2
4
|
export { CloudflareWebSocketDurableObject } from './durable-object.js';
|
|
5
|
+
export { CloudflareWebSocketGatewayDurableObject } from './gateway-durable-object.js';
|
|
3
6
|
export type { CloudflareWebSocketAdapterOptions } from './interfaces/adapter-options.interface.js';
|
|
4
7
|
export type { CloudflareWebSocketDurableObjectOptions } from './interfaces/durable-object-options.interface.js';
|
|
8
|
+
export type { CloudflareWebSocketGatewayOptions } from './interfaces/gateway-options.interface.js';
|
|
5
9
|
export type { CloudflareWebSocketMessage } from './interfaces/message.interface.js';
|
|
6
10
|
export type { CloudflareWebSocketServer } from './interfaces/server.interface.js';
|
|
7
11
|
export { InvalidWebSocketMessageException } from './invalid-message.exception.js';
|
package/dist/websockets/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
export { CloudflareWebSocketAdapter } from './adapter.js';
|
|
2
|
+
export { getCloudflareWebSocketContext } from './context.js';
|
|
2
3
|
export { CloudflareWebSocketDurableObject } from './durable-object.js';
|
|
4
|
+
export { CloudflareWebSocketGatewayDurableObject } from './gateway-durable-object.js';
|
|
3
5
|
export { InvalidWebSocketMessageException } from './invalid-message.exception.js';
|
|
@@ -5,6 +5,10 @@ import type { CloudflareWebSocketMessage } from './message.interface.js';
|
|
|
5
5
|
* @publicApi
|
|
6
6
|
*/
|
|
7
7
|
export interface CloudflareWebSocketAdapterOptions {
|
|
8
|
+
/** Maximum active messages per connection. Defaults to 1000; use 1 for serial handling. */
|
|
9
|
+
maxConcurrentMessages?: number;
|
|
8
10
|
/** Maps a frame to an event and payload, or returns void to ignore it. */
|
|
9
11
|
messageParser?: (data: string | ArrayBuffer) => CloudflareWebSocketMessage | void;
|
|
12
|
+
/** Serializes values returned by gateway handlers before sending them. */
|
|
13
|
+
messageSerializer?: (data: unknown) => string | ArrayBuffer;
|
|
10
14
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { INestApplicationContext } from '@nestjs/common';
|
|
2
|
+
import type { CloudflareWebSocketAdapter } from '../adapter.js';
|
|
3
|
+
/** Options for a non-hibernating Durable Object gateway host. */
|
|
4
|
+
export interface CloudflareWebSocketGatewayOptions {
|
|
5
|
+
/** Adapter installed on the Nest application. */
|
|
6
|
+
adapter: CloudflareWebSocketAdapter;
|
|
7
|
+
/** Gateway paths served by this Durable Object. */
|
|
8
|
+
paths: readonly string[];
|
|
9
|
+
/** Starts or retrieves the initialized Nest application. */
|
|
10
|
+
getApplication: () => Promise<INestApplicationContext>;
|
|
11
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Applies a concurrency limit to one socket's asynchronous dispatch. */
|
|
2
|
+
export declare class WebSocketMessageDispatcher {
|
|
3
|
+
private readonly pending;
|
|
4
|
+
private closed;
|
|
5
|
+
constructor(handle: (frame: string | ArrayBuffer) => Promise<void>, concurrency: number);
|
|
6
|
+
dispatch(frame: string | ArrayBuffer): Promise<void>;
|
|
7
|
+
close(): void;
|
|
8
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { catchError, defer, EMPTY, mergeMap, Subject, tap } from 'rxjs';
|
|
2
|
+
/** Applies a concurrency limit to one socket's asynchronous dispatch. */
|
|
3
|
+
export class WebSocketMessageDispatcher {
|
|
4
|
+
pending = new Subject();
|
|
5
|
+
closed = false;
|
|
6
|
+
constructor(handle, concurrency) {
|
|
7
|
+
this.pending
|
|
8
|
+
.pipe(mergeMap(task => defer(() => this.closed ? Promise.resolve() : handle(task.frame)).pipe(tap(() => task.resolve()), catchError((error) => {
|
|
9
|
+
task.reject(error);
|
|
10
|
+
return EMPTY;
|
|
11
|
+
})), concurrency))
|
|
12
|
+
.subscribe();
|
|
13
|
+
}
|
|
14
|
+
dispatch(frame) {
|
|
15
|
+
if (this.closed) {
|
|
16
|
+
return Promise.resolve();
|
|
17
|
+
}
|
|
18
|
+
return new Promise((resolve, reject) => {
|
|
19
|
+
this.pending.next({ frame, resolve, reject });
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
close() {
|
|
23
|
+
this.closed = true;
|
|
24
|
+
this.pending.complete();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -2,6 +2,7 @@ import 'reflect-metadata';
|
|
|
2
2
|
import { type INestApplication } from '@nestjs/common';
|
|
3
3
|
import type { CloudflareWorker } from '../interfaces/worker.interface.js';
|
|
4
4
|
import type { CloudflareWorkerOptions } from '../interfaces/worker-options.interface.js';
|
|
5
|
+
export { CloudflareRequestContext, type CloudflareRequestContextValue, } from './request-context.js';
|
|
5
6
|
/**
|
|
6
7
|
* Defers Nest bootstrap until the first event and caches the initialized application.
|
|
7
8
|
*
|
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
2
|
import { Logger } from '@nestjs/common';
|
|
3
|
+
import { ModuleRef } from '@nestjs/core';
|
|
3
4
|
import { httpServerHandler } from 'cloudflare:node';
|
|
4
5
|
import { CLOUDFLARE_ENV } from '../constants.js';
|
|
5
6
|
import { CLOUDFLARE_QUEUE_TRANSPORT } from '../queue/constants.js';
|
|
6
7
|
import { CRON_EXPLORER } from '../schedule/constants.js';
|
|
8
|
+
import { CloudflareRequestContext } from './request-context.js';
|
|
9
|
+
import { findWebSocketRoute, forwardWebSocketRequest, } from './websocket-routing.js';
|
|
10
|
+
export { CloudflareRequestContext, } from './request-context.js';
|
|
7
11
|
/**
|
|
8
12
|
* Defers Nest bootstrap until the first event and caches the initialized application.
|
|
9
13
|
*
|
|
@@ -13,8 +17,12 @@ export function createWorker(bootstrap, options = {}) {
|
|
|
13
17
|
const logger = new Logger('CloudflareWorker');
|
|
14
18
|
let application;
|
|
15
19
|
let http;
|
|
20
|
+
let routeMatcher;
|
|
16
21
|
const getApplication = () => {
|
|
17
|
-
|
|
22
|
+
if (application) {
|
|
23
|
+
return application;
|
|
24
|
+
}
|
|
25
|
+
const startup = (async () => {
|
|
18
26
|
const app = await bootstrap();
|
|
19
27
|
try {
|
|
20
28
|
app.get(CLOUDFLARE_ENV);
|
|
@@ -24,12 +32,14 @@ export function createWorker(bootstrap, options = {}) {
|
|
|
24
32
|
throw new Error('Import CloudflareModule.forRoot() in the application root module', { cause });
|
|
25
33
|
}
|
|
26
34
|
try {
|
|
35
|
+
validateRouting(app, options);
|
|
27
36
|
await app.init();
|
|
28
37
|
await app.startAllMicroservices();
|
|
29
38
|
if (!app.getHttpServer().listening) {
|
|
30
39
|
await app.listen(0);
|
|
31
40
|
}
|
|
32
41
|
http = httpServerHandler(app.getHttpServer());
|
|
42
|
+
routeMatcher = createRouteMatcher(app, options);
|
|
33
43
|
return app;
|
|
34
44
|
}
|
|
35
45
|
catch (error) {
|
|
@@ -37,63 +47,177 @@ export function createWorker(bootstrap, options = {}) {
|
|
|
37
47
|
throw error;
|
|
38
48
|
}
|
|
39
49
|
})();
|
|
50
|
+
application = startup;
|
|
51
|
+
startup.catch(() => {
|
|
52
|
+
if (application === startup) {
|
|
53
|
+
application = undefined;
|
|
54
|
+
}
|
|
55
|
+
});
|
|
40
56
|
return application;
|
|
41
57
|
};
|
|
58
|
+
const runWithContext = (app, value, callback) => app.get(CloudflareRequestContext).run(value, callback);
|
|
59
|
+
const matches = async (request) => {
|
|
60
|
+
if (findWebSocketRoute(request, options.websockets)) {
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
await getApplication();
|
|
64
|
+
return routeMatcher?.(request).matched ?? false;
|
|
65
|
+
};
|
|
42
66
|
return {
|
|
43
67
|
getApplication,
|
|
68
|
+
matches,
|
|
44
69
|
async fetch(request, env, ctx) {
|
|
45
|
-
|
|
46
|
-
|
|
70
|
+
const dispatch = async () => {
|
|
71
|
+
const websocket = findWebSocketRoute(request, options.websockets);
|
|
72
|
+
if (websocket) {
|
|
73
|
+
return forwardWebSocketRequest(request, env, websocket);
|
|
74
|
+
}
|
|
75
|
+
const app = await getApplication();
|
|
76
|
+
const route = routeMatcher?.(request) ?? { matched: false };
|
|
77
|
+
const fallback = options.fallback?.fetch;
|
|
78
|
+
if (!route.matched && fallback) {
|
|
79
|
+
return runWithContext(app, { request, env, ctx, routeError: route.routeError }, () => fallback(request, env, ctx));
|
|
80
|
+
}
|
|
81
|
+
return runWithContext(app, { request, env, ctx }, () => http.fetch(request, env, ctx));
|
|
82
|
+
};
|
|
83
|
+
const around = options.around?.fetch;
|
|
84
|
+
return around ? around(request, env, ctx, dispatch) : dispatch();
|
|
47
85
|
},
|
|
48
86
|
async scheduled(controller, env, ctx) {
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
scheduled
|
|
53
|
-
}
|
|
54
|
-
catch {
|
|
55
|
-
// The schedule integration is optional for applications without cron handlers.
|
|
56
|
-
}
|
|
57
|
-
if (scheduled?.dispatch(controller, ctx)) {
|
|
58
|
-
return;
|
|
59
|
-
}
|
|
60
|
-
if (options.fallback?.scheduled) {
|
|
61
|
-
await options.fallback.scheduled(controller, env, ctx);
|
|
62
|
-
}
|
|
63
|
-
else {
|
|
64
|
-
logger.warn(`No Cloudflare cron handler for expression: ${controller.cron}. Import CloudflareScheduleModule.forRoot() and declare a matching @Cron method`);
|
|
65
|
-
}
|
|
66
|
-
},
|
|
67
|
-
async queue(batch, env, ctx) {
|
|
68
|
-
const app = await getApplication();
|
|
69
|
-
const transports = [];
|
|
70
|
-
for (const microservice of app.getMicroservices()) {
|
|
71
|
-
let transport;
|
|
87
|
+
const dispatch = async () => {
|
|
88
|
+
const app = await getApplication();
|
|
89
|
+
const moduleRef = app.get(ModuleRef);
|
|
90
|
+
let scheduled;
|
|
72
91
|
try {
|
|
73
|
-
|
|
92
|
+
// ModuleRef lookups bypass the application's logging exception proxy.
|
|
93
|
+
scheduled = moduleRef.get(CRON_EXPLORER, {
|
|
94
|
+
strict: false,
|
|
95
|
+
});
|
|
74
96
|
}
|
|
75
97
|
catch {
|
|
76
|
-
|
|
98
|
+
// The schedule integration is optional for applications without cron handlers.
|
|
99
|
+
}
|
|
100
|
+
if (scheduled?.dispatchAndWait) {
|
|
101
|
+
if (await scheduled.dispatchAndWait(controller, ctx)) {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
77
104
|
}
|
|
78
|
-
if (
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
105
|
+
else if (scheduled?.dispatch(controller, ctx)) {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (options.fallback?.scheduled) {
|
|
109
|
+
await options.fallback.scheduled(controller, env, ctx);
|
|
83
110
|
}
|
|
111
|
+
else {
|
|
112
|
+
logger.warn(`No Cloudflare cron handler for expression: ${controller.cron}. Import CloudflareScheduleModule.forRoot() and declare a matching @Cron method`);
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
const invoke = async () => {
|
|
116
|
+
const app = await getApplication();
|
|
117
|
+
await runWithContext(app, { env, ctx }, () => dispatch());
|
|
118
|
+
};
|
|
119
|
+
const around = options.around?.scheduled;
|
|
120
|
+
return around ? around(controller, env, ctx, invoke) : invoke();
|
|
121
|
+
},
|
|
122
|
+
async queue(batch, env, ctx) {
|
|
123
|
+
const dispatch = async () => {
|
|
124
|
+
const app = await getApplication();
|
|
125
|
+
const transports = [];
|
|
126
|
+
for (const microservice of app.getMicroservices()) {
|
|
127
|
+
let transport;
|
|
128
|
+
try {
|
|
129
|
+
transport = microservice.unwrap();
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (typeof transport === 'object' &&
|
|
135
|
+
transport !== null &&
|
|
136
|
+
'transportId' in transport &&
|
|
137
|
+
transport.transportId === CLOUDFLARE_QUEUE_TRANSPORT) {
|
|
138
|
+
transports.push(transport);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (transports.length > 1) {
|
|
142
|
+
throw new Error('Connect exactly one CloudflareQueueServer to dispatch Worker queue events');
|
|
143
|
+
}
|
|
144
|
+
const fallback = options.fallback?.queue;
|
|
145
|
+
if (!transports[0]) {
|
|
146
|
+
if (fallback) {
|
|
147
|
+
await fallback(batch, env, ctx);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
throw new Error('Connect a CloudflareQueueServer with app.connectMicroservice() before handling queue events');
|
|
151
|
+
}
|
|
152
|
+
await transports[0].consume(batch, ctx, fallback ? () => fallback(batch, env, ctx) : undefined);
|
|
153
|
+
};
|
|
154
|
+
const invoke = async () => {
|
|
155
|
+
const app = await getApplication();
|
|
156
|
+
await runWithContext(app, { env, ctx }, () => dispatch());
|
|
157
|
+
};
|
|
158
|
+
const around = options.around?.queue;
|
|
159
|
+
return around ? around(batch, env, ctx, invoke) : invoke();
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function validateRouting(app, options) {
|
|
164
|
+
const instance = app.getHttpAdapter().getInstance();
|
|
165
|
+
const settings = [
|
|
166
|
+
[
|
|
167
|
+
'case sensitive routing',
|
|
168
|
+
options.routing?.caseSensitive ?? options.routing?.caseSensitiveRouting,
|
|
169
|
+
],
|
|
170
|
+
[
|
|
171
|
+
'strict routing',
|
|
172
|
+
options.routing?.strict ?? options.routing?.strictRouting,
|
|
173
|
+
],
|
|
174
|
+
];
|
|
175
|
+
for (const [name, expected] of settings) {
|
|
176
|
+
if (expected !== undefined && instance.enabled(name) !== expected) {
|
|
177
|
+
throw new Error(`Configure Express with instance.set('${name}', ${expected}) before passing it to new ExpressAdapter(instance) in bootstrap`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function createRouteMatcher(app, options) {
|
|
182
|
+
const instance = app.getHttpAdapter().getInstance();
|
|
183
|
+
const stack = instance._router?.stack ?? instance.router?.stack ?? [];
|
|
184
|
+
const headImplicitMatch = options.routing?.headImplicitMatch ?? true;
|
|
185
|
+
return request => {
|
|
186
|
+
const url = new URL(request.url);
|
|
187
|
+
for (const layer of stack) {
|
|
188
|
+
if (!layer.route) {
|
|
189
|
+
continue;
|
|
84
190
|
}
|
|
85
|
-
|
|
86
|
-
|
|
191
|
+
let pathMatches;
|
|
192
|
+
try {
|
|
193
|
+
pathMatches = layer.match(url.pathname);
|
|
87
194
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
await fallback(batch, env, ctx);
|
|
92
|
-
return;
|
|
195
|
+
catch (error) {
|
|
196
|
+
if (error instanceof URIError) {
|
|
197
|
+
return { matched: false, routeError: error };
|
|
93
198
|
}
|
|
94
|
-
throw
|
|
199
|
+
throw error;
|
|
95
200
|
}
|
|
96
|
-
|
|
97
|
-
|
|
201
|
+
if (!pathMatches) {
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
if (matchesMethod(layer.route, request.method, headImplicitMatch)) {
|
|
205
|
+
return { matched: true };
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return { matched: false };
|
|
98
209
|
};
|
|
99
210
|
}
|
|
211
|
+
function matchesMethod(route, method, headImplicitMatch) {
|
|
212
|
+
const name = method.toLowerCase();
|
|
213
|
+
if (name === 'head' && !headImplicitMatch) {
|
|
214
|
+
return Boolean(route.methods?.head);
|
|
215
|
+
}
|
|
216
|
+
const handlesMethod = route._handlesMethod ?? route._handles_method;
|
|
217
|
+
if (handlesMethod) {
|
|
218
|
+
return handlesMethod.call(route, method);
|
|
219
|
+
}
|
|
220
|
+
return Boolean(route.methods?._all ||
|
|
221
|
+
route.methods?.[name] ||
|
|
222
|
+
(name === 'head' && route.methods?.get));
|
|
223
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
type CloudflareExecutionContext = ExecutionContext | DurableObjectState;
|
|
2
|
+
type IncomingRequest = Request<unknown, IncomingRequestCfProperties>;
|
|
3
|
+
export interface CloudflareRequestContextValue<Env = unknown> {
|
|
4
|
+
readonly request?: IncomingRequest;
|
|
5
|
+
readonly env: Env;
|
|
6
|
+
readonly ctx: CloudflareExecutionContext;
|
|
7
|
+
readonly routeError?: URIError;
|
|
8
|
+
}
|
|
9
|
+
/** Provides the native event values for the current Nest invocation. */
|
|
10
|
+
export declare class CloudflareRequestContext<Env = unknown> {
|
|
11
|
+
private readonly storage;
|
|
12
|
+
run<T>(value: CloudflareRequestContextValue<Env>, callback: () => T): T;
|
|
13
|
+
get(): CloudflareRequestContextValue<Env>;
|
|
14
|
+
getRequest(): IncomingRequest | undefined;
|
|
15
|
+
getEnv(): Env;
|
|
16
|
+
getExecutionContext(): CloudflareExecutionContext;
|
|
17
|
+
getRouteError(): URIError | undefined;
|
|
18
|
+
}
|
|
19
|
+
export {};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
8
|
+
import { Injectable } from '@nestjs/common';
|
|
9
|
+
/** Provides the native event values for the current Nest invocation. */
|
|
10
|
+
let CloudflareRequestContext = class CloudflareRequestContext {
|
|
11
|
+
storage = new AsyncLocalStorage();
|
|
12
|
+
run(value, callback) {
|
|
13
|
+
return this.storage.run(value, callback);
|
|
14
|
+
}
|
|
15
|
+
get() {
|
|
16
|
+
const value = this.storage.getStore();
|
|
17
|
+
if (!value) {
|
|
18
|
+
throw new Error('Cloudflare request context is unavailable outside an event');
|
|
19
|
+
}
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
getRequest() {
|
|
23
|
+
return this.get().request;
|
|
24
|
+
}
|
|
25
|
+
getEnv() {
|
|
26
|
+
return this.get().env;
|
|
27
|
+
}
|
|
28
|
+
getExecutionContext() {
|
|
29
|
+
return this.get().ctx;
|
|
30
|
+
}
|
|
31
|
+
getRouteError() {
|
|
32
|
+
return this.get().routeError;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
CloudflareRequestContext = __decorate([
|
|
36
|
+
Injectable()
|
|
37
|
+
], CloudflareRequestContext);
|
|
38
|
+
export { CloudflareRequestContext };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { CloudflareWorkerWebSocketRoute } from '../interfaces/worker-options.interface.js';
|
|
2
|
+
export declare function findWebSocketRoute<Env>(request: Request, routes?: readonly CloudflareWorkerWebSocketRoute<Env>[]): CloudflareWorkerWebSocketRoute<Env> | undefined;
|
|
3
|
+
export declare function forwardWebSocketRequest<Env>(request: Request<unknown, IncomingRequestCfProperties>, env: Env, route: CloudflareWorkerWebSocketRoute<Env>): Promise<Response>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export function findWebSocketRoute(request, routes = []) {
|
|
2
|
+
const path = new URL(request.url).pathname;
|
|
3
|
+
return routes.find(route => route.paths.includes(path));
|
|
4
|
+
}
|
|
5
|
+
export function forwardWebSocketRequest(request, env, route) {
|
|
6
|
+
const namespace = env[route.binding];
|
|
7
|
+
const object = typeof route.object === 'function' ? route.object(request) : route.object;
|
|
8
|
+
const id = typeof object === 'string' ? namespace.idFromName(object) : object;
|
|
9
|
+
return namespace.get(id).fetch(request);
|
|
10
|
+
}
|
package/package.json
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nestjs-cloudflare",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": {
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
8
8
|
"import": "./dist/index.js"
|
|
9
9
|
},
|
|
10
|
+
"./durable-objects": {
|
|
11
|
+
"types": "./dist/durable-objects/index.d.ts",
|
|
12
|
+
"import": "./dist/durable-objects/index.js"
|
|
13
|
+
},
|
|
10
14
|
"./queue": {
|
|
11
15
|
"types": "./dist/queue/index.d.ts",
|
|
12
16
|
"import": "./dist/queue/index.js"
|