@jini-ai/http-kit 0.7.1 → 0.7.3-next.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +2 -2
  2. package/README.md +6 -6
  3. package/dist/adapter.d.ts +7 -50
  4. package/dist/adapter.js +12 -54
  5. package/dist/api-security-middleware.d.ts +0 -16
  6. package/dist/api-security-middleware.js +2 -18
  7. package/dist/index.d.ts +10 -15
  8. package/dist/index.js +7 -10
  9. package/dist/internal-error.d.ts +42 -0
  10. package/dist/internal-error.js +48 -0
  11. package/dist/local-daemon-request.d.ts +11 -4
  12. package/dist/local-daemon-request.js +1 -28
  13. package/dist/middleware.d.ts +1 -0
  14. package/dist/middleware.js +1 -0
  15. package/dist/node-bridge.d.ts +108 -0
  16. package/dist/node-bridge.js +356 -0
  17. package/dist/observability.d.ts +3 -14
  18. package/dist/origin.d.ts +13 -30
  19. package/dist/origin.js +13 -13
  20. package/dist/range.d.ts +53 -0
  21. package/dist/range.js +93 -0
  22. package/dist/rate-limit.d.ts +1 -13
  23. package/dist/rate-limit.js +5 -2
  24. package/dist/request.d.ts +2 -13
  25. package/dist/request.js +0 -13
  26. package/dist/response.d.ts +8 -7
  27. package/dist/response.js +0 -36
  28. package/dist/route-registration-guard.d.ts +14 -0
  29. package/dist/route-registration-guard.js +17 -0
  30. package/dist/run-credentials.d.ts +73 -0
  31. package/dist/run-credentials.js +71 -0
  32. package/dist/settings/contracts.d.ts +49 -0
  33. package/dist/settings/contracts.js +2 -0
  34. package/dist/settings/http-request.d.ts +36 -0
  35. package/dist/settings/http-request.js +50 -0
  36. package/dist/settings/http.d.ts +10 -0
  37. package/dist/settings/http.js +216 -0
  38. package/dist/settings/index.d.ts +4 -0
  39. package/dist/settings/index.js +3 -0
  40. package/dist/settings/shared.d.ts +16 -0
  41. package/dist/settings/shared.js +16 -0
  42. package/dist/settings/stream.d.ts +25 -0
  43. package/dist/settings/stream.js +180 -0
  44. package/dist/sse.d.ts +1 -15
  45. package/dist/sse.js +77 -72
  46. package/dist/trust-proxy.d.ts +36 -0
  47. package/dist/trust-proxy.js +45 -0
  48. package/dist/types.d.ts +4 -52
  49. package/dist/types.js +1 -4
  50. package/package.json +24 -14
  51. package/dist/raw-sse.d.ts +0 -49
  52. package/dist/raw-sse.js +0 -92
  53. package/dist/verified-origin/configured-origin.d.ts +0 -37
  54. package/dist/verified-origin/configured-origin.js +0 -99
  55. package/dist/verified-origin/index.d.ts +0 -7
  56. package/dist/verified-origin/index.js +0 -6
  57. package/dist/verified-origin/loopback-host.d.ts +0 -9
  58. package/dist/verified-origin/loopback-host.js +0 -17
  59. package/dist/verified-origin/origin.d.ts +0 -64
  60. package/dist/verified-origin/origin.js +0 -162
  61. package/dist/verified-origin/ports.d.ts +0 -38
  62. package/dist/verified-origin/ports.js +0 -2
  63. package/dist/verified-origin/repo.memory.d.ts +0 -32
  64. package/dist/verified-origin/repo.memory.js +0 -34
  65. package/dist/verified-origin/site-path.d.ts +0 -113
  66. package/dist/verified-origin/site-path.js +0 -188
  67. package/dist/verified-origin/types.d.ts +0 -33
  68. package/dist/verified-origin/types.js +0 -30
  69. package/dist/verified-origin.d.ts +0 -2
  70. package/dist/verified-origin.js +0 -2
