@opencode/client 0.0.0-reserved → 2.0.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 (62) hide show
  1. package/README.md +24 -2
  2. package/dist/contract.d.ts +1 -0
  3. package/dist/contract.js +1 -0
  4. package/dist/effect/api/api.d.ts +2698 -0
  5. package/dist/effect/api/api.js +0 -0
  6. package/dist/effect/api.d.ts +8 -0
  7. package/dist/effect/api.js +0 -0
  8. package/dist/effect/client.d.ts +2464 -0
  9. package/dist/effect/client.js +29 -0
  10. package/dist/effect/generated/client-error.d.ts +7 -0
  11. package/dist/effect/generated/client-error.js +5 -0
  12. package/dist/effect/generated/client.d.ts +2463 -0
  13. package/dist/effect/generated/client.js +603 -0
  14. package/dist/effect/generated/index.d.ts +2 -0
  15. package/dist/effect/generated/index.js +2 -0
  16. package/dist/effect/index.d.ts +35 -0
  17. package/dist/effect/index.js +30 -0
  18. package/dist/effect/rpc.d.ts +20 -0
  19. package/dist/effect/rpc.js +49 -0
  20. package/dist/effect/service.d.ts +78 -0
  21. package/dist/effect/service.js +259 -0
  22. package/dist/promise/api.d.ts +24 -0
  23. package/dist/promise/api.js +0 -0
  24. package/dist/promise/client.d.ts +257 -0
  25. package/dist/promise/client.js +13 -0
  26. package/dist/promise/generated/client-error.d.ts +6 -0
  27. package/dist/promise/generated/client-error.js +8 -0
  28. package/dist/promise/generated/client.d.ts +264 -0
  29. package/dist/promise/generated/client.js +1426 -0
  30. package/dist/promise/generated/index.d.ts +3 -0
  31. package/dist/promise/generated/index.js +3 -0
  32. package/dist/promise/generated/types.d.ts +8777 -0
  33. package/dist/promise/generated/types.js +30 -0
  34. package/dist/promise/index.d.ts +6 -0
  35. package/dist/promise/index.js +2 -0
  36. package/dist/promise/rpc.d.ts +32 -0
  37. package/dist/promise/rpc.js +86 -0
  38. package/dist/promise/service.d.ts +26 -0
  39. package/dist/promise/service.js +247 -0
  40. package/dist/pty-handoff.d.ts +9 -0
  41. package/dist/pty-handoff.js +121 -0
  42. package/dist/rpc-runtime.d.ts +21 -0
  43. package/dist/rpc-runtime.js +32 -0
  44. package/dist/service-contender.d.ts +11 -0
  45. package/dist/service-contender.js +56 -0
  46. package/dist/service-timing.d.ts +13 -0
  47. package/dist/service-timing.js +19 -0
  48. package/dist/service-version.d.ts +2 -0
  49. package/dist/service-version.js +9 -0
  50. package/dist/service.d.ts +52 -0
  51. package/dist/service.js +0 -0
  52. package/dist/shared-events.d.ts +11 -0
  53. package/dist/shared-events.js +137 -0
  54. package/dist/solid/connection.d.ts +37 -0
  55. package/dist/solid/connection.js +246 -0
  56. package/dist/solid/data.d.ts +201 -0
  57. package/dist/solid/data.js +1731 -0
  58. package/dist/solid/index.d.ts +3 -0
  59. package/dist/solid/index.js +3 -0
  60. package/dist/solid/pty.d.ts +22 -0
  61. package/dist/solid/pty.js +43 -0
  62. package/package.json +76 -6
