@zyncbase/testing 0.0.0-stage → 0.4.2

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/LICENSE ADDED
@@ -0,0 +1,69 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ Copyright 2026 Mustafa Dokumacı
58
+
59
+ Licensed under the Apache License, Version 2.0 (the "License");
60
+ you may not use this file except in compliance with the License.
61
+ You may obtain a copy of the License at
62
+
63
+ http://www.apache.org/licenses/LICENSE-2.0
64
+
65
+ Unless required by applicable law or agreed to in writing, software
66
+ distributed under the License is distributed on an "AS IS" BASIS,
67
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
68
+ See the License for the specific language governing permissions and
69
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,162 @@
1
- # Temporary Holding Version
1
+ # @zyncbase/testing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Test helpers for ZyncBase apps: an ephemeral server, connected clients, auth
4
+ helpers, and awaitable snapshots.
5
+
6
+ ```sh
7
+ bun add -d --exact @zyncbase/testing
8
+ ```
9
+
10
+ Requires Bun or Node 22+ (the SDK needs a global `WebSocket`). The package's
11
+ own peer dependencies are `zyncbase`, `@zyncbase/client`, and
12
+ `@zyncbase/backend`.
13
+
14
+ ## Quick start
15
+
16
+ ```ts
17
+ import { afterAll, expect, test } from "bun:test";
18
+ import { createTestRuntime, subscribeRows } from "@zyncbase/testing";
19
+
20
+ const rt = await createTestRuntime({ config: "./zyncbase-config.json" });
21
+ afterAll(() => rt.stop());
22
+
23
+ test("a write reaches the subscriber", async () => {
24
+ const writer = await rt.connect({ auth: rt.anonymousAuth() });
25
+ const reader = await rt.connect({ auth: rt.anonymousAuth() });
26
+
27
+ const rows = await subscribeRows(reader, "tasks", {
28
+ where: { status: { eq: "active" } },
29
+ });
30
+ await writer.store.create("tasks", { status: "active" });
31
+
32
+ const active = await rows.next((current) => current.length === 1);
33
+ expect(active[0]).toMatchObject({ status: "active" });
34
+ await rows.unsubscribe();
35
+ });
36
+ ```
37
+
38
+ `createTestRuntime` starts the server with an ephemeral data directory, a free
39
+ port, isolated environment variables, and quiet logs. Every client created with
40
+ `rt.connect` is disconnected before the server stops. Use
41
+ `await using rt = await createTestRuntime(...)` if your test runner supports
42
+ explicit resource management.
43
+
44
+ ## API
45
+
46
+ | Export | Purpose |
47
+ |---|---|
48
+ | `createTestRuntime({ config, overrides?, serverBin? })` | Start an ephemeral server |
49
+ | `rt.connect({ auth, ...clientOptions })` | Create and connect a tracked client |
50
+ | `rt.userAuth({ sub, claims?, ttlSeconds? })` | Mint a user token |
51
+ | `rt.serviceAuth({ sub, claims?, ttlSeconds? })` | Mint service auth (`sub` starts with `service:`) |
52
+ | `rt.anonymousAuth()` | Anonymous auth when the config enables it |
53
+ | `rt.uniqueNamespace(prefix)` | `prefix:<uuid>` for isolated namespaces |
54
+ | `rt.stop()` | Run `onStop` callbacks, disconnect clients, then stop the server (idempotent) |
55
+ | `subscribeRows(client, collection, query?, { timeoutMs }?)` | Live-query handle with `rows`, `next()`, `unsubscribe()`; `timeoutMs` is the default for its `next()` calls |
56
+ | `nextPresence(client, predicate?, options?)` | Resolve on the current or next matching presence snapshot from the server |
57
+ | `once(client, event, options?)` | Resolve with a lifecycle event's args |
58
+ | `eventually(label, check, timeout?)` | Poll until truthy |
59
+ | `freePort()` | Reserve a free localhost port for an app listener |
60
+ | `waitForHttp(url)` | Poll a URL until it answers 2xx |
61
+ | `recordWebSockets()` / `dropSockets(recorder)` | Capture and close a client's transport |
62
+ | `decodeJwt(token)` | Read a token payload (diagnostics only) |
63
+
64
+ `rows.next`, `nextPresence`, and `once` default to 10 seconds and take
65
+ `{ timeoutMs }`. `subscribeRows`' fourth argument, `{ timeoutMs }`, changes
66
+ that default for the handle's `next()` calls; subscribing itself has no
67
+ timeout. `eventually` also defaults to 10 seconds but takes
68
+ the timeout as a number, `eventually(label, check, 5_000)`. `waitForHttp`
69
+ defaults to 30 seconds and takes `{ timeoutMs, intervalMs }`.
70
+
71
+ ## Recipes
72
+
73
+ ### Authorization matrix
74
+
75
+ ```ts
76
+ const member = await rt.connect({
77
+ auth: rt.userAuth({ sub: "u:alice", claims: { room: "A", role: "member" } }),
78
+ storeNamespace: "room:A",
79
+ });
80
+ const worker = await rt.connect({
81
+ auth: rt.serviceAuth({ sub: "service:A", claims: { room: "A" } }),
82
+ storeNamespace: "room:A",
83
+ });
84
+
85
+ await expect(member.store.create("cards", card)).rejects.toMatchObject({
86
+ code: "PERMISSION_DENIED",
87
+ });
88
+ const id = await worker.store.create("cards", card);
89
+ expect(await member.store.get(["cards", id])).toMatchObject(card);
90
+ ```
91
+
92
+ ### Presence
93
+
94
+ ```ts
95
+ const alice = await rt.connect({ auth: rt.userAuth({ sub: "u:alice" }) });
96
+ const bob = await rt.connect({ auth: rt.userAuth({ sub: "u:bob" }) });
97
+ await alice.presence.set({ status: "online" });
98
+
99
+ const users = await nextPresence(
100
+ bob,
101
+ (current) => current.some((entry) => entry.data.status === "online"),
102
+ );
103
+ ```
104
+
105
+ ### Action worker
106
+
107
+ ```ts
108
+ const worker = await rt.connect({ auth: rt.serviceAuth({ sub: "service:worker" }) });
109
+ await worker.actions.handle("complete_task", (_ctx, params) => ({
110
+ status: "done",
111
+ params,
112
+ }));
113
+
114
+ const user = await rt.connect({ auth: rt.userAuth({ sub: "u:alice" }) });
115
+ const result = await user.actions.call("complete_task", { task_id: "t1" });
116
+ ```
117
+
118
+ ### Reconnect
119
+
120
+ ```ts
121
+ const recorder = recordWebSockets();
122
+ try {
123
+ const client = await rt.connect({ auth: rt.anonymousAuth(), reconnectDelay: 50 });
124
+ const disconnected = once(client, "disconnected");
125
+ dropSockets(recorder);
126
+ await disconnected;
127
+ await eventually("reconnected", () => client.status === "connected");
128
+ } finally {
129
+ recorder.restore();
130
+ }
131
+ ```
132
+
133
+ ### React hooks
134
+
135
+ ```tsx
136
+ import { renderHook } from "@testing-library/react";
137
+
138
+ const client = await rt.connect({ auth: rt.anonymousAuth() });
139
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
140
+ <ZyncBaseProvider client={client}>{children}</ZyncBaseProvider>
141
+ );
142
+ const { result } = renderHook(() => useQuery("tasks", {}), { wrapper });
143
+ ```
144
+
145
+ ### Yjs
146
+
147
+ ```ts
148
+ const client = await rt.connect({ auth: rt.anonymousAuth() });
149
+ // Use the provider from @zyncbase/client/yjs with client and a doc name,
150
+ // then wait for convergence with eventually().
151
+ ```
152
+
153
+ ## Notes
154
+
155
+ - Prefer one runtime per test file; each runtime owns its port and data
156
+ directory. Any number of runtimes can share a process: on SIGINT or SIGTERM
157
+ every running one is stopped before the process exits.
158
+ - The server binary is resolved like `zyncbase dev`: `ZYNCBASE_SERVER_BIN`,
159
+ `ZYNCBASE_BINARY`, `zig-out/bin/zyncbase`, then the release download. Set
160
+ `ZYNCBASE_SERVER_BIN` in CI or offline environments.
161
+ - An explicit `overrides.dataDir` disables the ephemeral directory, so the
162
+ data survives `stop()`.
@@ -0,0 +1,6 @@
1
+ export type { WaitForHttpOptions, WebSocketRecorder } from "./net.js";
2
+ export { decodeJwt, dropSockets, freePort, recordWebSockets, waitForHttp, } from "./net.js";
3
+ export type { TestConnectOptions, TestRuntime, TestRuntimeOptions, } from "./runtime.js";
4
+ export { createTestRuntime } from "./runtime.js";
5
+ export type { RowsHandle, WaitOptions } from "./wait.js";
6
+ export { eventually, nextPresence, once, subscribeRows, } from "./wait.js";
package/dist/index.js ADDED
@@ -0,0 +1,285 @@
1
+ // src/net.ts
2
+ import { createServer } from "node:net";
3
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4
+ async function freePort() {
5
+ const probe = createServer();
6
+ await new Promise((resolve, reject) => {
7
+ probe.once("error", reject);
8
+ probe.listen(0, "127.0.0.1", resolve);
9
+ });
10
+ const address = probe.address();
11
+ if (!address || typeof address === "string")
12
+ throw new Error("No port");
13
+ await new Promise((resolve, reject) => probe.close((error) => error ? reject(error) : resolve()));
14
+ return address.port;
15
+ }
16
+ async function waitForHttp(url, options = {}) {
17
+ const timeoutMs = options.timeoutMs ?? 30000;
18
+ const deadline = Date.now() + timeoutMs;
19
+ const interval = options.intervalMs ?? 100;
20
+ let timer;
21
+ const expired = new Promise((resolve) => {
22
+ timer = setTimeout(() => resolve(undefined), timeoutMs);
23
+ });
24
+ try {
25
+ while (Date.now() < deadline) {
26
+ try {
27
+ const response = await Promise.race([fetch(url), expired]);
28
+ if (response?.ok)
29
+ return;
30
+ } catch {}
31
+ await sleep(interval);
32
+ }
33
+ } finally {
34
+ clearTimeout(timer);
35
+ }
36
+ throw new Error(`Timed out waiting for ${options.label ?? url} at ${url}`);
37
+ }
38
+ function recordWebSockets() {
39
+ const Native = globalThis.WebSocket;
40
+ if (typeof Native !== "function") {
41
+ throw new Error("recordWebSockets needs a global WebSocket (Bun or Node 22+)");
42
+ }
43
+ const sockets = [];
44
+ globalThis.WebSocket = class extends Native {
45
+ constructor(url, protocols) {
46
+ super(url, protocols);
47
+ sockets.push(this);
48
+ }
49
+ };
50
+ return {
51
+ sockets,
52
+ restore: () => {
53
+ globalThis.WebSocket = Native;
54
+ }
55
+ };
56
+ }
57
+ function dropSockets(recorder) {
58
+ for (const socket of recorder.sockets)
59
+ socket.close();
60
+ }
61
+ function decodeJwt(token) {
62
+ const payload = token.split(".")[1];
63
+ if (!payload)
64
+ throw new Error("Not a JWT");
65
+ return JSON.parse(Buffer.from(payload, "base64url").toString());
66
+ }
67
+ // src/runtime.ts
68
+ import { serviceAuth as mintServiceAuth, mintToken } from "@zyncbase/backend";
69
+ import {
70
+ createClient
71
+ } from "@zyncbase/client";
72
+ import { startZyncBase } from "zyncbase/dev";
73
+ async function createTestRuntime(options) {
74
+ const inner = await startZyncBase({
75
+ config: options.config,
76
+ serverBin: options.serverBin,
77
+ test: true,
78
+ overrides: options.overrides
79
+ });
80
+ const clients = new Set;
81
+ let closed = false;
82
+ inner.onStop(() => {
83
+ closed = true;
84
+ for (const client of [...clients].reverse())
85
+ client.disconnect();
86
+ });
87
+ inner.stopOnSignals();
88
+ return {
89
+ get url() {
90
+ return inner.databaseUrl;
91
+ },
92
+ get databasePort() {
93
+ return inner.databasePort;
94
+ },
95
+ get dataDir() {
96
+ return inner.dataDir;
97
+ },
98
+ get jwtSecret() {
99
+ return inner.jwtSecret;
100
+ },
101
+ get serviceSecret() {
102
+ return inner.serviceSecret;
103
+ },
104
+ userAuth: (auth) => ({
105
+ token: mintToken({ secret: inner.jwtSecret, ...auth })
106
+ }),
107
+ serviceAuth: (auth) => mintServiceAuth({ secret: inner.serviceSecret, ...auth }),
108
+ anonymousAuth: () => ({ anonymous: true }),
109
+ async connect(connectOptions) {
110
+ if (closed)
111
+ throw new Error("createTestRuntime: connect() after stop()");
112
+ const { auth, ...rest } = connectOptions;
113
+ const client = createClient({
114
+ url: inner.databaseUrl,
115
+ auth,
116
+ ...rest
117
+ });
118
+ clients.add(client);
119
+ try {
120
+ await client.connect();
121
+ return client;
122
+ } catch (error) {
123
+ client.disconnect();
124
+ clients.delete(client);
125
+ throw error;
126
+ }
127
+ },
128
+ uniqueNamespace: (prefix) => `${prefix}:${crypto.randomUUID()}`,
129
+ onStop: (callback) => inner.onStop(callback),
130
+ stop: () => inner.stop(),
131
+ [Symbol.asyncDispose]: () => inner.stop()
132
+ };
133
+ }
134
+ // src/wait.ts
135
+ var DEFAULT_TIMEOUT_MS = 1e4;
136
+ var POLL_INTERVAL_MS = 50;
137
+ var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
138
+ var toError = (error) => error instanceof Error ? error : new Error(String(error));
139
+ async function eventually(label, check, timeoutMs = DEFAULT_TIMEOUT_MS) {
140
+ const deadline = Date.now() + timeoutMs;
141
+ let timer;
142
+ const expired = new Promise((resolve) => {
143
+ timer = setTimeout(() => resolve(undefined), timeoutMs);
144
+ });
145
+ try {
146
+ while (Date.now() < deadline) {
147
+ const value = await Promise.race([check(), expired]);
148
+ if (value)
149
+ return value;
150
+ await sleep2(POLL_INTERVAL_MS);
151
+ }
152
+ } finally {
153
+ clearTimeout(timer);
154
+ }
155
+ throw new Error(`Timed out: ${label}`);
156
+ }
157
+ async function subscribeRows(client, collection, options = {}, wait = {}) {
158
+ const defaultTimeout = wait.timeoutMs ?? DEFAULT_TIMEOUT_MS;
159
+ let rows = [];
160
+ let closed = false;
161
+ const waiters = new Set;
162
+ const settle = () => {
163
+ for (const waiter of [...waiters]) {
164
+ let matches;
165
+ try {
166
+ matches = waiter.predicate(rows);
167
+ } catch (error) {
168
+ clearTimeout(waiter.timer);
169
+ waiters.delete(waiter);
170
+ waiter.reject(toError(error));
171
+ continue;
172
+ }
173
+ if (!matches)
174
+ continue;
175
+ clearTimeout(waiter.timer);
176
+ waiters.delete(waiter);
177
+ waiter.resolve(rows);
178
+ }
179
+ };
180
+ const handle = await client.store.subscribe(collection, options, (next) => {
181
+ rows = next;
182
+ settle();
183
+ });
184
+ rows = handle.getSnapshot();
185
+ return {
186
+ get rows() {
187
+ return rows;
188
+ },
189
+ async next(predicate = () => true, nextOptions = {}) {
190
+ if (closed) {
191
+ throw new Error(`subscribeRows("${collection}"): unsubscribed`);
192
+ }
193
+ if (predicate(rows))
194
+ return rows;
195
+ const timeout = nextOptions.timeoutMs ?? defaultTimeout;
196
+ return new Promise((resolve, reject) => {
197
+ const waiter = {
198
+ predicate,
199
+ resolve,
200
+ reject,
201
+ timer: setTimeout(() => {
202
+ waiters.delete(waiter);
203
+ reject(new Error(`Timed out after ${timeout}ms waiting for rows in "${collection}" (last: ${rows.length} rows)`));
204
+ }, timeout)
205
+ };
206
+ waiters.add(waiter);
207
+ });
208
+ },
209
+ async unsubscribe() {
210
+ closed = true;
211
+ for (const waiter of waiters) {
212
+ clearTimeout(waiter.timer);
213
+ waiter.reject(new Error(`subscribeRows("${collection}"): unsubscribed`));
214
+ }
215
+ waiters.clear();
216
+ await handle.unsubscribe();
217
+ }
218
+ };
219
+ }
220
+ function nextPresence(client, predicate = () => true, options = {}) {
221
+ const timeout = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
222
+ let users = [];
223
+ return new Promise((resolve, reject) => {
224
+ let unsubscribe;
225
+ let settled = false;
226
+ let timer;
227
+ const finish = (error) => {
228
+ if (settled)
229
+ return;
230
+ settled = true;
231
+ clearTimeout(timer);
232
+ unsubscribe?.().catch(() => {});
233
+ if (error)
234
+ reject(error);
235
+ else
236
+ resolve(users);
237
+ };
238
+ timer = setTimeout(() => {
239
+ finish(new Error(`Timed out after ${timeout}ms waiting for presence (last: ${users.length} users)`));
240
+ }, timeout);
241
+ client.presence.subscribe((next) => {
242
+ if (settled)
243
+ return;
244
+ users = next;
245
+ try {
246
+ if (predicate(users))
247
+ finish();
248
+ } catch (error) {
249
+ finish(toError(error));
250
+ }
251
+ }).then((stop) => {
252
+ unsubscribe = stop;
253
+ if (settled)
254
+ stop().catch(() => {});
255
+ }, (error) => finish(toError(error)));
256
+ });
257
+ }
258
+ function once(client, event, options = {}) {
259
+ const timeout = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
260
+ return new Promise((resolve, reject) => {
261
+ let timer;
262
+ const handler = (...args) => {
263
+ clearTimeout(timer);
264
+ client.off(event, handler);
265
+ resolve(args);
266
+ };
267
+ timer = setTimeout(() => {
268
+ client.off(event, handler);
269
+ reject(new Error(`Timed out after ${timeout}ms waiting for "${event}"`));
270
+ }, timeout);
271
+ client.on(event, handler);
272
+ });
273
+ }
274
+ export {
275
+ createTestRuntime,
276
+ decodeJwt,
277
+ dropSockets,
278
+ eventually,
279
+ freePort,
280
+ nextPresence,
281
+ once,
282
+ recordWebSockets,
283
+ subscribeRows,
284
+ waitForHttp
285
+ };
package/dist/net.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ /** Reserves and releases a free localhost port. */
2
+ export declare function freePort(): Promise<number>;
3
+ export interface WaitForHttpOptions {
4
+ timeoutMs?: number;
5
+ intervalMs?: number;
6
+ label?: string;
7
+ }
8
+ /** Polls a URL until it answers 2xx. */
9
+ export declare function waitForHttp(url: string, options?: WaitForHttpOptions): Promise<void>;
10
+ export interface WebSocketRecorder {
11
+ readonly sockets: WebSocket[];
12
+ restore(): void;
13
+ }
14
+ /**
15
+ * Records every WebSocket opened until `restore()`, so a test can drop a
16
+ * client's transport. The SDK opens sockets through the global constructor.
17
+ */
18
+ export declare function recordWebSockets(): WebSocketRecorder;
19
+ /** Closes every socket recorded so far. */
20
+ export declare function dropSockets(recorder: WebSocketRecorder): void;
21
+ /** Decodes a JWT payload without verifying it. Test diagnostics only. */
22
+ export declare function decodeJwt(token: string): Record<string, unknown>;
@@ -0,0 +1,49 @@
1
+ import { type AuthConfig, type ClientOptions, type SchemaLike, type ZyncBaseClient } from "@zyncbase/client";
2
+ import { type ZyncBaseDevOverrides } from "zyncbase/dev";
3
+ export interface TestRuntimeOptions {
4
+ /** Path to `zyncbase-config.json`. Relative paths inside it resolve against its directory. */
5
+ config: string;
6
+ /**
7
+ * Passed through to the launcher. The harness always sets `databasePort: 0`
8
+ * and `ephemeral: true` (unless `dataDir` is given).
9
+ */
10
+ overrides?: Omit<ZyncBaseDevOverrides, "databasePort" | "ephemeral">;
11
+ /** Server executable; defaults to the launcher's resolution. */
12
+ serverBin?: string;
13
+ }
14
+ export type TestConnectOptions = Omit<ClientOptions, "url" | "auth"> & {
15
+ auth: AuthConfig;
16
+ };
17
+ export interface TestRuntime {
18
+ /** WebSocket URL of the running server. */
19
+ readonly url: string;
20
+ readonly databasePort: number;
21
+ readonly dataDir: string;
22
+ readonly jwtSecret: string;
23
+ readonly serviceSecret: string;
24
+ /** A user token signed with this runtime's JWT secret. */
25
+ userAuth(options: {
26
+ sub: string;
27
+ claims?: Record<string, unknown>;
28
+ ttlSeconds?: number;
29
+ }): AuthConfig;
30
+ /** Service auth signed with this runtime's service secret. */
31
+ serviceAuth(options: {
32
+ sub: string;
33
+ claims?: Record<string, unknown>;
34
+ ttlSeconds?: number;
35
+ }): AuthConfig;
36
+ anonymousAuth(): AuthConfig;
37
+ /** Creates a client against this runtime and tracks it for cleanup. */
38
+ connect<S extends object = SchemaLike, A = never, P = never>(options: TestConnectOptions): Promise<ZyncBaseClient<S, A, P>>;
39
+ /** A namespace unique to this call: `room:<uuid>` for prefix `room`. */
40
+ uniqueNamespace(prefix: string): string;
41
+ onStop(callback: () => void | Promise<void>): void;
42
+ /**
43
+ * Runs `onStop` callbacks, disconnects tracked clients, then stops the
44
+ * server. Idempotent; `connect()` rejects once the clients are disconnected.
45
+ */
46
+ stop(): Promise<void>;
47
+ [Symbol.asyncDispose](): Promise<void>;
48
+ }
49
+ export declare function createTestRuntime(options: TestRuntimeOptions): Promise<TestRuntime>;
package/dist/wait.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { ClientEvents, CollectionsOf, DocumentRowOf, LifecycleEvent, PresenceEntry, QueryOptionsFor, ZyncBaseClient } from "@zyncbase/client";
2
+ export interface WaitOptions {
3
+ timeoutMs?: number;
4
+ }
5
+ /** Polls a check until it returns a truthy value. */
6
+ export declare function eventually<T>(label: string, check: () => T | Promise<T>, timeoutMs?: number): Promise<T>;
7
+ export interface RowsHandle<Row> {
8
+ /** Latest delivered snapshot. */
9
+ readonly rows: readonly Row[];
10
+ /** Resolves with the next snapshot matching `predicate` (or the current one). */
11
+ next(predicate?: (rows: readonly Row[]) => boolean, options?: WaitOptions): Promise<readonly Row[]>;
12
+ unsubscribe(): Promise<void>;
13
+ }
14
+ /** Subscribes to a live query and exposes awaitable snapshots. */
15
+ export declare function subscribeRows<S extends object, C extends CollectionsOf<S>, A, P>(client: ZyncBaseClient<S, A, P>, collection: C, options?: QueryOptionsFor<S, C>, wait?: WaitOptions): Promise<RowsHandle<DocumentRowOf<S, C>>>;
16
+ /**
17
+ * Resolves with the next server presence snapshot matching `predicate` (or
18
+ * the current one). Only subscription snapshots count: the local cache is
19
+ * empty until the server answers, so it is never checked.
20
+ */
21
+ export declare function nextPresence<S extends object, A, P>(client: ZyncBaseClient<S, A, P>, predicate?: (users: PresenceEntry<P>[]) => boolean, options?: WaitOptions): Promise<PresenceEntry<P>[]>;
22
+ /** Resolves with the args of the next lifecycle event. */
23
+ export declare function once<E extends LifecycleEvent>(client: Pick<ZyncBaseClient, "on" | "off">, event: E, options?: WaitOptions): Promise<Parameters<ClientEvents[E]>>;
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
- "name": "@zyncbase/testing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@zyncbase/testing",
3
+ "version": "0.4.2",
4
+ "description": "Test helpers for ZyncBase apps: ephemeral runtime, clients, auth, and waiters.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "sideEffects": false,
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ }
16
+ },
17
+ "keywords": [
18
+ "zyncbase",
19
+ "testing",
20
+ "realtime",
21
+ "websocket"
22
+ ],
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/mstdokumaci/zyncbase.git"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "scripts": {
31
+ "build": "rm -rf dist && bun build --root src src/index.ts --outdir dist --format esm --target node --external zyncbase --external 'zyncbase/*' --external @zyncbase/client --external '@zyncbase/client/*' --external @zyncbase/backend --external '@zyncbase/backend/*' && tsc --emitDeclarationOnly --outDir dist"
32
+ },
33
+ "peerDependencies": {
34
+ "@zyncbase/backend": "^0.4.2",
35
+ "@zyncbase/client": "^0.4.2",
36
+ "zyncbase": "^0.4.2"
37
+ },
38
+ "devDependencies": {
39
+ "@types/bun": "^1.3.11",
40
+ "@zyncbase/backend": "workspace:*",
41
+ "@zyncbase/client": "workspace:*",
42
+ "typescript": "^5.0.0",
43
+ "zyncbase": "workspace:*"
44
+ }
45
+ }