@@ -0,0 +1,216 @@
1
+ import { AliasDepthExceededError, DefinitionInvalidError, DefinitionNotFoundError, DefinitionTombstonedError, ForbiddenError, PrincipalNotFoundError, RenameRetypeConflictError, ScopeNotAllowedError, SecretNotSupportedError, ValueValidationFailedError, resolveTargetWorkspaceId, resolveUserLayerReadTarget, settingsWritePermission, } from "@jini-ai/core/settings";
2
+ import { openSettingsChangeStream } from "./stream.js";
3
+ import { failRequest, readValueMutation, resolvePrincipal, SETTING_SCOPES, unauthenticated, VALUE_MUTATION_REQUIRED } from "./http-request.js";
4
+ const VALUE_ERRORS = [
5
+ { matches: (e) => e instanceof PrincipalNotFoundError, status: 404, code: "PRINCIPAL_NOT_FOUND" },
6
+ { matches: (e) => e instanceof DefinitionNotFoundError, status: 404, code: "DEFINITION_NOT_FOUND" },
7
+ { matches: (e) => e instanceof DefinitionTombstonedError, status: 409, code: "DEFINITION_TOMBSTONED" },
8
+ { matches: (e) => e instanceof ScopeNotAllowedError, status: 400, code: "SCOPE_NOT_ALLOWED" },
9
+ { matches: (e) => e instanceof ValueValidationFailedError, status: 400, code: "VALUE_VALIDATION_FAILED" },
10
+ { matches: (e) => e instanceof ForbiddenError, status: 403, code: "FORBIDDEN" },
11
+ ];
12
+ const DEFINITION_ERRORS = [
13
+ { matches: (e) => e instanceof SecretNotSupportedError, status: 400, code: "SECRET_NOT_SUPPORTED" },
14
+ { matches: (e) => e instanceof DefinitionInvalidError, status: 400, code: "DEFINITION_INVALID" },
15
+ { matches: (e) => e instanceof RenameRetypeConflictError, status: 409, code: "RENAME_RETYPE_CONFLICT" },
16
+ { matches: (e) => e instanceof AliasDepthExceededError, status: 409, code: "ALIAS_DEPTH_EXCEEDED" },
17
+ { matches: (e) => e instanceof DefinitionTombstonedError, status: 409, code: "DEFINITION_TOMBSTONED" },
18
+ { matches: (e) => e instanceof ForbiddenError, status: 403, code: "FORBIDDEN" },
19
+ ];
20
+ const RESET_ERRORS = VALUE_ERRORS.filter((m) => m.code === "FORBIDDEN");
21
+ function validation(res, error) {
22
+ res.status(400).json({ error, code: "VALIDATION_ERROR" });
23
+ }
24
+ function denied(res, principalId, permission, reason) {
25
+ res.status(403).json({ error: `principal '${principalId}' is not authorized for '${permission}' (${reason})`,
26
+ code: "FORBIDDEN", details: { permission, reason } });
27
+ }
28
+ function bodyOf(req) {
29
+ return req.body && typeof req.body === "object" && !Array.isArray(req.body) ? req.body : {};
30
+ }
31
+ /** Shared request plumbing: disposal/workspace/auth gate, permission check, and user-layer read target. */
32
+ function createRouteKit(required, optional) {
33
+ const { workspaceId, routes, permissions } = required;
34
+ const state = { disposed: false, streams: new Set() };
35
+ const wrap = (handler, mappings = []) => async (req, res) => {
36
+ if (state.disposed) {
37
+ res.status(503).json({ error: "settings routes are disposed", code: "UNAVAILABLE" });
38
+ return;
39
+ }
40
+ if (String(req.params[routes.workspaceParam] ?? "") !== workspaceId) {
41
+ res.status(404).json({ error: "workspace was not found" });
42
+ return;
43
+ }
44
+ const principal = await resolvePrincipal(required, { request: req, response: res });
45
+ if (!principal) {
46
+ unauthenticated(res);
47
+ return;
48
+ }
49
+ try {
50
+ await handler(req, res, principal.id);
51
+ }
52
+ catch (error) {
53
+ failRequest({ response: res, error, mappings }, optional);
54
+ }
55
+ };
56
+ const check = async (res, principalId, permission, entityType) => {
57
+ const result = await required.authorize({ principalId, permission, workspaceId, entityType });
58
+ if (!result.allowed)
59
+ denied(res, principalId, permission, result.reason);
60
+ return result.allowed;
61
+ };
62
+ const readTarget = async (res, principalId, requestedPrincipalId) => {
63
+ const result = await resolveUserLayerReadTarget({ deps: { workspaceId, authorize: required.authorize, permission: permissions.readOtherUser },
64
+ input: { callerPrincipalId: principalId, requestedPrincipalId } });
65
+ if (!result.allowed)
66
+ res.status(403).json({
67
+ error: `principal '${principalId}' is not authorized to read another principal's user-layer value (${result.reason})`,
68
+ code: "FORBIDDEN", details: { permission: permissions.readOtherUser, reason: result.reason },
69
+ });
70
+ return result;
71
+ };
72
+ return { required, optional, state, wrap, check, readTarget };
73
+ }
74
+ function registerReadRoutes(kit) {
75
+ const { required: { app, workspaceId, service, routes, permissions }, wrap, check, readTarget } = kit;
76
+ app.get(routes.definitions, wrap(async (_req, res, principalId) => {
77
+ if (!await check(res, principalId, permissions.readDefinitions, "setting-definition"))
78
+ return;
79
+ const definitions = await service.listDefinitions({ workspaceId });
80
+ const data = definitions.map(({ namespace, key, ownerKind, scopes, status, version }) => ({ namespace, key, ownerKind, scopes, status, version }))
81
+ .sort((a, b) => a.namespace.localeCompare(b.namespace) || a.key.localeCompare(b.key));
82
+ res.json({ data });
83
+ }));
84
+ app.get(routes.effective, wrap(async (req, res, principalId) => {
85
+ if (!await check(res, principalId, permissions.read, "setting-value"))
86
+ return;
87
+ const namespace = String(req.query.namespace ?? "");
88
+ if (!namespace) {
89
+ validation(res, "'namespace' query param is required");
90
+ return;
91
+ }
92
+ const target = await readTarget(res, principalId, req.query.principalId ? String(req.query.principalId) : principalId);
93
+ if (!target.allowed)
94
+ return;
95
+ res.json({ data: await service.effective({ namespace, workspaceId, principalId: target.principalId }) });
96
+ }));
97
+ app.get(routes.raw, wrap(async (req, res, principalId) => {
98
+ if (!await check(res, principalId, permissions.readRaw, "setting-value"))
99
+ return;
100
+ const namespace = String(req.query.namespace ?? "");
101
+ const key = String(req.query.key ?? "");
102
+ if (!namespace || !key) {
103
+ validation(res, "'namespace' and 'key' query params are required");
104
+ return;
105
+ }
106
+ const target = await readTarget(res, principalId, req.query.principalId ? String(req.query.principalId) : undefined);
107
+ if (!target.allowed)
108
+ return;
109
+ const result = await service.raw({ namespace, key, workspaceId, principalId: target.principalId });
110
+ if (!result) {
111
+ res.status(404).json({ error: `definition '${namespace}.${key}' was not found`, code: "DEFINITION_NOT_FOUND" });
112
+ return;
113
+ }
114
+ res.json(result);
115
+ }));
116
+ }
117
+ function registerDefinitionWriteRoute(kit) {
118
+ const { required: { app, workspaceId, service, routes, permissions }, wrap, check } = kit;
119
+ app.post(routes.definitions, wrap(async (req, res, principalId) => {
120
+ if (!await check(res, principalId, permissions.manageDefinitions, "setting-definition"))
121
+ return;
122
+ const items = bodyOf(req).definitions;
123
+ if (!Array.isArray(items)) {
124
+ validation(res, "'definitions' must be an array");
125
+ return;
126
+ }
127
+ const result = await service.definitions({ items, callerPrincipalId: principalId, authWorkspaceId: workspaceId });
128
+ if ("unknownOp" in result) {
129
+ validation(res, `unknown op '${result.unknownOp}'`);
130
+ return;
131
+ }
132
+ res.json(result);
133
+ }, DEFINITION_ERRORS));
134
+ }
135
+ function registerValueRoutes(kit) {
136
+ const { required: { app, workspaceId, service, routes, permissions }, wrap, check } = kit;
137
+ const mutate = (operation) => async (req, res, callerPrincipalId) => {
138
+ const body = bodyOf(req);
139
+ const fields = readValueMutation({ body, operation });
140
+ if (!fields) {
141
+ validation(res, VALUE_MUTATION_REQUIRED[operation]);
142
+ return;
143
+ }
144
+ const { namespace, key, scope } = fields;
145
+ const target = resolveTargetWorkspaceId({ workspaceId, input: { bodyWorkspaceId: body.workspaceId, scope } });
146
+ if (!target.ok) {
147
+ validation(res, target.error);
148
+ return;
149
+ }
150
+ const principalId = body.principalId ? String(body.principalId) : undefined;
151
+ const permission = settingsWritePermission({ permissions, scope, callerPrincipalId, targetPrincipalId: principalId });
152
+ if (!await check(res, callerPrincipalId, permission, "setting-value"))
153
+ return;
154
+ const input = { namespace, key, scope, workspaceId: target.workspaceId, principalId, callerPrincipalId, authWorkspaceId: workspaceId };
155
+ const result = operation === "set" ? await service.set({ ...input, value: body.valueJson }) : await service.clear(input);
156
+ res.json({ key: `${namespace}.${key}`, scope, value: "value" in result ? result.value : null, revisionSeq: result.revisionSeq });
157
+ };
158
+ app.put(routes.value, wrap(mutate("set"), VALUE_ERRORS));
159
+ app.delete(routes.value, wrap(mutate("clear"), VALUE_ERRORS.filter((m) => m.code !== "VALUE_VALIDATION_FAILED")));
160
+ app.post(routes.reset, wrap(async (req, res, callerPrincipalId) => {
161
+ const body = bodyOf(req);
162
+ const namespace = String(body.namespace ?? "");
163
+ const scope = body.scope;
164
+ if (!namespace || !SETTING_SCOPES.includes(scope)) {
165
+ validation(res, "namespace and scope (global|workspace|user) are required");
166
+ return;
167
+ }
168
+ const target = resolveTargetWorkspaceId({ workspaceId, input: { bodyWorkspaceId: body.workspaceId, scope } });
169
+ if (!target.ok) {
170
+ validation(res, target.error);
171
+ return;
172
+ }
173
+ if (!await check(res, callerPrincipalId, permissions.reset[scope], "setting-namespace"))
174
+ return;
175
+ const result = await service.reset({ namespace, scope, workspaceId: target.workspaceId, callerPrincipalId, authWorkspaceId: workspaceId });
176
+ res.json({ namespace, ...result });
177
+ }, RESET_ERRORS));
178
+ }
179
+ function registerEventsRoute(kit) {
180
+ const { required, optional, state, wrap, check } = kit;
181
+ const { app, workspaceId, routes, permissions } = required;
182
+ app.get(routes.events, wrap(async (req, res, principalId) => {
183
+ if (!await check(res, principalId, permissions.read, "setting-value"))
184
+ return;
185
+ const close = await openSettingsChangeStream({ request: req, response: res, workspaceId, principalId,
186
+ changeFeed: required.changeFeed, authorize: required.authorize, permission: permissions.read, scheduler: required.scheduler,
187
+ onClose: ({ close }) => { state.streams.delete(close); }, isDisposed: () => state.disposed }, optional);
188
+ if (state.disposed) {
189
+ close();
190
+ return;
191
+ }
192
+ if (!res.destroyed && !res.writableEnded)
193
+ state.streams.add(close);
194
+ }));
195
+ }
196
+ /** Mount all eight endpoints. The returned disposer closes active feeds and cancels their schedules.
197
+ * Injected policy and services preserve the settings HTTP response envelopes.
198
+ * O(1) mounting; read/mutation work is delegated. Feed resources are bounded per connection.
199
+ * @example registerSettingsRoutes({ app, workspaceId, ready, service, changeFeed, principalResolver, authorize, scheduler, routes, permissions });
200
+ */
201
+ export function registerSettingsRoutes(required, optional = {}) {
202
+ const kit = createRouteKit(required, optional);
203
+ registerReadRoutes(kit);
204
+ registerDefinitionWriteRoute(kit);
205
+ registerValueRoutes(kit);
206
+ registerEventsRoute(kit);
207
+ return {
208
+ dispose: () => {
209
+ kit.state.disposed = true;
210
+ for (const close of kit.state.streams)
211
+ close();
212
+ kit.state.streams.clear();
213
+ },
214
+ };
215
+ }
216
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1,4 @@
1
+ export type { PrincipalResolver, Scheduler, SettingsRoutes, SettingsHttpRequired, SettingsHttpOptions, } from "./contracts.js";
2
+ export { respondToSettingsError, type SettingsErrorMapping } from "./shared.js";
3
+ export { registerSettingsRoutes } from "./http.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,3 @@
1
+ export { respondToSettingsError } from "./shared.js";
2
+ export { registerSettingsRoutes } from "./http.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,16 @@
1
+ import type { Response } from "express";
2
+ export interface SettingsErrorMapping {
3
+ readonly matches: (error: unknown) => boolean;
4
+ readonly status: number;
5
+ readonly code: string;
6
+ }
7
+ /** Write the first matching status/code, or a fixed 500 that does not disclose unknown errors.
8
+ * @complexity O(mapping count) time, O(1) space; response write effect.
9
+ * @example respondToSettingsError({ response, error, mappings });
10
+ */
11
+ export declare function respondToSettingsError(required: {
12
+ response: Pick<Response, "status" | "json">;
13
+ error: unknown;
14
+ mappings: readonly SettingsErrorMapping[];
15
+ }): void;
16
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1,16 @@
1
+ /** Write the first matching status/code, or a fixed 500 that does not disclose unknown errors.
2
+ * @complexity O(mapping count) time, O(1) space; response write effect.
3
+ * @example respondToSettingsError({ response, error, mappings });
4
+ */
5
+ export function respondToSettingsError(required) {
6
+ const { response, error, mappings } = required;
7
+ const message = error instanceof Error ? error.message : String(error);
8
+ for (const mapping of mappings) {
9
+ if (mapping.matches(error)) {
10
+ response.status(mapping.status).json({ error: message, code: mapping.code });
11
+ return;
12
+ }
13
+ }
14
+ response.status(500).json({ error: "internal error", code: "INTERNAL_ERROR" });
15
+ }
16
+ //# sourceMappingURL=shared.js.map
@@ -0,0 +1,25 @@
1
+ import type { Request, Response } from "express";
2
+ import type { Authorize, SettingsChangeFeed } from "@jini-ai/core/settings";
3
+ import type { SettingsHttpOptions, Scheduler } from "./contracts.js";
4
+ interface StreamRequired {
5
+ request: Request;
6
+ response: Response;
7
+ workspaceId: string;
8
+ principalId: string;
9
+ changeFeed: SettingsChangeFeed;
10
+ authorize: Authorize;
11
+ permission: string;
12
+ scheduler: Scheduler;
13
+ onClose: (required: {
14
+ close: () => void;
15
+ }) => void;
16
+ isDisposed: () => boolean;
17
+ }
18
+ /** Starts after HTTP authorization. All scheduling and storage are injected.
19
+ * Poll with bounded pages, tenant-scoped ids and retryable reads; close cancels all schedules.
20
+ * O(page size) per tick and O(1) connection state; repository effects live behind the feed port.
21
+ * Invalid scheduler intervals/page sizes throw RangeError before opening; initial read errors propagate.
22
+ */
23
+ export declare function openSettingsChangeStream(required: StreamRequired, optional?: SettingsHttpOptions): Promise<() => void>;
24
+ export {};
25
+ //# sourceMappingURL=stream.d.ts.map
@@ -0,0 +1,180 @@
1
+ import { createConsoleLogger } from "@jini-ai/core/primitives";
2
+ /** One poll step: collect a bounded page and emit a settings-changed event; overlapping ticks are skipped. */
3
+ function createPollTick({ response, changeFeed, viewer, pageSize, cursor: initialCursor, isClosed, reportError }) {
4
+ let cursor = initialCursor;
5
+ let lastEmittedId = initialCursor;
6
+ let ticking = false;
7
+ return async () => {
8
+ if (isClosed() || ticking)
9
+ return;
10
+ ticking = true;
11
+ try {
12
+ // Snapshot head before the page: concurrent writes must never be skipped.
13
+ const ledgerHead = await changeFeed.head({});
14
+ if (isClosed())
15
+ return;
16
+ const batch = await changeFeed.collect({ sinceSeq: cursor, limit: pageSize, viewer });
17
+ if (isClosed())
18
+ return;
19
+ const examined = batch.examinedCount < pageSize ? ledgerHead : batch.cursor;
20
+ cursor = Math.max(cursor, examined, batch.cursor);
21
+ if (!batch.namespaces.length)
22
+ return;
23
+ // The internal global head is never disclosed as an event id.
24
+ lastEmittedId = Math.max(lastEmittedId, batch.cursor);
25
+ response.write(`id: ${lastEmittedId}\nevent: settings-changed\ndata: ${JSON.stringify({ namespaces: batch.namespaces })}\n\n`);
26
+ }
27
+ catch (error) {
28
+ if (!isClosed())
29
+ reportError("poll", error);
30
+ }
31
+ finally {
32
+ ticking = false;
33
+ }
34
+ };
35
+ }
36
+ /** Periodic re-authorization: closes the stream once the principal loses the permission. */
37
+ function createReauthorizer({ required, isClosed, close, reportError }) {
38
+ let checkingAuthorization = false;
39
+ return async () => {
40
+ if (isClosed() || checkingAuthorization)
41
+ return;
42
+ checkingAuthorization = true;
43
+ try {
44
+ const { principalId, workspaceId, permission } = required;
45
+ const result = await required.authorize({ principalId, workspaceId, permission, entityType: "setting-value" });
46
+ if (!isClosed() && !result.allowed)
47
+ close();
48
+ }
49
+ catch (error) {
50
+ if (!isClosed())
51
+ reportError("re-authorization", error);
52
+ }
53
+ finally {
54
+ checkingAuthorization = false;
55
+ }
56
+ };
57
+ }
58
+ /** Starts after HTTP authorization. All scheduling and storage are injected.
59
+ * Poll with bounded pages, tenant-scoped ids and retryable reads; close cancels all schedules.
60
+ * O(page size) per tick and O(1) connection state; repository effects live behind the feed port.
61
+ * Invalid scheduler intervals/page sizes throw RangeError before opening; initial read errors propagate.
62
+ */
63
+ export async function openSettingsChangeStream(required, optional = {}) {
64
+ const { request, response, workspaceId, principalId, changeFeed, scheduler } = required;
65
+ const { pageSize, pollIntervalMs, keepaliveIntervalMs, reauthorizeIntervalMs } = readStreamTimings(optional);
66
+ let closed = false;
67
+ const cancellations = [];
68
+ const reportError = createErrorReporter(optional);
69
+ const recover = (operation, effect) => {
70
+ try {
71
+ effect();
72
+ }
73
+ catch (error) {
74
+ reportError(operation, error);
75
+ }
76
+ };
77
+ const release = () => {
78
+ // Every resource gets its own recovery boundary so one failing cancellation cannot leak others.
79
+ for (const cancel of cancellations.splice(0))
80
+ recover("cancel", cancel);
81
+ recover("request-listener", () => { request.off("close", close); });
82
+ recover("response-listener", () => { response.off("close", close); });
83
+ };
84
+ const close = () => {
85
+ if (closed)
86
+ return;
87
+ closed = true;
88
+ release();
89
+ recover("close", () => { required.onClose({ close }); });
90
+ if (!response.writableEnded && !response.destroyed)
91
+ recover("end", () => { response.end(); });
92
+ };
93
+ request.on("close", close);
94
+ response.on("close", close);
95
+ try {
96
+ const head = await changeFeed.head({});
97
+ const gone = () => closed || required.isDisposed() || response.destroyed || response.writableEnded;
98
+ if (gone()) {
99
+ close();
100
+ return close;
101
+ }
102
+ const cursor = resumeCursor({ lastEventId: request.headers["last-event-id"], head });
103
+ response.writeHead(200, sseHeaders({ httpVersionMajor: request.httpVersionMajor }));
104
+ const tick = createPollTick({ response, changeFeed, viewer: { workspaceId, principalId }, pageSize, cursor, isClosed: () => closed, reportError });
105
+ const reauthorize = createReauthorizer({ required, isClosed: () => closed, close, reportError });
106
+ const schedule = (intervalMs, callback) => {
107
+ const cancel = scheduler.every({ intervalMs, callback });
108
+ if (closed)
109
+ recover("cancel", cancel);
110
+ else
111
+ cancellations.push(cancel);
112
+ };
113
+ schedule(pollIntervalMs, () => { void tick(); });
114
+ schedule(keepaliveIntervalMs, () => {
115
+ if (closed)
116
+ return;
117
+ try {
118
+ response.write(": keepalive\n\n");
119
+ }
120
+ catch (error) {
121
+ reportError("keepalive", error);
122
+ close();
123
+ }
124
+ });
125
+ schedule(reauthorizeIntervalMs, () => { void reauthorize(); });
126
+ if (!closed)
127
+ response.write(": connected\n\n");
128
+ return close;
129
+ }
130
+ catch (error) {
131
+ // Cancel schedules even when opening a feed fails. Let the HTTP wrapper map the error.
132
+ if (response.headersSent)
133
+ close();
134
+ else {
135
+ closed = true;
136
+ release();
137
+ }
138
+ throw error;
139
+ }
140
+ }
141
+ /** Fill the documented defaults, then refuse any non-positive page size or interval before an effect. Pure. */
142
+ function readStreamTimings(optional) {
143
+ const timings = {
144
+ pageSize: optional.revisionPageSize ?? 200,
145
+ pollIntervalMs: optional.pollIntervalMs ?? 1_000,
146
+ keepaliveIntervalMs: optional.keepaliveIntervalMs ?? 25_000,
147
+ reauthorizeIntervalMs: optional.reauthorizeIntervalMs ?? 30_000,
148
+ };
149
+ const intervals = [timings.pollIntervalMs, timings.keepaliveIntervalMs, timings.reauthorizeIntervalMs];
150
+ if (!Number.isSafeInteger(timings.pageSize) || timings.pageSize <= 0 || intervals.some((n) => !Number.isFinite(n) || n <= 0)) {
151
+ throw new RangeError("settings feed page size and intervals must be positive");
152
+ }
153
+ return timings;
154
+ }
155
+ function createErrorReporter(optional) {
156
+ const settingsLogger = createConsoleLogger({ prefix: '[settings]' });
157
+ return (operation, error) => {
158
+ // Reporting is best-effort: a host hook must never turn recovery into an unhandled rejection.
159
+ try {
160
+ if (optional.onError)
161
+ optional.onError({ operation, error });
162
+ else
163
+ settingsLogger.error({ message: `change feed ${operation} failed` }, { error });
164
+ }
165
+ catch { /* Diagnostic failures cannot interrupt stream cleanup or retries. */ }
166
+ };
167
+ }
168
+ /** A client's Last-Event-ID resumes at or before the ledger head; a missing or unusable id starts at head. Pure. */
169
+ function resumeCursor(required) {
170
+ const resumeFrom = Number(required.lastEventId);
171
+ return Number.isFinite(resumeFrom) && resumeFrom >= 0 ? Math.min(resumeFrom, required.head) : required.head;
172
+ }
173
+ /** HTTP/2 forbids the Connection header; HTTP/1 needs it to keep the stream open. Pure. */
174
+ function sseHeaders(required) {
175
+ return {
176
+ "Content-Type": "text/event-stream", "Cache-Control": "no-cache, no-transform",
177
+ ...(required.httpVersionMajor < 2 ? { Connection: "keep-alive" } : {}), "X-Accel-Buffering": "no",
178
+ };
179
+ }
180
+ //# sourceMappingURL=stream.js.map
package/dist/sse.d.ts CHANGED
@@ -21,22 +21,8 @@
21
21
  * invented-from-scratch design.
