@brickkit/core 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/chunks/client.d.ts +13 -1862
- package/dist/chunks/client.js +328 -83
- package/dist/chunks/client.js.map +1 -1
- package/dist/chunks/index.d.ts +1106 -0
- package/dist/chunks/server.js +4624 -0
- package/dist/chunks/server.js.map +1 -0
- package/dist/chunks/types.d.ts +2701 -0
- package/dist/chunks/workflow.d.ts +74 -0
- package/dist/client.d.ts +3 -2
- package/dist/index.d.ts +5 -1076
- package/dist/index.js +756 -3726
- package/dist/index.js.map +1 -1
- package/dist/pg.d.ts +0 -2
- package/dist/tanstack-query.d.ts +2 -3
- package/dist/tanstack-query.js +1 -2
- package/dist/testing.d.ts +31 -0
- package/dist/testing.js +47 -0
- package/dist/testing.js.map +1 -0
- package/dist/workflow.d.ts +2 -0
- package/dist/workflow.js +93 -0
- package/dist/workflow.js.map +1 -0
- package/package.json +32 -18
- package/dist/chunks/client.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/pg.d.ts.map +0 -1
- package/dist/tanstack-query.d.ts.map +0 -1
package/dist/chunks/client.js
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import { Kind, TransformKind } from "@sinclair/typebox";
|
|
2
2
|
import { Check } from "@sinclair/typebox/value";
|
|
3
|
-
|
|
3
|
+
// src/kebab.ts
|
|
4
|
+
/**
|
|
5
|
+
* The URL segment for a declared name: `orderBilling` becomes `order-billing`,
|
|
6
|
+
* `importCSV` becomes `import-csv`. Dots and existing dashes stay.
|
|
7
|
+
*/
|
|
8
|
+
function kebabCase(name) {
|
|
9
|
+
return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").toLowerCase();
|
|
10
|
+
}
|
|
11
|
+
// src/types.ts
|
|
4
12
|
var ValidationError = class extends Error {
|
|
5
13
|
code = "VALIDATION_FAILED";
|
|
6
14
|
status;
|
|
@@ -42,8 +50,7 @@ var ActionExecutionError = class extends Error {
|
|
|
42
50
|
};
|
|
43
51
|
}
|
|
44
52
|
};
|
|
45
|
-
|
|
46
|
-
//#region src/socket-schema.ts
|
|
53
|
+
// src/socket-schema.ts
|
|
47
54
|
const kinds = /* @__PURE__ */ new Set([
|
|
48
55
|
"Array",
|
|
49
56
|
"Boolean",
|
|
@@ -93,10 +100,23 @@ function restoreSocketSchema(value) {
|
|
|
93
100
|
function isSocketEnvelope(value) {
|
|
94
101
|
return value !== null && typeof value === "object" && !Array.isArray(value) && "event" in value && typeof value.event === "string" && "data" in value && Object.keys(value).length === 2;
|
|
95
102
|
}
|
|
103
|
+
/** `prefix:value`, at most 200 bytes, without control characters. */
|
|
104
|
+
function isSocketRoom(value) {
|
|
105
|
+
return typeof value === "string" && /^[A-Za-z][\w-]*:[^\u0000-\u001f\u007f]+$/.test(value) && new TextEncoder().encode(value).byteLength <= 200;
|
|
106
|
+
}
|
|
107
|
+
/** A replay sequence: `<number>-<number>`, the shape of a Redis stream id, then `.` and the server's signature for its room. */
|
|
108
|
+
function isSocketSeq(value) {
|
|
109
|
+
return typeof value === "string" && /^\d{1,20}-\d{1,20}\.[\w-]{22}$/.test(value);
|
|
110
|
+
}
|
|
111
|
+
function compareSocketSeq(a, b) {
|
|
112
|
+
const [a1, a2] = a.split(".")[0].split("-").map(BigInt);
|
|
113
|
+
const [b1, b2] = b.split(".")[0].split("-").map(BigInt);
|
|
114
|
+
if (a1 !== b1) return a1 > b1 ? 1 : -1;
|
|
115
|
+
return a2 === b2 ? 0 : a2 > b2 ? 1 : -1;
|
|
116
|
+
}
|
|
96
117
|
const SOCKET_MAX_BYTES = 65536;
|
|
97
118
|
const SOCKET_BUFFER_BYTES = 1048576;
|
|
98
|
-
|
|
99
|
-
//#region src/socket-types.ts
|
|
119
|
+
// src/socket-types.ts
|
|
100
120
|
var BrickSocketError = class extends Error {
|
|
101
121
|
kind;
|
|
102
122
|
constructor(kind, message, options) {
|
|
@@ -105,8 +125,20 @@ var BrickSocketError = class extends Error {
|
|
|
105
125
|
this.name = "BrickSocketError";
|
|
106
126
|
}
|
|
107
127
|
};
|
|
108
|
-
|
|
109
|
-
|
|
128
|
+
// src/socket-client.ts
|
|
129
|
+
/** Normal close, policy and auth refusals, protocol errors: retrying would not help. */
|
|
130
|
+
const STOP_CODES = /* @__PURE__ */ new Set([
|
|
131
|
+
1e3,
|
|
132
|
+
1003,
|
|
133
|
+
1007,
|
|
134
|
+
1008,
|
|
135
|
+
1009,
|
|
136
|
+
4e3,
|
|
137
|
+
4401,
|
|
138
|
+
4403
|
|
139
|
+
]);
|
|
140
|
+
/** RFC 6455 subprotocols are RFC 7230 tokens. */
|
|
141
|
+
const TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
110
142
|
function connectSocket(baseUrl, contract, options) {
|
|
111
143
|
const url = new URL(`${baseUrl.replace(/\/$/, "")}${contract.config.path}`);
|
|
112
144
|
if (![
|
|
@@ -117,47 +149,88 @@ function connectSocket(baseUrl, contract, options) {
|
|
|
117
149
|
].includes(url.protocol)) throw new Error("Invalid socket URL protocol");
|
|
118
150
|
url.protocol = url.protocol === "https:" || url.protocol === "wss:" ? "wss:" : "ws:";
|
|
119
151
|
if (url.search || url.hash) throw new Error("Socket base URL must not contain a query or fragment");
|
|
152
|
+
if (options.timeoutMs !== void 0 && (!Number.isFinite(options.timeoutMs) || options.timeoutMs < 0)) throw new Error("Socket timeoutMs must be a finite nonnegative number");
|
|
153
|
+
const backoff = options.reconnect === false ? void 0 : {
|
|
154
|
+
minDelayMs: 500,
|
|
155
|
+
maxDelayMs: 3e4,
|
|
156
|
+
jitter: .2,
|
|
157
|
+
...options.reconnect
|
|
158
|
+
};
|
|
159
|
+
if (backoff && !(backoff.minDelayMs >= 0 && backoff.maxDelayMs >= backoff.minDelayMs && Number.isFinite(backoff.maxDelayMs) && backoff.jitter >= 0 && backoff.jitter <= 1)) throw new Error("Socket reconnect needs 0 <= minDelayMs <= maxDelayMs and jitter from 0 to 1");
|
|
120
160
|
const schemas = new Map(Object.entries(contract.output).map(([name, schema]) => [name, restoreSocketSchema(schema)]));
|
|
121
161
|
const events = /* @__PURE__ */ new Map();
|
|
122
162
|
const errors = /* @__PURE__ */ new Set();
|
|
163
|
+
const failures = /* @__PURE__ */ new Set();
|
|
123
164
|
const closes = /* @__PURE__ */ new Set();
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
165
|
+
const leaves = /* @__PURE__ */ new Set();
|
|
166
|
+
const statuses = /* @__PURE__ */ new Set();
|
|
167
|
+
const reconnects = /* @__PURE__ */ new Set();
|
|
168
|
+
const gaps = /* @__PURE__ */ new Set();
|
|
169
|
+
/** The last sequence seen per room, for sockets with replay. */
|
|
170
|
+
const seqs = /* @__PURE__ */ new Map();
|
|
171
|
+
/** Rooms the server accepted for this client, rejoined after a reconnect. */
|
|
172
|
+
const rooms = /* @__PURE__ */ new Set();
|
|
173
|
+
const joins = /* @__PURE__ */ new Map();
|
|
174
|
+
const ready = Promise.withResolvers();
|
|
175
|
+
ready.promise.catch(() => {});
|
|
176
|
+
let status = "connecting";
|
|
131
177
|
let opened = false;
|
|
132
|
-
let
|
|
178
|
+
let openedAt = 0;
|
|
179
|
+
let attempts = 0;
|
|
180
|
+
let attempting = false;
|
|
133
181
|
let ws;
|
|
134
182
|
let timer;
|
|
183
|
+
let retry;
|
|
135
184
|
const signal = options.signal;
|
|
185
|
+
const page = globalThis.document;
|
|
136
186
|
const report = (error) => {
|
|
137
187
|
for (const listener of errors) listener(error);
|
|
138
188
|
};
|
|
139
|
-
const
|
|
140
|
-
if (
|
|
141
|
-
|
|
189
|
+
const setStatus = (next) => {
|
|
190
|
+
if (status === next) return;
|
|
191
|
+
status = next;
|
|
192
|
+
for (const listener of statuses) listener(next);
|
|
193
|
+
};
|
|
194
|
+
const settleJoins = (error) => {
|
|
195
|
+
for (const settle of [...joins.values()].flat()) settle(error);
|
|
196
|
+
joins.clear();
|
|
197
|
+
};
|
|
198
|
+
const detach = () => {
|
|
142
199
|
clearTimeout(timer);
|
|
200
|
+
if (!ws) return;
|
|
201
|
+
ws.onopen = null;
|
|
202
|
+
ws.onerror = null;
|
|
203
|
+
ws.onmessage = null;
|
|
204
|
+
ws.onclose = null;
|
|
205
|
+
};
|
|
206
|
+
/** Ends the client for good. */
|
|
207
|
+
const finish = (info, error) => {
|
|
208
|
+
if (status === "closed") return;
|
|
209
|
+
detach();
|
|
210
|
+
clearTimeout(retry);
|
|
143
211
|
signal?.removeEventListener("abort", abort);
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
ws.onclose = null;
|
|
149
|
-
}
|
|
150
|
-
if (!opened) rejectReady(error ?? new BrickSocketError("connection", "Socket closed before opening"));
|
|
212
|
+
globalThis.removeEventListener?.("online", wake);
|
|
213
|
+
page?.removeEventListener("visibilitychange", wake);
|
|
214
|
+
if (!opened) ready.reject(error ?? new BrickSocketError("connection", "Socket closed before opening"));
|
|
215
|
+
settleJoins(new BrickSocketError("connection", "Socket closed before joining"));
|
|
151
216
|
try {
|
|
217
|
+
setStatus("closed");
|
|
152
218
|
for (const listener of closes) listener(info);
|
|
153
219
|
} finally {
|
|
154
220
|
events.clear();
|
|
155
|
-
|
|
156
|
-
|
|
221
|
+
for (const listeners of [
|
|
222
|
+
errors,
|
|
223
|
+
failures,
|
|
224
|
+
closes,
|
|
225
|
+
leaves,
|
|
226
|
+
statuses,
|
|
227
|
+
reconnects,
|
|
228
|
+
gaps
|
|
229
|
+
]) listeners.clear();
|
|
157
230
|
}
|
|
158
231
|
};
|
|
159
232
|
const stop = (error, code = 1e3, reason = "") => {
|
|
160
|
-
if (
|
|
233
|
+
if (status === "closed") return;
|
|
161
234
|
try {
|
|
162
235
|
if (error instanceof BrickSocketError) report(error);
|
|
163
236
|
} finally {
|
|
@@ -171,11 +244,218 @@ function connectSocket(baseUrl, contract, options) {
|
|
|
171
244
|
}
|
|
172
245
|
}
|
|
173
246
|
};
|
|
174
|
-
|
|
247
|
+
/** The connection ended without `close()`: retry unless the code says not to. */
|
|
248
|
+
const dropped = (info, error) => {
|
|
249
|
+
if (status === "closed") return;
|
|
250
|
+
detach();
|
|
251
|
+
ws = void 0;
|
|
252
|
+
if (error) report(error);
|
|
253
|
+
if (!backoff || STOP_CODES.has(info.code)) return finish(info, error);
|
|
254
|
+
settleJoins(new BrickSocketError("connection", "Socket closed before joining"));
|
|
255
|
+
if (openedAt && Date.now() - openedAt >= 1e4) attempts = 0;
|
|
256
|
+
openedAt = 0;
|
|
257
|
+
setStatus("reconnecting");
|
|
258
|
+
for (const listener of closes) listener(info);
|
|
259
|
+
schedule();
|
|
260
|
+
};
|
|
261
|
+
const schedule = () => {
|
|
262
|
+
if (status !== "reconnecting" || attempting || retry !== void 0) return;
|
|
263
|
+
if (globalThis.navigator?.onLine === false) return;
|
|
264
|
+
const delay = Math.min(backoff.maxDelayMs, backoff.minDelayMs * 2 ** attempts++);
|
|
265
|
+
retry = setTimeout(() => {
|
|
266
|
+
retry = void 0;
|
|
267
|
+
attempt();
|
|
268
|
+
}, delay * (1 + backoff.jitter * (Math.random() * 2 - 1)));
|
|
269
|
+
};
|
|
270
|
+
function wake() {
|
|
271
|
+
if (status !== "reconnecting" || attempting || ws || page?.visibilityState === "hidden") return;
|
|
272
|
+
clearTimeout(retry);
|
|
273
|
+
retry = void 0;
|
|
274
|
+
attempt();
|
|
275
|
+
}
|
|
276
|
+
const attempt = async () => {
|
|
277
|
+
attempting = true;
|
|
278
|
+
let protocols;
|
|
279
|
+
try {
|
|
280
|
+
if (options.token) {
|
|
281
|
+
let token;
|
|
282
|
+
try {
|
|
283
|
+
token = await options.token();
|
|
284
|
+
} catch (cause) {
|
|
285
|
+
attempting = false;
|
|
286
|
+
return dropped({
|
|
287
|
+
code: 1006,
|
|
288
|
+
reason: ""
|
|
289
|
+
}, new BrickSocketError("connection", "Socket token failed", { cause }));
|
|
290
|
+
}
|
|
291
|
+
if (status === "closed") return;
|
|
292
|
+
if (typeof token !== "string" || !TOKEN.test(token)) return stop(new BrickSocketError("protocol", "Socket token must use RFC 6455 token characters, such as a JWT or base64url without = padding"));
|
|
293
|
+
protocols = ["brick.v1", `brick.token.${token}`];
|
|
294
|
+
}
|
|
295
|
+
try {
|
|
296
|
+
ws = protocols ? new WebSocket(url, protocols) : new WebSocket(url);
|
|
297
|
+
} catch (cause) {
|
|
298
|
+
attempting = false;
|
|
299
|
+
return dropped({
|
|
300
|
+
code: 1006,
|
|
301
|
+
reason: ""
|
|
302
|
+
}, new BrickSocketError("connection", "Socket connection failed", { cause }));
|
|
303
|
+
}
|
|
304
|
+
} finally {
|
|
305
|
+
attempting = false;
|
|
306
|
+
}
|
|
307
|
+
const failed = (message) => {
|
|
308
|
+
const socket = ws;
|
|
309
|
+
dropped({
|
|
310
|
+
code: 1006,
|
|
311
|
+
reason: ""
|
|
312
|
+
}, new BrickSocketError("connection", message));
|
|
313
|
+
socket?.close();
|
|
314
|
+
};
|
|
315
|
+
ws.onopen = () => {
|
|
316
|
+
clearTimeout(timer);
|
|
317
|
+
openedAt = Date.now();
|
|
318
|
+
setStatus("open");
|
|
319
|
+
if (!opened) {
|
|
320
|
+
opened = true;
|
|
321
|
+
ready.resolve();
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
for (const room of rooms) request(room, seqs.get(room)).catch(() => {});
|
|
325
|
+
for (const room of seqs.keys()) if (!rooms.has(room)) {
|
|
326
|
+
seqs.delete(room);
|
|
327
|
+
notifyGap(room);
|
|
328
|
+
}
|
|
329
|
+
for (const listener of reconnects) listener();
|
|
330
|
+
};
|
|
331
|
+
ws.onerror = () => failed("Socket connection failed");
|
|
332
|
+
ws.onclose = ({ code, reason }) => dropped({
|
|
333
|
+
code,
|
|
334
|
+
reason
|
|
335
|
+
});
|
|
336
|
+
ws.onmessage = receive;
|
|
337
|
+
if (options.timeoutMs !== void 0) timer = setTimeout(() => failed("Socket connection timed out"), options.timeoutMs);
|
|
338
|
+
};
|
|
339
|
+
const write = (event, data) => {
|
|
340
|
+
if (!ws || status !== "open" || ws.readyState !== 1) throw new BrickSocketError("connection", "Socket is not open");
|
|
341
|
+
ws.send(JSON.stringify({
|
|
342
|
+
event,
|
|
343
|
+
data
|
|
344
|
+
}));
|
|
345
|
+
};
|
|
346
|
+
const request = (room, since) => new Promise((resolve, reject) => {
|
|
347
|
+
write("$join", since === void 0 ? { room } : {
|
|
348
|
+
room,
|
|
349
|
+
since
|
|
350
|
+
});
|
|
351
|
+
joins.set(room, [...joins.get(room) ?? [], (result) => result === true ? resolve() : reject(result || new BrickSocketError("refused", `Join refused: ${room}`))]);
|
|
352
|
+
});
|
|
353
|
+
const notifyLeave = (room, reason) => {
|
|
354
|
+
seqs.delete(room);
|
|
355
|
+
for (const listener of leaves) listener(room, reason);
|
|
356
|
+
};
|
|
357
|
+
const notifyGap = (room) => {
|
|
358
|
+
for (const listener of gaps) listener(room);
|
|
359
|
+
};
|
|
360
|
+
/** Checks a room acknowledgement or removal; returns the work to run once it passed. */
|
|
361
|
+
const control = (event, data) => {
|
|
362
|
+
const fields = data ?? {};
|
|
363
|
+
if (event === "$error") {
|
|
364
|
+
const { event: input, code, message, status, details } = fields;
|
|
365
|
+
if (typeof input !== "string" || typeof code !== "string" || typeof message !== "string" || typeof status !== "number") throw new Error("Invalid control message");
|
|
366
|
+
return () => {
|
|
367
|
+
const failure = Object.assign(new ActionExecutionError(code, message, status, details), { event: input });
|
|
368
|
+
for (const listener of failures) listener(failure);
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
const { room, seq } = fields;
|
|
372
|
+
if (!isSocketRoom(room) || seq !== void 0 && !isSocketSeq(seq)) throw new Error("Invalid control message");
|
|
373
|
+
if (event === "$join" && typeof fields.ok === "boolean") {
|
|
374
|
+
const ok = fields.ok;
|
|
375
|
+
return () => {
|
|
376
|
+
const pending = joins.get(room);
|
|
377
|
+
if (!pending) return;
|
|
378
|
+
joins.delete(room);
|
|
379
|
+
if (ok) rooms.add(room);
|
|
380
|
+
else if (rooms.delete(room)) notifyLeave(room, "join refused");
|
|
381
|
+
if (ok && seq !== void 0 && !seqs.has(room)) seqs.set(room, seq);
|
|
382
|
+
for (const settle of pending) settle(ok);
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
if (event === "$left") {
|
|
386
|
+
const reason = typeof fields.reason === "string" ? fields.reason : void 0;
|
|
387
|
+
return () => {
|
|
388
|
+
rooms.delete(room);
|
|
389
|
+
notifyLeave(room, reason);
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
if (event === "$gap" && seq !== void 0) return () => {
|
|
393
|
+
seqs.set(room, seq);
|
|
394
|
+
notifyGap(room);
|
|
395
|
+
};
|
|
396
|
+
if (event === "$leave") return () => {};
|
|
397
|
+
throw new Error("Unknown control message");
|
|
398
|
+
};
|
|
399
|
+
const receive = ({ data }) => {
|
|
400
|
+
let message;
|
|
401
|
+
let action;
|
|
402
|
+
let room;
|
|
403
|
+
let seq;
|
|
404
|
+
try {
|
|
405
|
+
if (typeof data !== "string" || new TextEncoder().encode(data).byteLength > 65536) throw new Error("Expected JSON text under 64 KiB");
|
|
406
|
+
const parsed = JSON.parse(data);
|
|
407
|
+
const fields = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
408
|
+
({room, seq} = fields);
|
|
409
|
+
message = Object.fromEntries(Object.entries(fields).filter(([key]) => key !== "room" && key !== "seq"));
|
|
410
|
+
if ((room !== void 0 || seq !== void 0) && !(isSocketRoom(room) && isSocketSeq(seq))) throw new Error("Invalid socket sequence");
|
|
411
|
+
if (!isSocketEnvelope(message)) throw new Error("Invalid socket envelope");
|
|
412
|
+
if (message.event.startsWith("$")) {
|
|
413
|
+
if (seq !== void 0) throw new Error("Invalid control message");
|
|
414
|
+
action = control(message.event, message.data);
|
|
415
|
+
} else {
|
|
416
|
+
const schema = schemas.get(message.event);
|
|
417
|
+
if (!schema || !Check(schema, message.data)) throw new Error("Invalid socket output");
|
|
418
|
+
}
|
|
419
|
+
} catch (cause) {
|
|
420
|
+
stop(new BrickSocketError("protocol", "Server sent an invalid socket message", { cause }), 4e3, "Invalid server message");
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
if (action) return action();
|
|
424
|
+
if (isSocketRoom(room) && isSocketSeq(seq)) {
|
|
425
|
+
const last = seqs.get(room);
|
|
426
|
+
if (last !== void 0 && compareSocketSeq(seq, last) <= 0) return;
|
|
427
|
+
seqs.set(room, seq);
|
|
428
|
+
}
|
|
429
|
+
if (isSocketEnvelope(message)) for (const listener of events.get(message.event) ?? []) listener(message.data);
|
|
430
|
+
};
|
|
431
|
+
function abort() {
|
|
432
|
+
stop(signal?.reason ?? new DOMException("Aborted", "AbortError"));
|
|
433
|
+
}
|
|
434
|
+
const listen = (listeners, listener) => {
|
|
435
|
+
if (status !== "closed") listeners.add(listener);
|
|
436
|
+
return () => {
|
|
437
|
+
listeners.delete(listener);
|
|
438
|
+
};
|
|
439
|
+
};
|
|
175
440
|
const api = {
|
|
176
|
-
ready,
|
|
441
|
+
ready: ready.promise,
|
|
442
|
+
get status() {
|
|
443
|
+
return status;
|
|
444
|
+
},
|
|
445
|
+
join(room) {
|
|
446
|
+
if (!isSocketRoom(room)) return Promise.reject(new BrickSocketError("protocol", `Invalid room: ${String(room)}`));
|
|
447
|
+
return request(room);
|
|
448
|
+
},
|
|
449
|
+
leave(room) {
|
|
450
|
+
rooms.delete(room);
|
|
451
|
+
seqs.delete(room);
|
|
452
|
+
for (const settle of joins.get(room) ?? []) settle(new BrickSocketError("refused", `Left before joining: ${room}`));
|
|
453
|
+
joins.delete(room);
|
|
454
|
+
if (isSocketRoom(room) && status === "open" && ws?.readyState === 1) write("$leave", { room });
|
|
455
|
+
},
|
|
177
456
|
send(event, data) {
|
|
178
|
-
if (!ws ||
|
|
457
|
+
if (!ws || status !== "open" || ws.readyState !== 1) throw new BrickSocketError("connection", "Socket is not open");
|
|
458
|
+
if (event.startsWith("$")) throw new BrickSocketError("protocol", "Reserved socket event");
|
|
179
459
|
const frame = JSON.stringify({
|
|
180
460
|
event,
|
|
181
461
|
data
|
|
@@ -193,7 +473,7 @@ function connectSocket(baseUrl, contract, options) {
|
|
|
193
473
|
stop();
|
|
194
474
|
},
|
|
195
475
|
on(event, listener) {
|
|
196
|
-
if (
|
|
476
|
+
if (status === "closed") return () => {};
|
|
197
477
|
const listeners = events.get(event) ?? /* @__PURE__ */ new Set();
|
|
198
478
|
listeners.add(listener);
|
|
199
479
|
events.set(event, listeners);
|
|
@@ -202,62 +482,27 @@ function connectSocket(baseUrl, contract, options) {
|
|
|
202
482
|
if (!listeners.size) events.delete(event);
|
|
203
483
|
};
|
|
204
484
|
},
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
onClose(listener)
|
|
212
|
-
if (!finished) closes.add(listener);
|
|
213
|
-
return () => {
|
|
214
|
-
closes.delete(listener);
|
|
215
|
-
};
|
|
216
|
-
}
|
|
485
|
+
onLeave: (listener) => listen(leaves, listener),
|
|
486
|
+
onGap: (listener) => listen(gaps, listener),
|
|
487
|
+
onStatus: (listener) => listen(statuses, listener),
|
|
488
|
+
onReconnect: (listener) => listen(reconnects, listener),
|
|
489
|
+
onError: (listener) => listen(errors, listener),
|
|
490
|
+
onHandlerError: (listener) => listen(failures, listener),
|
|
491
|
+
onClose: (listener) => listen(closes, listener)
|
|
217
492
|
};
|
|
218
|
-
if (options.timeoutMs !== void 0 && (!Number.isFinite(options.timeoutMs) || options.timeoutMs < 0)) throw new Error("Socket timeoutMs must be a finite nonnegative number");
|
|
219
493
|
if (signal?.aborted) {
|
|
220
494
|
queueMicrotask(abort);
|
|
221
495
|
return api;
|
|
222
496
|
}
|
|
223
|
-
try {
|
|
224
|
-
ws = new WebSocket(url);
|
|
225
|
-
} catch (cause) {
|
|
226
|
-
queueMicrotask(() => stop(new BrickSocketError("connection", "Socket connection failed", { cause })));
|
|
227
|
-
return api;
|
|
228
|
-
}
|
|
229
|
-
ws.onopen = () => {
|
|
230
|
-
if (finished) return;
|
|
231
|
-
opened = true;
|
|
232
|
-
clearTimeout(timer);
|
|
233
|
-
resolveReady();
|
|
234
|
-
};
|
|
235
|
-
ws.onerror = () => stop(new BrickSocketError("connection", "Socket connection failed"));
|
|
236
|
-
ws.onclose = ({ code, reason }) => finish({
|
|
237
|
-
code,
|
|
238
|
-
reason
|
|
239
|
-
});
|
|
240
|
-
ws.onmessage = ({ data }) => {
|
|
241
|
-
let message;
|
|
242
|
-
try {
|
|
243
|
-
if (typeof data !== "string" || new TextEncoder().encode(data).byteLength > 65536) throw new Error("Expected JSON text under 64 KiB");
|
|
244
|
-
message = JSON.parse(data);
|
|
245
|
-
if (!isSocketEnvelope(message)) throw new Error("Invalid socket envelope");
|
|
246
|
-
const schema = schemas.get(message.event);
|
|
247
|
-
if (!schema || !Check(schema, message.data)) throw new Error("Invalid socket output");
|
|
248
|
-
} catch (cause) {
|
|
249
|
-
stop(new BrickSocketError("protocol", "Server sent an invalid socket message", { cause }), 4e3, "Invalid server message");
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
if (isSocketEnvelope(message)) for (const listener of events.get(message.event) ?? []) listener(message.data);
|
|
253
|
-
};
|
|
254
497
|
signal?.addEventListener("abort", abort, { once: true });
|
|
255
|
-
if (
|
|
256
|
-
|
|
498
|
+
if (backoff) {
|
|
499
|
+
globalThis.addEventListener?.("online", wake);
|
|
500
|
+
page?.addEventListener("visibilitychange", wake);
|
|
501
|
+
}
|
|
502
|
+
attempt();
|
|
257
503
|
return api;
|
|
258
504
|
}
|
|
259
|
-
|
|
260
|
-
//#region src/client.ts
|
|
505
|
+
// src/client.ts
|
|
261
506
|
/**
|
|
262
507
|
* The request never received a meaningful server answer: DNS / connection
|
|
263
508
|
* failure, a malformed body, or a 4xx response outside the declared contract
|
|
@@ -357,7 +602,7 @@ function planRequest(path, target, input, baseUrl, prefix) {
|
|
|
357
602
|
const action = typeof actionTarget?.name === "string" && actionTarget.name ? actionTarget.name : path.slice(1).join(".");
|
|
358
603
|
const method = actionConfig?.method ?? "POST";
|
|
359
604
|
const configuredPath = actionConfig?.path;
|
|
360
|
-
let actionPath = configuredPath ?? `${prefix}/${encodeURIComponent(service)}/${action.split(".").map(encodeURIComponent).join(".")}`;
|
|
605
|
+
let actionPath = configuredPath ?? `${prefix}/${encodeURIComponent(kebabCase(service))}/${action.split(".").map((part) => encodeURIComponent(kebabCase(part))).join(".")}`;
|
|
361
606
|
let remaining = input;
|
|
362
607
|
if (configuredPath !== void 0) {
|
|
363
608
|
if (!configuredPath.startsWith("/")) throw new Error("[Brick-TS client] Action paths must start with '/'.");
|
|
@@ -455,6 +700,7 @@ function createNamespace(resolved, path, node) {
|
|
|
455
700
|
if (typeof prop !== "string") return Reflect.get(target, prop, receiver);
|
|
456
701
|
if (prop === "then" || prop === "catch" || prop === "finally") return void 0;
|
|
457
702
|
if (prop === "connect" && node && typeof node === "object" && "kind" in node && node.kind === "socket") return (options) => connectSocket(resolved.baseUrl, node, {
|
|
703
|
+
...options,
|
|
458
704
|
signal: options?.signal ?? resolved.signal,
|
|
459
705
|
timeoutMs: options?.timeoutMs ?? resolved.timeoutMs
|
|
460
706
|
});
|
|
@@ -479,7 +725,6 @@ function createBrickClient(options) {
|
|
|
479
725
|
timeoutMs: options.timeoutMs
|
|
480
726
|
}, [], options.contract);
|
|
481
727
|
}
|
|
482
|
-
|
|
483
|
-
export { isBrickTransportError as a, SOCKET_MAX_BYTES as c, ActionExecutionError as d, ValidationError as f, isBrickServerError as i, isSocketEnvelope as l, BrickTransportError as n, BrickSocketError as o, createBrickClient as r, SOCKET_BUFFER_BYTES as s, BrickServerError as t, serializeSocketSchema as u };
|
|
728
|
+
export { isBrickTransportError as a, SOCKET_MAX_BYTES as c, isSocketRoom as d, isSocketSeq as f, kebabCase as g, ValidationError as h, isBrickServerError as i, compareSocketSeq as l, ActionExecutionError as m, BrickTransportError as n, BrickSocketError as o, serializeSocketSchema as p, createBrickClient as r, SOCKET_BUFFER_BYTES as s, BrickServerError as t, isSocketEnvelope as u };
|
|
484
729
|
|
|
485
730
|
//# sourceMappingURL=client.js.map
|