@nivaro/sdk 0.2.6 → 0.3.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.
Files changed (4) hide show
  1. package/README.md +286 -195
  2. package/dist/index.d.ts +2079 -208
  3. package/dist/index.js +863 -118
  4. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -517,6 +517,38 @@ function readIntegrationHealth() {
517
517
  return cmd("GET", "/integration-health");
518
518
  }
519
519
 
520
+ // src/commands/agents.ts
521
+ function askHuman(body) {
522
+ return cmd("POST", "/agent-questions", void 0, body);
523
+ }
524
+ function readAgentQuestion(id, wait2) {
525
+ return cmd("GET", `/agent-questions/${encodeURIComponent(id)}`, wait2 ? { wait: wait2 } : void 0);
526
+ }
527
+ function listMyAgentQuestions() {
528
+ return cmd("GET", "/agent-questions/mine");
529
+ }
530
+ function listAskedQuestions(query) {
531
+ return cmd("GET", "/agent-questions/asked", query);
532
+ }
533
+ function answerAgentQuestion(id, body) {
534
+ return cmd("POST", `/agent-questions/${encodeURIComponent(id)}/answer`, void 0, body);
535
+ }
536
+ function cancelAgentQuestion(id) {
537
+ return cmd("POST", `/agent-questions/${encodeURIComponent(id)}/cancel`);
538
+ }
539
+ function listTaskAgents(opts) {
540
+ return cmd("GET", "/tasks/agents", opts?.all ? { all: 1 } : void 0);
541
+ }
542
+ function listAgentTasks(status) {
543
+ return cmd("GET", "/tasks", { agent: "mine", ...status ? { status } : {} });
544
+ }
545
+ function listAgentTriggers() {
546
+ return cmd("GET", "/agent-triggers");
547
+ }
548
+ function listAgentTriggerDeliveries(query) {
549
+ return cmd("GET", "/agent-triggers/deliveries", query);
550
+ }
551
+
520
552
  // src/commands/ai.ts