22
22
  */
23
23
  import type { ServerResponse } from 'node:http';
24
+ import { type SseEvent } from '@jini-ai/core/contracts/server';
24
25
  import { type ApiError } from '@jini-ai/protocol';
25
- /** The minimal shape any event needs to flow through an `SseChannel`: an id for `Last-Event-ID` reconnect bookkeeping and a `kind` used as the wire `event:` field. */
26
- export interface SseEvent {
27
- readonly opaqueCursor: string;
28
- readonly kind: string;
29
- }
30
- /**
31
- * Cap on events queued for one client — covers both a pre-header replay
32
- * burst and any backlog built up while `res.write` reports backpressure
33
- * (`write() === false`, awaiting `'drain'`). A stalled or malicious client
34
- * would otherwise let an unbounded producer grow this array without limit
35
- * (SEC-006, carried forward from `runs.ts`'s original constant). Once
36
- * exceeded, the connection is dropped rather than accepting unbounded
37
- * memory growth.
38
- */
39
- export declare const DEFAULT_MAX_QUEUED_SSE_EVENTS = 1000;
40
26
  export interface CreateSseChannelOptions<E extends SseEvent> {
41
27
  /** Queued-event ceiling before the connection is dropped. Defaults to {@link DEFAULT_MAX_QUEUED_SSE_EVENTS}. */
42
28
  readonly maxQueuedEvents?: number;