@bowmark/web 1.29.1 → 1.29.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/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /// <reference path="./generated/library.d.ts" />
2
- import { type ClientOptions, type RunEnvelope } from "./transport.js";
2
+ import { type RunEnvelope, type RunOptions } from "./transport.js";
3
3
  export { type WireProblem, wireProblem } from "./guard.js";
4
4
  export { type ConnectionsApi, client, openManagedSession, type SessionHandle, session, } from "./session.js";
5
- export { type AuthNeed, BowmarkError, BowmarkNeedsUserError, type CallEnvelope, type ClientOptions, type ClosedSession, type ConnectionSummary, type FetchLike, type Handoff, type OpenedSession, type RunEnvelope, } from "./transport.js";
5
+ export { type AuthNeed, BowmarkError, BowmarkNeedsUserError, type CallEnvelope, type ClientOptions, type ClosedSession, type ConnectionSummary, type FetchLike, type Handoff, type OpenedSession, type RunEnvelope, type RunOptions, } from "./transport.js";
6
6
  /** The whole callable library, typed. `await bowmark.music.search("aphex twin")`.
7
7
  *
8
8
  * Each call opens its own one-shot session, which is right for ONE call and wrong
@@ -23,7 +23,12 @@ export declare const bowmark: BowmarkLibrary;
23
23
  *
24
24
  * Returns the envelope rather than throwing: a script is composite, so `status`,
25
25
  * `logs` and `result` are read together. `needs_user` carries a handoff URL in
26
- * `meta.handoff`. */
27
- export declare function run<T = unknown>(script: string, opts?: ClientOptions): Promise<RunEnvelope<T>>;
26
+ * `meta.handoff`.
27
+ *
28
+ * A NON-string is refused here, before anything is sent. A function does not
29
+ * serialize, so it reached the server as a missing `script` and came back as an
30
+ * envelope saying to send raw HTTP — a message that points at the wrong layer, in
31
+ * a return value a script never reads. A function belongs in `session()`. */
32
+ export declare function run<T = unknown>(script: string, opts?: RunOptions): Promise<RunEnvelope<T>>;
28
33
  export type Library = BowmarkLibrary;
29
34
  export type Providers = BowmarkProviders;
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@
15
15
  // running in an isolate on ours. The types are generated once and describe both, so
16
16
  // the two must stay in sync — see `packages/runtime/src/namespace.ts`.
17
17
  import { client } from "./session.js";
18
- import { postRun, resolveClient } from "./transport.js";
18
+ import { BowmarkError, postRun, resolveClient, } from "./transport.js";
19
19
  export { wireProblem } from "./guard.js";
20
20
  export { client, openManagedSession, session, } from "./session.js";
21
21
  export { BowmarkError, BowmarkNeedsUserError, } from "./transport.js";
@@ -39,7 +39,24 @@ export const bowmark = client();
39
39
  *
40
40
  * Returns the envelope rather than throwing: a script is composite, so `status`,
41
41
  * `logs` and `result` are read together. `needs_user` carries a handoff URL in
42
- * `meta.handoff`. */
42
+ * `meta.handoff`.
43
+ *
44
+ * A NON-string is refused here, before anything is sent. A function does not
45
+ * serialize, so it reached the server as a missing `script` and came back as an
46
+ * envelope saying to send raw HTTP — a message that points at the wrong layer, in
47
+ * a return value a script never reads. A function belongs in `session()`. */
43
48
  export function run(script, opts = {}) {
44
- return postRun(resolveClient(opts), script);
49
+ if (typeof script !== "string") {
50
+ return Promise.reject(new BowmarkError(`run() takes the script as a STRING, and got ${describeValue(script)}. ` +
51
+ "Write the script as text, e.g. run(\"return await bowmark.music.search('x')\"). " +
52
+ "To write code in your own file, use session(async (bm) => …), which takes a function.", { code: "run_not_a_string" }));
53
+ }
54
+ return postRun(resolveClient(opts), script, { idempotent: opts.idempotent });
55
+ }
56
+ function describeValue(value) {
57
+ if (value === null)
58
+ return "null";
59
+ if (typeof value === "function")
60
+ return "a function";
61
+ return Array.isArray(value) ? "an array" : `a ${typeof value}`;
45
62
  }
@@ -87,6 +87,15 @@ export interface RunEnvelope<T = unknown> {
87
87
  }[];
88
88
  };
89
89
  }
90
+ /** `run()`'s options: the client options, plus the one thing only the caller knows. */
91
+ export interface RunOptions extends ClientOptions {
92
+ /** Set `true` ONLY if the script can be sent again without doing anything twice: a
93
+ * read, a poll, or a `stop()` of a session that may already be stopped. Then a
94
+ * connection reset that returns no response is retried (3 attempts in about 1s).
95
+ * Left unset, a reset throws `network_error` at once, because the request may have
96
+ * started a billed action that a retry would start again. */
97
+ idempotent?: boolean;
98
+ }
90
99
  /** Which (capability, provider) pair has no live grant. */