521
553
  function aiGenerate(body) {
522
554
  return cmd("POST", "/ai/generate", void 0, body);
@@ -663,6 +695,11 @@ function listNotifications(query) {
663
695
  if (query?.page != null) params.page = query.page;
664
696
  if (query?.limit != null) params.limit = query.limit;
665
697
  if (query?.status) params.status = query.status;
698
+ if (query?.unread) params.unread = "true";
699
+ if (query?.search) params.search = query.search;
700
+ if (query?.collection) params.collection = query.collection;
701
+ if (query?.sender) params.sender = query.sender;
702
+ if (query?.snoozed) params.snoozed = "true";
666
703
  if (query?.app) params.app = query.app;
667
704
  if (query?.lane) params.lane = query.lane;
668
705
  if (query?.category) params.category = query.category;
@@ -807,8 +844,12 @@ function createChatChannel(body) {
807
844
  function updateChatChannel(id, body) {
808
845
  return cmd("PATCH", `/chat/channels/${id}`, void 0, body);
809
846
  }
810
- function listChatChannelMembers(id) {
811
- return cmd("GET", `/chat/channels/${id}/members`);
847
+ function listChatChannelMembers(id, opts) {
848
+ const query = {};
849
+ if (opts?.limit !== void 0) query.limit = opts.limit;
850
+ if (opts?.offset !== void 0) query.offset = opts.offset;
851
+ if (opts?.q !== void 0) query.q = opts.q;
852
+ return cmd("GET", `/chat/channels/${id}/members`, Object.keys(query).length ? query : void 0);
812
853
  }
813
854
  function addChatChannelMember(id, userId) {
814
855
  return cmd("POST", `/chat/channels/${id}/members`, void 0, { user_id: userId });
@@ -1128,6 +1169,24 @@ function readDashboardWidgetData(widgetId, filters) {
1128
1169
  filters?.length ? { extra_filters: JSON.stringify(filters) } : void 0
1129
1170
  );
1130
1171
  }
1172
+ function createDashboard(body) {
1173
+ return cmd("POST", "/dashboards", void 0, body);
1174
+ }
1175
+ function updateDashboard(id, body) {
1176
+ return cmd("PATCH", `/dashboards/${id}`, void 0, body);
1177
+ }
1178
+ function deleteDashboard(id) {
1179
+ return cmd("DELETE", `/dashboards/${id}`);
1180
+ }
1181
+ function createDashboardWidget(dashboardId, body) {
1182
+ return cmd("POST", `/dashboards/${dashboardId}/widgets`, void 0, body);
1183
+ }
1184
+ function updateDashboardWidget(widgetId, body) {
1185
+ return cmd("PATCH", `/dashboards/widgets/${widgetId}`, void 0, body);
1186
+ }
1187
+ function deleteDashboardWidget(widgetId) {
1188
+ return cmd("DELETE", `/dashboards/widgets/${widgetId}`);
1189
+ }
1131
1190
 
1132
1191
  // src/commands/devex.ts
1133
1192
  function getPostmanCollection() {
@@ -1175,8 +1234,8 @@ function updateSavedView(id, body) {
1175
1234
  function deleteSavedView(id) {
1176
1235
  return cmd("DELETE", `/saved-views/${id}`);
1177
1236
  }
1178
- function globalSearch(q) {
1179
- return cmd("GET", "/global-search", { q });
1237
+ function globalSearch(q, opts) {
1238
+ return cmd("GET", "/global-search", opts?.labels ? { q, labels: 1 } : { q });
1180
1239
  }
1181
1240
  function listApiKeys() {
1182
1241
  return cmd("GET", "/api-keys");
@@ -1399,6 +1458,9 @@ function updateFileMeta(id, data) {
1399
1458
  function deleteFile(id) {
1400
1459
  return cmd("DELETE", `/files/${id}`);
1401
1460
  }
1461
+ function attachFileToRecord(data) {
1462
+ return cmd("POST", "/files/attach", void 0, { ...data, item: String(data.item) });
1463
+ }
1402
1464
  function readFileUsage(id) {
1403
1465
  return cmd("GET", `/files/${id}/usage`);
1404
1466
  }
@@ -1420,6 +1482,23 @@ function fileTransformPath(id, options = {}) {
1420
1482
  return `/api/files/${id}/transform${qs ? `?${qs}` : ""}`;
1421
1483
  }
1422
1484
 
1485
+ // src/commands/form-tools.ts
1486
+ function drillDashboardWidgetRows(widgetId, body = {}) {
1487
+ return cmd("POST", `/dashboards/widgets/${widgetId}/rows`, void 0, body);
1488
+ }
1489
+ function drillReportWidgetRows(reportId, widgetId, body = {}) {
1490
+ return cmd("POST", `/report-studio/${reportId}/widgets/${widgetId}/rows`, void 0, body);
1491
+ }
1492
+ function readFormState(query) {
1493
+ return cmd("POST", "/collection-layouts/form-state", void 0, query);
1494
+ }
1495
+ function renderFormImage(query) {
1496
+ return cmd("POST", "/collection-layouts/render-form", void 0, query);
1497
+ }
1498
+ function readLayoutLint(layoutId) {
1499
+ return cmd("GET", `/collection-layouts/${layoutId}/lint`);
1500
+ }
1501
+
1423
1502
  // src/commands/help-videos.ts
1424
1503
  function listHelpVideos(params) {
1425
1504
  return cmd("GET", "/help-videos", params);
@@ -1530,6 +1609,85 @@ function discardHelpVideoPackageImport(id) {
1530
1609
  var listImportTemplates = (collection) => cmd("GET", "/import-templates", { collection });
1531
1610
  var executeImportTemplate = (id, payload) => cmd("POST", `/import-templates/${id}/execute`, void 0, payload);
1532
1611
 
1612
+ // src/commands/inbox.ts
1613
+ function snoozeNotification(id, opts) {
1614
+ return cmd(
1615
+ "POST",
1616
+ `/notifications/${id}/snooze`,
1617
+ void 0,
1618
+ opts.untilChange ? { until_change: true } : { until: opts.until ?? null }
1619
+ );
1620
+ }
1621
+ function acknowledgeNotification(id) {
1622
+ return cmd("POST", `/notifications/${id}/acknowledge`);
1623
+ }
1624
+ function filterBody(f) {
1625
+ const out = {};
1626
+ for (const [k, v] of Object.entries(f)) {
1627
+ if (v === void 0 || v === "") continue;
1628
+ out[k] = String(v);
1629
+ }
1630
+ return out;
1631
+ }
1632
+ function bulkNotificationAction(body) {
1633
+ return cmd("POST", "/notifications/bulk-action", void 0, {
1634
+ action: body.action,
1635
+ ...body.ids ? { ids: body.ids } : {},
1636
+ ...body.filter ? { filter: filterBody(body.filter) } : {},
1637
+ ...body.until ? { until: body.until } : {}
1638
+ });
1639
+ }
1640
+ function archiveReadNotifications(days) {
1641
+ return cmd("POST", "/notifications/archive-read", void 0, { days });
1642
+ }
1643
+ function listSentNotifications(query) {
1644
+ const params = {};
1645
+ if (query?.lane) params.lane = query.lane;
1646
+ if (query?.limit != null) params.limit = query.limit;
1647
+ return cmd("GET", "/notifications/sent", params);
1648
+ }
1649
+ function readRecordMute(collection, item) {
1650
+ return cmd("GET", `/notifications/mutes/${collection}/${item}`);
1651
+ }
1652
+ function toggleRecordMute(collection, item) {
1653
+ return cmd("POST", `/notifications/mutes/${collection}/${item}/toggle`);
1654
+ }
1655
+ function listReminders(includeSent) {
1656
+ return cmd("GET", "/reminders", includeSent ? { include_sent: "true" } : void 0);
1657
+ }
1658
+ function createReminder(body) {
1659
+ return cmd("POST", "/reminders", void 0, body);
1660
+ }
1661
+ function updateReminder(id, body) {
1662
+ return cmd("PATCH", `/reminders/${id}`, void 0, body);
1663
+ }
1664
+ function deleteReminder(id) {
1665
+ return cmd("DELETE", `/reminders/${id}`);
1666
+ }
1667
+ function listSavedSearches() {
1668
+ return cmd("GET", "/global-search/saved");
1669
+ }
1670
+ function createSavedSearch(body) {
1671
+ return cmd("POST", "/global-search/saved", void 0, body);
1672
+ }
1673
+ function deleteSavedSearch(id) {
1674
+ return cmd("DELETE", `/global-search/saved/${encodeURIComponent(id)}`);
1675
+ }
1676
+ function readSearchCounts(q, collections, opts) {
1677
+ return cmd("GET", "/global-search/counts", {
1678
+ q,
1679
+ collections: collections.join(","),
1680
+ ...opts?.labels ? { labels: 1 } : {}
1681
+ });
1682
+ }
1683
+ function readSearchRecords(q, collection, opts) {
1684
+ const params = { q, collection };
1685
+ if (opts?.offset != null) params.offset = opts.offset;
1686
+ if (opts?.limit != null) params.limit = opts.limit;
1687
+ if (opts?.labels) params.labels = 1;
1688
+ return cmd("GET", "/global-search/records", params);
1689
+ }
1690
+
1533
1691
  // src/commands/infra.ts
1534
1692
  function listWorkspaces() {
1535
1693
  return cmd("GET", "/workspaces");
@@ -1852,6 +2010,93 @@ function readMcpCapabilities() {
1852
2010
  return cmd("GET", "/mcp/capabilities");
1853
2011
  }
1854
2012
 
2013
+ // src/commands/observability.ts
2014
+ function readActivityEntry(id) {
2015
+ return cmd("GET", `/activity/${id}`);
2016
+ }
2017
+ function listActivityActions() {
2018
+ return cmd("GET", "/activity/actions");
2019
+ }
2020
+ function logExport(body) {
2021
+ return cmd("POST", "/activity/export-log", void 0, body);
2022
+ }
2023
+ function createActivityEntry(body) {
2024
+ return cmd("POST", "/activity", void 0, body);
2025
+ }
2026
+ function readChanges(query) {
2027
+ const params = {};
2028
+ if (query?.cursor) params.cursor = query.cursor;
2029
+ if (query?.since) params.since = query.since;
2030
+ if (query?.collections?.length) params.collections = query.collections.join(",");
2031
+ if (query?.limit != null) params.limit = query.limit;
2032
+ return cmd("GET", "/changes", params);
2033
+ }
2034
+ function readJobRunLog(id, after) {
2035
+ return cmd("GET", `/job-runs/${id}/log`, after ? { after } : void 0);
2036
+ }
2037
+ function cancelJobRun(id) {
2038
+ return cmd("POST", `/job-runs/${id}/cancel`);
2039
+ }
2040
+ function readBusyJobs() {
2041
+ return cmd("GET", "/job-runs/busy");
2042
+ }
2043
+ function listMyJobs() {
2044
+ return cmd("GET", "/my-jobs");
2045
+ }
2046
+ function estimateBackgroundRun(method, url) {
2047
+ return cmd("GET", "/background-runs/estimate", { method, url });
2048
+ }
2049
+ function startBackgroundRun(body) {
2050
+ return cmd("POST", "/background-runs", void 0, body);
2051
+ }
2052
+ function listBackgroundRuns() {
2053
+ return cmd("GET", "/background-runs");
2054
+ }
2055
+ function readBackgroundRun(id) {
2056
+ return cmd("GET", `/background-runs/${id}`);
2057
+ }
2058
+ function readBackgroundRunResult(id) {
2059
+ return cmd("GET", `/background-runs/${id}/result`);
2060
+ }
2061
+ function listApiRequests(query) {
2062
+ const params = {};
2063
+ for (const [k, v] of Object.entries(query ?? {})) {
2064
+ if (v === void 0 || v === "" || v === false) continue;
2065
+ if (k === "all_instances") params.instances = "all";
2066
+ else params[k] = v === true ? 1 : v;
2067
+ }
2068
+ return cmd("GET", "/api-analytics/requests", params);
2069
+ }
2070
+ function readApiAnalyticsByKey(hours) {
2071
+ return cmd("GET", "/api-analytics/by-key", hours != null ? { hours } : void 0);
2072
+ }
2073
+ function readApiKeyUsage(id) {
2074
+ return cmd("GET", `/api-keys/${id}/usage`);
2075
+ }
2076
+ function readApiKeyMonthlyUsage(id, month, format) {
2077
+ return cmd("GET", `/api-keys/${id}/usage`, format === "csv" ? { month, format } : { month });
2078
+ }
2079
+ function listMailLog(query) {
2080
+ const params = {};
2081
+ for (const [k, v] of Object.entries(query ?? {})) if (v !== void 0 && v !== "") params[k] = v;
2082
+ return cmd("GET", "/mail-log", params);
2083
+ }
2084
+ function readMailLogEntry(id) {
2085
+ return cmd("GET", `/mail-log/${id}`);
2086
+ }
2087
+ function resendMail(id) {
2088
+ return cmd("POST", `/mail-log/${id}/resend`);
2089
+ }
2090
+ function readMailStats(days) {
2091
+ return cmd("GET", "/mail-log/stats", days ? { days } : void 0);
2092
+ }
2093
+ function listRecordMail(collection, item) {
2094
+ return cmd("GET", `/mail-log/record/${collection}/${item}`);
2095
+ }
2096
+ function readNotificationHistory(limit) {
2097
+ return cmd("GET", "/users/me/notification-history", limit != null ? { limit } : void 0);
2098
+ }
2099
+
1855
2100
  // src/commands/ops.ts
1856
2101
  function readReadiness() {
1857
2102
  return cmd("GET", "/ready");
@@ -1952,6 +2197,116 @@ function setQueueDefaultView(id, viewId) {
1952
2197
  return cmd("PUT", `/queues/${id}/default-view`, void 0, { view_id: viewId });
1953
2198
  }
1954
2199
 
2200
+ // src/commands/records.ts
2201
+ function rehearseUpdateItem(collection, id, data) {
2202
+ return cmd("PATCH", `/items/${collection}/${id}`, { dry_run: 1 }, data);
2203
+ }
2204
+ function checkItemFilter(collection, filter) {
2205
+ return cmd("GET", `/items/${collection}/filter-check`, { filter: JSON.stringify(filter) });
2206
+ }
2207
+ function readItemBySlug(collection, slug, query) {
2208
+ return cmd(
2209
+ "GET",
2210
+ `/items/${collection}/by-slug/${encodeURIComponent(slug)}`,
2211
+ query?.fields?.length ? { fields: query.fields.join(",") } : void 0
2212
+ );
2213
+ }
2214
+ function readItemDistinct(collection, field, limit) {
2215
+ return cmd("GET", `/items/${collection}/distinct`, limit != null ? { field, limit } : { field });
2216
+ }
2217
+ function bulkUpdateItems(collection, ids, data, opts) {
2218
+ return cmd("POST", `/items/${collection}/bulk-update`, void 0, {
2219
+ ids,
2220
+ data,
2221
+ ...opts?.by_form ? { by_form: true } : {}
2222
+ });
2223
+ }
2224
+ function bulkDeleteItems(collection, ids) {
2225
+ return cmd("POST", `/items/${collection}/bulk-delete`, void 0, { ids });
2226
+ }
2227
+ function bulkTransitionItems(collection, ids, transitionId, comment) {
2228
+ return cmd("POST", `/items/${collection}/bulk-transition`, void 0, {
2229
+ ids,
2230
+ transition_id: transitionId,
2231
+ ...comment ? { comment } : {}
2232
+ });
2233
+ }
2234
+ function batchItems(collection, body) {
2235
+ return cmd("POST", `/items/${collection}/batch`, void 0, body);
2236
+ }
2237
+ function bulkWriteItems(collection, rows, opts) {
2238
+ return cmd("POST", `/items/${collection}/bulk`, opts?.returnIds ? { return: "ids" } : void 0, {
2239
+ rows,
2240
+ ...opts?.atomic ? { atomic: true } : {}
2241
+ });
2242
+ }
2243
+ function queueBulkWriteItems(collection, rows, opts) {
2244
+ return cmd(
2245
+ "POST",
2246
+ `/items/${collection}/bulk`,
2247
+ { async: 1, ...opts?.returnIds ? { return: "ids" } : {} },
2248
+ { rows, ...opts?.atomic ? { atomic: true } : {} }
2249
+ );
2250
+ }
2251
+ function readBulkRun(collection, runId) {
2252
+ return cmd("GET", `/items/${collection}/bulk/${runId}`);
2253
+ }
2254
+ function listTrash(query) {
2255
+ const params = {};
2256
+ for (const [k, v] of Object.entries(query ?? {})) if (v !== void 0 && v !== "") params[k] = v;
2257
+ return cmd("GET", "/trash", params);
2258
+ }
2259
+ function readRecordDeletion(collection, item) {
2260
+ return cmd("GET", "/trash/record", { collection, item });
2261
+ }
2262
+ function restoreTrashItem(trashId) {
2263
+ return cmd("POST", `/trash/${trashId}/restore`);
2264
+ }
2265
+ function bulkRestoreTrash(ids) {
2266
+ return cmd("POST", "/trash/bulk-restore", void 0, { ids });
2267
+ }
2268
+ function purgeTrashItem(trashId) {
2269
+ return cmd("DELETE", `/trash/${trashId}`);
2270
+ }
2271
+ function readOwnerHistory(collection, item) {
2272
+ return cmd("GET", `/owner-history/${collection}/${item}`);
2273
+ }
2274
+ function readCommentCounts(collection, ids) {
2275
+ return cmd("GET", "/comments/counts", { collection, ids: ids.join(",") });
2276
+ }
2277
+ function toggleCommentReaction(commentId, emoji) {
2278
+ return cmd("POST", `/comments/${commentId}/reactions`, void 0, { emoji });
2279
+ }
2280
+ function toggleEntryReaction(body) {
2281
+ return cmd("POST", "/comments/entry-reactions", void 0, body);
2282
+ }
2283
+ function readPipelineOutline(templateId) {
2284
+ return cmd("GET", `/pipelines/${templateId}/outline`);
2285
+ }
2286
+ function readMyOwnerSeats() {
2287
+ return cmd("GET", "/pipelines/my-seats");
2288
+ }
2289
+ function logout() {
2290
+ return cmd("POST", "/auth/logout");
2291
+ }
2292
+ function logoutAll() {
2293
+ return cmd("POST", "/auth/logout-all");
2294
+ }
2295
+ function readWsToken() {
2296
+ return cmd("GET", "/auth/ws-token");
2297
+ }
2298
+ function readAuthProviders() {
2299
+ return cmd("GET", "/auth/providers");
2300
+ }
2301
+
2302
+ // src/commands/schema-proposals.ts
2303
+ function proposeSchemaChange(body) {
2304
+ return cmd("POST", "/schema-proposals", void 0, body);
2305
+ }
2306
+ function readSchemaProposal(id) {
2307
+ return cmd("GET", `/schema-proposals/${id}`);
2308
+ }
2309
+
1955
2310
  // src/commands/support.ts
1956
2311
  function listSupportTickets(query) {
1957
2312
  return cmd("GET", "/support/tickets", query);
@@ -2087,71 +2442,113 @@ function createPresence(options) {
2087
2442
 
2088
2443
  // src/realtime.ts
2089
2444
  import { io } from "socket.io-client";
2445
+ var NOTIFICATIONS_CHANNEL = "cms_notifications";
2446
+ function parseRealtimeChanges(payload) {
2447
+ const collection = String(payload?.collection ?? "");
2448
+ if (!collection) return [];
2449
+ const action = payload.action === "create" || payload.action === "delete" ? payload.action : "update";
2450
+ const base = {
2451
+ collection,
2452
+ action,
2453
+ ...payload.changed_fields?.length ? { changed_fields: payload.changed_fields } : {},
2454
+ ...payload.source ? { source: payload.source } : {}
2455
+ };
2456
+ if (payload.coalesced || payload.items || payload.many) {
2457
+ if (payload.many || !payload.items)
2458
+ return [{ ...base, item: null, coalesced: true, many: true }];
2459
+ return payload.items.map((item) => ({ ...base, item, coalesced: true }));
2460
+ }
2461
+ return [{ ...base, item: payload.item ?? null }];
2462
+ }
2090
2463
  function createRealtime() {
2091
2464
  let socket = null;
2465
+ let signedIn = false;
2092
2466
  const subs = /* @__PURE__ */ new Map();
2093
2467
  const connectHandlers = [];
2094
2468
  const disconnectHandlers = [];
2469
+ const authHandlers = [];
2095
2470
  function subscriptionKey(collection, event) {
2096
- return event ? `${collection}:${event}` : `${collection}:*`;
2471
+ return event && event !== "*" ? `${collection}:${event}` : `${collection}:*`;
2472
+ }
2473
+ function subscribedCollections() {
2474
+ const out = /* @__PURE__ */ new Set();
2475
+ for (const s of subs.values()) if (s.collection !== NOTIFICATIONS_CHANNEL) out.add(s.collection);
2476
+ return [...out];
2477
+ }
2478
+ function dispatch(change, collection, action) {
2479
+ if (change.length === 0) return;
2480
+ const specific = subs.get(subscriptionKey(collection, action))?.callback;
2481
+ const any = subs.get(subscriptionKey(collection))?.callback;
2482
+ specific?.(change);
2483
+ if (any && any !== specific) any(change);
2097
2484
  }
2098
2485
  return {
2099
2486
  get connected() {
2100
2487
  return socket?.connected ?? false;
2101
2488
  },
2489
+ get authenticated() {
2490
+ return signedIn;
2491
+ },
2102
2492
  connect(url, token) {
2103
2493
  if (socket?.connected) return;
2104
2494
  socket = io(url.replace(/\/$/, ""), {
2105
2495
  path: "/socket.io",
2106
- auth: token ? { token } : void 0,
2107
2496
  withCredentials: true,
2108
2497
  // Websocket first; when a proxy blocks the upgrade, long-polling on the same attempt.
2109
2498
  transports: ["websocket", "polling"],
2110
2499
  tryAllTransports: true
2111
2500
  });
2112
- socket.on("connect", () => {
2501
+ const s = socket;
2502
+ s.on("connect", () => {
2503
+ signedIn = false;
2113
2504
  for (const fn of connectHandlers) fn();
2114
- for (const sub of subs.values()) {
2115
- socket?.emit("subscribe", {
2116
- collection: sub.collection,
2117
- event: sub.event
2118
- });
2119
- }
2120
- });
2121
- socket.on("disconnect", (reason) => {
2122
- for (const fn of disconnectHandlers) fn(reason);
2505
+ void (async () => {
2506
+ try {
2507
+ const t = typeof token === "function" ? await token() : token;
2508
+ if (t && s.connected) s.emit("auth", { token: t });
2509
+ } catch {
2510
+ }
2511
+ })();
2123
2512
  });
2124
- socket.on("items:create", ({ collection, data }) => {
2125
- const cb = subs.get(subscriptionKey(collection, "create"))?.callback ?? subs.get(subscriptionKey(collection))?.callback;
2126
- cb?.(data);
2513
+ s.on("auth:ok", (payload) => {
2514
+ signedIn = true;
2515
+ for (const collection of subscribedCollections()) s.emit("collection:join", { collection });
2516
+ for (const fn of authHandlers) fn(String(payload?.userId ?? ""));
2127
2517
  });
2128
- socket.on("items:update", ({ collection, data }) => {
2129
- const cb = subs.get(subscriptionKey(collection, "update"))?.callback ?? subs.get(subscriptionKey(collection))?.callback;
2130
- cb?.(data);
2518
+ s.on("disconnect", (reason) => {
2519
+ signedIn = false;
2520
+ for (const fn of disconnectHandlers) fn(reason);
2131
2521
  });
2132
- socket.on("items:delete", ({ collection, ids }) => {
2133
- const cb = subs.get(subscriptionKey(collection, "delete"))?.callback ?? subs.get(subscriptionKey(collection))?.callback;
2134
- cb?.(ids);
2522
+ s.on("collection:update", (payload) => {
2523
+ const changes = parseRealtimeChanges(payload);
2524
+ if (changes.length === 0) return;
2525
+ const collection = changes[0].collection;
2526
+ const byAction = /* @__PURE__ */ new Map();
2527
+ for (const c of changes) byAction.set(c.action, [...byAction.get(c.action) ?? [], c]);
2528
+ for (const [action, list] of byAction) dispatch(list, collection, action);
2135
2529
  });
2136
- socket.on("notification", (data) => {
2137
- const cb = subs.get("cms_notifications:*")?.callback;
2138
- cb?.([data]);
2530
+ s.on("notification:new", (data) => {
2531
+ subs.get(`${NOTIFICATIONS_CHANNEL}:*`)?.callback([data]);
2139
2532
  });
2140
2533
  },
2141
2534
  disconnect() {
2142
2535
  socket?.disconnect();
2143
2536
  socket = null;
2537
+ signedIn = false;
2144
2538
  },
2145
2539
  subscribe(collection, opts, callback) {
2146
2540
  const key = subscriptionKey(collection, opts.event);
2541
+ const already = subscribedCollections().includes(collection);
2147
2542
  subs.set(key, { collection, event: opts.event, callback });
2148
- if (socket?.connected) {
2149
- socket.emit("subscribe", { collection, event: opts.event, query: opts.query });
2543
+ if (socket?.connected && signedIn && !already && collection !== NOTIFICATIONS_CHANNEL) {
2544
+ socket.emit("collection:join", { collection });
2150
2545
  }
2151
2546
  return () => {
2547
+ if (subs.get(key)?.callback !== callback) return;
2152
2548
  subs.delete(key);
2153
- if (socket?.connected) {
2154
- socket.emit("unsubscribe", { collection, event: opts.event });
2549
+ const still = subscribedCollections().includes(collection);
2550
+ if (socket?.connected && !still && collection !== NOTIFICATIONS_CHANNEL) {
2551
+ socket.emit("collection:leave", { collection });
2155
2552
  }
2156
2553
  };
2157
2554
  },
@@ -2160,10 +2557,68 @@ function createRealtime() {
2160
2557
  },
2161
2558
  onDisconnect(fn) {
2162
2559
  disconnectHandlers.push(fn);
2560
+ },
2561
+ onAuthenticated(fn) {
2562
+ authHandlers.push(fn);
2163
2563
  }
2164
2564
  };
2165
2565
  }
2166
2566
 
2567
+ // src/errors.ts
2568
+ var REQUEST_ID_HEADER = "x-nivaro-request-id";
2569
+ var NivaroError = class extends Error {
2570
+ /** HTTP status of the answer. */
2571
+ status;
2572
+ /** The API's machine code (`body.code`, e.g. `QUOTA_EXCEEDED`, `SERVER_BUSY`), else null. */
2573
+ code;
2574
+ /**
2575
+ * The `x-nivaro-request-id` the server stamped — the id its slow-trace buffer, access
2576
+ * log and API request log carry. Null when the header was absent or unreadable (a
2577
+ * cross-origin browser call only sees it if the API exposes the header through CORS).
2578
+ */
2579
+ requestId;
2580
+ /** The parsed JSON body (or `{ error: statusText }` when the body was not JSON). */
2581
+ response;
2582
+ method;
2583
+ /** Path under `/api` (no query string). */
2584
+ path;
2585
+ /** Milliseconds from a `Retry-After` header (429 / 503), else null. */
2586
+ retryAfterMs;
2587
+ /** Import parse refusals: the per-row problems the API listed. */
2588
+ issues;
2589
+ constructor(init) {
2590
+ super(init.message);
2591
+ this.name = "NivaroError";
2592
+ this.status = init.status;
2593
+ this.code = init.code ?? null;
2594
+ this.requestId = init.requestId ?? null;
2595
+ this.response = init.response;
2596
+ this.method = init.method;
2597
+ this.path = init.path;
2598
+ this.retryAfterMs = init.retryAfterMs ?? null;
2599
+ if (init.issues !== void 0) this.issues = init.issues;
2600
+ }
2601
+ };
2602
+ function isNivaroError(err) {
2603
+ return err instanceof NivaroError || !!err && typeof err === "object" && err.name === "NivaroError" && typeof err.status === "number";
2604
+ }
2605
+ function errorBodyMessage(body) {
2606
+ if (!body || typeof body !== "object") return null;
2607
+ const b = body;
2608
+ const fastifyShaped = typeof b.statusCode === "number" && typeof b.message === "string";
2609
+ if (fastifyShaped && b.message) return b.message;
2610
+ if (typeof b.error === "string" && b.error) return b.error;
2611
+ if (typeof b.message === "string" && b.message) return b.message;
2612
+ return null;
2613
+ }
2614
+ function retryAfterMs(value, now = Date.now()) {
2615
+ if (!value) return null;
2616
+ const secs = Number(value);
2617
+ if (Number.isFinite(secs) && secs >= 0) return Math.round(secs * 1e3);
2618
+ const at = Date.parse(value);
2619
+ return Number.isFinite(at) ? Math.max(0, at - now) : null;
2620
+ }
2621
+
2167
2622
  // src/index.ts
2168
2623
  function readItems(collection, query) {
2169
2624
  const params = {};
@@ -2174,8 +2629,12 @@ function readItems(collection, query) {
2174
2629
  if (query?.offset != null) params.offset = query.offset;
2175
2630
  if (query?.page != null) params.page = query.page;
2176
2631
  if (query?.search) params.search = query.search;
2632
+ if (query?.search_fields?.length) params.search_fields = query.search_fields.join(",");
2633
+ if (query?.search_rank) params.search_rank = 1;
2177
2634
  if (query?.after != null) params.after = query.after;
2178
2635
  if (query?.count === false) params.count = 0;
2636
+ else if (query?.count === "approx") params.count = "approx";
2637
+ if (query?.labels) params.labels = 1;
2179
2638
  return cmd("GET", `/items/${collection}`, params);
2180
2639
  }
2181
2640
  function aggregateItems(collection, query) {
@@ -2200,8 +2659,12 @@ function aggregateItems(collection, query) {
2200
2659
  if (query.offset != null) params.offset = query.offset;
2201
2660
  return cmd("GET", `/items/${collection}/aggregate`, params);
2202
2661
  }
2203
- function readItem(collection, id) {
2204
- return cmd("GET", `/items/${collection}/${id}`);
2662
+ function readItem(collection, id, query) {
2663
+ return cmd(
2664
+ "GET",
2665
+ `/items/${collection}/${id}`,
2666
+ query?.fields?.length ? { fields: query.fields.join(",") } : void 0
2667
+ );
2205
2668
  }
2206
2669
  var READ_MANY_MAX = 20;
2207
2670
  function readMany(reads) {
@@ -2283,6 +2746,9 @@ function readCollection(collection) {
2283
2746
  function readRevisions(collection, item) {
2284
2747
  return cmd("GET", "/revisions", { collection, item });
2285
2748
  }
2749
+ function readLatestRevisionId(collection, item) {
2750
+ return cmd("GET", "/revisions", { collection, item, latest_only: 1 });
2751
+ }
2286
2752
  function readRevision(id) {
2287
2753
  return cmd("GET", `/revisions/${id}`);
2288
2754
  }
@@ -2601,18 +3067,51 @@ function getPresence(collection, itemId) {
2601
3067
  function listActivePresence() {
2602
3068
  return cmd("GET", "/presence/sessions");
2603
3069
  }
3070
+ var DEFAULT_RETRY_STATUSES = [408, 429, 502, 503, 504];
3071
+ function abortError() {
3072
+ return Object.assign(new Error("The operation was aborted"), { name: "AbortError" });
3073
+ }
3074
+ function wait(ms, signal) {
3075
+ return new Promise((resolve, reject) => {
3076
+ if (signal?.aborted) return reject(abortError());
3077
+ const onAbort = () => {
3078
+ clearTimeout(t);
3079
+ reject(abortError());
3080
+ };
3081
+ const t = setTimeout(() => {
3082
+ signal?.removeEventListener("abort", onAbort);
3083
+ resolve();
3084
+ }, ms);
3085
+ signal?.addEventListener("abort", onAbort, { once: true });
3086
+ });
3087
+ }
2604
3088
  function createNivaro(url, options = {}) {
2605
3089
  const baseUrl = url.replace(/\/$/, "");
2606
3090
  const fetcher = options.fetch ?? globalThis.fetch;
2607
3091
  let currentToken = options.token;
3092
+ const retry = (() => {
3093
+ const r = options.retry;
3094
+ if (r == null || r === 0) return null;
3095
+ const o = typeof r === "number" ? { retries: r } : r;
3096
+ const retries = Math.max(0, Math.floor(o.retries ?? 2));
3097
+ if (retries === 0) return null;
3098
+ return {
3099
+ retries,
3100
+ methods: o.methods ?? ["GET"],
3101
+ statuses: o.statuses ?? DEFAULT_RETRY_STATUSES,
3102
+ baseDelayMs: o.baseDelayMs ?? 300,
3103
+ maxDelayMs: o.maxDelayMs ?? 1e4
3104
+ };
3105
+ })();
2608
3106
  function setToken(token) {
2609
3107
  currentToken = token ?? void 0;
2610
3108
  }
2611
3109
  function getToken() {
2612
3110
  return currentToken;
2613
3111
  }
2614
- function authHeaders(json = true) {
2615
- const h = {};
3112
+ function baseHeaders(json) {
3113
+ const extra = typeof options.headers === "function" ? options.headers() : options.headers;
3114
+ const h = { ...extra ?? {} };
2616
3115
  if (json) h["Content-Type"] = "application/json";
2617
3116
  if (currentToken) h.Authorization = `Bearer ${currentToken}`;
2618
3117
  return h;
@@ -2620,6 +3119,117 @@ function createNivaro(url, options = {}) {
2620
3119
  function credentialsMode() {
2621
3120
  return options.credentials ?? (currentToken ? "omit" : "include");
2622
3121
  }
3122
+ function log(line, details) {
3123
+ const d = options.debug;
3124
+ if (!d) return;
3125
+ try {
3126
+ if (typeof d === "function") d(line, details);
3127
+ else console.debug(`[nivaro] ${line}`);
3128
+ } catch {
3129
+ }
3130
+ }
3131
+ function backoff(attempt, res) {
3132
+ if (!retry) return 0;
3133
+ const after = retryAfterMs(res?.headers.get("retry-after"));
3134
+ if (after != null) return Math.min(after, retry.maxDelayMs);
3135
+ const exp = retry.baseDelayMs * 2 ** attempt;
3136
+ return Math.min(retry.maxDelayMs, Math.round(exp / 2 + Math.random() * (exp / 2)));
3137
+ }
3138
+ async function send(kind, method, path, fullUrl, headers, run, signal) {
3139
+ const mayRetry = !!retry && retry.methods.includes(method);
3140
+ for (let attempt = 0; ; attempt++) {
3141
+ const info = {
3142
+ method,
3143
+ path,
3144
+ url: fullUrl,
3145
+ headers: { ...headers },
3146
+ attempt,
3147
+ kind
3148
+ };
3149
+ if (options.onRequest) await options.onRequest(info);
3150
+ const started = Date.now();
3151
+ let res;
3152
+ try {
3153
+ res = await run(info.headers);
3154
+ } catch (err) {
3155
+ const name = err?.name;
3156
+ const retryable = mayRetry && attempt < (retry?.retries ?? 0) && name !== "AbortError" && name !== "TimeoutError";
3157
+ log(
3158
+ `${method} ${path} failed (${err?.message ?? err})${retryable ? ", retrying" : ""}`,
3159
+ {
3160
+ method,
3161
+ path,
3162
+ attempt,
3163
+ error: err?.message
3164
+ }
3165
+ );
3166
+ if (!retryable) throw err;
3167
+ await wait(backoff(attempt, null), signal);
3168
+ continue;
3169
+ }
3170
+ const requestId = res.headers?.get?.(REQUEST_ID_HEADER) ?? null;
3171
+ const willRetry = mayRetry && !res.ok && attempt < (retry?.retries ?? 0) && !!retry?.statuses.includes(res.status);
3172
+ const durationMs = Date.now() - started;
3173
+ if (options.onResponse) {
3174
+ try {
3175
+ options.onResponse({
3176
+ method,
3177
+ path,
3178
+ url: fullUrl,
3179
+ attempt,
3180
+ kind,
3181
+ status: res.status,
3182
+ ok: res.ok,
3183
+ requestId,
3184
+ durationMs,
3185
+ willRetry
3186
+ });
3187
+ } catch {
3188
+ }
3189
+ }
3190
+ log(
3191
+ `${method} ${path} \u2192 ${res.status} in ${durationMs}ms${requestId ? ` (req ${requestId})` : ""}`,
3192
+ {
3193
+ method,
3194
+ path,
3195
+ status: res.status,
3196
+ durationMs,
3197
+ requestId,
3198
+ attempt
3199
+ }
3200
+ );
3201
+ if (!willRetry) return res;
3202
+ const delay = backoff(attempt, res);
3203
+ try {
3204
+ await res.body?.cancel();
3205
+ } catch {
3206
+ }
3207
+ await wait(delay, signal);
3208
+ }
3209
+ }
3210
+ async function httpError(res, method, path) {
3211
+ const body = await res.json().catch(() => ({ error: res.statusText }));
3212
+ const b = body ?? {};
3213
+ return new NivaroError({
3214
+ message: errorBodyMessage(body) || res.statusText || `HTTP ${res.status}`,
3215
+ status: res.status,
3216
+ code: typeof b.code === "string" ? b.code : null,
3217
+ requestId: res.headers?.get?.(REQUEST_ID_HEADER) ?? null,
3218
+ response: body,
3219
+ method,
3220
+ path,
3221
+ retryAfterMs: retryAfterMs(res.headers?.get?.("retry-after")),
3222
+ issues: b.issues
3223
+ });
3224
+ }
3225
+ function reportError(err, info, callerSignal) {
3226
+ if (!options.onError) return;
3227
+ if (callerSignal?.aborted && err?.name === "AbortError") return;
3228
+ try {
3229
+ options.onError(err instanceof Error ? err : new Error(String(err)), info);
3230
+ } catch {
3231
+ }
3232
+ }
2623
3233
  async function request(command) {
2624
3234
  const qs = command._params ? "?" + new URLSearchParams(
2625
3235
  Object.fromEntries(
@@ -2628,45 +3238,57 @@ function createNivaro(url, options = {}) {
2628
3238
  ).toString() : "";
2629
3239
  const timeoutMs = options.timeoutMs ?? 0;
2630
3240
  const timed = command._method === "GET" && timeoutMs > 0;
2631
- const ctrl = timed ? new AbortController() : null;
2632
- const timer = ctrl ? setTimeout(() => ctrl.abort(), timeoutMs) : null;
2633
3241
  const callerSignal = command._signal;
3242
+ let ctrl = null;
3243
+ let timer = null;
2634
3244
  const onCallerAbort = () => ctrl?.abort();
2635
- if (callerSignal && ctrl) {
2636
- if (callerSignal.aborted) ctrl.abort();
2637
- else callerSignal.addEventListener("abort", onCallerAbort, { once: true });
2638
- }
2639
- const signal = ctrl ? ctrl.signal : callerSignal;
3245
+ let wired = false;
3246
+ const fullUrl = `${baseUrl}/api${command._path}${qs}`;
3247
+ const where = { method: command._method, path: command._path, kind: "request" };
2640
3248
  try {
2641
- let res;
2642
- try {
2643
- res = await fetcher(`${baseUrl}/api${command._path}${qs}`, {
2644
- method: command._method,
2645
- headers: authHeaders(),
2646
- credentials: credentialsMode(),
2647
- body: command._body != null ? JSON.stringify(command._body) : void 0,
2648
- ...signal ? { signal } : {}
2649
- });
2650
- } catch (e) {
2651
- if (callerSignal?.aborted) throw e;
2652
- if (ctrl?.signal.aborted)
2653
- throw Object.assign(new Error(`Request timed out after ${timeoutMs / 1e3}s`), {
2654
- name: "TimeoutError"
2655
- });
2656
- throw e;
2657
- } finally {
2658
- if (timer) clearTimeout(timer);
2659
- }
3249
+ const res = await send(
3250
+ "request",
3251
+ command._method,
3252
+ command._path,
3253
+ fullUrl,
3254
+ baseHeaders(true),
3255
+ async (headers) => {
3256
+ ctrl = timed ? new AbortController() : null;
3257
+ const attemptCtrl = ctrl;
3258
+ timer = attemptCtrl ? setTimeout(() => attemptCtrl.abort(), timeoutMs) : null;
3259
+ if (callerSignal && attemptCtrl) {
3260
+ if (callerSignal.aborted) attemptCtrl.abort();
3261
+ else if (!wired) {
3262
+ callerSignal.addEventListener("abort", onCallerAbort, { once: true });
3263
+ wired = true;
3264
+ }
3265
+ }
3266
+ const signal = attemptCtrl ? attemptCtrl.signal : callerSignal;
3267
+ try {
3268
+ return await fetcher(fullUrl, {
3269
+ method: command._method,
3270
+ headers,
3271
+ credentials: credentialsMode(),
3272
+ body: command._body != null ? JSON.stringify(command._body) : void 0,
3273
+ ...signal ? { signal } : {}
3274
+ });
3275
+ } catch (e) {
3276
+ if (callerSignal?.aborted) throw e;
3277
+ if (attemptCtrl?.signal.aborted)
3278
+ throw Object.assign(new Error(`Request timed out after ${timeoutMs / 1e3}s`), {
3279
+ name: "TimeoutError"
3280
+ });
3281
+ throw e;
3282
+ } finally {
3283
+ if (timer) clearTimeout(timer);
3284
+ }
3285
+ },
3286
+ callerSignal
3287
+ );
2660
3288
  if (command._method === "DELETE" && res.status === 204) {
2661
3289
  return void 0;
2662
3290
  }
2663
- if (!res.ok) {
2664
- const err = await res.json().catch(() => ({ error: res.statusText }));
2665
- throw Object.assign(new Error(err.error ?? res.statusText), {
2666
- status: res.status,
2667
- response: err
2668
- });
2669
- }
3291
+ if (!res.ok) throw await httpError(res, command._method, command._path);
2670
3292
  const contentType = res.headers.get("content-type") ?? "";
2671
3293
  if (!contentType.includes("application/json")) {
2672
3294
  if (contentType.includes("application/pdf") || contentType.includes("application/octet-stream")) {
@@ -2675,8 +3297,11 @@ function createNivaro(url, options = {}) {
2675
3297
  return await res.text();
2676
3298
  }
2677
3299
  return await res.json();
3300
+ } catch (err) {
3301
+ reportError(err, where, callerSignal);
3302
+ throw err;
2678
3303
  } finally {
2679
- callerSignal?.removeEventListener("abort", onCallerAbort);
3304
+ if (wired) callerSignal?.removeEventListener("abort", onCallerAbort);
2680
3305
  }
2681
3306
  }
2682
3307
  async function upload(file, opts = {}) {
@@ -2684,20 +3309,24 @@ function createNivaro(url, options = {}) {
2684
3309
  fd.append("file", file);
2685
3310
  if (opts.title) fd.append("title", opts.title);
2686
3311
  if (opts.folder) fd.append("folder", opts.folder);
2687
- const res = await fetcher(`${baseUrl}/api/files/upload`, {
2688
- method: "POST",
2689
- headers: currentToken ? { Authorization: `Bearer ${currentToken}` } : {},
2690
- credentials: credentialsMode(),
2691
- body: fd
2692
- });
2693
- if (!res.ok) {
2694
- const err = await res.json().catch(() => ({ error: res.statusText }));
2695
- throw Object.assign(new Error(err.error ?? res.statusText), {
2696
- status: res.status
2697
- });
3312
+ const path = "/files/upload";
3313
+ const fullUrl = `${baseUrl}/api${path}`;
3314
+ try {
3315
+ const res = await send(
3316
+ "upload",
3317
+ "POST",
3318
+ path,
3319
+ fullUrl,
3320
+ baseHeaders(false),
3321
+ (headers) => fetcher(fullUrl, { method: "POST", headers, credentials: credentialsMode(), body: fd })
3322
+ );
3323
+ if (!res.ok) throw await httpError(res, "POST", path);
3324
+ const result = await res.json();
3325
+ return result.data;
3326
+ } catch (err) {
3327
+ reportError(err, { method: "POST", path, kind: "upload" });
3328
+ throw err;
2698
3329
  }
2699
- const result = await res.json();
2700
- return result.data;
2701
3330
  }
2702
3331
  function fileUrl(fileId) {
2703
3332
  return `${baseUrl}/api/files/${fileId}`;
@@ -2705,44 +3334,63 @@ function createNivaro(url, options = {}) {
2705
3334
  async function importParse(templateId, file, fileName) {
2706
3335
  const form = new FormData();
2707
3336
  form.append("file", file, fileName ?? file.name ?? "import.xlsx");
2708
- const res = await fetcher(`${baseUrl}/api/import-templates/${templateId}/parse`, {
2709
- method: "POST",
2710
- headers: currentToken ? { Authorization: `Bearer ${currentToken}` } : {},
2711
- credentials: credentialsMode(),
2712
- body: form
2713
- });
2714
- const json = await res.json().catch(() => ({ error: res.statusText }));
2715
- if (!res.ok)
2716
- throw Object.assign(new Error(json?.error || "Import parse failed"), {
2717
- status: res.status,
2718
- issues: json?.issues
2719
- });
2720
- return json.data;
3337
+ const path = `/import-templates/${templateId}/parse`;
3338
+ const fullUrl = `${baseUrl}/api${path}`;
3339
+ try {
3340
+ const res = await send(
3341
+ "import-parse",
3342
+ "POST",
3343
+ path,
3344
+ fullUrl,
3345
+ baseHeaders(false),
3346
+ (headers) => fetcher(fullUrl, { method: "POST", headers, credentials: credentialsMode(), body: form })
3347
+ );
3348
+ if (!res.ok) {
3349
+ const err = await httpError(res, "POST", path);
3350
+ if (!errorBodyMessage(err.response)) err.message = "Import parse failed";
3351
+ throw err;
3352
+ }
3353
+ const json = await res.json();
3354
+ return json.data;
3355
+ } catch (err) {
3356
+ reportError(err, { method: "POST", path, kind: "import-parse" });
3357
+ throw err;
3358
+ }
2721
3359
  }
2722
3360
  async function graphql(query, variables, operationName) {
2723
- const res = await fetcher(`${baseUrl}/api/graphql`, {
2724
- method: "POST",
2725
- headers: authHeaders(),
2726
- credentials: credentialsMode(),
2727
- body: JSON.stringify({ query, variables, operationName })
2728
- });
2729
- if (!res.ok) {
2730
- const err = await res.json().catch(() => ({ error: res.statusText }));
2731
- throw Object.assign(new Error(err.error ?? res.statusText), {
2732
- status: res.status,
2733
- response: err
2734
- });
2735
- }
2736
- const json = await res.json();
2737
- if (json.errors?.length) {
2738
- const first = json.errors[0];
2739
- throw Object.assign(new Error(first.message), {
2740
- graphqlErrors: json.errors,
2741
- extensions: first.extensions
2742
- });
3361
+ const path = "/graphql";
3362
+ const fullUrl = `${baseUrl}/api${path}`;
3363
+ const where = { method: "POST", path, kind: "graphql" };
3364
+ try {
3365
+ const res = await send(
3366
+ "graphql",
3367
+ "POST",
3368
+ path,
3369
+ fullUrl,
3370
+ baseHeaders(true),
3371
+ (headers) => fetcher(fullUrl, {
3372
+ method: "POST",
3373
+ headers,
3374
+ credentials: credentialsMode(),
3375
+ body: JSON.stringify({ query, variables, operationName })
3376
+ })
3377
+ );
3378
+ if (!res.ok) throw await httpError(res, "POST", path);
3379
+ const json = await res.json();
3380
+ if (json.errors?.length) {
3381
+ const first = json.errors[0];
3382
+ throw Object.assign(new Error(first.message), {
3383
+ graphqlErrors: json.errors,
3384
+ extensions: first.extensions,
3385
+ requestId: res.headers?.get?.(REQUEST_ID_HEADER) ?? null
3386
+ });
3387
+ }
3388
+ if (!json.data) throw new Error("GraphQL response contained no data");
3389
+ return json.data;
3390
+ } catch (err) {
3391
+ reportError(err, where);
3392
+ throw err;
2743
3393
  }
2744
- if (!json.data) throw new Error("GraphQL response contained no data");
2745
- return json.data;
2746
3394
  }
2747
3395
  return { request, graphql, upload, importParse, fileUrl, setToken, getToken, url: baseUrl };
2748
3396
  }
@@ -2974,8 +3622,11 @@ export {
2974
3622
  EDITOR_NOTE_MAX,
2975
3623
  GROUP_PATCH_KEYS,
2976
3624
  LAYOUT_PATCH_KEYS,
3625
+ NOTIFICATIONS_CHANNEL,
3626
+ NivaroError,
2977
3627
  PLACEMENT_PATCH_KEYS,
2978
3628
  READ_MANY_MAX,
3629
+ REQUEST_ID_HEADER,
2979
3630
  _and,
2980
3631
  _contains,
2981
3632
  _ends_with,
@@ -2995,6 +3646,7 @@ export {
2995
3646
  _some,
2996
3647
  _starts_with,
2997
3648
  abandonHelpVideoUpload,
3649
+ acknowledgeNotification,
2998
3650
  acquireItemLock,
2999
3651
  activateLayout,
3000
3652
  addChatChannelMember,
@@ -3012,6 +3664,7 @@ export {
3012
3664
  aiReview,
3013
3665
  aiSummarize,
3014
3666
  aiValidate,
3667
+ answerAgentQuestion,
3015
3668
  appendSessionRecordingEvents,
3016
3669
  applyContentBundle,
3017
3670
  applyHelpVideoPackageImport,
@@ -3020,19 +3673,32 @@ export {
3020
3673
  approveAddendum,
3021
3674
  approveAiProposal,
3022
3675
  archiveHelpVideo,
3676
+ archiveReadNotifications,
3023
3677
  asc,
3678
+ askHuman,
3679
+ attachFileToRecord,
3024
3680
  backupExportPath,
3681
+ batchItems,
3025
3682
  batchPickerExclusionStatus,
3683
+ bulkDeleteItems,
3684
+ bulkNotificationAction,
3026
3685
  bulkPickerExclusion,
3686
+ bulkRestoreTrash,
3687
+ bulkTransitionItems,
3688
+ bulkUpdateItems,
3689
+ bulkWriteItems,
3027
3690
  callExternalApi,
3028
3691
  callExternalApiEndpoint,
3029
3692
  callInstanceTool,
3693
+ cancelAgentQuestion,
3694
+ cancelJobRun,
3030
3695
  cancelScheduledChange,
3031
3696
  cancelStagedImport,
3032
3697
  captureCpuProfile,
3033
3698
  cascadeFieldDependencies,
3034
3699
  chaosWhatIf,
3035
3700
  checkBlackoutDate,
3701
+ checkItemFilter,
3036
3702
  claimQueueItem,
3037
3703
  claimSupportTicket,
3038
3704
  claimTask,
@@ -3044,6 +3710,7 @@ export {
3044
3710
  completeTask,
3045
3711
  copyReportWidget,
3046
3712
  createAccessAudit,
3713
+ createActivityEntry,
3047
3714
  createAddendum,
3048
3715
  createAlertDefinition,
3049
3716
  createAlertSubscription,
@@ -3057,6 +3724,8 @@ export {
3057
3724
  createChatRoomType,
3058
3725
  createCollectionLayout,
3059
3726
  createComment,
3727
+ createDashboard,
3728
+ createDashboardWidget,
3060
3729
  createDataQualityRule,
3061
3730
  createExternalApi,
3062
3731
  createExternalApiEndpoint,
@@ -3084,6 +3753,7 @@ export {
3084
3753
  createRealtime,
3085
3754
  createRecordLink,
3086
3755
  createRecordTemplate,
3756
+ createReminder,
3087
3757
  createReport,
3088
3758
  createReportAlert,
3089
3759
  createReportAnnotation,
@@ -3094,6 +3764,7 @@ export {
3094
3764
  createRole,
3095
3765
  createRolePolicy,
3096
3766
  createRule,
3767
+ createSavedSearch,
3097
3768
  createSavedView,
3098
3769
  createScheduledChange,
3099
3770
  createScheduledReport,
@@ -3124,6 +3795,8 @@ export {
3124
3795
  deleteChatMessage,
3125
3796
  deleteCollectionLayout,
3126
3797
  deleteComment,
3798
+ deleteDashboard,
3799
+ deleteDashboardWidget,
3127
3800
  deleteDataQualityRule,
3128
3801
  deleteExternalApi,
3129
3802
  deleteExternalApiEndpoint,
@@ -3147,6 +3820,7 @@ export {
3147
3820
  deleteQueueView,
3148
3821
  deleteRecordLink,
3149
3822
  deleteRecordTemplate,
3823
+ deleteReminder,
3150
3824
  deleteReport,
3151
3825
  deleteReportAlert,
3152
3826
  deleteReportAnnotation,
@@ -3158,6 +3832,7 @@ export {
3158
3832
  deleteRole,
3159
3833
  deleteRolePolicy,
3160
3834
  deleteRule,
3835
+ deleteSavedSearch,
3161
3836
  deleteSavedView,
3162
3837
  deleteScheduledReport,
3163
3838
  deleteSessionRecording,
@@ -3180,9 +3855,13 @@ export {
3180
3855
  diffLayoutVersion,
3181
3856
  disableTwoFactor,
3182
3857
  discardHelpVideoPackageImport,
3858
+ drillDashboardWidgetRows,
3183
3859
  drillReportRow,
3860
+ drillReportWidgetRows,
3184
3861
  editChatMessage,
3185
3862
  endSessionRecording,
3863
+ errorBodyMessage,
3864
+ estimateBackgroundRun,
3186
3865
  evaluateAlerts,
3187
3866
  evaluateAtRisk,
3188
3867
  evaluateFieldDefaults,
@@ -3241,6 +3920,7 @@ export {
3241
3920
  installBlueprint,
3242
3921
  installCollectionPreset,
3243
3922
  invokeInternalWidgetAction,
3923
+ isNivaroError,
3244
3924
  isPageSlot,
3245
3925
  joinChatRoom,
3246
3926
  leaveChatRoom,
@@ -3248,17 +3928,24 @@ export {
3248
3928
  listAccessAudits,
3249
3929
  listActiveAtRiskRules,
3250
3930
  listActivePresence,
3931
+ listActivityActions,
3251
3932
  listAddendums,
3933
+ listAgentTasks,
3934
+ listAgentTriggerDeliveries,
3935
+ listAgentTriggers,
3252
3936
  listAlertDefinitions,
3253
3937
  listAlertSubscriptions,
3254
3938
  listAllNotificationSubscriptions,
3255
3939
  listAnomalyDefinitions,
3256
3940
  listAnomalyRules,
3257
3941
  listApiKeys,
3942
+ listApiRequests,
3258
3943
  listApprovalChains,
3259
3944
  listApprovalInstances,
3945
+ listAskedQuestions,
3260
3946
  listAtRiskRules,
3261
3947
  listAttributeDefinitions,
3948
+ listBackgroundRuns,
3262
3949
  listBlackoutDates,
3263
3950
  listBulkActions,
3264
3951
  listChangeOrders,
@@ -3301,10 +3988,13 @@ export {
3301
3988
  listItemScheduledChanges,
3302
3989
  listJobRuns,
3303
3990
  listLayoutVersions,
3991
+ listMailLog,
3304
3992
  listMetricAlertRules,
3305
3993
  listMetricAlertSubscriptions,
3306
3994
  listMetricDefinitions,
3995
+ listMyAgentQuestions,
3307
3996
  listMyHelpVideoUploads,
3997
+ listMyJobs,
3308
3998
  listMyTasks,
3309
3999
  listNotificationSubscriptions,
3310
4000
  listNotifications,
@@ -3317,11 +4007,13 @@ export {
3317
4007
  listQueueViews,
3318
4008
  listQueues,
3319
4009
  listRecordLinks,
4010
+ listRecordMail,
3320
4011
  listRecordTemplates,
3321
4012
  listRegisteredExtensions,
3322
4013
  listRegisteredFlowOperations,
3323
4014
  listRegisteredFlowTriggers,
3324
4015
  listRelatedComments,
4016
+ listReminders,
3325
4017
  listReportAlerts,
3326
4018
  listReportAnnotations,
3327
4019
  listReportFilterPresets,
@@ -3337,10 +4029,12 @@ export {
3337
4029
  listRoleUsers,
3338
4030
  listRoles,
3339
4031
  listRules,
4032
+ listSavedSearches,
3340
4033
  listSavedViews,
3341
4034
  listScheduledChanges,
3342
4035
  listScheduledReports,
3343
4036
  listScopeDimensions,
4037
+ listSentNotifications,
3344
4038
  listSessionRecordings,
3345
4039
  listShareLinks,
3346
4040
  listSlaRules,
@@ -3349,10 +4043,12 @@ export {
3349
4043
  listSubRows,
3350
4044
  listSupportTickets,
3351
4045
  listSyncJobs,
4046
+ listTaskAgents,
3352
4047
  listTasks,
3353
4048
  listTeamTasks,
3354
4049
  listThroughputCollections,
3355
4050
  listTraces,
4051
+ listTrash,
3356
4052
  listTreePermissions,
3357
4053
  listViewSubscriptions,
3358
4054
  listVirtualCollections,
@@ -3361,6 +4057,9 @@ export {
3361
4057
  listWidgetFeeds,
3362
4058
  listWorkspaceTemplates,
3363
4059
  listWorkspaces,
4060
+ logExport,
4061
+ logout,
4062
+ logoutAll,
3364
4063
  markAllNotificationsRead,
3365
4064
  markChatRoomRead,
3366
4065
  markNotificationRead,
@@ -3370,6 +4069,7 @@ export {
3370
4069
  omniSearch,
3371
4070
  openHelpVideoPackageImport,
3372
4071
  openHelpVideoUpload,
4072
+ parseRealtimeChanges,
3373
4073
  presignFileUpload,
3374
4074
  previewContentBundle,
3375
4075
  previewHelpVideoPackageImport,
@@ -3377,28 +4077,42 @@ export {
3377
4077
  previewReportWidget,
3378
4078
  projectFieldConfig,
3379
4079
  proposeLayoutOps,
4080
+ proposeSchemaChange,
3380
4081
  publishHelpVideo,
3381
4082
  publishItem,
4083
+ purgeTrashItem,
3382
4084
  queryVirtualCollection,
4085
+ queueBulkWriteItems,
3383
4086
  readAccessAuditFindings,
3384
4087
  readActiveLayout,
3385
4088
  readActivity,
4089
+ readActivityEntry,
3386
4090
  readActivityReportSummary,
3387
4091
  readAddendum,
4092
+ readAgentQuestion,
3388
4093
  readAiSettings,
3389
4094
  readAlertLog,
3390
4095
  readAllStateOwners,
3391
4096
  readAnomalyLog,
4097
+ readApiAnalyticsByKey,
3392
4098
  readApiAnalyticsErrors,
3393
4099
  readApiAnalyticsSummary,
3394
4100
  readApiAnalyticsTimeseries,
3395
4101
  readApiAnalyticsTopCollections,
3396
4102
  readApiAnalyticsTopPaths,
3397
4103
  readApiKey,
4104
+ readApiKeyMonthlyUsage,
4105
+ readApiKeyUsage,
3398
4106
  readApprovalBrief,
3399
4107
  readApprovalChain,
3400
4108
  readAtRiskSummary,
4109
+ readAuthProviders,
4110
+ readBackgroundRun,
4111
+ readBackgroundRunResult,
3401
4112
  readBackupManifest,
4113
+ readBulkRun,
4114
+ readBusyJobs,
4115
+ readChanges,
3402
4116
  readChatConfig,
3403
4117
  readChatDirectory,
3404
4118
  readChatPeerRead,
@@ -3406,6 +4120,7 @@ export {
3406
4120
  readCollectionLayout,
3407
4121
  readCollectionLayouts,
3408
4122
  readCollections,
4123
+ readCommentCounts,
3409
4124
  readConfigInventory,
3410
4125
  readCoverageGaps,
3411
4126
  readDashboard,
@@ -3424,6 +4139,7 @@ export {
3424
4139
  readFileMeta,
3425
4140
  readFileUsage,
3426
4141
  readFilesByIds,
4142
+ readFormState,
3427
4143
  readHealthDetailed,
3428
4144
  readHelpVideo,
3429
4145
  readHelpVideoAnalytics,
@@ -3445,29 +4161,39 @@ export {
3445
4161
  readIssue,
3446
4162
  readIssueSummary,
3447
4163
  readItem,
4164
+ readItemBySlug,
4165
+ readItemDistinct,
3448
4166
  readItemLock,
3449
4167
  readItemLockConfig,
3450
4168
  readItems,
3451
4169
  readJobRegistry,
4170
+ readJobRunLog,
3452
4171
  readLastTouch,
4172
+ readLatestRevisionId,
3453
4173
  readLayoutAssignments,
3454
4174
  readLayoutBundle,
3455
4175
  readLayoutDrift,
3456
4176
  readLayoutGroups,
4177
+ readLayoutLint,
3457
4178
  readLayoutOverview,
3458
4179
  readLayoutProposals,
3459
4180
  readLayoutVersion,
4181
+ readMailLogEntry,
4182
+ readMailStats,
3460
4183
  readMany,
3461
4184
  readMcpCapabilities,
3462
4185
  readMcpToolsConfig,
3463
4186
  readMe,
3464
4187
  readMetricAlertLog,
4188
+ readMyOwnerSeats,
3465
4189
  readMyScopes,
3466
4190
  readMyWork,
3467
4191
  readNotificationCount,
4192
+ readNotificationHistory,
3468
4193
  readNotificationSubscriptionStats,
3469
4194
  readOnlinePresence,
3470
4195
  readOwnerGroups,
4196
+ readOwnerHistory,
3471
4197
  readPage,
3472
4198
  readPageWidgetData,
3473
4199
  readPdfTemplate,
@@ -3475,6 +4201,7 @@ export {
3475
4201
  readPickerExclusion,
3476
4202
  readPickerExclusions,
3477
4203
  readPipelineFlowMap,
4204
+ readPipelineOutline,
3478
4205
  readPipelineReplay,
3479
4206
  readPipelineTemplate,
3480
4207
  readPipelineTemplates,
@@ -3487,7 +4214,9 @@ export {
3487
4214
  readQueueTrends,
3488
4215
  readQueueWorkload,
3489
4216
  readReadiness,
4217
+ readRecordDeletion,
3490
4218
  readRecordGraph,
4219
+ readRecordMute,
3491
4220
  readRelationOptions,
3492
4221
  readReport,
3493
4222
  readReportAlertLog,
@@ -3503,7 +4232,10 @@ export {
3503
4232
  readRevisions,
3504
4233
  readRole,
3505
4234
  readRuntimeStats,
4235
+ readSchemaProposal,
3506
4236
  readScopeDimensionCoverage,
4237
+ readSearchCounts,
4238
+ readSearchRecords,
3507
4239
  readSessionRecordingEvents,
3508
4240
  readSettings,
3509
4241
  readSingleton,
@@ -3541,10 +4273,12 @@ export {
3541
4273
  readWorkflowInstances,
3542
4274
  readWorkspace,
3543
4275
  readWorkspaceUsage,
4276
+ readWsToken,
3544
4277
  rebuildTreePaths,
3545
4278
  recordHelpVideoProgress,
3546
4279
  registerHelpVideoPage,
3547
4280
  rehearseCreateItem,
4281
+ rehearseUpdateItem,
3548
4282
  reindexSemanticSearch,
3549
4283
  rejectAddendum,
3550
4284
  rejectAiProposal,
@@ -3553,6 +4287,7 @@ export {
3553
4287
  rematerializeQueue,
3554
4288
  removeChatChannelMember,
3555
4289
  removeInstanceOwner,
4290
+ renderFormImage,
3556
4291
  renderInternalWidget,
3557
4292
  renderPdfTemplate,
3558
4293
  reorderFieldGroups,
@@ -3567,6 +4302,7 @@ export {
3567
4302
  requeueStagedImport,
3568
4303
  rerecordHelpVideo,
3569
4304
  rerenderHelpVideo,
4305
+ resendMail,
3570
4306
  resetReportCache,
3571
4307
  resolveLayoutProposal,
3572
4308
  resolveReportAlert,
@@ -3575,6 +4311,7 @@ export {
3575
4311
  restoreLayoutVersion,
3576
4312
  restorePipelineVersion,
3577
4313
  restoreReportVersion,
4314
+ restoreTrashItem,
3578
4315
  retryDeadLetter,
3579
4316
  retryErpSubmission,
3580
4317
  retryWebhookDelivery,
@@ -3616,7 +4353,9 @@ export {
3616
4353
  simulatePermissions,
3617
4354
  simulatePipeline,
3618
4355
  simulatePipelineImpact,
4356
+ snoozeNotification,
3619
4357
  startApproval,
4358
+ startBackgroundRun,
3620
4359
  startMasquerade,
3621
4360
  startSessionRecording,
3622
4361
  startWorkflow,
@@ -3636,7 +4375,10 @@ export {
3636
4375
  testWebhook,
3637
4376
  toggleChatPin,
3638
4377
  toggleChatReaction,
4378
+ toggleCommentReaction,
4379
+ toggleEntryReaction,
3639
4380
  togglePinnedItem,
4381
+ toggleRecordMute,
3640
4382
  toggleReportAlert,
3641
4383
  touchRecordView,
3642
4384
  transitionWorkflow,
@@ -3660,6 +4402,8 @@ export {
3660
4402
  updateChatRoomType,
3661
4403
  updateCollectionLayout,
3662
4404
  updateComment,
4405
+ updateDashboard,
4406
+ updateDashboardWidget,
3663
4407
  updateDataQualityRule,
3664
4408
  updateDraftPublishConfig,
3665
4409
  updateErpSubmissionStatus,
@@ -3689,6 +4433,7 @@ export {
3689
4433
  updateQueueSources,
3690
4434
  updateQueueView,
3691
4435
  updateRecordTemplate,
4436
+ updateReminder,
3692
4437
  updateReport,
3693
4438
  updateReportAlert,
3694
4439
  updateReportWidgetPreset,