@nemphi/sdk 0.2.5272 → 0.3.5324

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.js CHANGED
@@ -35,62 +35,44 @@ const isJsonText = (value) => typeof value === "string";
35
35
  const isJsonMap = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
36
36
  /** A response body, parsed; anything that is not JSON reads as `null`. */
37
37
  const parsedBody = (res) => res.json().catch(() => null);
38
- /** Whether a member of a parsed response is a number. */
39
- const isJsonNumber = (value) => typeof value === "number";
40
- /** How often `openRealtimeSocket` polls `GET /v1/events/poll` while nothing is pending. */
41
- const REALTIME_POLL_MS = 2_000;
42
38
  /**
43
- * One event of a realtime poll's answer as a RealtimeEvent. The ledger and
44
- * notification rows become their wake-ups (`member` is the caller the
45
- * answer names); a frame is passed on as it is. A kind this build does not
46
- * know yet is dropped, since the next read shows the current state anyway.
39
+ * One server-sent frame's data as a realtime event: parsed, and checked by
40
+ * its discriminant. A frame that will not parse, or a kind this build does
41
+ * not know yet, is undefined.
47
42
  */
48
- const pollEventOf = (item, member) => {
49
- if (!isJsonMap(item) || !isJsonMap(item.data))
50
- return undefined;
51
- const data = item.data;
52
- if (item.event === "action") {
53
- if (!isJsonNumber(data.id) || !isJsonText(data.tool) || !isJsonText(data.actor_type))
54
- return undefined;
55
- const action = {
56
- type: "action",
57
- id: data.id,
58
- tool: data.tool,
59
- actor_type: data.actor_type,
60
- };
61
- if (isJsonText(data.actor_id))
62
- action.actor_id = data.actor_id;
63
- if (isJsonText(data.run_id))
64
- action.run_id = data.run_id;
65
- return action;
43
+ const realtimeEventOf = (data) => {
44
+ let parsed;
45
+ try {
46
+ parsed = JSON.parse(data);
66
47
  }
67
- if (item.event === "notification") {
68
- if (!isJsonText(data.id) || !isJsonText(data.kind) || member === "")
69
- return undefined;
70
- return { type: "notification", user_id: member, id: data.id, kind: data.kind };
48
+ catch {
49
+ return undefined;
71
50
  }
72
- return isRealtimeEvent(data) ? data : undefined;
51
+ return isRealtimeEvent(parsed) ? parsed : undefined;
73
52
  };
74
- /**
75
- * The frame ids a poller already handed on: a frame read before its
76
- * transaction settled is answered again once it does. The oldest are
77
- * forgotten past a thousand.
78
- */
79
- class RecentIds {
80
- #ids = new Set();
81
- /** Whether `id` is new, remembering it. */
82
- first(id) {
83
- if (this.#ids.has(id))
84
- return false;
85
- this.#ids.add(id);
86
- if (this.#ids.size > 1_000) {
87
- const oldest = this.#ids.values().next();
88
- if (!oldest.done)
89
- this.#ids.delete(oldest.value);
90
- }
91
- return true;
53
+ /** The first wait before a dropped stream is opened again; it doubles to `STREAM_RETRY_MAX_MS`. */
54
+ const STREAM_RETRY_MS = 1_000;
55
+ /** The longest wait between attempts to open a stream again. */
56
+ const STREAM_RETRY_MAX_MS = 30_000;
57
+ /** The wait before attempt `failures` + 1, with jitter so many clients do not return at once. */
58
+ const streamRetryDelay = (failures) => Math.min(STREAM_RETRY_MAX_MS, STREAM_RETRY_MS * 2 ** Math.min(failures, 5)) *
59
+ (0.75 + Math.random() / 2);
60
+ /** Waits `ms`, or less when `signal` aborts first. */
61
+ const pause = (ms, signal) => new Promise((resolve) => {
62
+ if (signal?.aborted) {
63
+ resolve();
64
+ return;
92
65
  }
93
- }
66
+ const done = () => {
67
+ clearTimeout(timer);
68
+ signal?.removeEventListener("abort", done);
69
+ resolve();
70
+ };
71
+ const timer = setTimeout(done, ms);
72
+ signal?.addEventListener("abort", done, { once: true });
73
+ });
74
+ /** A refusal that opening a stream again will not change: the caller, the thread or the request is wrong. */
75
+ const refusesForGood = (status) => status >= 400 && status < 500 && status !== 408 && status !== 429;
94
76
  /** Every operator a condition may use, in the order a picker shows them. */
95
77
  export const WorkflowConditionOperators = [
96
78
  "eq",
@@ -244,114 +226,96 @@ export function createClient(options) {
244
226
  throw new ApiError(res.status, isJsonText(error.code) ? error.code : "unknown", isJsonText(error.error) ? error.error : `stream failed with status ${res.status}`, body, fieldRefusalOf(error));
245
227
  }
246
228
  async function* streamEvents(opts) {
247
- const params = new URLSearchParams();
248
- if (opts?.cursor !== undefined)
249
- params.set("cursor", String(opts.cursor));
250
- const qs = params.toString();
251
- const res = await fetchFn(`${baseUrl}/v1/events/stream${qs ? `?${qs}` : ""}`, {
229
+ const res = await fetchFn(`${baseUrl}/v1/events/stream`, {
252
230
  headers: buildHeaders(undefined, false),
253
231
  signal: opts?.signal,
254
232
  });
255
233
  if (!res.ok || !res.body)
256
234
  await streamError(res);
257
235
  for await (const frame of sseFrames(res.body)) {
258
- const action = JSON.parse(frame.data);
259
- yield action;
236
+ const event = realtimeEventOf(frame.data);
237
+ if (event !== undefined)
238
+ yield event;
260
239
  }
261
240
  }
262
241
  const openRealtimeSocket = (options) => {
263
- let closed = false;
264
- let open = false;
242
+ const controller = new AbortController();
265
243
  let failures = 0;
266
- let timer;
267
- let controller;
268
- // The positions the last answer gave; empty starts at the head.
269
- let cursor = "";
270
- let eventsAfter = "";
271
- let shown;
272
- // This copy of the app, which each poll keeps online.
273
- const client = `sdk-${Math.random().toString(36).slice(2, 14)}`;
274
- const seen = new RecentIds();
275
- const schedule = (wait) => {
276
- if (closed)
277
- return;
278
- timer = setTimeout(() => void poll(), wait);
279
- };
280
- const poll = async () => {
281
- if (closed)
282
- return;
283
- controller = new AbortController();
284
- const params = new URLSearchParams({ client });
285
- if (cursor)
286
- params.set("cursor", cursor);
287
- if (eventsAfter)
288
- params.set("events_after", eventsAfter);
289
- let wait = REALTIME_POLL_MS;
290
- try {
291
- const res = await fetchFn(`${baseUrl}/v1/events/poll?${params.toString()}`, {
292
- headers: buildHeaders(undefined, false),
293
- signal: controller.signal,
294
- });
295
- if (!res.ok)
296
- await streamError(res);
297
- const body = await parsedBody(res);
298
- if (!isJsonObject(body) ||
299
- !isJsonText(body.cursor) ||
300
- !isJsonText(body.events_after) ||
301
- !Array.isArray(body.events))
302
- throw new Error("the realtime poll answered something else");
303
- if (closed)
304
- return;
305
- cursor = body.cursor;
306
- eventsAfter = body.events_after;
307
- failures = 0;
308
- if (!open) {
244
+ const follow = async () => {
245
+ while (!controller.signal.aborted) {
246
+ let open = false;
247
+ try {
248
+ const res = await fetchFn(`${baseUrl}/v1/events/stream`, {
249
+ headers: buildHeaders(undefined, false),
250
+ signal: controller.signal,
251
+ });
252
+ if (!res.ok || !res.body)
253
+ await streamError(res);
309
254
  open = true;
255
+ failures = 0;
310
256
  options.onOpen?.();
257
+ for await (const frame of sseFrames(res.body)) {
258
+ const event = realtimeEventOf(frame.data);
259
+ if (event !== undefined)
260
+ options.onEvent(event);
261
+ }
311
262
  }
312
- const member = isJsonText(body.user_id) ? body.user_id : "";
313
- for (const item of body.events) {
314
- if (isJsonMap(item) && isJsonNumber(item.id) && !seen.first(item.id))
315
- continue;
316
- const event = pollEventOf(item, member);
317
- if (event !== undefined)
318
- options.onEvent(event);
319
- }
320
- const users = Array.isArray(body.presence) ? body.presence.filter(isJsonText) : [];
321
- const key = [...users].sort().join(",");
322
- if (key !== shown) {
323
- shown = key;
324
- options.onEvent({ type: "presence", users });
263
+ catch {
264
+ // A refusal or a dropped connection: either way, try again.
325
265
  }
326
- // A full page reads on at once. A ledger held back by a running
327
- // write (`held`) can stay held for as long as that write runs, so it
328
- // waits the ordinary interval rather than polling back to back.
329
- if (body.more === true)
330
- wait = 0;
331
- }
332
- catch {
333
- if (closed)
266
+ if (controller.signal.aborted)
334
267
  return;
335
- if (open) {
336
- open = false;
268
+ if (open)
337
269
  options.onClose?.();
338
- }
270
+ else
271
+ failures += 1;
339
272
  // Back off to half a minute; a workspace switch or sign-out closes for good.
340
- failures += 1;
341
- wait = Math.min(30_000, 1_000 * 2 ** Math.min(failures, 5));
273
+ await pause(streamRetryDelay(failures), controller.signal);
342
274
  }
343
- schedule(wait);
344
- };
345
- void poll();
346
- return {
347
- close: () => {
348
- closed = true;
349
- if (timer !== undefined)
350
- clearTimeout(timer);
351
- controller?.abort();
352
- },
353
275
  };
276
+ void follow();
277
+ return { close: () => controller.abort() };
354
278
  };
279
+ async function* streamThread(threadId, opts) {
280
+ const signal = opts?.signal;
281
+ const url = `${baseUrl}/v1/threads/${encodeURIComponent(threadId)}/stream`;
282
+ let failures = 0;
283
+ while (!signal?.aborted) {
284
+ let res;
285
+ try {
286
+ res = await fetchFn(url, { headers: buildHeaders(undefined, false), signal });
287
+ }
288
+ catch {
289
+ res = undefined;
290
+ }
291
+ if (res !== undefined && (!res.ok || !res.body) && refusesForGood(res.status)) {
292
+ await streamError(res);
293
+ }
294
+ if (res?.ok && res.body) {
295
+ failures = 0;
296
+ opts?.onOpen?.();
297
+ try {
298
+ for await (const frame of sseFrames(res.body)) {
299
+ const event = realtimeEventOf(frame.data);
300
+ if ((event?.type === "run" || event?.type === "run_delta") &&
301
+ event.thread_id === threadId) {
302
+ yield event;
303
+ }
304
+ }
305
+ }
306
+ catch {
307
+ // The connection dropped mid-answer; the next one replays the turn.
308
+ }
309
+ }
310
+ else {
311
+ failures += 1;
312
+ await res?.body?.cancel();
313
+ }
314
+ if (signal?.aborted)
315
+ return;
316
+ await pause(streamRetryDelay(failures), signal);
317
+ }
318
+ }
355
319
  const sendTyping = (input) => post("/v1/events/typing", input);
356
320
  const sendViewing = (input) => post("/v1/events/viewing", input);
357
321
  async function* overviewChatStream(input, opts) {
@@ -1186,6 +1150,7 @@ export function createClient(options) {
1186
1150
  },
1187
1151
  streamEvents,
1188
1152
  openRealtimeSocket,
1153
+ streamThread,
1189
1154
  sendTyping,
1190
1155
  sendViewing,
1191
1156
  ping: () => invoke("system.ping"),
@@ -1227,6 +1192,7 @@ export function createClient(options) {
1227
1192
  stockLevels: (input) => invoke("inventory.levels", input ?? {}),
1228
1193
  stockMovements: (input) => invoke("inventory.movements", input ?? {}),
1229
1194
  inventoryValuation: (input) => invoke("inventory.valuation", input ?? {}),
1195
+ inventoryOverview: (month) => invoke("inventory.overview", month ? { month } : {}),
1230
1196
  reorderSuggestions: async (input) => {
1231
1197
  const res = await invoke("inventory.reorder_suggestions", input ?? {});
1232
1198
  return res.suggestions ?? [];