@oddington/sdk 0.1.72 → 0.1.74

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/README.md CHANGED
@@ -4,6 +4,47 @@ The importable client for OS apps, routines and response handlers.
4
4
  Node operations require Node.js 22.12.0 or later. The root import and hosted
5
5
  Data and Files APIs work in browsers. Installing the package grants no authority.
6
6
 
7
+ ## Server-side API client
8
+
9
+ Create a named workspace API client:
10
+
11
+ ```sh
12
+ os api-client create --name "Airtable Importer" --scope inbox:publish
13
+ ```
14
+
15
+ Keep the one-time token in your server's secret store and supply it explicitly:
16
+
17
+ ```ts
18
+ import { createClient, richTextBlock } from '@oddington/sdk';
19
+
20
+ const client = createClient({ workspace: 'example', token: process.env.OS_API_TOKEN! });
21
+ const digest = {
22
+ title: 'Import complete',
23
+ description: 'Three projects were added.',
24
+ recipients: ['office@example.com'],
25
+ body: [richTextBlock({ markdown: 'The new projects are ready for review.' })],
26
+ notifyImmediately: true,
27
+ };
28
+ const options = { requestKey: 'airtable-import/commit-123/new-projects' };
29
+ await client.inbox.checkDigest(digest, options); // Validates without publishing.
30
+ const { id } = await client.inbox.publishDigest(digest, options);
31
+ ```
32
+
33
+ Use the same request key and unchanged content to recover a lost receipt.
34
+ Changing content under an existing key conflicts. The key belongs to the client
35
+ and workspace, so token rotation preserves replay. Issue an overlapping token
36
+ with `os api-client token issue`, update the program, then revoke the old token
37
+ with `os api-client token revoke`. `os api-client list` shows safe token IDs and
38
+ status; `os api-client disable --client <client-id> --yes` stops all its tokens.
39
+
40
+ This client derives the fixed workspace Inbox origin and exposes only
41
+ `inbox.checkDigest` and `inbox.publishDigest`. It requires no CLI login or Routine
42
+ context. API tokens belong in trusted server-side automation; do not embed them
43
+ in browser code. API clients cannot publish Asks or Files Blocks, read Inbox or
44
+ Records, use Connections, or start Runs.
45
+
46
+ ## Apps and routines
47
+
7
48
  When developing OS alongside a customer repository, use the repository's
8
49
  [`dev:customer` helper](../../README.md) to run Bun tests and TypeScript checks
9
50
  against the built local SDK without changing the customer's released pin,
package/dist/browser.js CHANGED
@@ -5247,17 +5247,31 @@ function validateBlock(value) {
5247
5247
  let asks = distinctIds(b.asks, "Ask IDs");
5248
5248
  return asks.some((ask) => !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(ask)) && fail("Invalid Ask ID"), { kind: "asks", problem: text(b.problem, "problem"), asks };
5249
5249
  }
5250
- ["record", "records", "files"].includes(b.kind) || fail("Unknown Block kind"), keys(b, ["kind", "label", "initiallyExpanded", ...b.kind === "record" ? ["record"] : b.kind === "records" ? ["records"] : ["files"]], "Block");
5250
+ ["record", "records", "files"].includes(b.kind) || fail("Unknown Block kind"), keys(b, ["kind", "label", "initiallyExpanded", ...b.kind === "record" ? ["record", "fields"] : b.kind === "records" ? ["records", "previewCount"] : ["files", "previewCount"]], "Block");
5251
5251
  let label = text(b.label, "Block label");
5252
5252
  b.initiallyExpanded !== void 0 && typeof b.initiallyExpanded != "boolean" && fail("Invalid initiallyExpanded");
5253
5253
  let expanded = b.initiallyExpanded === void 0 ? {} : { initiallyExpanded: b.initiallyExpanded };
5254
- if (b.kind === "record") return { kind: "record", label, record: validateQualifiedRecordRef(b.record), ...expanded };
5254
+ if (b.kind === "record") {
5255
+ let fields4 = b.fields === void 0 ? void 0 : array(b.fields, "fields").map((value2) => text(value2, "field name"));
5256
+ return fields4 && (!fields4.length || new Set(fields4).size !== fields4.length) && fail("Empty or duplicate fields"), {
5257
+ kind: "record",
5258
+ label,
5259
+ record: validateQualifiedRecordRef(b.record),
5260
+ ...fields4 === void 0 ? {} : { fields: fields4 },
5261
+ ...expanded
5262
+ };
5263
+ }
5264
+ let preview = (length) => {
5265
+ if (b.previewCount === void 0) return {};
5266
+ let previewCount = natural(b.previewCount, "previewCount", 1);
5267
+ return previewCount > length && fail("previewCount exceeds collection length"), { previewCount };
5268
+ };
5255
5269
  if (b.kind === "records") {
5256
5270
  let records = array(b.records, "records").map(validateQualifiedRecordRef);
5257
- return (!records.length || new Set(records.map((r) => JSON.stringify([r.repository, r.ref]))).size !== records.length) && fail("Empty or duplicate records"), { kind: "records", label, records, ...expanded };
5271
+ return (!records.length || new Set(records.map((r) => JSON.stringify([r.repository, r.ref]))).size !== records.length) && fail("Empty or duplicate records"), { kind: "records", label, records, ...preview(records.length), ...expanded };
5258
5272
  }