91
100
  export interface AuthNeed {
92
101
  capability: string;
@@ -168,7 +177,13 @@ export declare function openSession(client: ResolvedClient): Promise<OpenedSessi
168
177
  * types promise. The envelope's other fields are not dropped: `logs` go to `onLog`,
169
178
  * and everything that is not `status: "ok"` becomes a throw carrying `code`. */
170
179
  export declare function callInSession(client: ResolvedClient, sessionId: string, path: readonly string[], args: readonly unknown[], extraHeaders?: Record<string, string>): Promise<unknown>;
171
- /** Close a session. Idempotent server-side, so a `finally` that runs twice is fine. */
180
+ /** Close a session. Idempotent server-side, so a `finally` that runs twice is fine.
181
+ *
182
+ * A close is retried on a transport reset, and a close that still cannot reach Bowmark
183
+ * RETURNS `null` (reported through `onLog`) rather than throwing. By the time it runs
184
+ * the caller's work is done and its result is in hand, so a dropped socket here must
185
+ * not turn a finished script into a failed one. The session's TTL reaps what was not
186
+ * closed. Any other failure still throws. */
172
187
  export declare function closeSession(client: ResolvedClient, sessionId: string): Promise<ClosedSession | null>;
173
188
  /** One saved login, as `GET /v1/connections` reports it. Mirrors the `.d.ts`'s
174
189
  * ambient `ConnectionSummary` — see `scripts/gen-public-types.ts`'s
@@ -235,4 +250,6 @@ export declare function updateConnection(client: ResolvedClient, id: string, pat
235
250
  /** The string surface. Returns the ENVELOPE rather than throwing, because a script
236
251
  * is composite: a `needs_user` or an `error` is a fact about the run that a caller
237
252
  * reads alongside `logs` and `result`, not an exception in their control flow. */
238
- export declare function postRun<T>(client: ResolvedClient, script: string): Promise<RunEnvelope<T>>;
253
+ export declare function postRun<T>(client: ResolvedClient, script: string, opts?: {
254
+ idempotent?: boolean;
255
+ }): Promise<RunEnvelope<T>>;
package/dist/transport.js CHANGED
@@ -1,9 +1,11 @@
1
1
  // The transport — `fetch` and nothing else.
2
2
  //
3
- // Three session endpoints plus the string surface. No retries, no backoff, no
4
- // connection pool: every one of those is a policy a caller can hold better than we
5
- // can, and a client that silently retries a `addToCart` is the bug the idempotency
6
- // discussion in `docs/reference/building-capabilities.md` exists to prevent.
3
+ // Three session endpoints plus the string surface. No connection pool, and no retry
4
+ // of anything a caller did not say is safe to repeat: a client that silently retries
5
+ // an `addToCart` is the bug the idempotency discussion in
6
+ // `docs/reference/building-capabilities.md` exists to prevent. The two exceptions are
7
+ // bounded and named: an edge 429 (never reached the api), and a transport reset on a
8
+ // request the caller declared `idempotent` or a session close (see `sendRequest`).
7
9
  //
8
10
  // ZERO RUNTIME DEPENDENCIES, permanently — including on `@bowmark/schema`. The
9
11
  // envelope shapes below are hand-restated rather than imported, because importing a
@@ -92,7 +94,7 @@ export function resolveClient(opts = {}) {
92
94
  * so `authorization` and `content-type`, set last, always win. A header that
93
95
  * silently replaced the api key would make an unauthenticated call look like a
94
96
  * permissions problem on our side. */
95
- async function sendRequest(client, method, path, body, extraHeaders) {
97
+ async function sendRequest(client, method, path, body, extraHeaders, retryTransport = false) {
96
98
  const headers = {
97
99
  ...client.headers,
98
100
  ...extraHeaders,
@@ -122,6 +124,15 @@ async function sendRequest(client, method, path, body, extraHeaders) {
122
124
  // Extract the underlying cause if available (e.g., from undici).
123
125
  const cause = err instanceof Error ? err : undefined;
124
126
  const causeMessage = cause?.cause instanceof Error ? `${cause.cause.message}` : cause?.message || String(err);
127
+ // No response arrived, so the request may not have reached Bowmark at all. A
128
+ // caller who declared this request safe to repeat gets the same bounded retry the
129
+ // edge 429 gets. Responses are never retried here, whatever their status.
130
+ if (retryTransport && attempt < TRANSPORT_ATTEMPTS - 1 && !client.signal?.aborted) {
131
+ const wait = TRANSPORT_RETRY_WAITS_MS[attempt] ?? TRANSPORT_RETRY_WAITS_MS.at(-1) ?? 0;
132
+ client.onLog?.(`[bowmark] ${path} did not reach Bowmark (${causeMessage}), retrying in ${wait}ms`);
133
+ await new Promise((resolve) => setTimeout(resolve, wait));
134
+ continue;
135
+ }
125
136
  const message = `could not reach ${client.baseUrl}${path}: ${causeMessage}`;
126
137
  throw new BowmarkError(message, {
127
138
  code: "network_error",
@@ -195,10 +206,17 @@ async function paceForEdge(baseUrl) {
195
206
  * block lasts 10 seconds, so 2s + 4s + 8s outlasts it. */
196
207
  const EDGE_429_RETRIES = 3;
197
208
  const EDGE_429_MAX_WAIT_MS = 10_000;
209
+ /** Attempts for a request the caller declared safe to repeat, when no response came
210
+ * back (`retryTransport`), and the waits between them. Three attempts in 1.0s total:
211
+ * a reset is usually one dropped socket, and a longer wait just holds a caller's
212
+ * script open while the answer it already has goes unused. Responses are never
213
+ * retried, so a request the origin answered is never sent twice by this path. */
214
+ const TRANSPORT_ATTEMPTS = 3;
215
+ const TRANSPORT_RETRY_WAITS_MS = [250, 750];
198
216
  /** POST JSON and parse JSON back. `extraHeaders` rides THIS call only — never
199
217
  * captured, never applied to a later call on the same client. */
200
- async function postJson(client, path, body, extraHeaders) {
201
- return sendRequest(client, "POST", path, body, extraHeaders);
218
+ async function postJson(client, path, body, extraHeaders, retryTransport = false) {
219
+ return sendRequest(client, "POST", path, body, extraHeaders, retryTransport);
202
220
  }
203
221
  export async function openSession(client) {
204
222
  const { status, payload } = await postJson(client, "/v1/session", {});
@@ -242,9 +260,26 @@ export async function callInSession(client, sessionId, path, args, extraHeaders)
242
260
  }
243
261
  return payload.result;
244
262
  }
245
- /** Close a session. Idempotent server-side, so a `finally` that runs twice is fine. */
263
+ /** Close a session. Idempotent server-side, so a `finally` that runs twice is fine.
264
+ *
265
+ * A close is retried on a transport reset, and a close that still cannot reach Bowmark
266
+ * RETURNS `null` (reported through `onLog`) rather than throwing. By the time it runs
267
+ * the caller's work is done and its result is in hand, so a dropped socket here must
268
+ * not turn a finished script into a failed one. The session's TTL reaps what was not
269
+ * closed. Any other failure still throws. */
246
270
  export async function closeSession(client, sessionId) {
247
- const { status, payload } = await postJson(client, `/v1/session/${encodeURIComponent(sessionId)}/close`, {});
271
+ let response;
272
+ try {
273
+ response = await postJson(client, `/v1/session/${encodeURIComponent(sessionId)}/close`, {}, undefined, true);
274
+ }
275
+ catch (err) {
276
+ if (err instanceof BowmarkError && err.code === "network_error") {
277
+ client.onLog?.(`[bowmark] could not close session ${sessionId}: ${err.message}`);
278
+ return null;
279
+ }
280
+ throw err;
281
+ }
282
+ const { status, payload } = response;
248
283
  if (status !== 200 || payload?.ok !== true)
249
284
  return null;
250
285
  return { ok: true, calls: payload.calls, ms: payload.ms };
@@ -253,7 +288,7 @@ export async function closeSession(client, sessionId) {
253
288
  * CLIENT-SIDE, after the fetch, which is cheap at the scale one account's saved
254
289
  * logins reach. */
255
290
  export async function listConnections(client, filter = {}) {
256
- const { status, payload } = await sendRequest(client, "GET", "/v1/connections");
291
+ const { status, payload } = await sendRequest(client, "GET", "/v1/connections", undefined, undefined, true);
257
292
  if (status !== 200 || !payload?.connections) {
258
293
  throw new BowmarkError(payload?.error ?? `could not list connections (HTTP ${status})`, {
259
294
  code: `http_${status}`,
@@ -312,8 +347,12 @@ export async function updateConnection(client, id, patch) {
312
347
  /** The string surface. Returns the ENVELOPE rather than throwing, because a script
313
348
  * is composite: a `needs_user` or an `error` is a fact about the run that a caller
314
349
  * reads alongside `logs` and `result`, not an exception in their control flow. */
315
- export async function postRun(client, script) {
316
- const { status, payload } = await postJson(client, "/v1/run", { script });
350
+ export async function postRun(client, script, opts = {}) {
351
+ // Retried on a transport reset ONLY when the caller says the script is safe to send
352
+ // twice. The transport cannot tell from the text: a script that starts a billed
353
+ // browser session and one that polls it are the same string shape, and a retry of
354
+ // the first is a second session.
355
+ const { status, payload } = await postJson(client, "/v1/run", { script }, undefined, opts.idempotent === true);
317
356
  if (client.onLog)
318
357
  for (const line of payload?.logs ?? [])
319
358
  client.onLog(line);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bowmark/web",
3
- "version": "1.29.1",
3
+ "version": "1.29.2",
4
4
  "type": "module",
5
5
  "description": "The public client for the Bowmark capability library: real TypeScript for the whole bowmark.* surface, with no Bowmark source on the caller's disk. ZERO runtime dependencies, deliberately and permanently.",
6
6
  "license": "MIT",