@cloudhal/cloudflare 0.0.0-stage → 0.1.1

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,569 @@
1
+ /**
2
+ * The Cloudhal admin Worker (ADR-0012): one origin for the Studio SPA (static assets), the HTTP
3
+ * API, Better Auth and the MCP endpoint — all over the deployment's D1 database and R2 bucket.
4
+ *
5
+ * After every publish/rollback it purges the site Worker's edge cache through the `SITE` service
6
+ * binding (cache purges are scoped to the Worker that cached the responses): only the tags of what
7
+ * changed between the previously live snapshot and the new one (`purge.ts`), everything when that
8
+ * cannot be worked out.
9
+ *
10
+ * Site analytics (RFC-0006 §7.5, §8): with `CLOUDHAL_ANALYTICS_DATASET` set the deployment records to
11
+ * Workers Analytics Engine; Studio and MCP read it through the `ANALYTICS_SQL` binding (no API
12
+ * token), and the hourly `scheduled` handler rolls finished days into D1 and deletes old salts. A
13
+ * missing binding means the "can't read yet" state (`reader: "none"`), never a crash.
14
+ *
15
+ * Reader comments (RFC-0007 step 5, `comments.ts`): with `CLOUDHAL_COMMENTS_KEY` (the site Worker's
16
+ * secret) the API and MCP serve comments; moderation queues comment cache tags, which the flusher
17
+ * sends through `SITE` within the purge budget publishes share (every purge request is logged in
18
+ * `cache_purge_log`): takedowns 2 s after the write, normal tags 20 s later, and on any later
19
+ * admin request whose queue is due; the hourly job applies retention, purges threads that closed by
20
+ * time and deletes old salts.
21
+ *
22
+ * Schedules (RFC-0008 §8, `scheduler.ts`): one tick a minute runs due releases, automation
23
+ * occurrences and the hourly jobs behind `system_jobs` watermarks — from the `* * * * *` cron
24
+ * trigger (`scheduled`), or, with `CLOUDHAL_SCHEDULER=alarm`, from the `SchedulerClock` Durable
25
+ * Object this module exports; admin requests are the backstop when the heartbeat is stale.
26
+ *
27
+ * Email (RFC-0011, `mail.ts`): with the `EMAIL` send binding and `CLOUDHAL_MAIL_FROM` the API mails
28
+ * invites and reset links through Cloudflare Email Service, after the response where it must not
29
+ * show (`defer` → `waitUntil`).
30
+ *
31
+ * In-editor AI (RFC-0016): with the `AI` binding (`ai` in cloudhal.json) the API reaches Workers AI
32
+ * without a secret; each site's owner turns it on, picks the model and sets the daily cap in Studio.
33
+ *
34
+ * Secrets: BETTER_AUTH_SECRET, MCP_STATE_KEY, CLOUDHAL_PREVIEW_SECRET, CLOUDHAL_PURGE_TOKEN,
35
+ * CLOUDHAL_DEPLOY_TOKEN, CLOUDHAL_COMMENTS_KEY (all ≥ 32 chars; `cloudhal deploy` generates them).
36
+ */
37
+
38
+ import {
39
+ ApprovalStore,
40
+ AuditLog,
41
+
42
+
43
+ skillFromSource,
44
+ } from "@cloudhal/agent-runtime";
45
+ import { parseAnalyticsDefaults } from "@cloudhal/analytics";
46
+ import { AnalyticsService } from "@cloudhal/analytics/service";
47
+ import { SqlQueryBudget } from "@cloudhal/analytics/sql";
48
+ import { DATASET_RE, WaeReader } from "@cloudhal/analytics/wae";
49
+ import { AiStore, bindingTransport, createApi } from "@cloudhal/api";
50
+ import { createAuth } from "@cloudhal/api/auth";
51
+ import { PURGE_LIMITS } from "@cloudhal/comments";
52
+ import { SqlCommentStore } from "@cloudhal/comments/sql";
53
+ import { SiteGraphStore, searchProviderFromEnv } from "@cloudhal/core-ts";
54
+ import { createBlockRegistry, } from "@cloudhal/core-ts/blocks";
55
+ import { SqlScheduleStore } from "@cloudhal/schedules/sql";
56
+ import { migrate, migrations, } from "@cloudhal/storage";
57
+ import { D1Driver } from "@cloudhal/storage/d1";
58
+ import { R2BlobStore } from "@cloudhal/storage/r2";
59
+ import { browserRenderingRenderer } from "./browser-render.js";
60
+ import { buildRoomClass, createDurableBuildHub } from "./build-rooms.js";
61
+ import { adminComments, commentsOn, flushCommentPurges } from "./comments.js";
62
+ import { siteGateSupport } from "./features.js";
63
+ import { adminMail, } from "./mail.js";
64
+ import { purgeSiteCache } from "./purge.js";
65
+ import {
66
+
67
+ followUpDelay,
68
+ releasePurger,
69
+ requestBackstop,
70
+ runAdminTick,
71
+
72
+ schedulerClockClass,
73
+ schedulerRuntime,
74
+ } from "./scheduler.js";
75
+ import { routedSite } from "./site-routes.js";
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+  
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+  
96
+
97
+
98
+
99
+  
100
+
101
+
102
+
103
+  
104
+
105
+
106
+
107
+
108
+
109
+ /** Default daily budget of uncached live queries: 80 % of WAE Free's 10,000 (§7.7, A2). */
110
+ export const DEFAULT_ANALYTICS_BUDGET = 8000;
111
+
112
+ const PURGE_URL = "https://site.internal/__cloudhal/purge";
113
+
114
+ /**
115
+ * A purge of one site's cache (RFC-0034 §4): a multi-site Worker purges only that site's tags; a
116
+ * single-site Worker purges everything, as before.
117
+ */
118
+ function sitePurge(token , siteId ) {
119
+ return {
120
+ method: "POST",
121
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
122
+ body: JSON.stringify({ siteId }),
123
+ };
124
+ }
125
+
126
+ /**
127
+ * `CLOUDHAL_ANALYTICS_DEFAULTS` as the Site Worker reads it (`deploymentDefaults` in the renderer):
128
+ * cloudhal.json's `analytics` block, in which `enabled` defaults to `true`.
129
+ */
130
+ export function analyticsDefaults(json ) {
131
+ let parsed ;
132
+ try {
133
+ parsed = json ? JSON.parse(json) : {};
134
+ } catch {
135
+ parsed = {};
136
+ }
137
+ const o = parsed && typeof parsed === "object" ? (parsed ) : {};
138
+ return parseAnalyticsDefaults({ enabled: true, ...o });
139
+ }
140
+
141
+ /**
142
+ * The deployment's analytics (RFC-0006 §8) from its bindings and vars. Plain construction, no I/O,
143
+ * so it is built per request or scheduled run (ADR-0012: nothing but plain values is cached).
144
+ */
145
+ export function adminAnalytics(
146
+ env ,
147
+ sql ,
148
+ options = {},
149
+ ) {
150
+ const dataset = env.CLOUDHAL_ANALYTICS_DATASET;
151
+ const on = typeof dataset === "string" && DATASET_RE.test(dataset);
152
+ const budgetVar = Number(env.CLOUDHAL_ANALYTICS_BUDGET);
153
+ const budget =
154
+ Number.isInteger(budgetVar) && budgetVar >= 0 ? budgetVar : DEFAULT_ANALYTICS_BUDGET;
155
+ const binding = on ? env.ANALYTICS_SQL : undefined;
156
+ const log = options.log ?? ((line ) => console.log(line));
157
+ const onError = (message , error ) =>
158
+ log(`${message}: ${error instanceof Error ? error.message : String(error ?? "")}`);
159
+ const site = routedSite(env);
160
+ const token = env.CLOUDHAL_PURGE_TOKEN;
161
+ return new AnalyticsService({
162
+ sql,
163
+ store: on ? "wae" : "none",
164
+ ...(binding && on
165
+ ? {
166
+ live: new WaeReader(binding, {
167
+ dataset,
168
+ budget: new SqlQueryBudget(sql, { limit: budget }),
169
+ onError,
170
+ }),
171
+ // The rollup job's own reads are exempt from the budget (§7.7).
172
+ source: new WaeReader(binding, { dataset, onError }),
173
+ }
174
+ : {}),
175
+ defaults: analyticsDefaults(env.CLOUDHAL_ANALYTICS_DEFAULTS),
176
+ budget: on ? budget : null,
177
+ // Every deployment has a ticker now (cron or the clock, RFC-0008 §8.3): rollups are scheduled.
178
+ rollups: "scheduled",
179
+ ...(options.now ? { now: options.now } : {}),
180
+ // The script tag lives in cached HTML: a settings change purges the site's whole cache (§5.1).
181
+ ...(site && token
182
+ ? {
183
+ purgeSite: async (siteId ) => {
184
+ const res = await site.fetch(PURGE_URL, sitePurge(token, siteId));
185
+ await logPurge(sql, "analytics");
186
+ log(`purge everything after analytics settings of ${siteId}: ${res.status}`);
187
+ if (!res.ok) throw new Error(`purge failed: ${res.status}`);
188
+ },
189
+ }
190
+ : {}),
191
+ onError,
192
+ });
193
+ }
194
+
195
+ /** Records one purge request in the budget comments share with publishing (RFC-0007 §8.4). */
196
+ async function logPurge(sql , source ) {
197
+ try {
198
+ await new SqlCommentStore(sql).purgeQueue.log(source);
199
+ } catch {
200
+ // the log is a budget hint: never fail a purge over it
201
+ }
202
+ }
203
+
204
+ const sleep = (ms ) => new Promise((resolve) => setTimeout(resolve, ms));
205
+
206
+
207
+
208
+
209
+  
210
+
211
+  
212
+
213
+  
214
+
215
+
216
+
217
+
218
+ /**
219
+ * The store's optional parts: the theme's settings and DESIGN.md, and the deployment's search
220
+ * provider, so publishes here mirror into the AI Search bucket when it has one (RFC-0029 §3).
221
+ */
222
+ function storeExtras(options , env , sql ) {
223
+ const search = searchProviderFromEnv(env, sql, {
224
+ onError: (e) => console.error("semantic search failed, FTS5 answered:", e),
225
+ });
226
+ return {
227
+ ...(options.themeSettings ? { themeSettings: options.themeSettings } : {}),
228
+ ...(options.themeDesign ? { themeDesign: options.themeDesign } : {}),
229
+ ...(search ? { search } : {}),
230
+ };
231
+ }
232
+
233
+ /**
234
+ * What `apps/studio/public/_headers` sets on Studio's static files, also on the shell this Worker
235
+ * serves for client routes: Studio is the most privileged origin of a deployment (sessions,
236
+ * approvals, members), so it is never framed, loads no plugins and keeps its `<base>`.
237
+ */
238
+ export const STUDIO_SECURITY_HEADERS = {
239
+ "content-security-policy": "frame-ancestors 'none'; object-src 'none'; base-uri 'none'",
240
+ "x-frame-options": "DENY",
241
+ "x-content-type-options": "nosniff",
242
+ "referrer-policy": "strict-origin-when-cross-origin",
243
+ "strict-transport-security": "max-age=31536000",
244
+ };
245
+
246
+ function withStudioHeaders(res ) {
247
+ const out = new Response(res.body, res);
248
+ for (const [k, v] of Object.entries(STUDIO_SECURITY_HEADERS)) out.headers.set(k, v);
249
+ return out;
250
+ }
251
+
252
+ const WORKER_PATHS = /^\/(api\/|mcp(\/|$)|\.well-known\/)/;
253
+
254
+ function required(env , key ) {
255
+ const value = env[key];
256
+ if (typeof value !== "string" || value.length < 32)
257
+ throw new Error(`secret ${key} is missing or shorter than 32 characters`);
258
+ return value;
259
+ }
260
+
261
+ export function createAdminWorker(options = {}) {
262
+ const skills = (options.skills ?? []).map((s) => skillFromSource(s));
263
+ // Checked once per isolate; `cloudhal deploy` refused invalid types before uploading.
264
+ const blocks = createBlockRegistry(options.blockTypes ?? []);
265
+ const log = options.log ?? ((line ) => console.log(line));
266
+ // Only plain values survive between requests. Workers do not let one request await I/O started
267
+ // by another (it hangs), so no promise, auth instance or binding wrapper is cached here.
268
+ let migrated = false;
269
+ /** The request backstop's isolate state (RFC-0008 §8.6); plain numbers. */
270
+ const backstop = { lastCheck: 0, lastRun: 0 };
271
+ /** The site Worker confirmed it enforces time gates (RFC-0008 §7.7); a plain boolean. */
272
+ let gatesConfirmed = false;
273
+ const ensureMigrated = async (sql ) => {
274
+ if (migrated) return;
275
+ try {
276
+ await migrate(sql, migrations);
277
+ } catch {
278
+ // A concurrent request or isolate applied them first; a second pass sees them as done.
279
+ await migrate(sql, migrations);
280
+ }
281
+ migrated = true;
282
+ };
283
+
284
+ return {
285
+ async fetch(request , env , ctx ) {
286
+ const url = new URL(request.url);
287
+ // The assets layer answers existing files before the Worker runs, so a request for a file
288
+ // under /assets/ that reaches us is missing (e.g. a chunk from an older Studio build). Answer
289
+ // 404, never the SPA shell: an HTML 200 for a script URL can be cached and shadow the real
290
+ // file once it exists.
291
+ if (url.pathname.startsWith("/assets/"))
292
+ return new Response("not found", {
293
+ status: 404,
294
+ headers: { "content-type": "text/plain", "cache-control": "no-store" },
295
+ });
296
+ if (!WORKER_PATHS.test(url.pathname)) {
297
+ // A client-side route (/sites/…, /login, …): answer with the Studio shell.
298
+ if (!env.ASSETS) return new Response("not found", { status: 404 });
299
+ return withStudioHeaders(
300
+ await env.ASSETS.fetch(new Request(new URL("/", url), { headers: request.headers })),
301
+ );
302
+ }
303
+
304
+ const sql = new D1Driver(env.DB);
305
+ const blobs = new R2BlobStore(env.BLOBS);
306
+ await ensureMigrated(sql);
307
+
308
+ // A takedown (RFC-0004 §4.6) purges the asset's media URLs at once, not at the next publish.
309
+ const purgeTags = async (tags , what , siteId ) => {
310
+ const target = routedSite(env);
311
+ if (!target || !env.CLOUDHAL_PURGE_TOKEN) return;
312
+ const res = await target.fetch("https://site.internal/__cloudhal/purge", {
313
+ method: "POST",
314
+ headers: {
315
+ authorization: `Bearer ${env.CLOUDHAL_PURGE_TOKEN}`,
316
+ "content-type": "application/json",
317
+ },
318
+ body: JSON.stringify({ tags, siteId }),
319
+ });
320
+ await logPurge(sql, "media");
321
+ log(`purge after ${what}: ${res.status} ${await res.text()}`);
322
+ };
323
+ // RFC-0007 §8.4: comment purges go through the queue; the flusher shares the budget.
324
+ const siteBinding = routedSite(env); // RFC-0034 §4: to the Worker serving the purge's site
325
+ const purgeToken = env.CLOUDHAL_PURGE_TOKEN;
326
+ const flush = (siteId ) =>
327
+ siteBinding && purgeToken
328
+ ? flushCommentPurges({
329
+ store: new SqlCommentStore(sql),
330
+ fetch: (u, init) =>
331
+ siteBinding.fetch(u, init ) ,
332
+ token: purgeToken,
333
+ siteId,
334
+ log,
335
+ }).catch((e) => {
336
+ log(`comments purge flush failed: ${e instanceof Error ? e.message : String(e)}`);
337
+ })
338
+ : Promise.resolve();
339
+ const comments = await adminComments(env, sql, {
340
+ // takedowns after a 2 s micro-batch, normal changes after 20 s (V5: waitUntil keeps it alive)
341
+ wake: (siteId, priority) =>
342
+ ctx.waitUntil(
343
+ sleep(
344
+ priority === "takedown"
345
+ ? PURGE_LIMITS.takedownMicrobatchMs
346
+ : PURGE_LIMITS.normalDelayMs,
347
+ ).then(() => flush(siteId)),
348
+ ),
349
+ ...(siteBinding && purgeToken
350
+ ? {
351
+ purgeSite: async (siteId ) => {
352
+ const res = await siteBinding.fetch(PURGE_URL, sitePurge(purgeToken, siteId));
353
+ await logPurge(sql, "comments");
354
+ log(`purge everything for comments of ${siteId}: ${res.status}`);
355
+ if (!res.ok) throw new Error(`purge failed: ${res.status}`);
356
+ },
357
+ }
358
+ : {}),
359
+ });
360
+ // Every admin request also flushes what is due (Studio polls every 15–60 s).
361
+ if (comments) ctx.waitUntil(flush());
362
+ const store = new SiteGraphStore({
363
+ sql,
364
+ blobs,
365
+ blocks,
366
+ ...storeExtras(options, env, sql),
367
+ // S15: `availability` is refused until the site Worker says it enforces gates.
368
+ gates: siteGateSupport({
369
+ fetch: siteBinding
370
+ ? (u, init) => siteBinding.fetch(u, init )
371
+ : undefined,
372
+ token: purgeToken,
373
+ confirmed: () => gatesConfirmed,
374
+ remember: () => {
375
+ gatesConfirmed = true;
376
+ },
377
+ log,
378
+ }),
379
+ onPublished: async (site, change) => {
380
+ const binding = routedSite(env);
381
+ if (!binding || !env.CLOUDHAL_PURGE_TOKEN) return;
382
+ // Only what changed between the snapshot that was live and the new one (RFC-0002 §7).
383
+ const result = await purgeSiteCache({
384
+ fetch: (url, init) => binding.fetch(url, init ) ,
385
+ token: env.CLOUDHAL_PURGE_TOKEN,
386
+ store,
387
+ change,
388
+ siteId: site.id,
389
+ log: (line) => log(`${site.id}: ${line}`),
390
+ onRequest: () => logPurge(sql, "publish"),
391
+ });
392
+ log(
393
+ `purge after publishing ${site.id} (${change.from ?? "nothing"} → ${change.to ?? "nothing"}): ${result.mode}, ${result.tags.length} tag(s), ${result.requests} request(s)`,
394
+ );
395
+ },
396
+ onMediaPurged: async (siteId, assetIds) =>
397
+ purgeTags(
398
+ assetIds.map((id) => `cloudhal-asset-${id}`),
399
+ `taking down media of ${siteId}`,
400
+ siteId,
401
+ ),
402
+ onHookError: (e) => log(`purge failed: ${e instanceof Error ? e.message : String(e)}`),
403
+ });
404
+ // RFC-0008 §8.6: a stale heartbeat makes this request run a tick (at most once a minute).
405
+ const due = requestBackstop(env, backstop, {
406
+ log,
407
+ analytics: (s, now) => adminAnalytics(env, s, { now: () => now, log }),
408
+ commentsOn: commentsOn(env),
409
+ waitUntil: (p) => ctx.waitUntil(p),
410
+ });
411
+ if (due) ctx.waitUntil(due);
412
+
413
+ // Per request: Better Auth keeps request-scoped state (background tasks, plugin promises),
414
+ // and its construction does no I/O.
415
+ const auth = createAuth({
416
+ database: env.DB,
417
+ sql,
418
+ baseURL: url.origin,
419
+ secret: required(env, "BETTER_AUTH_SECRET"),
420
+ signUp:
421
+ env.CLOUDHAL_SIGNUP === "open" || env.CLOUDHAL_SIGNUP === "closed"
422
+ ? env.CLOUDHAL_SIGNUP
423
+ : "first-user",
424
+ setupToken: env.CLOUDHAL_SETUP_TOKEN,
425
+ workers: { waitUntil: (p) => ctx.waitUntil(p) },
426
+ });
427
+ const audit = new AuditLog(sql);
428
+ const approvals = new ApprovalStore(sql);
429
+ const mail = adminMail(env);
430
+ const app = createApi({
431
+ store,
432
+ resolveActor: auth.resolveActor,
433
+ resolvePrincipal: auth.resolvePrincipal,
434
+ authHandler: auth.handler,
435
+ agentKeys: auth.agentKeys,
436
+ staff: auth.staff,
437
+ signUp: auth.signUp,
438
+ audit,
439
+ // RFC-0011: emailed invites and reset links when `cloudhal deploy` bound a sender.
440
+ ...(mail ? { mail } : {}),
441
+ defer: (task) => ctx.waitUntil(task),
442
+ // RFC-0020 §6: build events cross isolates through one Durable Object per page.
443
+ ...(env.BUILD_ROOMS ? { build: createDurableBuildHub(env.BUILD_ROOMS) } : {}),
444
+ mcp: {
445
+ stateKey: required(env, "MCP_STATE_KEY"),
446
+ audit,
447
+ skills,
448
+ previewSecret: env.CLOUDHAL_PREVIEW_SECRET,
449
+ approvals,
450
+ // Remote clients must speak the stateless 2026-07-28 protocol or be served statelessly.
451
+ legacy: "stateless",
452
+ // fetch_asset_url never reaches this Worker's own host (Studio, API, purge); each site's
453
+ // domains are refused too. Workers cannot pin DNS: see `workersTransport` (RFC-0004 §5.7).
454
+ media: { blockedHosts: [url.hostname] },
455
+ // RFC-0021 §4: render_page opens the preview link in Browser Rendering.
456
+ ...(env.BROWSER && env.CLOUDHAL_RENDER !== "off"
457
+ ? { render: { renderer: browserRenderingRenderer(env.BROWSER) } }
458
+ : {}),
459
+ },
460
+ ...(env.CLOUDHAL_PREVIEW_SECRET
461
+ ? { preview: { secret: env.CLOUDHAL_PREVIEW_SECRET } }
462
+ : {}),
463
+ ...(env.CLOUDHAL_DEPLOY_TOKEN
464
+ ? { admin: { deployToken: env.CLOUDHAL_DEPLOY_TOKEN, storage: { sql, blobs } } }
465
+ : {}),
466
+ analytics: adminAnalytics(env, sql, { log }),
467
+ ...(comments ? { comments } : {}),
468
+ // RFC-0016: settings always; commands only with the binding.
469
+ ai: {
470
+ store: new AiStore(sql),
471
+ ...(env.AI ? { transport: bindingTransport(env.AI) } : {}),
472
+ },
473
+ // RFC-0008 §12–§13: the schedule routes and tools; "Publish now" purges like a tick.
474
+ schedules: {
475
+ store: new SqlScheduleStore(sql),
476
+ purge: releasePurger(env, sql, { log }),
477
+ automationsEnabled: env.CLOUDHAL_AUTOMATIONS !== "off",
478
+ },
479
+ scheduler: {
480
+ ...schedulerRuntime(env, log),
481
+ runDue: (trigger) =>
482
+ runAdminTick(env, {
483
+ trigger,
484
+ now: new Date(),
485
+ log,
486
+ analytics: (s, now) => adminAnalytics(env, s, { now: () => now, log }),
487
+ commentsOn: commentsOn(env),
488
+ waitUntil: (p) => ctx.waitUntil(p),
489
+ }),
490
+ },
491
+ });
492
+ return app.fetch(request, env, ctx);
493
+ },
494
+
495
+ /**
496
+ * The minute tick (RFC-0008 §8.2, cron `* * * * *`): due releases, automation occurrences, and
497
+ * the hourly jobs behind their watermarks — the analytics rollup (RFC-0006 §7.5) and the
498
+ * comments job (RFC-0007 §8.5) at :17, unchanged and with their log lines. Bounded work per
499
+ * invocation (`TickBudget`); a missed minute is caught up by the next tick.
500
+ */
501
+ async scheduled(
502
+ controller ,
503
+ env ,
504
+ ctx ,
505
+ ) {
506
+ const sql = new D1Driver(env.DB);
507
+ await ensureMigrated(sql);
508
+ const tick = (now ) =>
509
+ runAdminTick(env, {
510
+ trigger: "cron",
511
+ now,
512
+ log,
513
+ analytics: (s, at) => adminAnalytics(env, s, { now: () => at, log }),
514
+ commentsOn: commentsOn(env),
515
+ waitUntil: (p) => ctx.waitUntil(p),
516
+ });
517
+ try {
518
+ const started = controller.scheduledTime || Date.now();
519
+ const report = await tick(new Date(started));
520
+ // Work due before the next tick runs at its time, not up to a minute later.
521
+ const wait = followUpDelay(report, Math.max(started, Date.now()));
522
+ if (wait !== undefined) {
523
+ const due = Math.max(started, Date.now()) + wait;
524
+ await new Promise((resolve) => setTimeout(resolve, wait));
525
+ await tick(new Date(Math.max(Date.now(), due)));
526
+ }
527
+ } catch (e) {
528
+ log(`schedules tick (cron) failed: ${e instanceof Error ? e.message : String(e)}`);
529
+ }
530
+ },
531
+ };
532
+ }
533
+
534
+ /**
535
+ * Build rooms (RFC-0020 §6): one Durable Object per page carrying Studio's Build view events
536
+ * between isolates (`BUILD_ROOMS`, SQLite-backed, hibernatable WebSockets). The generated admin
537
+ * entry re-exports it.
538
+ */
539
+ export const BuildRoom = buildRoomClass();
540
+
541
+ /** Migrations applied by this isolate's clock (a plain value, like the Worker's own flag). */
542
+ let clockMigrated = false;
543
+
544
+ /**
545
+ * The scheduler's Durable Object clock (RFC-0008 §8.3), declared by every deploy
546
+ * (`SCHEDULER_CLOCK`, SQLite-backed) and woken only with `CLOUDHAL_SCHEDULER=alarm`. The generated
547
+ * admin entry re-exports it.
548
+ */
549
+ export const SchedulerClock = schedulerClockClass(async (env, o) => {
550
+ const e = env ;
551
+ const sql = new D1Driver(e.DB);
552
+ if (!clockMigrated) {
553
+ try {
554
+ await migrate(sql, migrations);
555
+ } catch {
556
+ await migrate(sql, migrations);
557
+ }
558
+ clockMigrated = true;
559
+ }
560
+ const log = (line ) => console.log(line);
561
+ return runAdminTick(e, {
562
+ trigger: "alarm",
563
+ now: o.now,
564
+ log,
565
+ analytics: (s, now) => adminAnalytics(e, s, { now: () => now, log }),
566
+ commentsOn: commentsOn(e),
567
+ waitUntil: o.waitUntil,
568
+ });
569
+ });
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `render_page` on Workers (RFC-0021 §4): Cloudflare Browser Rendering through the admin Worker's
3
+ * `BROWSER` binding. One browser per call: acquired, driven over its DevTools socket and closed.
4
+ * The binding's socket carries messages in chunks (Workers caps a WebSocket message at 1 MiB and
5
+ * screenshots are larger): a 4-byte little-endian length, then the UTF-8 message, in pieces.
6
+ */
7
+ import { type CdpSocket, type PageRenderer } from "@cloudhal/mcp-server/render";
8
+ /** The Browser Rendering binding (`browser = { binding = "BROWSER" }`). */
9
+ export interface BrowserBinding {
10
+ fetch(input: string, init?: RequestInit): Promise<Response>;
11
+ }
12
+ /** Splits one DevTools message into the binding's chunks. */
13
+ export declare function messageToChunks(message: string): Uint8Array[];
14
+ /** Collects chunks until a whole message has arrived; returns it and drops its chunks. */
15
+ export declare function chunksToMessage(chunks: Uint8Array[]): string | undefined;
16
+ /** The binding's DevTools socket as a `CdpSocket` (exported for tests). */
17
+ export declare function bindingSocket(ws: WebSocket): CdpSocket;
18
+ export declare function browserRenderingRenderer(binding: BrowserBinding): PageRenderer;