5259
5273
  let files3 = array(b.files, "files").map(validateInboxFile);
5260
- return (!files3.length || new Set(files3.map((file2) => file2.id)).size !== files3.length) && fail("Empty or duplicate files"), { kind: "files", label, files: files3, ...expanded };
5274
+ return (!files3.length || new Set(files3.map((file2) => file2.id)).size !== files3.length) && fail("Empty or duplicate files"), { kind: "files", label, files: files3, ...preview(files3.length), ...expanded };
5261
5275
  }
5262
5276
  function richTextBlock(value) {
5263
5277
  return validateBlock({ ...value, kind: "rich-text" });
@@ -5478,6 +5492,13 @@ function publicationRequestKey(value) {
5478
5492
  let options = object(value, "publication options");
5479
5493
  return keys(options, ["requestKey"], "publication options"), id(options.requestKey, "publication request key");
5480
5494
  }
5495
+ function digestPublicationRequest(value, options) {
5496
+ let source2 = object(value, "digest");
5497
+ return keys(source2, ["title", "description", "recipients", "views", "body", "notifyImmediately"], "digest"), {
5498
+ requestKey: publicationRequestKey(options),
5499
+ item: enforcePublicationSize(validatePublication({ ...source2, kind: "digest" }))
5500
+ };
5501
+ }
5481
5502
  function createInboxPublisher(transport) {
5482
5503
  return {
5483
5504
  async publishAsk(value, options) {
@@ -5490,12 +5511,7 @@ function createInboxPublisher(transport) {
5490
5511
  return id(result2.id, "published ask ID"), (!("revision" in result2) || !Number.isSafeInteger(result2.revision) || result2.revision !== 1) && fail("Initial ask publication must return revision 1"), { id: result2.id, revision: result2.revision };
5491
5512
  },
5492
5513
  async publishDigest(value, options) {
5493
- let source2 = object(value, "digest");
5494
- keys(source2, ["title", "description", "recipients", "views", "body", "notifyImmediately"], "digest");
5495
- let result2 = await transport.publish({
5496
- requestKey: publicationRequestKey(options),
5497
- item: enforcePublicationSize(validatePublication({ ...source2, kind: "digest" }))
5498
- });
5514
+ let result2 = await transport.publish(digestPublicationRequest(value, options));
5499
5515
  return { id: id(result2.id, "published digest ID") };
5500
5516
  },
5501
5517
  async publishResolution(askId, value) {
@@ -5523,6 +5539,10 @@ var RecordSelectionError = class extends InboxContractError {
5523
5539
  };
5524
5540
 
5525
5541
  var inboxPublicationRefusals = {
5542
+ "API clients can publish only Digests without Files Blocks": {
5543
+ error: "API clients can publish only Digests without Files Blocks",
5544
+ status: 403
5545
+ },
5526
5546
  "Publication retry changed": {
5527
5547
  error: "This request key was already used for different content. Use the original content or a new request key.",
5528
5548
  status: 409
@@ -9806,6 +9826,71 @@ function runtimeConnections() {
9806
9826
  }
9807
9827
  var connections = /* @__PURE__ */ runtimeConnections();
9808
9828
 
9829
+ function validApiToken(value) {
9830
+ return typeof value == "string" && /^os_api_[A-Za-z0-9_-]{43}$/.test(value);
9831
+ }
9832
+
9833
+ async function requestInboxPublication(operation2, request3, caller) {
9834
+ let attempt = () => {
9835
+ if (caller?.aborted) throw caller.reason;
9836
+ let timeout = AbortSignal.timeout(3e4);
9837
+ return request3(caller ? AbortSignal.any([caller, timeout]) : timeout);
9838
+ };
9839
+ if (operation2 !== "publish") return attempt();
9840
+ try {
9841
+ let response2 = await attempt();
9842
+ if (response2.status !== 408 && response2.status !== 429 && response2.status < 500) return response2;
9843
+ await response2.body?.cancel();
9844
+ } catch (error) {
9845
+ if (caller?.aborted) throw error;
9846
+ }
9847
+ if (caller?.aborted) throw caller.reason;
9848
+ return attempt();
9849
+ }
9850
+
9851
+ function createClient(options) {
9852
+ if (!options || typeof options != "object" || Array.isArray(options) || Object.keys(options).sort().join(",") !== "token,workspace" || typeof options.workspace != "string" || options.workspace.length > 63 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(options.workspace) || ["auth", "www", "api", "os"].includes(options.workspace) || !validApiToken(options.token))
9853
+ throw new Error("Supply a valid workspace slug and explicit OS API token");
9854
+ let origin = `https://${options.workspace}.oddington.ai`, token = options.token;
9855
+ async function send3(operation2, request3) {
9856
+ if (request3.item.body?.some((block) => block.kind === "files"))
9857
+ throw new InboxPublicationError("API clients can publish only Digests without Files Blocks");
9858
+ let body = JSON.stringify(request3);
9859
+ try {
9860
+ let response2 = await requestInboxPublication(operation2, async (signal) => {
9861
+ let result3 = await fetch(`${origin}/api/inbox/${operation2}`, {
9862
+ method: "POST",
9863
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
9864
+ body,
9865
+ signal,
9866
+ redirect: "error",
9867
+ credentials: "omit",
9868
+ cache: "no-store"
9869
+ });
9870
+ if (result3.redirected || result3.status >= 300 && result3.status < 400) throw new InboxPublicationError(void 0);
9871
+ return result3;
9872
+ }), result2 = await response2.json();
9873
+ if (!response2.ok) throw new InboxPublicationError(result2?.error);
9874
+ if (!result2 || typeof result2 != "object" || Array.isArray(result2)) throw new InboxPublicationError(void 0);
9875
+ return result2;
9876
+ } catch (error) {
9877
+ throw error instanceof InboxPublicationError ? error : new InboxPublicationError(void 0);
9878
+ }
9879
+ }
9880
+ let publisher = createInboxPublisher({
9881
+ publish: (request3) => send3("publish", request3),
9882
+ async resolve() {
9883
+ throw new Error("API clients cannot resolve Asks");
9884
+ }
9885
+ });
9886
+ return { inbox: {
9887
+ async checkDigest(value, options2) {
9888
+ await send3("check", digestPublicationRequest(value, options2));
9889
+ },
9890
+ publishDigest: publisher.publishDigest
9891
+ } };
9892
+ }
9893
+
9809
9894
  function locationIdentity(location) {
9810
9895
  let coordinates = location.provider === "os" ? [location.file] : location.provider === "gmail" ? [location.connection, location.message, location.attachment] : location.provider === "dropbox" ? [location.connection, location.file] : location.provider === "outlook" ? [
9811
9896
  location.connection,
@@ -10094,7 +10179,7 @@ function parseInboxCurrent(value) {
10094
10179
  }
10095
10180
  function parseInboxItem(value) {
10096
10181
  let item = object8(json2(value));
10097
- return assert(id2(item.id) && id2(item.workspaceId) && integer(item.number) && integer(item.revision) && integer(item.activityVersion, 0) && ["ask", "digest"].includes(String(item.kind)) && ["open", "closed"].includes(String(item.lifecycle)) && text4(item.title) && text4(item.description, !0) && text4(item.author) && date(item.publishedAt) && optionalDate(item.seenAt) && optionalDate(item.digestReadAt)), item.outcome !== null && assert(text4(object8(item.outcome).outcome)), "canonicalRoutineId" in item && assert(item.canonicalRoutineId === null || isAppRoutineName(item.canonicalRoutineId)), item.kind === "ask" ? askMetadata(item) : assert(!("tags" in item) && !("recordRefs" in item)), array2(item.body).forEach(validateBlock), array2(item.views).forEach((value2) => {
10182
+ return assert(id2(item.id) && id2(item.workspaceId) && integer(item.number) && integer(item.revision) && integer(item.activityVersion, 0) && ["ask", "digest"].includes(String(item.kind)) && ["open", "closed"].includes(String(item.lifecycle)) && text4(item.title) && text4(item.description, !0) && text4(item.author) && date(item.publishedAt) && optionalDate(item.seenAt) && optionalDate(item.digestReadAt)), item.outcome !== null && assert(text4(object8(item.outcome).outcome)), "canonicalRoutineId" in item && assert(item.canonicalRoutineId === null || isAppRoutineName(item.canonicalRoutineId)), "apiClientId" in item && assert(item.apiClientId === null || id2(item.apiClientId) && item.kind === "digest"), item.kind === "ask" ? askMetadata(item) : assert(!("tags" in item) && !("recordRefs" in item)), array2(item.body).forEach(validateBlock), array2(item.views).forEach((value2) => {
10098
10183
  let view = object8(value2);
10099
10184
  assert(text4(view.id) && text4(view.view) && text4(view.implementation)), json2(view.input);
10100
10185
  }), array2(item.people).forEach((value2) => {
@@ -10128,7 +10213,9 @@ function parseInboxItem(value) {
10128
10213
  }
10129
10214
  }), array2(item.activity).forEach((value2) => {
10130
10215
  let event = object8(value2);
10131
- assert(integer(event.id) && text4(event.type) && (event.actorId === null || id2(event.actorId)) && (event.questionId === null || text4(event.questionId)) && integer(event.revision) && date(event.createdAt)), object8(event.data);
10216
+ assert(integer(event.id) && text4(event.type) && (event.actorId === null || id2(event.actorId)) && (event.questionId === null || text4(event.questionId)) && integer(event.revision) && date(event.createdAt));
10217
+ let data3 = object8(event.data);
10218
+ event.type === "recipient-added" && (keys6(data3, ["personId"]), assert(id2(event.actorId) && id2(data3.personId)));
10132
10219
  }), array2(item.work).forEach((value2) => {
10133
10220
  let work = object8(value2);
10134
10221
  assert(id2(work.id) && text4(work.questionId) && text4(work.reason) && optionalDate(work.settledAt));
@@ -11627,7 +11714,7 @@ async function provider(configuration, guard) {
11627
11714
  let { AuthClient } = await prepareProvider();
11628
11715
  if (!guard.current(guard.revision())) throw new BrowserAuthError("stale");
11629
11716
  let authorizationRequest, authorizationQueue = Promise.resolve(), storage = globalThis.localStorage, storageKey = `sb-${new URL(configuration.providerUrl).hostname.split(".")[0]}-auth-token`, listeners = /* @__PURE__ */ new Set(), instance;
11630
- function createClient(clearing = !1) {
11717
+ function createClient2(clearing = !1) {
11631
11718
  let provenance = /* @__PURE__ */ new Map(), revocation, removalRevision = clearing ? guard.revision() : void 0, lifetime = new AbortController(), alive = () => !lifetime.signal.aborted, client = new AuthClient({
11632
11719
  url: `${configuration.providerUrl}/auth/v1`,
11633
11720
  headers: { apikey: configuration.publishableKey, Authorization: `Bearer ${configuration.publishableKey}` },
@@ -11713,7 +11800,7 @@ async function provider(configuration, guard) {
11713
11800
  lifetime.abort(), provenance.clear(), client.dispose();
11714
11801
  } };
11715
11802
  }
11716
- let activeClient = () => (instance ??= createClient()).client, retire = () => {
11803
+ let activeClient = () => (instance ??= createClient2()).client, retire = () => {
11717
11804
  instance?.close(), instance = void 0;
11718
11805
  };
11719
11806
  activeClient();
@@ -11770,7 +11857,7 @@ async function provider(configuration, guard) {
11770
11857
  }
11771
11858
  retire();
11772
11859
  let revision = guard.revision();
11773
- instance = createClient(!0);
11860
+ instance = createClient2(!0);
11774
11861
  let client = instance.client, cleared = await instance.clearSession();
11775
11862
  if (!guard.current(revision)) throw new BrowserAuthError("stale");
11776
11863
  if (cleared.error) return cleared;
@@ -12116,24 +12203,6 @@ var app = /* @__PURE__ */ Object.freeze({
12116
12203
  })
12117
12204
  });
12118
12205
 
12119
- async function requestInboxPublication(operation2, request3, caller) {
12120
- let attempt = () => {
12121
- if (caller?.aborted) throw caller.reason;
12122
- let timeout = AbortSignal.timeout(3e4);
12123
- return request3(caller ? AbortSignal.any([caller, timeout]) : timeout);
12124
- };
12125
- if (operation2 !== "publish") return attempt();
12126
- try {
12127
- let response2 = await attempt();
12128
- if (response2.status !== 408 && response2.status !== 429 && response2.status < 500) return response2;
12129
- await response2.body?.cancel();
12130
- } catch (error) {
12131
- if (caller?.aborted) throw error;
12132
- }
12133
- if (caller?.aborted) throw caller.reason;
12134
- return attempt();
12135
- }
12136
-
12137
12206
  function routinePublicationClient2(options = {}) {
12138
12207
  let environment = {}, installed2 = options.request ? void 0 : routineTransport(), local2 = options.request ? void 0 : installed2?.request ?? void 0, workspace = installed2 ? "installed" : options.workspace ?? environment.OS_ROUTINE_WORKSPACE, capability = options.capability ?? (options.request ? void 0 : environment.OS_ROUTINE_RUN);
12139
12208
  if (!workspace || !/^[a-z0-9][a-z0-9-]*$/.test(workspace) || capability !== void 0 && !/^[0-9a-f]{64}$/.test(capability))
@@ -12186,6 +12255,7 @@ export {
12186
12255
  auth,
12187
12256
  connections,
12188
12257
  continueAsk,
12258
+ createClient,
12189
12259
  data,
12190
12260
  defineHandler,
12191
12261
  defineResponse,