@@ -0,0 +1,56 @@
1
+ import { spawn } from "node:child_process";
2
+ const stderrLimit = 8 * 1024;
3
+ export function spawnServiceContender(command, args, env) {
4
+ const child = spawn(command, args, {
5
+ detached: true,
6
+ stdio: ["ignore", "ignore", "pipe"],
7
+ env: { ...process.env, ...env },
8
+ });
9
+ let error;
10
+ let closed = false;
11
+ let stderr = Buffer.alloc(0);
12
+ const onStderr = (chunk) => {
13
+ const tail = chunk.subarray(-stderrLimit);
14
+ stderr =
15
+ tail.length === stderrLimit
16
+ ? Buffer.from(tail)
17
+ : Buffer.concat([stderr.subarray(-(stderrLimit - tail.length)), tail]);
18
+ };
19
+ child.stderr?.on("data", onStderr);
20
+ if (child.stderr !== null && "unref" in child.stderr && typeof child.stderr.unref === "function")
21
+ child.stderr.unref();
22
+ child.once("error", (cause) => {
23
+ error = new Error("Failed to start server", { cause });
24
+ });
25
+ child.once("close", () => {
26
+ closed = true;
27
+ });
28
+ child.unref();
29
+ return {
30
+ child,
31
+ error: () => error,
32
+ closed: () => closed,
33
+ stderr: () => stderr.toString("utf8").trim(),
34
+ release: () => {
35
+ child.stderr?.off("data", onStderr);
36
+ child.stderr?.resume();
37
+ stderr = Buffer.alloc(0);
38
+ },
39
+ };
40
+ }
41
+ export function contenderFailure(contender) {
42
+ const error = contender.error();
43
+ if (error !== undefined)
44
+ return error;
45
+ if (contender.child.exitCode !== null && contender.child.exitCode !== 0)
46
+ return startupError(`Server process exited with code ${contender.child.exitCode}`, contender.stderr());
47
+ if (contender.child.signalCode !== null)
48
+ return startupError(`Server process terminated by ${contender.child.signalCode}`, contender.stderr());
49
+ return undefined;
50
+ }
51
+ export function contenderFinished(contender) {
52
+ return contender.error() !== undefined || contender.closed();
53
+ }
54
+ function startupError(message, stderr) {
55
+ return new Error(stderr ? `${message}\n${stderr}` : message);
56
+ }
@@ -0,0 +1,13 @@
1
+ export type EnsureTiming = {
2
+ readonly pollInterval: number;
3
+ readonly attempts: number;
4
+ readonly requestTimeout: number;
5
+ readonly spawnDelay: number;
6
+ readonly maxSpawnDelay: number;
7
+ readonly promiseTimeout: number;
8
+ readonly stopPollInterval: number;
9
+ readonly stopPollAttempts: number;
10
+ };
11
+ export declare const defaultEnsureTiming: EnsureTiming;
12
+ export declare function ensureTiming(options: object): EnsureTiming;
13
+ export declare function withEnsureTiming<A extends object>(options: A, overrides: Partial<EnsureTiming>): A;
@@ -0,0 +1,19 @@
1
+ const timings = new WeakMap();
2
+ export const defaultEnsureTiming = {
3
+ pollInterval: 100,
4
+ attempts: 1_200,
5
+ requestTimeout: 2_000,
6
+ spawnDelay: 5_000,
7
+ maxSpawnDelay: 30_000,
8
+ promiseTimeout: 120_000,
9
+ stopPollInterval: 50,
10
+ stopPollAttempts: 100,
11
+ };
12
+ export function ensureTiming(options) {
13
+ return timings.get(options) ?? defaultEnsureTiming;
14
+ }
15
+ // Keep test timing out of the public lifecycle option types.
16
+ export function withEnsureTiming(options, overrides) {
17
+ timings.set(options, { ...defaultEnsureTiming, ...overrides });
18
+ return options;
19
+ }
@@ -0,0 +1,2 @@
1
+ import type { DiscoverOptions } from "./service.js";
2
+ export declare function matchesVersion(version: string | undefined, options: DiscoverOptions): boolean;
@@ -0,0 +1,9 @@
1
+ export function matchesVersion(version, options) {
2
+ if (options.version === undefined)
3
+ return true;
4
+ if (version === undefined)
5
+ return false;
6
+ if (typeof options.version === "function")
7
+ return options.version(version);
8
+ return version === options.version;
9
+ }
@@ -0,0 +1,52 @@
1
+ /** Connection details for a local OpenCode service. */
2
+ export type Endpoint = {
3
+ /** Base URL of the service. */
4
+ readonly url: string;
5
+ /** Authentication required by the service, when configured. */
6
+ readonly auth?: {
7
+ /** HTTP authentication scheme. */
8
+ readonly type: "basic";
9
+ /** Basic authentication username. */
10
+ readonly username: string;
11
+ /** Basic authentication password. */
12
+ readonly password: string;
13
+ };
14
+ };
15
+ /** Options used to discover the local OpenCode service. */
16
+ export type DiscoverOptions = {
17
+ /** Absolute registration file path. Defaults to the XDG state directory. */
18
+ readonly file?: string;
19
+ /** Required exact service version or compatibility predicate. */
20
+ readonly version?: string | ((version: string) => boolean);
21
+ };
22
+ /** Reason ensuring the service requires a new process. */
23
+ export type EnsureReason = "missing" | "version-mismatch";
24
+ /** Options used to ensure the local OpenCode service is running. */
25
+ export type EnsureOptions = DiscoverOptions & {
26
+ /** Service command and arguments. Defaults to `opencode serve --service`. */
27
+ readonly command?: ReadonlyArray<string>;
28
+ /** Environment variables added to the inherited service process environment. */
29
+ readonly env?: Readonly<Record<string, string>>;
30
+ /** Called once before spawning a new service process. */
31
+ readonly onStart?: (reason: EnsureReason, previousVersion?: string) => void;
32
+ };
33
+ /** Options used to stop the local OpenCode service. */
34
+ export type StopOptions = {
35
+ /** Absolute registration file path. Defaults to the XDG state directory. */
36
+ readonly file?: string;
37
+ /** How to handle persistent terminals before stopping the service. */
38
+ readonly pty?: "clear" | "handoff";
39
+ };
40
+ /** Contents of the local service registration file. */
41
+ export type Info = {
42
+ /** Unique service instance identifier. */
43
+ readonly id?: string;
44
+ /** OpenCode version served by the process. */
45
+ readonly version?: string;
46
+ /** Base URL advertised by the service. */
47
+ readonly url: string;
48
+ /** Operating system process identifier. */
49
+ readonly pid: number;
50
+ /** Private service password, when authentication is enabled. */
51
+ readonly password?: string;
52
+ };
File without changes
@@ -0,0 +1,11 @@
1
+ export * as SharedEvents from "./shared-events.js";
2
+ export type SubscribeOptions = {
3
+ readonly signal?: AbortSignal;
4
+ /** Reports transport activity on the shared stream, including keepalive frames that carry no event. */
5
+ readonly onActivity?: () => void;
6
+ };
7
+ export declare function make<A extends {
8
+ readonly type: string;
9
+ }>(connect: (signal: AbortSignal, onActivity: () => void) => AsyncIterable<A>): {
10
+ subscribe(options?: SubscribeOptions): AsyncIterable<A>;
11
+ };
@@ -0,0 +1,137 @@
1
+ export * as SharedEvents from "./shared-events.js";
2
+ export function make(connect) {
3
+ let current;
4
+ const capacity = 4_096;
5
+ function stop(connection) {
6
+ connection.connected = undefined;
7
+ connection.controller.abort();
8
+ if (current === connection)
9
+ current = undefined;
10
+ }
11
+ async function run(connection) {
12
+ let iterator;
13
+ let completion = {};
14
+ try {
15
+ if (connection.controller.signal.aborted)
16
+ return;
17
+ iterator = connect(connection.controller.signal, () => {
18
+ connection.subscribers.forEach((subscriber) => subscriber.activity?.());
19
+ })[Symbol.asyncIterator]();
20
+ while (!connection.controller.signal.aborted) {
21
+ const item = await iterator.next();
22
+ if (item.done || connection.controller.signal.aborted)
23
+ break;
24
+ if (item.value.type === "server.connected")
25
+ connection.connected = item.value;
26
+ connection.subscribers.forEach((subscriber) => subscriber.push(item.value));
27
+ }
28
+ }
29
+ catch (error) {
30
+ completion = { error };
31
+ }
32
+ finally {
33
+ stop(connection);
34
+ try {
35
+ await iterator?.return?.();
36
+ }
37
+ catch (error) {
38
+ if (!("error" in completion))
39
+ completion = { error };
40
+ }
41
+ connection.subscribers.forEach((subscriber) => subscriber.finish(completion));
42
+ }
43
+ }
44
+ return {
45
+ subscribe(options) {
46
+ return {
47
+ [Symbol.asyncIterator]() {
48
+ const pending = [];
49
+ const queued = [];
50
+ let started = false;
51
+ let completion;
52
+ let connection;
53
+ function finish(result, discard = true) {
54
+ completion = result;
55
+ if (discard)
56
+ queued.length = 0;
57
+ options?.signal?.removeEventListener("abort", abort);
58
+ if (connection?.subscribers.delete(subscriber) && !connection.subscribers.size)
59
+ stop(connection);
60
+ pending.splice(0).forEach((request) => {
61
+ if ("error" in result)
62
+ request.reject(result.error);
63
+ else
64
+ request.resolve({ done: true, value: undefined });
65
+ });
66
+ }
67
+ function abort() {
68
+ finish({});
69
+ }
70
+ const subscriber = {
71
+ activity: options?.onActivity,
72
+ finish(result) {
73
+ finish(result, false);
74
+ },
75
+ push(value) {
76
+ if (completion)
77
+ return;
78
+ const request = pending.shift();
79
+ if (request) {
80
+ request.resolve({ done: false, value });
81
+ return;
82
+ }
83
+ if (queued.length === capacity) {
84
+ finish({ error: new Error(`Event subscriber exceeded its ${capacity}-event capacity`) });
85
+ return;
86
+ }
87
+ queued.push(value);
88
+ },
89
+ };
90
+ function start() {
91
+ if (completion)
92
+ return;
93
+ const fresh = !current;
94
+ connection = current ?? {
95
+ controller: new AbortController(),
96
+ subscribers: new Set(),
97
+ };
98
+ current = connection;
99
+ connection.subscribers.add(subscriber);
100
+ if (connection.connected)
101
+ void subscriber.push(connection.connected);
102
+ if (fresh)
103
+ void run(connection);
104
+ }
105
+ return {
106
+ next() {
107
+ const value = queued.shift();
108
+ if (value)
109
+ return Promise.resolve({ done: false, value });
110
+ if (completion) {
111
+ if ("error" in completion)
112
+ return Promise.reject(completion.error);
113
+ return Promise.resolve({ done: true, value: undefined });
114
+ }
115
+ if (options?.signal?.aborted) {
116
+ abort();
117
+ return Promise.resolve({ done: true, value: undefined });
118
+ }
119
+ const request = Promise.withResolvers();
120
+ pending.push(request);
121
+ if (!started) {
122
+ started = true;
123
+ options?.signal?.addEventListener("abort", abort, { once: true });
124
+ start();
125
+ }
126
+ return request.promise;
127
+ },
128
+ return() {
129
+ finish({});
130
+ return Promise.resolve({ done: true, value: undefined });
131
+ },
132
+ };
133
+ },
134
+ };
135
+ },
136
+ };
137
+ }
@@ -0,0 +1,37 @@
1
+ import type { OpenCodeClient, OpenCodeEvent } from "../promise";
2
+ export type ClientConnectionStatus = "connected" | "connecting" | "reconnecting";
3
+ export type ClientConnectionEvent = {
4
+ readonly type: "client.connection";
5
+ readonly created: number;
6
+ readonly data: {
7
+ readonly status: "connecting" | "connected" | "disconnected" | "reconnecting";
8
+ readonly attempt: number;
9
+ readonly error?: string;
10
+ };
11
+ };
12
+ export type ClientConnectionOptions = {
13
+ readonly reconnect?: (signal: AbortSignal) => Promise<OpenCodeClient>;
14
+ readonly onEvent: (event: OpenCodeEvent) => void;
15
+ readonly flushInterval?: number;
16
+ readonly pageLifecycle?: boolean;
17
+ /**
18
+ * Abort and reconnect a stream that receives no bytes for this long. The server writes a keepalive
19
+ * comment every 15 seconds, so a quiet but healthy stream never trips this.
20
+ */
21
+ readonly idleTimeout?: number;
22
+ readonly log?: {
23
+ readonly debug?: (message: string, data?: Readonly<Record<string, unknown>>) => void;
24
+ readonly info?: (message: string, data?: Readonly<Record<string, unknown>>) => void;
25
+ };
26
+ };
27
+ export declare const defaultIdleTimeout = 45000;
28
+ export declare const foregroundIdleThreshold = 20000;
29
+ export declare function createClientConnection(initialApi: OpenCodeClient, options: ClientConnectionOptions): {
30
+ status: () => ClientConnectionStatus;
31
+ attempt: () => number;
32
+ error: () => string | undefined;
33
+ internal: {
34
+ history: () => ClientConnectionEvent[];
35
+ resync: (reason: string) => void;
36
+ };
37
+ };
@@ -0,0 +1,246 @@
1
+ import { batch, onCleanup } from "solid-js";
2
+ import { createStore } from "solid-js/store";
3
+ const connectTimeout = 2_000;
4
+ const reconnectDelay = 1_000;
5
+ const connectionHistoryLimit = 50;
6
+ export const defaultIdleTimeout = 45_000;
7
+ // Longer than one server keepalive interval: a stream that is silent this long when the page
8
+ // returns to the foreground is probably half-open after the device slept.
9
+ export const foregroundIdleThreshold = 20_000;
10
+ export function createClientConnection(initialApi, options) {
11
+ const abort = new AbortController();
12
+ const history = [];
13
+ const idleTimeout = options.idleTimeout ?? defaultIdleTimeout;
14
+ const [connection, setConnection] = createStore({ status: "connecting", attempt: 0 });
15
+ let api = initialApi;
16
+ let pending = [];
17
+ let flushTimer;
18
+ let stream;
19
+ let current;
20
+ let run;
21
+ let started = false;
22
+ let generation = 0;
23
+ let lastActivity = 0;
24
+ let forced = false;
25
+ function record(status, attempt, error) {
26
+ history.push({ type: "client.connection", created: Date.now(), data: { status, attempt, error } });
27
+ if (history.length > connectionHistoryLimit)
28
+ history.shift();
29
+ }
30
+ function publish(event) {
31
+ pending.push(event);
32
+ if (flushTimer)
33
+ return;
34
+ flushTimer = setTimeout(() => {
35
+ flushTimer = undefined;
36
+ const events = pending;
37
+ pending = [];
38
+ batch(() => events.forEach(options.onEvent));
39
+ }, options.flushInterval ?? 10);
40
+ }
41
+ async function connect(signal, attempt) {
42
+ let connectedAt;
43
+ const request = new AbortController();
44
+ current = request;
45
+ const cancel = () => request.abort(signal.reason);
46
+ const timeout = setTimeout(() => request.abort(new Error("Timed out connecting to server")), connectTimeout);
47
+ signal.addEventListener("abort", cancel, { once: true });
48
+ // Any received bytes, including keepalive comments, push the stall deadline out. A timer whose
49
+ // deadline passed while the page was suspended fires as soon as the page resumes.
50
+ let watchdog;
51
+ const touch = () => {
52
+ lastActivity = Date.now();
53
+ if (connectedAt === undefined)
54
+ return;
55
+ clearTimeout(watchdog);
56
+ watchdog = setTimeout(() => request.abort(new Error("Event stream stalled")), idleTimeout);
57
+ };
58
+ try {
59
+ record(attempt === 0 ? "connecting" : "reconnecting", attempt);
60
+ options.log?.info?.("event stream connecting", { attempt });
61
+ const iterator = api.event.subscribe({ signal: request.signal, onActivity: touch })[Symbol.asyncIterator]();
62
+ const first = await iterator.next();
63
+ if (signal.aborted)
64
+ return { error: undefined, connectedAt };
65
+ if (first.done)
66
+ return {
67
+ error: request.signal.reason instanceof Error ? request.signal.reason : new Error("Event stream disconnected"),
68
+ connectedAt,
69
+ };
70
+ if (first.value.type !== "server.connected")
71
+ return { error: new Error("Event stream did not start with server.connected"), connectedAt };
72
+ clearTimeout(timeout);
73
+ record("connected", attempt);
74
+ connectedAt = Date.now();
75
+ touch();
76
+ options.log?.info?.("event stream connected");
77
+ publish(first.value);
78
+ setConnection({ status: "connected", attempt: 0, error: undefined });
79
+ while (!signal.aborted) {
80
+ const event = await iterator.next();
81
+ if (signal.aborted)
82
+ return { error: undefined, connectedAt };
83
+ if (event.done)
84
+ return {
85
+ error: request.signal.reason instanceof Error ? request.signal.reason : new Error("Event stream disconnected"),
86
+ connectedAt,
87
+ };
88
+ touch();
89
+ if ("durable" in event.value && event.value.durable)
90
+ options.log?.debug?.("event", {
91
+ type: event.value.type,
92
+ aggregateID: event.value.durable.aggregateID,
93
+ seq: event.value.durable.seq,
94
+ });
95
+ publish(event.value);
96
+ }
97
+ return { error: undefined, connectedAt };
98
+ }
99
+ catch (error) {
100
+ return { error, connectedAt };
101
+ }
102
+ finally {
103
+ request.abort();
104
+ if (current === request)
105
+ current = undefined;
106
+ clearTimeout(timeout);
107
+ clearTimeout(watchdog);
108
+ signal.removeEventListener("abort", cancel);
109
+ }
110
+ }
111
+ async function runStream(active) {
112
+ let attempt = 0;
113
+ while (!abort.signal.aborted && started && generation === active) {
114
+ setConnection({ status: attempt === 0 ? "connecting" : "reconnecting", attempt });
115
+ const controller = new AbortController();
116
+ stream = controller;
117
+ const cancel = () => controller.abort(abort.signal.reason);
118
+ abort.signal.addEventListener("abort", cancel);
119
+ const result = await connect(controller.signal, attempt);
120
+ abort.signal.removeEventListener("abort", cancel);
121
+ if (abort.signal.aborted || !started || generation !== active)
122
+ return;
123
+ if (result.connectedAt !== undefined && Date.now() - result.connectedAt >= reconnectDelay)
124
+ attempt = 0;
125
+ attempt += 1;
126
+ const message = errorMessage(result.error);
127
+ record("disconnected", attempt, message);
128
+ options.log?.info?.("event stream disconnected", { attempt, error: message });
129
+ setConnection({ status: "reconnecting", attempt, error: message });
130
+ if (options.reconnect) {
131
+ const next = await options.reconnect(controller.signal).catch((error) => {
132
+ if (!controller.signal.aborted)
133
+ options.log?.info?.("server resolution failed", { attempt, error: errorMessage(error) });
134
+ });
135
+ if (abort.signal.aborted || controller.signal.aborted || !started || generation !== active)
136
+ return;
137
+ if (next) {
138
+ api = next;
139
+ if (attempt === 1)
140
+ continue;
141
+ }
142
+ }
143
+ // A deliberate resync already knows the old socket is gone; reconnect without backing off.
144
+ if (forced) {
145
+ forced = false;
146
+ continue;
147
+ }
148
+ await wait(reconnectDelay, controller.signal);
149
+ }
150
+ }
151
+ function start() {
152
+ if (started)
153
+ return run;
154
+ started = true;
155
+ forced = false;
156
+ const active = ++generation;
157
+ const previous = run;
158
+ const current = (async () => {
159
+ if (previous)
160
+ await previous;
161
+ await runStream(active);
162
+ })().finally(() => {
163
+ if (run !== current)
164
+ return;
165
+ run = undefined;
166
+ });
167
+ run = current;
168
+ return run;
169
+ }
170
+ function stop() {
171
+ if (!started)
172
+ return;
173
+ started = false;
174
+ generation += 1;
175
+ stream?.abort();
176
+ // Nothing is listening once stopped, so consumers must treat their data as stale until start() reconnects.
177
+ setConnection({ status: "connecting", attempt: 0, error: undefined });
178
+ }
179
+ // Drop the live request so the reconnect loop replaces it now instead of waiting for the idle watchdog.
180
+ function resync(reason) {
181
+ if (!started || connection.status !== "connected")
182
+ return;
183
+ options.log?.info?.("event stream resync", { reason, idle: Date.now() - lastActivity });
184
+ forced = true;
185
+ current?.abort(new Error(reason));
186
+ }
187
+ if (options.pageLifecycle) {
188
+ const pagehide = () => stop();
189
+ const pageshow = () => void start();
190
+ // Locking a phone or switching apps hides the document without a pagehide; the socket usually
191
+ // dies while the page is suspended, and the browser may never report that on the hung read.
192
+ const visibility = () => {
193
+ if (document.visibilityState !== "visible")
194
+ return;
195
+ if (Date.now() - lastActivity < foregroundIdleThreshold)
196
+ return;
197
+ resync("Page returned to the foreground after the event stream went quiet");
198
+ };
199
+ const online = () => resync("Network connection restored");
200
+ window.addEventListener("pagehide", pagehide);
201
+ window.addEventListener("pageshow", pageshow);
202
+ window.addEventListener("online", online);
203
+ document.addEventListener("visibilitychange", visibility);
204
+ onCleanup(() => {
205
+ window.removeEventListener("pagehide", pagehide);
206
+ window.removeEventListener("pageshow", pageshow);
207
+ window.removeEventListener("online", online);
208
+ document.removeEventListener("visibilitychange", visibility);
209
+ });
210
+ }
211
+ void start();
212
+ onCleanup(() => {
213
+ stop();
214
+ abort.abort();
215
+ if (flushTimer)
216
+ clearTimeout(flushTimer);
217
+ pending = [];
218
+ });
219
+ return {
220
+ status: () => connection.status,
221
+ attempt: () => connection.attempt,
222
+ error: () => connection.error,
223
+ internal: {
224
+ history: () => history.slice(),
225
+ resync,
226
+ },
227
+ };
228
+ }
229
+ function errorMessage(error) {
230
+ if (error === undefined)
231
+ return undefined;
232
+ if (error instanceof Error)
233
+ return error.message;
234
+ return String(error);
235
+ }
236
+ function wait(delay, signal) {
237
+ return new Promise((resolve) => {
238
+ const timer = setTimeout(done, delay);
239
+ signal.addEventListener("abort", done, { once: true });
240
+ function done() {
241
+ clearTimeout(timer);
242
+ signal.removeEventListener("abort", done);
243
+ resolve();
244
+ }
245
+ });
246
+ }