@guren/plugin-cloudflare 0.8.0 → 0.9.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/dist/{build-Bq9KODjL.js → build-DN7RvfKD.js} +22 -10
- package/dist/commands.js +1 -1
- package/dist/index.d.ts +77 -1
- package/dist/index.js +61 -12
- package/package.json +1 -1
|
@@ -650,22 +650,33 @@ function renderWorkerModule(input) {
|
|
|
650
650
|
const hasAgents = input.agents.length > 0;
|
|
651
651
|
const lines = ["// Generated by `guren cloudflare:build`. Do not edit — regenerate instead."];
|
|
652
652
|
if (input.hasEnvModule) lines.push("import './worker-env.js'");
|
|
653
|
-
lines.push("import { createWorkersHandler } from '@guren/plugin-cloudflare'");
|
|
653
|
+
lines.push(input.mcpOAuth ? "import { createWorkersHandler, sweepOAuthStorage } from '@guren/plugin-cloudflare'" : "import { createWorkersHandler } from '@guren/plugin-cloudflare'");
|
|
654
654
|
if (hasAgents) lines.push(`import { configureAgentRuntime } from ${JSON.stringify(AGENTS_RUNTIME_SPECIFIER)}`, `import { routeGuardedAgentRequest } from ${JSON.stringify(AGENTS_ROUTER_SPECIFIER)}`, `import agentsConfig from ${quotedImport(input.out, resolve(input.root, AGENTS_CONFIG_FILE))}`);
|
|
655
655
|
if (input.mcpOAuth) lines.push(`import { OAuthProvider } from ${JSON.stringify(OAUTH_PROVIDER_PACKAGE)}`, `import { mcpOAuthPropsToAuth, presentExternalMcpAuth } from ${JSON.stringify(MCP_OAUTH_SEAM_SPECIFIER)}`);
|
|
656
656
|
if (input.ssrImport) lines.push("import { setInertiaSsrRenderer } from '@guren/core'", `import * as ssrModule from ${quotedImport(input.out, input.ssrImport.file)}`);
|
|
657
657
|
lines.push(`import app from ${quotedImport(input.out, input.appEntry)}`, "");
|
|
658
658
|
if (input.ssrImport) lines.push(`setInertiaSsrRenderer(ssrModule.${input.ssrImport.rendererExport})`, "");
|
|
659
|
-
if (!input.mcpOAuth && !hasAgents) {
|
|
660
|
-
lines.push("export default createWorkersHandler(app)", "");
|
|
661
|
-
return lines.join("\n");
|
|
662
|
-
}
|
|
663
659
|
lines.push("const handler = createWorkersHandler(app)", "");
|
|
664
660
|
if (hasAgents) lines.push(renderAgentWiring(input.out, input.root, input.agents, input.agentBindings), "");
|
|
665
|
-
|
|
666
|
-
lines.push(input.mcpOAuth ?
|
|
661
|
+
if (input.mcpOAuth) lines.push(renderOAuthProvider(input.mcpPath, hasAgents ? "agentEntry" : "handler"), "");
|
|
662
|
+
lines.push(renderDefaultExport(input.mcpOAuth ? "oauth" : hasAgents ? "agentEntry" : "handler", input.mcpOAuth), "");
|
|
667
663
|
return lines.join("\n");
|
|
668
664
|
}
|
|
665
|
+
/**
|
|
666
|
+
* The module's one default export, emitted the same way for every shape so none
|
|
667
|
+
* can gain a `fetch` without a `scheduled` beside it — a cron trigger reaching
|
|
668
|
+
* an export that has none does nothing at all, with no error anywhere. Neither
|
|
669
|
+
* `agentEntry` nor `OAuthProvider` carries one, so `scheduled` is the handler's.
|
|
670
|
+
*/
|
|
671
|
+
function renderDefaultExport(fetchEntry, sweepsOAuthStorage) {
|
|
672
|
+
return `export default {
|
|
673
|
+
fetch: (request, env, ctx) => ${fetchEntry}.fetch(request, env, ctx),
|
|
674
|
+
${sweepsOAuthStorage ? `scheduled: async (event, env, ctx) => {
|
|
675
|
+
await sweepOAuthStorage(oauth, event, env)
|
|
676
|
+
await handler.scheduled(event, env, ctx)
|
|
677
|
+
}` : "scheduled: (event, env, ctx) => handler.scheduled(event, env, ctx)"},
|
|
678
|
+
}`;
|
|
679
|
+
}
|
|
669
680
|
/** An import specifier for the generated worker, relative to it and quoted. */
|
|
670
681
|
function quotedImport(out, target) {
|
|
671
682
|
return JSON.stringify(importSpecifier(out, target, "Cloudflare build"));
|
|
@@ -736,14 +747,14 @@ function wranglerConfigExists(path) {
|
|
|
736
747
|
*/
|
|
737
748
|
const HTML_HANDLING = "none";
|
|
738
749
|
/**
|
|
739
|
-
* The OAuth-fronted
|
|
750
|
+
* The OAuth-fronted entry: the module's one handler threaded through both
|
|
740
751
|
* halves of the provider. The grant travels through the seam, not a header:
|
|
741
752
|
* `ctx.props` is what the provider decrypted from the access token it validated.
|
|
742
753
|
* @param defaultEntry What unprotected paths reach — the agent-routing entry
|
|
743
754
|
* when this app hosts agents, so `/agents/*` stays mounted and guarded.
|
|
744
755
|
*/
|
|
745
|
-
function
|
|
746
|
-
return `
|
|
756
|
+
function renderOAuthProvider(mcpPath, defaultEntry) {
|
|
757
|
+
return `const oauth = new OAuthProvider({
|
|
747
758
|
apiRoute: ${JSON.stringify(mcpPath)},
|
|
748
759
|
apiHandler: {
|
|
749
760
|
fetch(request, env, ctx) {
|
|
@@ -823,6 +834,7 @@ function scaffoldWranglerConfig(root, out, packageName, mcpPlugin, mcpOAuth, age
|
|
|
823
834
|
const notes = ["fill in d1_databases[0].database_id"];
|
|
824
835
|
if (mcpOAuth) notes.push(`create the ${OAUTH_KV_BINDING} namespace (wrangler kv namespace create ${OAUTH_KV_BINDING}) and fill in its id`);
|
|
825
836
|
console.log(`Cloudflare build: scaffolded ${configPath} — ${notes.join(", and ")} before deploying.`);
|
|
837
|
+
console.log(` Scheduled tasks need a cron trigger — add "triggers": { "crons": ["* * * * *"] } to run them. The worker runs whichever tasks are due at each firing, so a trigger coarser than your finest task means that task never runs.`);
|
|
826
838
|
}
|
|
827
839
|
/**
|
|
828
840
|
* The consent flow, written once into the app and never overwritten, on the same
|
package/dist/commands.js
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,13 @@ interface WorkersExecutionContext {
|
|
|
6
6
|
waitUntil(promise: Promise<unknown>): void;
|
|
7
7
|
passThroughOnException?(): void;
|
|
8
8
|
}
|
|
9
|
+
/** The `ScheduledEvent` a cron trigger delivers, structural like `WorkersExecutionContext`. */
|
|
10
|
+
interface WorkersScheduledEvent {
|
|
11
|
+
/** The `triggers.crons` entry that fired. */
|
|
12
|
+
cron?: string;
|
|
13
|
+
/** Epoch ms of the minute the trigger was *meant* for; workerd may deliver it late. */
|
|
14
|
+
scheduledTime?: number;
|
|
15
|
+
}
|
|
9
16
|
/**
|
|
10
17
|
* The shape the Workers entrypoints need from an app. Structural rather than
|
|
11
18
|
* `Application` itself, so `boot()` is not assumed to be idempotent.
|
|
@@ -13,6 +20,10 @@ interface WorkersExecutionContext {
|
|
|
13
20
|
interface WorkersAppLike {
|
|
14
21
|
boot(): Promise<void>;
|
|
15
22
|
fetch(request: Request, env?: unknown, executionCtx?: unknown): Response | Promise<Response>;
|
|
23
|
+
/** Only the cron entrypoint reads it, so an app-like that never receives one still satisfies boot/fetch. */
|
|
24
|
+
container?: {
|
|
25
|
+
makeOptional<T>(key: string): T | undefined;
|
|
26
|
+
};
|
|
16
27
|
}
|
|
17
28
|
/**
|
|
18
29
|
* Boot `app` against `env`, once per isolate.
|
|
@@ -24,10 +35,24 @@ interface WorkersAppLike {
|
|
|
24
35
|
declare function bootWorkersApp(app: WorkersAppLike, env: unknown): Promise<void>;
|
|
25
36
|
/** Boot, then dispatch — the topology every Workers entrypoint shares. */
|
|
26
37
|
declare function bootAndFetch(app: WorkersAppLike, request: Request, env: unknown, ctx?: WorkersExecutionContext): Promise<Response>;
|
|
38
|
+
/**
|
|
39
|
+
* Boot, then run every task whose cron matches the trigger's minute.
|
|
40
|
+
*
|
|
41
|
+
* `scheduledTime` rather than the wall clock: workerd may deliver a trigger late.
|
|
42
|
+
* @throws When no provider bound a `scheduler` — a cron that swept nothing must
|
|
43
|
+
* not report success on a schedule nobody reads.
|
|
44
|
+
*/
|
|
45
|
+
declare function bootAndRunDueTasks(app: WorkersAppLike, event: WorkersScheduledEvent, env: unknown): Promise<void>;
|
|
27
46
|
//#endregion
|
|
28
47
|
//#region src/handler.d.ts
|
|
29
48
|
interface WorkersHandler {
|
|
30
49
|
fetch(request: Request, env: unknown, ctx: WorkersExecutionContext): Promise<Response>;
|
|
50
|
+
/**
|
|
51
|
+
* A cron trigger declared in `triggers.crons`, dispatched to the app's
|
|
52
|
+
* `scheduler`. Awaited rather than handed to `ctx.waitUntil`: the invocation
|
|
53
|
+
* lives exactly as long as the tasks it fired.
|
|
54
|
+
*/
|
|
55
|
+
scheduled(event: WorkersScheduledEvent, env: unknown, ctx: WorkersExecutionContext): Promise<void>;
|
|
31
56
|
/**
|
|
32
57
|
* Boot without dispatching, for an entrypoint that holds `env` but no request
|
|
33
58
|
* — an agent Durable Object woken by an alarm (RFC 0017 §6).
|
|
@@ -42,6 +67,57 @@ interface WorkersHandler {
|
|
|
42
67
|
*/
|
|
43
68
|
declare function createWorkersHandler(app: WorkersAppLike): WorkersHandler;
|
|
44
69
|
//#endregion
|
|
70
|
+
//#region src/oauth-sweep.d.ts
|
|
71
|
+
/** Only what this sweep calls, so `@cloudflare/workers-types` stays a devDependency. */
|
|
72
|
+
interface OAuthSweepKvLike {
|
|
73
|
+
get(key: string): Promise<string | null>;
|
|
74
|
+
put(key: string, value: string): Promise<void>;
|
|
75
|
+
}
|
|
76
|
+
/** The provider binding the sweep reads, fixed by `OAuthProvider`. */
|
|
77
|
+
interface OAuthSweepEnv {
|
|
78
|
+
OAUTH_KV: OAuthSweepKvLike;
|
|
79
|
+
}
|
|
80
|
+
interface OAuthPurgeOptions {
|
|
81
|
+
batchSize?: number;
|
|
82
|
+
purgeOrphanedGrants?: boolean;
|
|
83
|
+
purgeExpiredGrants?: boolean;
|
|
84
|
+
purgeOrphanedTokens?: boolean;
|
|
85
|
+
}
|
|
86
|
+
/** `done` is false when the pass stopped at `batchSize` with keys left over. */
|
|
87
|
+
interface OAuthPurgeResult {
|
|
88
|
+
done: boolean;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Structural view of `OAuthProvider`, which is a devDependency: the sweep is
|
|
92
|
+
* handed the instance the generated worker constructs, never its class.
|
|
93
|
+
*/
|
|
94
|
+
interface OAuthPurgerLike<Env> {
|
|
95
|
+
purgeExpiredData(env: Env, options?: OAuthPurgeOptions): Promise<OAuthPurgeResult>;
|
|
96
|
+
}
|
|
97
|
+
/** Under a prefix the provider never lists — it lists `client:`, `grant:` and `token:` only. */
|
|
98
|
+
declare const OAUTH_PURGE_MARKER = "guren:oauth-purge:last";
|
|
99
|
+
/**
|
|
100
|
+
* How often to sweep, independent of the cron the app declares. The trigger
|
|
101
|
+
* belongs to the app and the build scaffolds none, so no cadence may be assumed
|
|
102
|
+
* and `event.cron` cannot be matched against.
|
|
103
|
+
*/
|
|
104
|
+
declare const OAUTH_PURGE_INTERVAL_MS = 3600000;
|
|
105
|
+
/**
|
|
106
|
+
* The depth of the only window ever swept, not a throughput knob: the provider's
|
|
107
|
+
* cursor lives inside one call and `PurgeOptions` carries none, so every firing
|
|
108
|
+
* restarts at the head of the key space and records past this many are never
|
|
109
|
+
* reached. Sized for Free's 50 subrequests per invocation (Paid allows 10000, and
|
|
110
|
+
* a worker cannot tell which it is on); KV reads count, as do the app's own tasks.
|
|
111
|
+
*/
|
|
112
|
+
declare const OAUTH_PURGE_BATCH = 15;
|
|
113
|
+
/**
|
|
114
|
+
* Sweep `oauth`'s KV, at most once per `OAUTH_PURGE_INTERVAL_MS`.
|
|
115
|
+
*
|
|
116
|
+
* Never throws: a cron firing runs the app's own scheduled tasks after this, and
|
|
117
|
+
* they still have to be reached. A failed sweep is reported through `logger`.
|
|
118
|
+
*/
|
|
119
|
+
declare function sweepOAuthStorage<Env extends OAuthSweepEnv>(oauth: OAuthPurgerLike<Env>, event: WorkersScheduledEvent, env: Env, logger?: Pick<Console, 'warn' | 'error'>): Promise<void>;
|
|
120
|
+
//#endregion
|
|
45
121
|
//#region src/build.d.ts
|
|
46
122
|
interface BuildCloudflareOutputOptions {
|
|
47
123
|
/** App root directory. Defaults to the current working directory. */
|
|
@@ -276,4 +352,4 @@ interface CloudflarePluginConfig {}
|
|
|
276
352
|
/** Register the Cloudflare plugin: `createApp({ providers: [cloudflarePlugin()] })`. */
|
|
277
353
|
declare function cloudflarePlugin(config?: CloudflarePluginConfig): ServiceProviderConstructor;
|
|
278
354
|
//#endregion
|
|
279
|
-
export { type BuildCloudflareOutputOptions, CloudflarePluginConfig, type R2BucketLike, R2Driver, type R2DriverOptions, type R2PresignOptions, type WorkersAppLike, type WorkersExecutionContext, type WorkersHandler, bootAndFetch, bootWorkersApp, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, isWorkersRuntime, resetWorkersEnv };
|
|
355
|
+
export { type BuildCloudflareOutputOptions, CloudflarePluginConfig, OAUTH_PURGE_BATCH, OAUTH_PURGE_INTERVAL_MS, OAUTH_PURGE_MARKER, type OAuthPurgeOptions, type OAuthPurgeResult, type OAuthPurgerLike, type OAuthSweepEnv, type OAuthSweepKvLike, type R2BucketLike, R2Driver, type R2DriverOptions, type R2PresignOptions, type WorkersAppLike, type WorkersExecutionContext, type WorkersHandler, type WorkersScheduledEvent, bootAndFetch, bootAndRunDueTasks, bootWorkersApp, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, isWorkersRuntime, resetWorkersEnv, sweepOAuthStorage };
|
package/dist/index.js
CHANGED
|
@@ -1,17 +1,7 @@
|
|
|
1
1
|
import { captureWorkersEnv, getWorkersEnv, isWorkersRuntime, resetWorkersEnv } from "./env.js";
|
|
2
|
-
import { n as flattenD1Migrations, t as buildCloudflareOutput } from "./build-
|
|
2
|
+
import { n as flattenD1Migrations, t as buildCloudflareOutput } from "./build-DN7RvfKD.js";
|
|
3
3
|
import { definePlugin } from "@guren/core";
|
|
4
4
|
//#region src/boot.ts
|
|
5
|
-
/**
|
|
6
|
-
* The isolate's one boot slot (RFC 0017 §6).
|
|
7
|
-
*
|
|
8
|
-
* A worker's `fetch` export is not the only entrypoint: an alarm can wake an
|
|
9
|
-
* agent Durable Object before any request has arrived, and a second entrypoint
|
|
10
|
-
* with its own boot would race the module-global env holder. So boot is a
|
|
11
|
-
* shared primitive — promise-latched, first caller wins, everyone awaits the
|
|
12
|
-
* same latch. Keyed per app (a Bun test suite boots many); the env holder stays
|
|
13
|
-
* module-global, since `getWorkersEnv()` has no app to key on — one per isolate.
|
|
14
|
-
*/
|
|
15
5
|
const latches = /* @__PURE__ */ new WeakMap();
|
|
16
6
|
/**
|
|
17
7
|
* Boot `app` against `env`, once per isolate.
|
|
@@ -43,6 +33,19 @@ async function bootAndFetch(app, request, env, ctx) {
|
|
|
43
33
|
await bootWorkersApp(app, env);
|
|
44
34
|
return app.fetch(request, env, ctx);
|
|
45
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* Boot, then run every task whose cron matches the trigger's minute.
|
|
38
|
+
*
|
|
39
|
+
* `scheduledTime` rather than the wall clock: workerd may deliver a trigger late.
|
|
40
|
+
* @throws When no provider bound a `scheduler` — a cron that swept nothing must
|
|
41
|
+
* not report success on a schedule nobody reads.
|
|
42
|
+
*/
|
|
43
|
+
async function bootAndRunDueTasks(app, event, env) {
|
|
44
|
+
await bootWorkersApp(app, env);
|
|
45
|
+
const scheduler = app.container?.makeOptional("scheduler");
|
|
46
|
+
if (!scheduler) throw new Error("A Cloudflare cron trigger fired, but this app binds no `scheduler`. Register a provider that binds createScheduler() as `scheduler` and defines the tasks, or remove \"triggers.crons\" from wrangler.jsonc.");
|
|
47
|
+
await scheduler.runDueTasks(event.scheduledTime ? new Date(event.scheduledTime) : /* @__PURE__ */ new Date());
|
|
48
|
+
}
|
|
46
49
|
//#endregion
|
|
47
50
|
//#region src/handler.ts
|
|
48
51
|
/**
|
|
@@ -54,10 +57,56 @@ async function bootAndFetch(app, request, env, ctx) {
|
|
|
54
57
|
function createWorkersHandler(app) {
|
|
55
58
|
return {
|
|
56
59
|
fetch: (request, env, ctx) => bootAndFetch(app, request, env, ctx),
|
|
60
|
+
scheduled: (event, env) => bootAndRunDueTasks(app, event, env),
|
|
57
61
|
boot: (env) => bootWorkersApp(app, env)
|
|
58
62
|
};
|
|
59
63
|
}
|
|
60
64
|
//#endregion
|
|
65
|
+
//#region src/oauth-sweep.ts
|
|
66
|
+
/** Under a prefix the provider never lists — it lists `client:`, `grant:` and `token:` only. */
|
|
67
|
+
const OAUTH_PURGE_MARKER = "guren:oauth-purge:last";
|
|
68
|
+
/**
|
|
69
|
+
* How often to sweep, independent of the cron the app declares. The trigger
|
|
70
|
+
* belongs to the app and the build scaffolds none, so no cadence may be assumed
|
|
71
|
+
* and `event.cron` cannot be matched against.
|
|
72
|
+
*/
|
|
73
|
+
const OAUTH_PURGE_INTERVAL_MS = 36e5;
|
|
74
|
+
/**
|
|
75
|
+
* The depth of the only window ever swept, not a throughput knob: the provider's
|
|
76
|
+
* cursor lives inside one call and `PurgeOptions` carries none, so every firing
|
|
77
|
+
* restarts at the head of the key space and records past this many are never
|
|
78
|
+
* reached. Sized for Free's 50 subrequests per invocation (Paid allows 10000, and
|
|
79
|
+
* a worker cannot tell which it is on); KV reads count, as do the app's own tasks.
|
|
80
|
+
*/
|
|
81
|
+
const OAUTH_PURGE_BATCH = 15;
|
|
82
|
+
/**
|
|
83
|
+
* Sweep `oauth`'s KV, at most once per `OAUTH_PURGE_INTERVAL_MS`.
|
|
84
|
+
*
|
|
85
|
+
* Never throws: a cron firing runs the app's own scheduled tasks after this, and
|
|
86
|
+
* they still have to be reached. A failed sweep is reported through `logger`.
|
|
87
|
+
*/
|
|
88
|
+
async function sweepOAuthStorage(oauth, event, env, logger = console) {
|
|
89
|
+
const now = event.scheduledTime ?? Date.now();
|
|
90
|
+
try {
|
|
91
|
+
const last = await env.OAUTH_KV.get(OAUTH_PURGE_MARKER);
|
|
92
|
+
const elapsed = now - Number(last);
|
|
93
|
+
if (last && elapsed >= 0 && elapsed < 36e5) return;
|
|
94
|
+
await env.OAUTH_KV.put(OAUTH_PURGE_MARKER, String(now));
|
|
95
|
+
const grants = await oauth.purgeExpiredData(env, {
|
|
96
|
+
batchSize: 15,
|
|
97
|
+
purgeOrphanedTokens: false
|
|
98
|
+
});
|
|
99
|
+
const tokens = await oauth.purgeExpiredData(env, {
|
|
100
|
+
batchSize: 15,
|
|
101
|
+
purgeOrphanedGrants: false,
|
|
102
|
+
purgeExpiredGrants: false
|
|
103
|
+
});
|
|
104
|
+
if (!grants.done || !tokens.done) logger.warn("OAuth sweep stopped at its batch limit; records past it stay unswept.", grants, tokens);
|
|
105
|
+
} catch (error) {
|
|
106
|
+
logger.error("OAuth storage sweep failed.", error);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
//#endregion
|
|
61
110
|
//#region src/storage/sigv4.ts
|
|
62
111
|
const ALGORITHM = "AWS4-HMAC-SHA256";
|
|
63
112
|
const TERMINATOR = "aws4_request";
|
|
@@ -414,4 +463,4 @@ function cloudflarePlugin(config = {}) {
|
|
|
414
463
|
return factory(config);
|
|
415
464
|
}
|
|
416
465
|
//#endregion
|
|
417
|
-
export { R2Driver, bootAndFetch, bootWorkersApp, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, isWorkersRuntime, resetWorkersEnv };
|
|
466
|
+
export { OAUTH_PURGE_BATCH, OAUTH_PURGE_INTERVAL_MS, OAUTH_PURGE_MARKER, R2Driver, bootAndFetch, bootAndRunDueTasks, bootWorkersApp, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, isWorkersRuntime, resetWorkersEnv, sweepOAuthStorage };
|