experimental-a2 0.3.0 → 0.5.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 +207 -0
- package/dist/ai-CFNeCrRl.d.ts +334 -0
- package/dist/ai-CFNeCrRl.d.ts.map +1 -0
- package/dist/ai-server.browser.js +2 -0
- package/dist/ai-server.browser.js.map +1 -0
- package/dist/ai-server.d.ts +49 -9
- package/dist/ai-server.d.ts.map +1 -0
- package/dist/ai-server.js +123 -49
- package/dist/ai-server.js.map +1 -0
- package/dist/ai.d.ts +2 -303
- package/dist/ai.js +233 -86
- package/dist/ai.js.map +1 -0
- package/dist/cli-B3VuxoDe.js +599 -0
- package/dist/cli-B3VuxoDe.js.map +1 -0
- package/dist/cli-bin.d.ts +1 -0
- package/dist/cli-bin.js +7 -0
- package/dist/cli-bin.js.map +1 -0
- package/dist/cli.d.ts +20 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +2 -0
- package/dist/client-BKlyLiOU.js +1008 -0
- package/dist/client-BKlyLiOU.js.map +1 -0
- package/dist/client-D7mvIXrF.d.ts +191 -0
- package/dist/client-D7mvIXrF.d.ts.map +1 -0
- package/dist/client.d.ts +2 -90
- package/dist/client.js +1 -409
- package/dist/{contract-CG_adnu_.js → contract-48bUMgcL.js} +12 -2
- package/dist/contract-48bUMgcL.js.map +1 -0
- package/dist/{contract-C_3dIIEU.d.ts → contract-jIfaR085.d.ts} +63 -8
- package/dist/contract-jIfaR085.d.ts.map +1 -0
- package/dist/devtools-J_jZ2vQf.d.ts +152 -0
- package/dist/devtools-J_jZ2vQf.d.ts.map +1 -0
- package/dist/devtools-kJJaORn-.js +340 -0
- package/dist/devtools-kJJaORn-.js.map +1 -0
- package/dist/devtools-server.browser.js +3 -1
- package/dist/devtools-server.browser.js.map +1 -0
- package/dist/devtools-server.d.ts +4 -3
- package/dist/devtools-server.d.ts.map +1 -0
- package/dist/devtools-server.js +226 -43
- package/dist/devtools-server.js.map +1 -0
- package/dist/devtools.d.ts +2 -0
- package/dist/devtools.js +2 -0
- package/dist/{errors-BJRMd-h6.js → errors-BQuJpe82.js} +6 -4
- package/dist/errors-BQuJpe82.js.map +1 -0
- package/dist/{errors-xL_JTXsY.d.ts → errors-W6nwJ-fm.d.ts} +3 -2
- package/dist/errors-W6nwJ-fm.d.ts.map +1 -0
- package/dist/http.d.ts +135 -28
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +647 -61
- package/dist/http.js.map +1 -0
- package/dist/{idempotent-replay-BMyHrP0L.js → idempotent-replay-DuqEkYA7.js} +4 -2
- package/dist/idempotent-replay-DuqEkYA7.js.map +1 -0
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -2
- package/dist/{inspection-E7qbD0Xj.js → inspection-DaxB5jM2.js} +4 -1
- package/dist/inspection-DaxB5jM2.js.map +1 -0
- package/dist/internal-DstsI6Re.js +211 -0
- package/dist/internal-DstsI6Re.js.map +1 -0
- package/dist/otel.d.ts +3 -2
- package/dist/otel.d.ts.map +1 -0
- package/dist/otel.js +2 -0
- package/dist/otel.js.map +1 -0
- package/dist/platform-B4TnJtWu.js +34 -0
- package/dist/platform-B4TnJtWu.js.map +1 -0
- package/dist/react.d.ts +47 -15
- package/dist/react.d.ts.map +1 -0
- package/dist/react.js +30 -15
- package/dist/react.js.map +1 -0
- package/dist/retryable-lazy-DZWmHpii.js +2 -0
- package/dist/retryable-lazy-DZWmHpii.js.map +1 -0
- package/dist/scheduler-qstash.d.ts +79 -0
- package/dist/scheduler-qstash.d.ts.map +1 -0
- package/dist/scheduler-qstash.js +501 -0
- package/dist/scheduler-qstash.js.map +1 -0
- package/dist/scheduler-task-BpzhPnRS.js +56 -0
- package/dist/scheduler-task-BpzhPnRS.js.map +1 -0
- package/dist/{recovery-vercel.d.ts → scheduler-vercel.d.ts} +18 -24
- package/dist/scheduler-vercel.d.ts.map +1 -0
- package/dist/scheduler-vercel.js +228 -0
- package/dist/scheduler-vercel.js.map +1 -0
- package/dist/server-C72KOw51.js +1457 -0
- package/dist/server-C72KOw51.js.map +1 -0
- package/dist/server-DUF9pjsx.d.ts +261 -0
- package/dist/server-DUF9pjsx.d.ts.map +1 -0
- package/dist/server.browser.js +2 -0
- package/dist/server.browser.js.map +1 -0
- package/dist/server.d.ts +4 -155
- package/dist/server.js +2 -2
- package/dist/{log-ldf5g8Cx.d.ts → store-DysUkTH3.d.ts} +120 -35
- package/dist/store-DysUkTH3.d.ts.map +1 -0
- package/dist/{log-yJbXUf72.js → store-N8PXxDAS.js} +3 -1
- package/dist/store-N8PXxDAS.js.map +1 -0
- package/dist/store-codec-DTG0Ftek.js +10 -0
- package/dist/store-codec-DTG0Ftek.js.map +1 -0
- package/dist/store-memory.d.ts +12 -0
- package/dist/store-memory.d.ts.map +1 -0
- package/dist/{log-memory.js → store-memory.js} +145 -34
- package/dist/store-memory.js.map +1 -0
- package/dist/{log-polling-DZ1MiKLg.js → store-polling-dSeLxzfb.js} +7 -5
- package/dist/store-polling-dSeLxzfb.js.map +1 -0
- package/dist/{log-postgres.d.ts → store-postgres.d.ts} +7 -6
- package/dist/store-postgres.d.ts.map +1 -0
- package/dist/{log-postgres.js → store-postgres.js} +214 -24
- package/dist/store-postgres.js.map +1 -0
- package/dist/{log-redis-core-CyJ5L8yR.js → store-redis-core-BFLwz0Wj.js} +271 -66
- package/dist/store-redis-core-BFLwz0Wj.js.map +1 -0
- package/dist/{log-redis-http.d.ts → store-redis-http.d.ts} +8 -7
- package/dist/store-redis-http.d.ts.map +1 -0
- package/dist/{log-redis-http.js → store-redis-http.js} +22 -12
- package/dist/store-redis-http.js.map +1 -0
- package/dist/{log-redis.d.ts → store-redis.d.ts} +7 -6
- package/dist/store-redis.d.ts.map +1 -0
- package/dist/{log-redis.js → store-redis.js} +101 -39
- package/dist/store-redis.js.map +1 -0
- package/dist/{log-sqlite.d.ts → store-sqlite.d.ts} +7 -6
- package/dist/store-sqlite.d.ts.map +1 -0
- package/dist/{log-sqlite.js → store-sqlite.js} +118 -22
- package/dist/store-sqlite.js.map +1 -0
- package/dist/{telemetry-Cso0qyHQ.d.ts → telemetry-BjYHTfh2.d.ts} +3 -2
- package/dist/telemetry-BjYHTfh2.d.ts.map +1 -0
- package/dist/testing.browser.d.ts +1 -0
- package/dist/testing.browser.js +6 -0
- package/dist/testing.browser.js.map +1 -0
- package/dist/testing.d.ts +32 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +103 -0
- package/dist/testing.js.map +1 -0
- package/dist/validate-XKT4FSNn.js +2 -0
- package/dist/validate-XKT4FSNn.js.map +1 -0
- package/dist/wire-BFQmSJ-9.js +284 -0
- package/dist/wire-BFQmSJ-9.js.map +1 -0
- package/docs/01-quickstart.mdx +3 -3
- package/docs/concepts/01-contracts.mdx +18 -13
- package/docs/concepts/02-handlers.mdx +7 -7
- package/docs/concepts/03-durability.mdx +21 -21
- package/docs/concepts/04-state.mdx +18 -21
- package/docs/guides/01-timers.mdx +154 -49
- package/docs/guides/02-cancellation.mdx +30 -4
- package/docs/guides/03-react.mdx +76 -57
- package/docs/guides/04-local-first.mdx +1 -1
- package/docs/guides/05-production.mdx +310 -61
- package/docs/guides/06-ai-agents.mdx +252 -74
- package/docs/guides/07-devtools.mdx +137 -12
- package/docs/guides/08-application-data.mdx +1 -1
- package/docs/guides/09-presence.mdx +263 -0
- package/docs/guides/10-transports.mdx +140 -0
- package/docs/index.mdx +18 -14
- package/docs/reference/01-api.mdx +839 -110
- package/docs/reference/02-errors.mdx +13 -6
- package/package.json +24 -7
- package/src/ai-coordinator.ts +358 -0
- package/src/ai-projector.ts +524 -0
- package/src/ai-sdk-step.ts +261 -0
- package/src/ai-server.browser.ts +5 -0
- package/src/ai-server.ts +1719 -0
- package/src/ai.ts +2155 -0
- package/src/cache-indexeddb.ts +10 -0
- package/src/cli-bin.ts +5 -0
- package/src/cli.ts +1046 -0
- package/src/client.ts +1826 -0
- package/src/contract.ts +206 -0
- package/src/deterministic-id.ts +72 -0
- package/src/devtools-app.ts +989 -0
- package/src/devtools-server.browser.ts +5 -0
- package/src/devtools-server.ts +604 -0
- package/src/devtools.ts +716 -0
- package/src/errors.ts +50 -0
- package/src/http.ts +394 -0
- package/src/idempotent-replay.ts +53 -0
- package/src/index.ts +37 -0
- package/src/inspection.ts +39 -0
- package/src/internal.ts +426 -0
- package/src/otel.ts +59 -0
- package/src/platform.ts +60 -0
- package/src/push-envelope.ts +137 -0
- package/src/react.ts +284 -0
- package/src/reducer.ts +108 -0
- package/src/retryable-lazy.ts +27 -0
- package/src/scheduler-qstash.ts +915 -0
- package/src/scheduler-task.ts +106 -0
- package/src/scheduler-vercel.ts +437 -0
- package/src/server.browser.ts +12 -0
- package/src/server.ts +2700 -0
- package/src/session-socket.ts +548 -0
- package/src/sse.ts +141 -0
- package/src/standard-schema.ts +77 -0
- package/src/store-codec.ts +10 -0
- package/src/store-memory.ts +788 -0
- package/src/store-polling.ts +102 -0
- package/src/store-postgres.ts +1212 -0
- package/src/store-redis-core.ts +1494 -0
- package/src/store-redis-http.ts +116 -0
- package/src/store-redis.ts +458 -0
- package/src/store-sqlite.ts +1108 -0
- package/src/store.ts +385 -0
- package/src/telemetry.ts +47 -0
- package/src/testing.browser.ts +5 -0
- package/src/testing.ts +185 -0
- package/src/validate.ts +39 -0
- package/src/wire.ts +454 -0
- package/dist/internal-gCd5qMry.js +0 -44
- package/dist/log-memory.d.ts +0 -11
- package/dist/recovery-vercel.js +0 -119
- package/dist/server-BcLa4RFL.js +0 -877
- package/dist/wire-BVsgR8o9.js +0 -62
package/dist/http.js
CHANGED
|
@@ -1,66 +1,48 @@
|
|
|
1
|
-
import { t as A2Error } from "./errors-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
1
|
+
import { t as A2Error } from "./errors-BQuJpe82.js";
|
|
2
|
+
import { _ as schedulerForServer, c as STREAM_TIMINGS, d as assertServerSchedulerBindings, o as RESERVED_PARTICIPANT_IDS, s as SOCKET_TIMINGS, u as assertSchedulerTargets } from "./internal-DstsI6Re.js";
|
|
3
|
+
import { t as invocationDeadlineMs } from "./platform-B4TnJtWu.js";
|
|
4
|
+
import { _ as socketErrorAckFor, a as errorToWire, b as socketUnsubscribedFor, g as socketAckFor, h as presenceSnapshotToWire, i as errorStatus, n as asA2Error, p as presencePatchToWire, r as errorFromWire, s as eventToWire, t as SOCKET_PING_FRAME, v as socketFrameFor, y as socketSubscribedFor } from "./wire-BFQmSJ-9.js";
|
|
5
|
+
//#region src/sse.ts
|
|
5
6
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* route and the client's `push` share.
|
|
7
|
+
* The SSE response protocol — framing, heartbeat, deadline, and
|
|
8
|
+
* teardown for the live stream lane. Internal module: `handle`'s
|
|
9
|
+
* stream branch is the one sanctioned caller; the framing rules stay
|
|
10
|
+
* documented on `sseResponse` because the client's parser (and the
|
|
11
|
+
* stall watchdog) depend on them.
|
|
12
12
|
*/
|
|
13
|
-
const invalid = (message) => new A2Error("INVALID_PAYLOAD", `malformed push body: ${message}`);
|
|
14
|
-
/**
|
|
15
|
-
* Validate the push envelope — `{ sessionId, events }` — throwing
|
|
16
|
-
* `INVALID_PAYLOAD` on a malformed body. Payload validation against the
|
|
17
|
-
* machine's schemas happens in `append`, not here.
|
|
18
|
-
*/
|
|
19
|
-
async function parsePushBody(req) {
|
|
20
|
-
let body;
|
|
21
|
-
try {
|
|
22
|
-
body = await req.json();
|
|
23
|
-
} catch (cause) {
|
|
24
|
-
throw new A2Error("INVALID_PAYLOAD", "push body is not valid JSON", { cause });
|
|
25
|
-
}
|
|
26
|
-
if (body === null || typeof body !== "object") throw invalid("expected an object");
|
|
27
|
-
const { sessionId, events } = body;
|
|
28
|
-
if (typeof sessionId !== "string" || sessionId.length === 0) throw invalid("sessionId must be a non-empty string");
|
|
29
|
-
if (!Array.isArray(events) || events.length === 0) throw invalid("events must be a non-empty array");
|
|
30
|
-
return {
|
|
31
|
-
sessionId,
|
|
32
|
-
events: events.map((event, i) => {
|
|
33
|
-
if (event === null || typeof event !== "object") throw invalid(`events[${i}] must be an object`);
|
|
34
|
-
const { type, payload, id } = event;
|
|
35
|
-
if (typeof type !== "string" || type.length === 0) throw invalid(`events[${i}].type must be a non-empty string`);
|
|
36
|
-
if (id !== void 0 && typeof id !== "string") throw invalid(`events[${i}].id must be a string when present`);
|
|
37
|
-
const out = {
|
|
38
|
-
type,
|
|
39
|
-
payload
|
|
40
|
-
};
|
|
41
|
-
if (id !== void 0) out.id = id;
|
|
42
|
-
Object.defineProperty(out, "~a2.pushed", { value: true });
|
|
43
|
-
return out;
|
|
44
|
-
})
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
13
|
/**
|
|
48
14
|
* Pipe a live event iterable into an SSE `Response`. Each event is one
|
|
49
|
-
* frame — `id:` carries the log index, `data:` the JSON event. A
|
|
15
|
+
* frame — `id:` carries the event-log index, `data:` the JSON event. A
|
|
16
|
+
* `stream({ presence: true })` iterable also yields presence items,
|
|
17
|
+
* which ride as named frames old clients skip: `event:
|
|
18
|
+
* presence-snapshot` first (the map, ISO dates), then `event: presence`
|
|
19
|
+
* per patch — no `id:`, presence never advances the resume frontier. A
|
|
50
20
|
* disconnecting client cancels the stream, which closes the underlying
|
|
51
21
|
* subscription. Two kinds of comment frames ride along: a `: connected`
|
|
52
22
|
* prelude that flushes headers immediately, and a `: ping` heartbeat
|
|
53
23
|
* every 15 seconds so clients (and proxies) can tell a quiet stream
|
|
54
24
|
* from a dead connection — the session client's stall watchdog counts
|
|
55
|
-
* on it.
|
|
25
|
+
* on it. When the platform exposes an invocation deadline, the response
|
|
26
|
+
* closes cleanly one second before it so the client reconnects without
|
|
27
|
+
* a platform-timeout failure.
|
|
56
28
|
*/
|
|
57
29
|
function sseResponse(iterable) {
|
|
58
30
|
const iterator = iterable[Symbol.asyncIterator]();
|
|
59
31
|
const encoder = new TextEncoder();
|
|
60
32
|
let heartbeat;
|
|
61
|
-
|
|
33
|
+
let deadlineTimer;
|
|
34
|
+
let closed = false;
|
|
35
|
+
let iteratorReturned = false;
|
|
36
|
+
const stopTimers = () => {
|
|
62
37
|
if (heartbeat !== void 0) clearInterval(heartbeat);
|
|
38
|
+
if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
|
|
63
39
|
heartbeat = void 0;
|
|
40
|
+
deadlineTimer = void 0;
|
|
41
|
+
};
|
|
42
|
+
const returnIterator = async () => {
|
|
43
|
+
if (iteratorReturned) return;
|
|
44
|
+
iteratorReturned = true;
|
|
45
|
+
await iterator.return?.();
|
|
64
46
|
};
|
|
65
47
|
const stream = new ReadableStream({
|
|
66
48
|
start(controller) {
|
|
@@ -69,23 +51,49 @@ function sseResponse(iterable) {
|
|
|
69
51
|
try {
|
|
70
52
|
controller.enqueue(encoder.encode(": ping\n\n"));
|
|
71
53
|
} catch {
|
|
72
|
-
|
|
54
|
+
stopTimers();
|
|
73
55
|
}
|
|
74
56
|
}, STREAM_TIMINGS.sseHeartbeatMs);
|
|
75
57
|
heartbeat.unref?.();
|
|
58
|
+
const invocationDeadline = invocationDeadlineMs();
|
|
59
|
+
if (invocationDeadline !== null) {
|
|
60
|
+
const delay = Math.max(0, invocationDeadline - Date.now() - STREAM_TIMINGS.sseDeadlineGraceMs);
|
|
61
|
+
deadlineTimer = setTimeout(() => {
|
|
62
|
+
if (closed) return;
|
|
63
|
+
closed = true;
|
|
64
|
+
stopTimers();
|
|
65
|
+
returnIterator().catch(() => {});
|
|
66
|
+
try {
|
|
67
|
+
controller.close();
|
|
68
|
+
} catch {}
|
|
69
|
+
}, delay);
|
|
70
|
+
deadlineTimer.unref?.();
|
|
71
|
+
}
|
|
76
72
|
},
|
|
77
73
|
async pull(controller) {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
74
|
+
try {
|
|
75
|
+
const { value, done } = await iterator.next();
|
|
76
|
+
if (closed) return;
|
|
77
|
+
if (done) {
|
|
78
|
+
closed = true;
|
|
79
|
+
stopTimers();
|
|
80
|
+
controller.close();
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
controller.enqueue(encoder.encode(frameFor(value)));
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (closed) return;
|
|
86
|
+
closed = true;
|
|
87
|
+
stopTimers();
|
|
88
|
+
returnIterator().catch(() => {});
|
|
89
|
+
throw error;
|
|
83
90
|
}
|
|
84
|
-
controller.enqueue(encoder.encode(`id: ${value.index}\ndata: ${JSON.stringify(eventToWire(value))}\n\n`));
|
|
85
91
|
},
|
|
86
92
|
async cancel() {
|
|
87
|
-
|
|
88
|
-
|
|
93
|
+
if (closed) return;
|
|
94
|
+
closed = true;
|
|
95
|
+
stopTimers();
|
|
96
|
+
await returnIterator();
|
|
89
97
|
}
|
|
90
98
|
});
|
|
91
99
|
return new Response(stream, {
|
|
@@ -97,15 +105,433 @@ function sseResponse(iterable) {
|
|
|
97
105
|
}
|
|
98
106
|
});
|
|
99
107
|
}
|
|
108
|
+
function frameFor(item) {
|
|
109
|
+
if ("snapshot" in item) return `event: presence-snapshot\ndata: ${JSON.stringify(presenceSnapshotToWire(item))}\n\n`;
|
|
110
|
+
if ("participant" in item) return `event: presence\ndata: ${JSON.stringify(presencePatchToWire(item))}\n\n`;
|
|
111
|
+
return `id: ${item.index}\ndata: ${JSON.stringify(eventToWire(item))}\n\n`;
|
|
112
|
+
}
|
|
113
|
+
//#endregion
|
|
114
|
+
//#region src/push-envelope.ts
|
|
115
|
+
/**
|
|
116
|
+
* The push envelope's trust boundary — parsing and provenance-branding
|
|
117
|
+
* for `{ sessionId, events, presence? }`, shared verbatim by the HTTP
|
|
118
|
+
* POST lane and the socket's push/presence frames so INVALID_PAYLOAD
|
|
119
|
+
* shapes are one implementation. Internal module — `handle` (and the
|
|
120
|
+
* socket handler) compose it; it is not part of the public surface.
|
|
121
|
+
*/
|
|
122
|
+
const invalidPushBody = (message) => new A2Error("INVALID_PAYLOAD", `malformed push body: ${message}`);
|
|
123
|
+
const invalid = invalidPushBody;
|
|
124
|
+
function parsePresenceSibling(value) {
|
|
125
|
+
if (value === void 0) return void 0;
|
|
126
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw invalid("presence must be an object when present");
|
|
127
|
+
const { participant, values, seen, at } = value;
|
|
128
|
+
if (typeof participant !== "string" || participant.length === 0) throw invalid("presence.participant must be a non-empty string");
|
|
129
|
+
if (RESERVED_PARTICIPANT_IDS.has(participant)) throw invalid(`presence.participant must not be '${participant}'`);
|
|
130
|
+
if (values === null || typeof values !== "object" || Array.isArray(values)) throw invalid("presence.values must be an object");
|
|
131
|
+
if (seen !== void 0 && (typeof seen !== "number" || !Number.isFinite(seen) || seen < 0)) throw invalid("presence.seen must be a non-negative number when present");
|
|
132
|
+
if (at !== void 0 && (typeof at !== "number" || !Number.isFinite(at) || at < 0 || at > 864e13)) throw invalid("presence.at must be a non-negative epoch-milliseconds timestamp within the Date range when present");
|
|
133
|
+
const out = {
|
|
134
|
+
participant,
|
|
135
|
+
values
|
|
136
|
+
};
|
|
137
|
+
if (seen !== void 0) out.seen = seen;
|
|
138
|
+
if (at !== void 0) out.at = at;
|
|
139
|
+
Object.defineProperty(out, "~a2.pushed", { value: true });
|
|
140
|
+
return out;
|
|
141
|
+
}
|
|
142
|
+
/** The events half of the envelope — shared verbatim by the POST body
|
|
143
|
+
* and the socket's `push` frames, so the provenance brand and the
|
|
144
|
+
* INVALID_PAYLOAD shapes are one implementation. */
|
|
145
|
+
function parsePushEvents(events) {
|
|
146
|
+
if (!Array.isArray(events) || events.length === 0) throw invalid("events must be a non-empty array");
|
|
147
|
+
return events.map((event, i) => {
|
|
148
|
+
if (event === null || typeof event !== "object") throw invalid(`events[${i}] must be an object`);
|
|
149
|
+
const { type, payload, id } = event;
|
|
150
|
+
if (typeof type !== "string" || type.length === 0) throw invalid(`events[${i}].type must be a non-empty string`);
|
|
151
|
+
if (id !== void 0 && typeof id !== "string") throw invalid(`events[${i}].id must be a string when present`);
|
|
152
|
+
const out = {
|
|
153
|
+
type,
|
|
154
|
+
payload
|
|
155
|
+
};
|
|
156
|
+
if (id !== void 0) out.id = id;
|
|
157
|
+
Object.defineProperty(out, "~a2.pushed", { value: true });
|
|
158
|
+
return out;
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Validate the push envelope — `{ sessionId, events, presence? }` —
|
|
163
|
+
* throwing `INVALID_PAYLOAD` on a malformed body. Payload validation
|
|
164
|
+
* against the machine's schemas happens in `append` and `setPresence`,
|
|
165
|
+
* not here. Either plane may appear alone: a presence-only push has no
|
|
166
|
+
* (or empty) `events`.
|
|
167
|
+
*/
|
|
168
|
+
async function parsePushBody(req) {
|
|
169
|
+
let body;
|
|
170
|
+
try {
|
|
171
|
+
body = await req.json();
|
|
172
|
+
} catch (cause) {
|
|
173
|
+
throw new A2Error("INVALID_PAYLOAD", "push body is not valid JSON", { cause });
|
|
174
|
+
}
|
|
175
|
+
if (body === null || typeof body !== "object") throw invalid("expected an object");
|
|
176
|
+
const { sessionId, events, presence } = body;
|
|
177
|
+
if (typeof sessionId !== "string" || sessionId.length === 0) throw invalid("sessionId must be a non-empty string");
|
|
178
|
+
const parsedPresence = parsePresenceSibling(presence);
|
|
179
|
+
if (parsedPresence !== void 0 && (events === void 0 || Array.isArray(events) && events.length === 0)) return {
|
|
180
|
+
sessionId,
|
|
181
|
+
events: [],
|
|
182
|
+
presence: parsedPresence
|
|
183
|
+
};
|
|
184
|
+
const parsed = parsePushEvents(events);
|
|
185
|
+
return parsedPresence !== void 0 ? {
|
|
186
|
+
sessionId,
|
|
187
|
+
events: parsed,
|
|
188
|
+
presence: parsedPresence
|
|
189
|
+
} : {
|
|
190
|
+
sessionId,
|
|
191
|
+
events: parsed
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
//#endregion
|
|
195
|
+
//#region src/session-socket.ts
|
|
196
|
+
/**
|
|
197
|
+
* The A2 socket protocol's server half (specs/a2-api.md §13): the
|
|
198
|
+
* per-socket shell — teardown, backpressure, heartbeat, the malformed
|
|
199
|
+
* budget, the in-flight bound — and `sessionsSocket`, the multiplexed
|
|
200
|
+
* frame handler riding it. Internal module: `handle`'s upgrade lane is
|
|
201
|
+
* the sanctioned mount; only `A2Socket` (the structural socket the
|
|
202
|
+
* platform hands over) is re-exported as public surface.
|
|
203
|
+
*/
|
|
204
|
+
const messageText = (data) => {
|
|
205
|
+
if (typeof data === "string") return data;
|
|
206
|
+
if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
|
|
207
|
+
if (ArrayBuffer.isView(data)) return new TextDecoder().decode(data);
|
|
208
|
+
if (Array.isArray(data) && data.every(ArrayBuffer.isView)) {
|
|
209
|
+
const decoder = new TextDecoder();
|
|
210
|
+
let text = "";
|
|
211
|
+
for (const part of data) text += decoder.decode(part, { stream: true });
|
|
212
|
+
return text + decoder.decode();
|
|
213
|
+
}
|
|
214
|
+
return null;
|
|
215
|
+
};
|
|
216
|
+
/**
|
|
217
|
+
* How many unparseable or invalid frames a socket may send before it
|
|
218
|
+
* is closed (1008): the budget absorbs isolated client bugs without
|
|
219
|
+
* letting a broken peer spin the validation path forever. Push frames
|
|
220
|
+
* with a usable `req` never count — their failures are answered with
|
|
221
|
+
* error acks, exactly like the POST path's 4xx bodies.
|
|
222
|
+
*/
|
|
223
|
+
const MAX_MALFORMED_FRAMES = 5;
|
|
224
|
+
function socketShell(socket, release, onFrame, deadlineAt) {
|
|
225
|
+
let torn = false;
|
|
226
|
+
let malformed = 0;
|
|
227
|
+
let heartbeat;
|
|
228
|
+
let deadline;
|
|
229
|
+
const teardown = () => {
|
|
230
|
+
if (torn) return;
|
|
231
|
+
torn = true;
|
|
232
|
+
if (heartbeat !== void 0) clearInterval(heartbeat);
|
|
233
|
+
if (deadline !== void 0) clearTimeout(deadline);
|
|
234
|
+
release();
|
|
235
|
+
};
|
|
236
|
+
const shutdown = (code, reason) => {
|
|
237
|
+
if (torn) return;
|
|
238
|
+
teardown();
|
|
239
|
+
try {
|
|
240
|
+
socket.close(code, reason);
|
|
241
|
+
} catch {}
|
|
242
|
+
};
|
|
243
|
+
const send = (data) => {
|
|
244
|
+
if (torn) return;
|
|
245
|
+
if (typeof socket.bufferedAmount === "number" && socket.bufferedAmount > SOCKET_TIMINGS.disconnectWaterMarkBytes) {
|
|
246
|
+
shutdown(1008, "backpressure: peer not reading");
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
try {
|
|
250
|
+
socket.send(data);
|
|
251
|
+
} catch {
|
|
252
|
+
teardown();
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
const malformedFrame = (reason) => {
|
|
256
|
+
malformed += 1;
|
|
257
|
+
if (malformed >= MAX_MALFORMED_FRAMES) shutdown(1008, `too many malformed frames (last: ${reason})`);
|
|
258
|
+
};
|
|
259
|
+
let inFlight = 0;
|
|
260
|
+
const track = (work) => {
|
|
261
|
+
inFlight += 1;
|
|
262
|
+
work.finally(() => {
|
|
263
|
+
inFlight -= 1;
|
|
264
|
+
});
|
|
265
|
+
};
|
|
266
|
+
const handleMessage = (data) => {
|
|
267
|
+
if (torn) return;
|
|
268
|
+
const text = messageText(data);
|
|
269
|
+
if (text === null) {
|
|
270
|
+
malformedFrame("non-text frame");
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
let parsed;
|
|
274
|
+
try {
|
|
275
|
+
parsed = JSON.parse(text);
|
|
276
|
+
} catch {
|
|
277
|
+
malformedFrame("frame is not valid JSON");
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
281
|
+
malformedFrame("frame is not an object");
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
onFrame(parsed);
|
|
285
|
+
};
|
|
286
|
+
socket.on("message", handleMessage);
|
|
287
|
+
socket.on("close", teardown);
|
|
288
|
+
socket.on("error", teardown);
|
|
289
|
+
heartbeat = setInterval(() => send(SOCKET_PING_FRAME), STREAM_TIMINGS.sseHeartbeatMs);
|
|
290
|
+
heartbeat.unref?.();
|
|
291
|
+
if (deadlineAt !== void 0) {
|
|
292
|
+
deadline = setTimeout(() => shutdown(1e3, "deadline"), Math.max(0, deadlineAt - Date.now()));
|
|
293
|
+
deadline.unref?.();
|
|
294
|
+
}
|
|
295
|
+
return {
|
|
296
|
+
torn: () => torn,
|
|
297
|
+
send,
|
|
298
|
+
shutdown,
|
|
299
|
+
malformedFrame,
|
|
300
|
+
buffered: () => typeof socket.bufferedAmount === "number" ? socket.bufferedAmount : 0,
|
|
301
|
+
overCap: () => inFlight >= SOCKET_TIMINGS.maxInFlightMessages,
|
|
302
|
+
track
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
const stopSubscription = (subscription) => {
|
|
306
|
+
subscription.stopped = true;
|
|
307
|
+
subscription.iterator.return?.()?.catch(() => {});
|
|
308
|
+
};
|
|
309
|
+
const parseSubscribeEntries = (value) => {
|
|
310
|
+
if (!Array.isArray(value) || value.length === 0) return null;
|
|
311
|
+
const entries = [];
|
|
312
|
+
for (const entry of value) {
|
|
313
|
+
if (entry === null || typeof entry !== "object") return null;
|
|
314
|
+
const { id, index } = entry;
|
|
315
|
+
if (typeof id !== "string" || id.length === 0) return null;
|
|
316
|
+
if (typeof index !== "number" || !Number.isInteger(index) || index < 0) return null;
|
|
317
|
+
entries.push({
|
|
318
|
+
id,
|
|
319
|
+
index
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
return entries;
|
|
323
|
+
};
|
|
324
|
+
/**
|
|
325
|
+
* Speak the multiplexed A2 socket protocol (specs/a2-api.md §13)
|
|
326
|
+
* against many sessions on one socket. `subscribe` frames open a
|
|
327
|
+
* per-session pump at that session's own resume frontier; push and
|
|
328
|
+
* presence frames route by `sessionId` through the same validation
|
|
329
|
+
* seams as the POST lane; every down frame carries the `sessionId` it
|
|
330
|
+
* belongs to. One heartbeat, one
|
|
331
|
+
* malformed budget, one in-flight bound, one backpressure gauge — per
|
|
332
|
+
* socket, shared by all sessions. A session's stream ending or failing
|
|
333
|
+
* answers `unsubscribed` for that session; only the peer, the
|
|
334
|
+
* deadline, the malformed budget, or backpressure closes the socket.
|
|
335
|
+
*/
|
|
336
|
+
function sessionsSocket(resolve, socket, options) {
|
|
337
|
+
const presence = options?.presence === true;
|
|
338
|
+
const subscriptions = /* @__PURE__ */ new Map();
|
|
339
|
+
const retire = (id, subscription) => {
|
|
340
|
+
if (subscriptions.get(id) === subscription) subscriptions.delete(id);
|
|
341
|
+
};
|
|
342
|
+
const pump = async (id, subscription) => {
|
|
343
|
+
for (;;) {
|
|
344
|
+
for (;;) {
|
|
345
|
+
if (shell.torn() || subscription.stopped || shell.buffered() <= SOCKET_TIMINGS.highWaterMarkBytes) break;
|
|
346
|
+
await new Promise((wake) => setTimeout(wake, SOCKET_TIMINGS.resumePollMs));
|
|
347
|
+
}
|
|
348
|
+
if (shell.torn() || subscription.stopped) return;
|
|
349
|
+
const { value, done } = await subscription.iterator.next();
|
|
350
|
+
if (shell.torn() || subscription.stopped) return;
|
|
351
|
+
if (done) return;
|
|
352
|
+
shell.send(socketFrameFor(value, id));
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
const runSubscription = async (id, subscription) => {
|
|
356
|
+
try {
|
|
357
|
+
await pump(id, subscription);
|
|
358
|
+
if (shell.torn() || subscription.stopped) return;
|
|
359
|
+
retire(id, subscription);
|
|
360
|
+
shell.send(socketUnsubscribedFor(id));
|
|
361
|
+
} catch {
|
|
362
|
+
if (shell.torn() || subscription.stopped) return;
|
|
363
|
+
retire(id, subscription);
|
|
364
|
+
shell.send(socketUnsubscribedFor(id, "stream failed"));
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
const startSubscription = async (id, index) => {
|
|
368
|
+
let session;
|
|
369
|
+
try {
|
|
370
|
+
session = await resolve(id, index);
|
|
371
|
+
} catch {
|
|
372
|
+
session = null;
|
|
373
|
+
}
|
|
374
|
+
if (shell.torn()) return;
|
|
375
|
+
if (session === null) {
|
|
376
|
+
shell.send(socketUnsubscribedFor(id, "subscribe rejected"));
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
const target = session;
|
|
380
|
+
const existing = subscriptions.get(id);
|
|
381
|
+
if (existing) stopSubscription(existing);
|
|
382
|
+
const subscription = {
|
|
383
|
+
target,
|
|
384
|
+
iterator: (presence ? target.stream({
|
|
385
|
+
startAfter: index,
|
|
386
|
+
presence: true
|
|
387
|
+
}) : target.stream({ startAfter: index }))[Symbol.asyncIterator](),
|
|
388
|
+
stopped: false
|
|
389
|
+
};
|
|
390
|
+
subscriptions.set(id, subscription);
|
|
391
|
+
shell.send(socketSubscribedFor(id));
|
|
392
|
+
runSubscription(id, subscription);
|
|
393
|
+
};
|
|
394
|
+
let controlTail = Promise.resolve();
|
|
395
|
+
const control = (work) => {
|
|
396
|
+
controlTail = controlTail.then(work).catch(() => {});
|
|
397
|
+
};
|
|
398
|
+
const handlePush = async (frame, req, sessionId) => {
|
|
399
|
+
const subscription = subscriptions.get(sessionId);
|
|
400
|
+
if (subscription === void 0) {
|
|
401
|
+
shell.send(socketErrorAckFor(req, new A2Error("STORE_UNAVAILABLE", "session is not subscribed on this socket"), sessionId));
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
try {
|
|
405
|
+
const events = parsePushEvents(frame["events"]);
|
|
406
|
+
const denial = await options?.gatePush?.(sessionId, events) ?? null;
|
|
407
|
+
if (denial !== null) {
|
|
408
|
+
shell.send(socketErrorAckFor(req, denial, sessionId));
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
const appended = await subscription.target.append(...events);
|
|
412
|
+
shell.send(socketAckFor(req, appended, sessionId));
|
|
413
|
+
} catch (err) {
|
|
414
|
+
shell.send(socketErrorAckFor(req, asA2Error(err), sessionId));
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
const handlePresence = async (frame, sessionId) => {
|
|
418
|
+
const subscription = subscriptions.get(sessionId);
|
|
419
|
+
if (subscription === void 0) return;
|
|
420
|
+
if (typeof subscription.target.setPresence !== "function") {
|
|
421
|
+
shell.malformedFrame("presence frame on a presence-less session");
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
try {
|
|
425
|
+
const patch = parsePresenceSibling(frame);
|
|
426
|
+
if (patch) await subscription.target.setPresence(patch);
|
|
427
|
+
} catch {
|
|
428
|
+
shell.malformedFrame("invalid presence frame");
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
const handleFrame = (frame) => {
|
|
432
|
+
switch (frame["kind"]) {
|
|
433
|
+
case "subscribe": {
|
|
434
|
+
const entries = parseSubscribeEntries(frame["sessions"]);
|
|
435
|
+
if (entries === null) {
|
|
436
|
+
shell.malformedFrame("malformed subscribe frame");
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
for (const entry of entries) control(() => startSubscription(entry.id, entry.index));
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
case "unsubscribe": {
|
|
443
|
+
const ids = frame["sessions"];
|
|
444
|
+
if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === "string")) {
|
|
445
|
+
shell.malformedFrame("malformed unsubscribe frame");
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
for (const id of ids) control(() => {
|
|
449
|
+
const subscription = subscriptions.get(id);
|
|
450
|
+
if (subscription === void 0) return;
|
|
451
|
+
stopSubscription(subscription);
|
|
452
|
+
subscriptions.delete(id);
|
|
453
|
+
});
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
case "push": {
|
|
457
|
+
const req = frame["req"];
|
|
458
|
+
const sessionId = frame["sessionId"];
|
|
459
|
+
if (shell.overCap()) {
|
|
460
|
+
if (typeof req === "number") shell.send(socketErrorAckFor(req, new A2Error("STORE_UNAVAILABLE", "push shed: too many in flight on this socket"), typeof sessionId === "string" ? sessionId : void 0));
|
|
461
|
+
else shell.malformedFrame("push frame without a numeric req");
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
if (typeof req !== "number") {
|
|
465
|
+
shell.malformedFrame("push frame without a numeric req");
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
if (typeof sessionId !== "string" || sessionId.length === 0) {
|
|
469
|
+
shell.send(socketErrorAckFor(req, new A2Error("INVALID_PAYLOAD", "push frame without a sessionId")));
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
shell.track(handlePush(frame, req, sessionId));
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
case "presence": {
|
|
476
|
+
if (shell.overCap()) return;
|
|
477
|
+
const sessionId = frame["sessionId"];
|
|
478
|
+
if (typeof sessionId !== "string" || sessionId.length === 0) {
|
|
479
|
+
shell.malformedFrame("presence frame without a sessionId");
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
shell.track(handlePresence(frame, sessionId));
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
default: return;
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
const shell = socketShell(socket, () => {
|
|
489
|
+
for (const subscription of subscriptions.values()) stopSubscription(subscription);
|
|
490
|
+
subscriptions.clear();
|
|
491
|
+
}, (frame) => handleFrame(frame), options?.deadline);
|
|
492
|
+
}
|
|
493
|
+
//#endregion
|
|
494
|
+
//#region src/http.ts
|
|
495
|
+
/**
|
|
496
|
+
* experimental-a2/http — the wire's server half (specs/a2-api.md §9–10, §13).
|
|
497
|
+
*
|
|
498
|
+
* A thin public assembly. The surface: `handle` — GET, POST, and the
|
|
499
|
+
* socket's frames parsed into intents (stream, history, push,
|
|
500
|
+
* ws-upgrade) with `before`/`after` hooks around them for policy —
|
|
501
|
+
* plus `A2Intent`/`A2Outcome`/`UpgradeFn`/`A2Socket` (its argument
|
|
502
|
+
* types), `errorResponse`/`deserializeError` (the A2Error wire pair
|
|
503
|
+
* both sides branch on), and `schedulerHandler` (the scheduler
|
|
504
|
+
* callback mount). The machinery lives in internal modules — the SSE
|
|
505
|
+
* framing in sse.ts, the push-envelope trust boundary in
|
|
506
|
+
* push-envelope.ts, the socket shell and multiplexed handler in
|
|
507
|
+
* session-socket.ts — because nothing outside `handle` is sanctioned
|
|
508
|
+
* to compose them. Policy — auth, caching, quotas — never enters this
|
|
509
|
+
* module: the hooks own it.
|
|
510
|
+
*/
|
|
511
|
+
/**
|
|
512
|
+
* Create one scheduler callback route for servers sharing the same configured
|
|
513
|
+
* scheduler. Configuration mistakes throw immediately while the route module
|
|
514
|
+
* is evaluated, before a delivery can be acknowledged by the wrong adapter.
|
|
515
|
+
*/
|
|
516
|
+
function schedulerHandler(firstServer, ...servers) {
|
|
517
|
+
if (firstServer === void 0) throw new TypeError("schedulerHandler() requires at least one A2 server");
|
|
518
|
+
const scheduler = schedulerForServer(firstServer);
|
|
519
|
+
const targets = [firstServer, ...servers];
|
|
520
|
+
assertSchedulerTargets(targets, { allowStructural: false });
|
|
521
|
+
assertServerSchedulerBindings(scheduler, targets);
|
|
522
|
+
return scheduler.handler(...targets);
|
|
523
|
+
}
|
|
100
524
|
/**
|
|
101
525
|
* Serialize an error into the documented wire shape,
|
|
102
526
|
* `{ error: { code, message, details } }`, with the mapped status
|
|
103
|
-
* (400 for caller bugs, 503 for
|
|
104
|
-
* 503
|
|
105
|
-
* failure is retryable-once, not a protocol contract.
|
|
527
|
+
* (400 for caller bugs, 503 for STORE_UNAVAILABLE). Non-A2Errors become a
|
|
528
|
+
* 503 STORE_UNAVAILABLE — from the client's perspective an unknown server
|
|
529
|
+
* failure is retryable-once, not a protocol contract. The natural
|
|
530
|
+
* return value of a `before` hook that wants the wire's own error
|
|
531
|
+
* shapes.
|
|
106
532
|
*/
|
|
107
533
|
function errorResponse(error) {
|
|
108
|
-
const a2error =
|
|
534
|
+
const a2error = asA2Error(error);
|
|
109
535
|
return Response.json(errorToWire(a2error), { status: errorStatus(a2error.code) });
|
|
110
536
|
}
|
|
111
537
|
/**
|
|
@@ -116,5 +542,165 @@ function errorResponse(error) {
|
|
|
116
542
|
function deserializeError(body) {
|
|
117
543
|
return errorFromWire(body);
|
|
118
544
|
}
|
|
545
|
+
const parseHistoryBounds = (gte, lte) => {
|
|
546
|
+
if (gte === null || lte === null) throw new A2Error("INVALID_PAYLOAD", "a history read takes both gte and lte");
|
|
547
|
+
const bounds = {
|
|
548
|
+
gte: Number(gte),
|
|
549
|
+
lte: Number(lte)
|
|
550
|
+
};
|
|
551
|
+
for (const [name, value] of Object.entries(bounds)) if (!Number.isSafeInteger(value) || value < 0) throw new A2Error("INVALID_PAYLOAD", `history ${name} must be a non-negative safe integer`);
|
|
552
|
+
if (bounds.gte > bounds.lte) throw new A2Error("INVALID_PAYLOAD", "history gte must be less than or equal to lte");
|
|
553
|
+
return bounds;
|
|
554
|
+
};
|
|
555
|
+
const parseResumeIndex = (raw) => {
|
|
556
|
+
if (raw === null) return 0;
|
|
557
|
+
const index = Number(raw);
|
|
558
|
+
if (!Number.isSafeInteger(index) || index < 0) throw new A2Error("INVALID_PAYLOAD", "stream index must be a non-negative safe integer");
|
|
559
|
+
return index;
|
|
560
|
+
};
|
|
561
|
+
/**
|
|
562
|
+
* The session route pair as one call: `export const { GET, POST } =
|
|
563
|
+
* handle(server, options?)` serves the live stream (SSE GET, resumed
|
|
564
|
+
* at `index`), the history slice (GET with `gte`/`lte`), the push
|
|
565
|
+
* envelope (POST), and — with `options.upgrade` — the multiplexed
|
|
566
|
+
* WebSocket, all through one pair of policy hooks.
|
|
567
|
+
*
|
|
568
|
+
* Parsing is protocol, hooks are policy: a request that fails to parse
|
|
569
|
+
* (missing sessionId, malformed bounds, bad push envelope) answers
|
|
570
|
+
* INVALID_PAYLOAD on the wire before any hook runs. `before` sees
|
|
571
|
+
* every parsed intent — HTTP requests and socket frames alike, with
|
|
572
|
+
* `request` always the original (for socket frames: upgrade) Request —
|
|
573
|
+
* and short-circuits by returning a Response: over HTTP it is the
|
|
574
|
+
* response verbatim; over the socket it is translated to the wire's
|
|
575
|
+
* own vocabulary (subscribe → `unsubscribed { reason: 'subscribe
|
|
576
|
+
* rejected' }`, push → an INVALID_PAYLOAD error ack), because a
|
|
577
|
+
* Response body cannot cross a socket. `after` runs only where the
|
|
578
|
+
* library produced an HTTP response — never after a short-circuit,
|
|
579
|
+
* never for socket frames — and may mutate `response.headers` in place
|
|
580
|
+
* or return a replacement (history caching policy lives here, on
|
|
581
|
+
* `outcome.covered`). `options.deadline` (epoch ms) closes sockets
|
|
582
|
+
* cleanly ahead of a known platform deadline, so clients reconnect on
|
|
583
|
+
* our schedule.
|
|
584
|
+
*/
|
|
585
|
+
function handle(server, options) {
|
|
586
|
+
const presence = options?.presence === true;
|
|
587
|
+
const before = async (request, intent) => {
|
|
588
|
+
const result = await options?.before?.({
|
|
589
|
+
request,
|
|
590
|
+
intent
|
|
591
|
+
});
|
|
592
|
+
return result instanceof Response ? result : null;
|
|
593
|
+
};
|
|
594
|
+
const decorate = async (request, intent, outcome, response) => {
|
|
595
|
+
const replaced = await options?.after?.({
|
|
596
|
+
request,
|
|
597
|
+
intent,
|
|
598
|
+
outcome,
|
|
599
|
+
response
|
|
600
|
+
});
|
|
601
|
+
return replaced instanceof Response ? replaced : response;
|
|
602
|
+
};
|
|
603
|
+
const attach = (request) => (socket) => {
|
|
604
|
+
sessionsSocket(async (sessionId, startAfter) => {
|
|
605
|
+
return await before(request, {
|
|
606
|
+
type: "stream",
|
|
607
|
+
sessionId,
|
|
608
|
+
startAfter,
|
|
609
|
+
transport: "ws"
|
|
610
|
+
}) === null ? server.session(sessionId) : null;
|
|
611
|
+
}, socket, {
|
|
612
|
+
presence,
|
|
613
|
+
...options?.deadline === void 0 ? {} : { deadline: options.deadline },
|
|
614
|
+
gatePush: async (sessionId, events) => {
|
|
615
|
+
return await before(request, {
|
|
616
|
+
type: "push",
|
|
617
|
+
sessionId,
|
|
618
|
+
events,
|
|
619
|
+
transport: "ws"
|
|
620
|
+
}) === null ? null : new A2Error("INVALID_PAYLOAD", "push rejected");
|
|
621
|
+
}
|
|
622
|
+
});
|
|
623
|
+
};
|
|
624
|
+
return {
|
|
625
|
+
async GET(req) {
|
|
626
|
+
try {
|
|
627
|
+
if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
|
|
628
|
+
const short = await before(req, { type: "ws-upgrade" });
|
|
629
|
+
if (short !== null) return short;
|
|
630
|
+
if (options?.upgrade === void 0) return new Response("WebSocket upgrade requested, but handle() has no upgrade implementation — pass options.upgrade, e.g. { upgrade: (attach) => experimental_upgradeWebSocket(attach) } from '@vercel/functions'", { status: 426 });
|
|
631
|
+
return await options.upgrade(attach(req));
|
|
632
|
+
}
|
|
633
|
+
const { searchParams } = new URL(req.url);
|
|
634
|
+
const sessionId = searchParams.get("sessionId");
|
|
635
|
+
if (sessionId === null || sessionId.length === 0) throw new A2Error("INVALID_PAYLOAD", "missing sessionId");
|
|
636
|
+
const gteRaw = searchParams.get("gte");
|
|
637
|
+
const lteRaw = searchParams.get("lte");
|
|
638
|
+
if (gteRaw !== null || lteRaw !== null) {
|
|
639
|
+
const bounds = parseHistoryBounds(gteRaw, lteRaw);
|
|
640
|
+
const intent = {
|
|
641
|
+
type: "history",
|
|
642
|
+
sessionId,
|
|
643
|
+
...bounds
|
|
644
|
+
};
|
|
645
|
+
const short = await before(req, intent);
|
|
646
|
+
if (short !== null) return short;
|
|
647
|
+
const events = await server.session(sessionId).history(bounds);
|
|
648
|
+
const covered = events.length === bounds.lte - bounds.gte + 1;
|
|
649
|
+
return await decorate(req, intent, {
|
|
650
|
+
type: "history",
|
|
651
|
+
covered,
|
|
652
|
+
events
|
|
653
|
+
}, Response.json(events.map(eventToWire)));
|
|
654
|
+
}
|
|
655
|
+
const startAfter = parseResumeIndex(searchParams.get("index"));
|
|
656
|
+
const intent = {
|
|
657
|
+
type: "stream",
|
|
658
|
+
sessionId,
|
|
659
|
+
startAfter,
|
|
660
|
+
transport: "sse"
|
|
661
|
+
};
|
|
662
|
+
const short = await before(req, intent);
|
|
663
|
+
if (short !== null) return short;
|
|
664
|
+
const target = server.session(sessionId);
|
|
665
|
+
const response = sseResponse(presence ? target.stream({
|
|
666
|
+
startAfter,
|
|
667
|
+
presence: true
|
|
668
|
+
}) : target.stream({ startAfter }));
|
|
669
|
+
return await decorate(req, intent, { type: "stream" }, response);
|
|
670
|
+
} catch (err) {
|
|
671
|
+
return errorResponse(err);
|
|
672
|
+
}
|
|
673
|
+
},
|
|
674
|
+
async POST(req) {
|
|
675
|
+
try {
|
|
676
|
+
const body = await parsePushBody(req);
|
|
677
|
+
const intent = {
|
|
678
|
+
type: "push",
|
|
679
|
+
sessionId: body.sessionId,
|
|
680
|
+
events: body.events,
|
|
681
|
+
...body.presence === void 0 ? {} : { presence: body.presence },
|
|
682
|
+
transport: "http"
|
|
683
|
+
};
|
|
684
|
+
const short = await before(req, intent);
|
|
685
|
+
if (short !== null) return short;
|
|
686
|
+
const session = server.session(body.sessionId);
|
|
687
|
+
if (body.presence !== void 0) {
|
|
688
|
+
const target = session;
|
|
689
|
+
if (typeof target.setPresence !== "function") throw invalidPushBody("presence is not declared by this contract");
|
|
690
|
+
await target.setPresence(body.presence);
|
|
691
|
+
}
|
|
692
|
+
const appended = body.events.length === 0 ? [] : await session.append(...body.events);
|
|
693
|
+
return await decorate(req, intent, {
|
|
694
|
+
type: "push",
|
|
695
|
+
appended
|
|
696
|
+
}, Response.json(appended));
|
|
697
|
+
} catch (err) {
|
|
698
|
+
return errorResponse(err);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
}
|
|
119
703
|
//#endregion
|
|
120
|
-
export { deserializeError, errorResponse,
|
|
704
|
+
export { deserializeError, errorResponse, handle, schedulerHandler };
|
|
705
|
+
|
|
706
|
+
//# sourceMappingURL=http.js.map
|