@niwa-labs/client 0.0.0-stage → 0.0.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/src/wire.ts ADDED
@@ -0,0 +1,315 @@
1
+ /**
2
+ * The wire between a client and a host: newline-delimited JSON over a unix socket.
3
+ *
4
+ * A client asks the host to do something; the host answers, and it streams records to the
5
+ * subscriptions it opened. Every message carries the id of the request it belongs to, so an
6
+ * answer is always matched to its question.
7
+ *
8
+ * A boundary: nothing is believed before a schema has said so. The identifiers in types.ts
9
+ * are branded, so this file is also where a plain string becomes a domain value.
10
+ */
11
+
12
+ import { z } from "zod";
13
+
14
+ import {
15
+ principalSchema,
16
+ actionName,
17
+ grantId,
18
+ ValidationError,
19
+ JsonSchemaValue,
20
+ RecordQuerySchema,
21
+ recordId,
22
+ recordTypeName,
23
+ seq,
24
+ streamId,
25
+ timestamp,
26
+ } from "@niwa-labs/core";
27
+ import { token } from "./token.ts";
28
+ import { channelName } from "./live.ts";
29
+ import type { ClientId, HandlerId, InvocationId } from "@niwa-labs/core";
30
+
31
+ /** The largest pending line the decoder accepts, in characters: a UTF-8 char takes up to 4 bytes. */
32
+ const DEFAULT_MAX_LINE_LENGTH = 8 * 1024 * 1024;
33
+
34
+ /** The path of the socket a host listens on: `${home}/niwa.sock`. One home, one host, one socket. */
35
+ export function socketPath(home: string): string {
36
+ if (typeof home !== "string" || home.length === 0) {
37
+ throw new TypeError("a home must be a non-empty path");
38
+ }
39
+ return `${home}/niwa.sock`;
40
+ }
41
+
42
+ /** A schema that builds a domain identifier; a refusal becomes a schema issue, not a crash. */
43
+ function identifier<S extends string | number, T extends string | number>(
44
+ schema: z.ZodType<S, S>,
45
+ build: (value: S) => T,
46
+ ) {
47
+ return schema.transform((value, ctx) => {
48
+ try {
49
+ return build(value);
50
+ } catch (error) {
51
+ ctx.addIssue({ code: "custom", message: error instanceof Error ? error.message : "not a valid identifier" });
52
+ return z.NEVER;
53
+ }
54
+ });
55
+ }
56
+
57
+ /** A branded name: a non-empty string without whitespace — the wire's own client, handler and invocation names. */
58
+ function nameSchema<T extends string>(what: string) {
59
+ return identifier(z.string(), (value) => {
60
+ if (value.trim().length === 0) throw new TypeError(`${what} must not be empty`);
61
+ if (/\s/.test(value)) throw new TypeError(`${what} must not contain whitespace: ${JSON.stringify(value)}`);
62
+ return value as T;
63
+ });
64
+ }
65
+
66
+ const requestIdSchema = z.number().int().nonnegative(); // the counter of the client that sent it
67
+ const clientIdSchema = nameSchema<ClientId>("client id"); // the name a client gives itself
68
+ const actionNameSchema = identifier(z.string(), actionName); // the registry owns the rules
69
+ const recordTypeNameSchema = identifier(z.string(), recordTypeName);
70
+ const recordIdSchema = identifier(z.string(), recordId);
71
+ const streamIdSchema = identifier(z.string(), streamId);
72
+ const seqSchema = identifier(z.number(), seq);
73
+ const timestampSchema = identifier(z.number(), timestamp);
74
+ const handlerIdSchema = nameSchema<HandlerId>("handler id");
75
+ const invocationIdSchema = nameSchema<InvocationId>("invocation id");
76
+ const channelSchema = identifier(z.string(), channelName);
77
+ const tokenSchema = identifier(z.string(), token);
78
+
79
+ /** Who did something: the actor is bound by the runtime or the transport, never by a payload. */
80
+ export const callerSchema = z.discriminatedUnion("kind", [
81
+ z.strictObject({ kind: z.literal("host"), issuedBy: z.string().min(1).optional() }),
82
+ z.strictObject({
83
+ kind: z.literal("client"),
84
+ id: clientIdSchema,
85
+ issuedBy: z.string().min(1).optional(),
86
+ principal: principalSchema.optional(),
87
+ grant: z.string().min(1).transform((id) => grantId(id)).optional(),
88
+ }),
89
+ z.strictObject({ kind: z.literal("handler"), issuedBy: z.string().min(1).optional(), handler: handlerIdSchema, invocation: invocationIdSchema }),
90
+ ]);
91
+
92
+ /** A committed record as it travels over the wire: every field of the stored record. */
93
+ export const storedRecordSchema = z.strictObject({
94
+ id: recordIdSchema,
95
+ seq: seqSchema,
96
+ stream: streamIdSchema,
97
+ type: recordTypeNameSchema,
98
+ schema: z.number().int().positive(), // the version of the schema of this record's type
99
+ data: z.unknown().default(undefined), // JSON has no `undefined`: a missing key means "no data"
100
+ actor: callerSchema,
101
+ cause: recordIdSchema.nullable(),
102
+ root: recordIdSchema,
103
+ at: timestampSchema,
104
+ });
105
+
106
+ /**
107
+ * A live frame as it travels: the channel it was sent on and its payload.
108
+ *
109
+ * The payload is not read here: the shape of a frame belongs to whoever uses the channel, and
110
+ * the wire only carries it. What the wire does check is the channel, because it is a key on
111
+ * both sides.
112
+ */
113
+ export const liveFrameSchema = z.strictObject({
114
+ channel: channelSchema,
115
+ data: z.unknown().default(undefined),
116
+ });
117
+
118
+ /** A record in a trace as it travels over the wire: the record, and the depth it was found at. */
119
+ export const tracedRecordSchema = storedRecordSchema.extend({ depth: z.number().int().nonnegative() });
120
+
121
+ /** The self-description as it travels: the actions and the record types with their JSON Schemas. */
122
+ export const descriptionSchema = z.strictObject({
123
+ actions: z.array(
124
+ z.strictObject({
125
+ name: actionNameSchema,
126
+ description: z.string(),
127
+ recovery: z.enum(["repeat", "repeat-with-key", "do-not-repeat"]),
128
+ effect: z.enum(["read", "record", "write", "irreversible"]),
129
+ world: z.enum(["niwa", "local", "external"]).optional(),
130
+ idempotent: z.boolean().optional(),
131
+ destructive: z.boolean().optional(),
132
+ input: JsonSchemaValue,
133
+ output: JsonSchemaValue,
134
+ }),
135
+ ),
136
+ types: z.array(
137
+ z.strictObject({
138
+ name: recordTypeNameSchema,
139
+ version: z.number().int().positive(),
140
+ schema: JsonSchemaValue,
141
+ }),
142
+ ),
143
+ });
144
+
145
+ const emitFields = {
146
+ type: recordTypeNameSchema,
147
+ data: z.unknown().optional(),
148
+ record: recordIdSchema.optional(),
149
+ links: z.array(recordIdSchema).optional(),
150
+ };
151
+
152
+ /** What a client may send to the host: `op` tells the operations apart. */
153
+ export const clientMessageSchema = z.discriminatedUnion("op", [
154
+ // The token is what says who the connection is; the client label only names it for people.
155
+ z.strictObject({ id: requestIdSchema, op: z.literal("hello"), client: clientIdSchema, token: tokenSchema.optional() }),
156
+ z.strictObject({
157
+ id: requestIdSchema,
158
+ op: z.literal("call"),
159
+ action: actionNameSchema,
160
+ input: z.unknown().optional(),
161
+ reason: z.string().min(1).optional(),
162
+ /** The caller's id for the call: a retry under it answers what the first call answered. */
163
+ operation: z.string().min(1).max(256).optional(),
164
+ }),
165
+ z.strictObject({
166
+ id: requestIdSchema,
167
+ op: z.literal("emit"),
168
+ ...emitFields,
169
+ }),
170
+ z.strictObject({id: requestIdSchema, op: z.literal("emitAll"), entries: z.array(z.strictObject(emitFields))}),
171
+ z.strictObject({
172
+ id: requestIdSchema,
173
+ op: z.literal("since"),
174
+ /** The records wanted, history then live: the same query a read takes. */
175
+ query: RecordQuerySchema,
176
+ }),
177
+ z.strictObject({
178
+ id: requestIdSchema,
179
+ op: z.literal("read"),
180
+ query: RecordQuerySchema,
181
+ limit: z.number().int().positive().optional(),
182
+ }),
183
+ z.strictObject({ id: requestIdSchema, op: z.literal("describe") }),
184
+ z.strictObject({ id: requestIdSchema, op: z.literal("live.send"), channel: channelSchema, data: z.unknown().optional() }),
185
+ z.strictObject({ id: requestIdSchema, op: z.literal("live.subscribe"), channel: channelSchema }),
186
+ z.strictObject({ id: requestIdSchema, op: z.literal("trace"), record: recordIdSchema }),
187
+ z.strictObject({ id: requestIdSchema, op: z.literal("causes"), record: recordIdSchema }),
188
+ ]);
189
+
190
+ /** What a refusal by a grant carries to the caller. */
191
+ export const deniedSchema = z.strictObject({
192
+ grant: z.string().min(1),
193
+ missing: z.string().min(1),
194
+ record: z.string().min(1).optional(),
195
+ });
196
+
197
+ /** What the host may send: an answer, a record of a subscription, or a live frame. */
198
+ export const hostMessageSchema = z.union([
199
+ z.discriminatedUnion("ok", [
200
+ z.strictObject({ id: requestIdSchema, ok: z.literal(true), value: z.unknown().optional() }),
201
+ z.strictObject({
202
+ id: requestIdSchema,
203
+ ok: z.literal(false),
204
+ error: z.string(),
205
+ code: z.string().optional(),
206
+ /** Set when a grant refused the call: whose grant, and the rule it lacks. */
207
+ denied: deniedSchema.optional(),
208
+ refusal: z.strictObject({
209
+ code: z.string(), reason: z.string(), entity: z.string(), recordType: recordTypeNameSchema, audit: storedRecordSchema,
210
+ }).optional(),
211
+ }),
212
+ ]),
213
+ z.strictObject({ id: requestIdSchema, record: storedRecordSchema }),
214
+ z.strictObject({ id: requestIdSchema, frame: liveFrameSchema }),
215
+ ]);
216
+
217
+ export type ClientMessage = z.output<typeof clientMessageSchema>; // a message a client sent
218
+ export type HostMessage = z.output<typeof hostMessageSchema>; // a message the host sent
219
+ export type WireMessage = ClientMessage | HostMessage; // a message of either direction
220
+
221
+ /** One message, ready for the socket: JSON and a newline. The newline is the frame. */
222
+ export function encode(msg: WireMessage): string {
223
+ const text = JSON.stringify(msg);
224
+ if (text === undefined) throw new TypeError("a wire message must be a JSON value");
225
+ return `${text}\n`;
226
+ }
227
+
228
+ /** What the decoder does with a line it could not use. */
229
+ export interface LineDecoderOptions {
230
+ /** Called for a line that is not valid JSON. The line is dropped: the framing is intact. */
231
+ onError?: (error: Error, line: string) => void;
232
+ /** The largest pending line accepted, in characters. Default 8 MiB; past that the decoder gives up. */
233
+ maxLineLength?: number;
234
+ }
235
+
236
+ /**
237
+ * A decoder: bytes in, messages out. Chunks arrive in whatever sizes the socket chose, so a
238
+ * message can be split across several of them and several messages can arrive in one; the
239
+ * decoder buffers what is left of a line and hands over one message per complete line.
240
+ */
241
+ export function lineDecoder(
242
+ onMessage: (m: unknown) => void,
243
+ opts?: LineDecoderOptions,
244
+ ): (chunk: Uint8Array | string) => void {
245
+ const maxLineLength = opts?.maxLineLength ?? DEFAULT_MAX_LINE_LENGTH;
246
+ const onError = opts?.onError;
247
+ const decoder = new TextDecoder();
248
+ let pending = "";
249
+ let scanned = 0; // the part of `pending` that is known to hold no newline
250
+ let stopped = false;
251
+
252
+ return (chunk: Uint8Array | string): void => {
253
+ if (stopped) return;
254
+ pending += typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
255
+ let start = 0;
256
+ for (;;) {
257
+ const end = pending.indexOf("\n", Math.max(start, scanned));
258
+ if (end === -1) break;
259
+ const line = pending.slice(start, end);
260
+ start = end + 1;
261
+ if (line.length > maxLineLength) {
262
+ // The limit holds for a line however the socket cut it: a complete line is judged like its remainder.
263
+ stopped = true;
264
+ pending = "";
265
+ onError?.(new Error(`a wire line longer than ${maxLineLength} characters was refused`), line.slice(0, 200));
266
+ return;
267
+ }
268
+ const text = line.trim();
269
+ if (text.length === 0) continue; // a blank line is a keep-alive, not a message
270
+ let value: unknown;
271
+ try {
272
+ value = JSON.parse(text);
273
+ } catch (error) {
274
+ onError?.(error instanceof Error ? error : new Error("not valid JSON"), line);
275
+ continue;
276
+ }
277
+ onMessage(value);
278
+ }
279
+ pending = pending.slice(start);
280
+ scanned = pending.length;
281
+ if (pending.length > maxLineLength) {
282
+ stopped = true;
283
+ const head = pending.slice(0, 200);
284
+ pending = "";
285
+ onError?.(new Error(`a wire line longer than ${maxLineLength} characters was refused`), head);
286
+ }
287
+ };
288
+ }
289
+
290
+ /** Parse with a schema, refusing with a `ValidationError` that carries the schema's issues. */
291
+ function decode<S extends z.ZodType>(schema: S, message: string, value: unknown): z.output<S> {
292
+ const parsed = schema.safeParse(value);
293
+ if (!parsed.success) throw new ValidationError(message, parsed.error.issues);
294
+ return parsed.data;
295
+ }
296
+
297
+ /** Parse what a client sent. */
298
+ export function decodeClientMessage(value: unknown): ClientMessage {
299
+ return decode(clientMessageSchema, "not a valid client message", value);
300
+ }
301
+
302
+ /** Parse what the host sent. */
303
+ export function decodeHostMessage(value: unknown): HostMessage {
304
+ return decode(hostMessageSchema, "not a valid host message", value);
305
+ }
306
+
307
+ /**
308
+ * The id of the request a message belongs to, if it has one: a message that does not fit the
309
+ * schema may still carry an id, and the host needs it to answer a broken `call`.
310
+ */
311
+ export function requestIdOf(value: unknown): number | undefined {
312
+ if (value === null || typeof value !== "object") return undefined;
313
+ const id = (value as { id?: unknown }).id;
314
+ return typeof id === "number" && Number.isInteger(id) && id >= 0 ? id : undefined;
315
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The directory a call is for: where the caller works.
3
+ *
4
+ * An action that takes a `directory` (the project a run belongs to) is told where the caller works when the caller names
5
+ * none. The surfaces that act for a person or an agent in a working directory, the CLI and the MCP server, fill it in
6
+ * from the schema of the action: they keep no list of the actions that take one.
7
+ */
8
+
9
+ import type { JsonSchema } from "@niwa-labs/core";
10
+
11
+ /** The field of an action's input that holds the directory the call is for. */
12
+ export const DIRECTORY_FIELD = "directory";
13
+
14
+ /** Does the input schema of an action declare a directory? */
15
+ export function takesDirectory(input: JsonSchema | undefined): boolean {
16
+ const properties = (input as { properties?: unknown } | undefined)?.properties;
17
+ return properties !== null && typeof properties === "object" && Object.hasOwn(properties, DIRECTORY_FIELD);
18
+ }
19
+
20
+ /** The input with the caller's working directory in `directory`, when the action takes one and the input has none. */
21
+ export function withWorkingDirectory(
22
+ input: JsonSchema | undefined,
23
+ args: Record<string, unknown>,
24
+ cwd: string = process.cwd(),
25
+ ): Record<string, unknown> {
26
+ if (!takesDirectory(input) || args[DIRECTORY_FIELD] !== undefined) return args;
27
+ return { ...args, [DIRECTORY_FIELD]: cwd };
28
+ }
@@ -0,0 +1,17 @@
1
+ // A connection that does not come up leaves no socket behind.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { connect } from "../src/index.ts";
6
+ import { quietHost, within } from "./helpers.ts";
7
+
8
+ test("a connection whose hello cannot be built closes its socket", async () => {
9
+ const host = quietHost();
10
+ try {
11
+ await expect(connect({ home: host.home, id: "has a space" })).rejects.toThrow();
12
+ expect(host.accepted()).toBe(1);
13
+ expect(await within(2_000, () => host.ended() === 1)).toBe(true);
14
+ } finally {
15
+ host.stop();
16
+ }
17
+ });
@@ -0,0 +1,5 @@
1
+ // Prints the owner token of the home named on the command line, or "none".
2
+
3
+ import { readOwnerToken } from "../../src/index.ts";
4
+
5
+ console.log(readOwnerToken(process.argv[2] ?? "") ?? "none");
@@ -0,0 +1,54 @@
1
+ // A host that is only a socket: it lets a client connect, answers nothing, and says when a connection ended.
2
+
3
+ import { mkdtempSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+
7
+ import { socketPath } from "../src/index.ts";
8
+
9
+ export interface QuietHost {
10
+ readonly home: string;
11
+ /** How many connections it accepted, and how many of them ended. */
12
+ readonly accepted: () => number;
13
+ readonly ended: () => number;
14
+ stop(): void;
15
+ }
16
+
17
+ export function quietHost(): QuietHost {
18
+ const home = mkdtempSync(join(tmpdir(), "niwa-client-"));
19
+ let accepted = 0;
20
+ let ended = 0;
21
+ const server = Bun.listen({
22
+ unix: socketPath(home),
23
+ socket: {
24
+ open: () => {
25
+ accepted += 1;
26
+ },
27
+ data: () => undefined,
28
+ // A client that is done sends its end; one that is gone closes.
29
+ end: (socket) => {
30
+ ended += 1;
31
+ socket.end();
32
+ },
33
+ },
34
+ });
35
+ return {
36
+ home,
37
+ accepted: () => accepted,
38
+ ended: () => ended,
39
+ stop: () => {
40
+ server.stop(true);
41
+ rmSync(home, { recursive: true, force: true });
42
+ },
43
+ };
44
+ }
45
+
46
+ /** Wait until a condition holds; false when it did not within the time. */
47
+ export async function within(ms: number, holds: () => boolean): Promise<boolean> {
48
+ const until = Date.now() + ms;
49
+ while (Date.now() < until) {
50
+ if (holds()) return true;
51
+ await Bun.sleep(10);
52
+ }
53
+ return holds();
54
+ }
@@ -0,0 +1,37 @@
1
+ // The line decoder judges a line by what it holds, not by where the socket cut the chunks.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { lineDecoder } from "../src/index.ts";
6
+
7
+ function run(chunks: string[], maxLineLength: number): { messages: unknown[]; errors: string[] } {
8
+ const messages: unknown[] = [];
9
+ const errors: string[] = [];
10
+ const decode = lineDecoder((message) => messages.push(message), { maxLineLength, onError: (error) => errors.push(error.message) });
11
+ for (const chunk of chunks) decode(chunk);
12
+ return { messages, errors };
13
+ }
14
+
15
+ const LINE = JSON.stringify({ text: "x".repeat(40) });
16
+
17
+ test("a line over the limit is refused whether its newline arrives with it or after it", () => {
18
+ const together = run([`${LINE}\n`], 20);
19
+ const apart = run([LINE, "\n"], 20);
20
+ expect(together.messages).toEqual([]);
21
+ expect(apart.messages).toEqual([]);
22
+ expect(together.errors).toHaveLength(1);
23
+ expect(apart.errors).toHaveLength(1);
24
+ });
25
+
26
+ test("a line within the limit is read for any split of its bytes", () => {
27
+ const whole = run([`${LINE}\n`], 100);
28
+ const split = run([LINE.slice(0, 10), LINE.slice(10), "\n"], 100);
29
+ expect(whole.messages).toEqual([{ text: "x".repeat(40) }]);
30
+ expect(split.messages).toEqual(whole.messages);
31
+ });
32
+
33
+ test("the decoder stops after it refused a line", () => {
34
+ const { messages, errors } = run([`${LINE}\n{"ok":true}\n`], 20);
35
+ expect(messages).toEqual([]);
36
+ expect(errors).toHaveLength(1);
37
+ });
@@ -0,0 +1,24 @@
1
+ // A live subscription gives its socket back when the consumer stops, even on a channel that says nothing.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { connect } from "../src/index.ts";
6
+ import { quietHost, within } from "./helpers.ts";
7
+
8
+ test("returning a live subscription wakes the read that waits on a quiet channel and releases the socket", async () => {
9
+ const host = quietHost();
10
+ const client = await connect({ home: host.home });
11
+ try {
12
+ const frames = client.live.subscribe("quiet")[Symbol.asyncIterator]();
13
+ const waiting = frames.next();
14
+ // The subscription has its own socket, next to the one of the calls.
15
+ expect(await within(2_000, () => host.accepted() === 2)).toBe(true);
16
+ const stopped = await Promise.race([frames.return?.().then(() => "returned"), Bun.sleep(2_000).then(() => "stuck")]);
17
+ expect(stopped).toBe("returned");
18
+ expect(await waiting).toEqual({ done: true, value: undefined });
19
+ expect(await within(2_000, () => host.ended() === 1)).toBe(true);
20
+ } finally {
21
+ await client.close();
22
+ host.stop();
23
+ }
24
+ }, 15_000);
@@ -0,0 +1,49 @@
1
+ // The local feed of a channel: it ends when its reader returns, and it holds a bounded backlog.
2
+
3
+ import { expect, test } from "bun:test";
4
+ import type { LiveFrame } from "@niwa-labs/core";
5
+
6
+ import { LiveBus, LiveFeed, MAX_QUEUED_FRAMES } from "../src/index.ts";
7
+
8
+ const frame = (n: number): LiveFrame => ({ channel: "c", data: n });
9
+
10
+ async function settles<T>(work: Promise<T>): Promise<T | "stuck"> {
11
+ return await Promise.race([work, Bun.sleep(1_000).then(() => "stuck" as const)]);
12
+ }
13
+
14
+ test("returning while a read waits on a quiet channel ends the read and leaves the channel", async () => {
15
+ const bus = new LiveBus();
16
+ const stream = bus.subscribe("c").iterate();
17
+ const waiting = stream.next();
18
+ expect(await settles(stream.return())).toEqual({ done: true, value: undefined });
19
+ expect(await settles(waiting)).toEqual({ done: true, value: undefined });
20
+ // The channel has no listener left: a frame sent now finds nobody.
21
+ const late = bus.subscribe("c").iterate();
22
+ bus.send("c", frame(1));
23
+ expect((await late.next()).value).toEqual(frame(1));
24
+ });
25
+
26
+ test("returning before the first read leaves the channel", async () => {
27
+ let left = false;
28
+ const stream = new LiveFeed(() => {
29
+ left = true;
30
+ }).iterate();
31
+ await stream.return();
32
+ expect(left).toBe(true);
33
+ expect(await stream.next()).toEqual({ done: true, value: undefined });
34
+ });
35
+
36
+ test("a reader that is slower than the sender loses the oldest frames", async () => {
37
+ const bus = new LiveBus();
38
+ const stream = bus.subscribe("c").iterate();
39
+ const total = MAX_QUEUED_FRAMES + 10;
40
+ for (let n = 0; n < total; n += 1) bus.send("c", frame(n));
41
+ const first = await stream.next();
42
+ expect(first.value).toEqual(frame(10));
43
+ let rest = 0;
44
+ for (; rest < MAX_QUEUED_FRAMES - 1; rest += 1) await stream.next();
45
+ expect(rest).toBe(MAX_QUEUED_FRAMES - 1);
46
+ bus.send("c", frame(-1));
47
+ expect((await stream.next()).value).toEqual(frame(-1));
48
+ await stream.return();
49
+ });
@@ -0,0 +1,79 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import ts from "typescript";
6
+
7
+ const SQLITE = "bun:sqlite";
8
+ const ENTRY = fileURLToPath(new URL("../src/index.ts", import.meta.url));
9
+ const transpiler = new Bun.Transpiler({ loader: "ts" });
10
+
11
+ interface Edge {
12
+ kind: string;
13
+ from: string;
14
+ specifier: string;
15
+ }
16
+
17
+ /** Every import the client entry reaches by loading, followed through workspace files. */
18
+ function reachable(entry: string): { files: Set<string>; edges: Edge[] } {
19
+ const files = new Set<string>();
20
+ const edges: Edge[] = [];
21
+ const queue = [entry];
22
+ while (queue.length > 0) {
23
+ const file = queue.pop() as string;
24
+ if (files.has(file)) continue;
25
+ files.add(file);
26
+ for (const { kind, path } of transpiler.scanImports(readFileSync(file, "utf8"))) {
27
+ edges.push({ kind, from: file, specifier: path });
28
+ if (kind !== "import-statement" || path.startsWith("node:") || path.startsWith("bun:")) continue;
29
+ const resolved = Bun.resolveSync(path, dirname(file));
30
+ if (!resolved.includes("/node_modules/")) queue.push(resolved);
31
+ }
32
+ }
33
+ return { files, edges };
34
+ }
35
+
36
+ /** Whether a file calls `require("bun:sqlite")` or `import("bun:sqlite")` where the module loads, outside any function. */
37
+ function loadsSqliteAtModuleLevel(file: string): boolean {
38
+ const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.ESNext, true);
39
+ let found = false;
40
+ const visit = (node: ts.Node, insideFunction: boolean): void => {
41
+ if (ts.isCallExpression(node) && !insideFunction) {
42
+ const callee = node.expression;
43
+ const named = ts.isIdentifier(callee) && callee.text === "require";
44
+ const dynamic = callee.kind === ts.SyntaxKind.ImportKeyword;
45
+ const first = node.arguments[0];
46
+ if ((named || dynamic) && first !== undefined && ts.isStringLiteralLike(first) && first.text === SQLITE) found = true;
47
+ }
48
+ const entersFunction = ts.isFunctionLike(node) || ts.isClassStaticBlockDeclaration(node);
49
+ ts.forEachChild(node, (child) => visit(child, insideFunction || entersFunction));
50
+ };
51
+ visit(source, false);
52
+ return found;
53
+ }
54
+
55
+ describe("the client entry", () => {
56
+ const { files, edges } = reachable(ENTRY);
57
+
58
+ test("follows the entry into the contracts of core", () => {
59
+ expect([...files].some((file) => file.endsWith("/core/src/index.ts"))).toBe(true);
60
+ });
61
+
62
+ test("never loads bun:sqlite, itself or through a package it imports", () => {
63
+ const loading = edges.filter((edge) => edge.kind === "import-statement" && edge.specifier === SQLITE);
64
+ expect(loading).toEqual([]);
65
+ });
66
+
67
+ test("never requires bun:sqlite where a module loads, in any file it reaches", () => {
68
+ expect([...files].filter(loadsSqliteAtModuleLevel)).toEqual([]);
69
+ });
70
+
71
+ test("does not reach the journal entry of core", () => {
72
+ expect([...files].filter((file) => file.endsWith("/core/src/journal.ts") || file.includes("/core/src/journal/"))).toEqual([]);
73
+ });
74
+
75
+ test("opens the database only inside the holder probe, when it runs", () => {
76
+ const lazy = edges.filter((edge) => edge.specifier === SQLITE);
77
+ expect(lazy.map((edge) => [edge.kind, edge.from.replace(/^.*\/packages\//, "")])).toEqual([["require-call", "client/src/holder.ts"]]);
78
+ });
79
+ });
@@ -0,0 +1,31 @@
1
+ // Where the owner's token is read from: a home written with `~` is the same home as the socket's.
2
+
3
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+
7
+ import { expect, test } from "bun:test";
8
+ import { OWNER_TOKEN_FILE } from "@niwa-labs/core";
9
+
10
+ const READER = join(import.meta.dir, "fixtures/owner-token-of.ts");
11
+
12
+ /** The token a fresh process reads for a home, when the user's home is `user`. */
13
+ async function tokenRead(user: string, home: string): Promise<string> {
14
+ const child = Bun.spawn([process.execPath, READER, home], { env: { ...process.env, HOME: user }, stdout: "pipe", stderr: "pipe" });
15
+ const [out, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
16
+ expect(code).toBe(0);
17
+ return out.trim();
18
+ }
19
+
20
+ test("the owner token of a home written with a leading ~ is read from the home of the user", async () => {
21
+ const user = mkdtempSync(join(tmpdir(), "niwa-user-"));
22
+ try {
23
+ mkdirSync(join(user, ".niwa"));
24
+ writeFileSync(join(user, ".niwa", OWNER_TOKEN_FILE), "ab12\n");
25
+ expect(await tokenRead(user, "~/.niwa")).toBe("ab12");
26
+ expect(await tokenRead(user, join(user, ".niwa"))).toBe("ab12");
27
+ expect(await tokenRead(user, "~/.elsewhere")).toBe("none");
28
+ } finally {
29
+ rmSync(user, { recursive: true, force: true });
30
+ }
31
+ }, 30_000);
@@ -0,0 +1,20 @@
1
+ // A query the wire refuses is told to the caller at once; it is not retried as if the socket had dropped.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { connect } from "../src/index.ts";
6
+ import { quietHost } from "./helpers.ts";
7
+
8
+ test("a subscription to a query the wire does not accept fails before any connection is made", async () => {
9
+ const host = quietHost();
10
+ const client = await connect({ home: host.home });
11
+ try {
12
+ expect(() => client.records.since({ stream: "" })).toThrow(/stream: /);
13
+ await Bun.sleep(300);
14
+ // Only the connection of the calls was ever opened.
15
+ expect(host.accepted()).toBe(1);
16
+ } finally {
17
+ await client.close();
18
+ host.stop();
19
+ }
20
+ });