@oddington/sdk 0.1.75 → 0.1.76

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
@@ -69,8 +69,12 @@ Questions after authentication. The SDK validates and privately snapshots the
69
69
  filter across pagination. Local apps supply the same explicit filter; their
70
70
  trusted host rejects undeclared IDs. Each Question names its `assignee`,
71
71
  explicit `canAnswer` permission and server-calculated `status`. Focused
72
- Question requests carry the `question-work-v1` contract marker; an older app
73
- receives `client_update_required` instead of a generic Inbox outage.
72
+ Question requests carry the fixed `question-work-v2` contract marker. New Questions
73
+ expose numbered `response.options`; submit `{ option, value, note? }` and pass
74
+ `option` to `listRecordOptions` for the chosen picker. V2 also reads legacy
75
+ source-shaped Questions and submits their `{ selection, note? }` answers. Deployed
76
+ V1 clients retain that legacy contract and receive `client_update_required` when
77
+ an operation reaches a new ordered-options Question.
74
78
  Accepted Actions stay visible while waiting, working, unable to start or needing
75
79
  review; completed Actions and accepted handlerless Questions leave the list.
76
80
  Both use the same answer and Record-search methods, without a filter or prior list.
@@ -539,7 +543,11 @@ After a lost transact/discard response, `DataOperationError.effect` is
539
543
  initialize again to inspect authoritative work; do not replay the transaction.
540
544
  A lost publication response may be retried on the same handle with the same
541
545
  selection and summary; the SDK retains its canonical operation identity. If the
542
- host accepted work but local persistence fails, the error reports `applied` and
546
+ server refuses an encompassing publication because earlier work remains fenced,
547
+ it reports `apply_pending`, `retryable: false`, `effect: uncertain`. That outcome
548
+ preserves the earlier admissions and starts no new Git work. The SDK preserves
549
+ those facts and sends no automatic publication request. If the host accepted
550
+ work but local persistence fails, the error reports `applied` and
543
551
  invalidates the handle. Initialize again to recover coherent local state.
544
552
 
545
553
  First-party Auth uses the handle without initializing workspace context. Its
@@ -1180,9 +1188,11 @@ try {
1180
1188
  When the routine cannot continue, rethrow the original error to preserve its
1181
1189
  type and guidance. A new generic `Error` loses the SDK's bounded failure facts.
1182
1190
 
1183
- `apply_pending` is retryable and may report `uncertain` or `applied`;
1184
- retry the same change set to reconcile its retained identity. A transport failure
1185
- also keeps that identity. Concurrent `apply()` calls coalesce, confirmed calls
1191
+ `apply_pending` is normally retryable and may report `uncertain` or `applied`;
1192
+ retry the same change set to reconcile its retained identity. A blocked
1193
+ encompassing shared Change publication instead reports non-retryable uncertainty
1194
+ as described above. A transport failure also keeps that identity.
1195
+ Concurrent `apply()` calls coalesce, confirmed calls
1186
1196
  replay the result, and changed intent requires a new change set. Updates are
1187
1197
  bounded with creates and deletions to 10,000 total operations, with one operation
1188
1198
  per ref. The complete serialized change request is limited to 32 MiB for local
@@ -1247,6 +1257,45 @@ completed Data writes as ordinary uncommitted files for review, even after later
1247
1257
  failure. Inbox publication has no Record methods;
1248
1258
  managed Response handlers retain their separately injected repository capability.
1249
1259
 
1260
+ Question selection authoring uses one ordered list of explicit options:
1261
+
1262
+ ```ts
1263
+ response: selection({ options: [
1264
+ { type: 'choice', value: 'approve', label: 'Approve' },
1265
+ { type: 'choice', value: 'changes', label: 'Request changes',
1266
+ note: { placeholder: 'What should change?' } },
1267
+ { type: 'record', value: { repository: 'general', ref: 'entities/one' },
1268
+ label: 'Reviewed entity', description: 'Matches the supplier' },
1269
+ { type: 'record-picker', label: 'Choose another entity', source: {
1270
+ collection: { repository: 'general', name: 'entities' },
1271
+ where: { active: true }, refPrefix: 'entities/',
1272
+ } },
1273
+ ] })
1274
+ ```
1275
+
1276
+ Supply one to nine options. OS assigns published option IDs `1..N` in authored
1277
+ order. Authors supply each direct Record's value, label, and optional description;
1278
+ OS stores them unchanged without reading Data or checking Record existence or
1279
+ freshness. Authors do not supply IDs. Picker sources inherit the
1280
+ collection schema's title declaration; they accept only `collection`, optional
1281
+ scalar equality `where`, and optional literal `refPrefix`. The picker label is
1282
+ also its heading. A `note` declaration on a choice requires a nonempty answer;
1283
+ validation trims its edges and preserves internal whitespace.
1284
+
1285
+ `SelectionDefinitionInput` describes authoring; `SelectionDefinition` describes
1286
+ immutable numbered publication. New accepted answers are `SelectionResponse`
1287
+ values `{ option, value, note? }`. The value is the authored choice string or a
1288
+ qualified Record reference. A displayed picker label is retained separately as
1289
+ presentation and never enters the handler's answer value. Handlers can narrow
1290
+ `QuestionResponse` with `response.selection !== undefined` for retained legacy answers;
1291
+ otherwise read `response.option` and `response.value`.
1292
+
1293
+ Source-shaped `selection({ source })` authoring is deprecated but supported.
1294
+ `LegacyResponseDefinition` and `LegacyQuestionResponse` retain the original
1295
+ source definitions and `{ selection, note? }` payloads, including legacy search,
1296
+ suggestions and display fields. Stored legacy answers and handler input are not
1297
+ converted to numbered options.
1298
+
1250
1299
  Record presentation uses qualified current identities:
1251
1300
 
1252
1301
  ```ts
package/dist/browser.js CHANGED
@@ -5302,26 +5302,27 @@ function asksBlock(value) {
5302
5302
  }
5303
5303
  function selection(value) {
5304
5304
  let input = object(value, "selection");
5305
- return keys(input, ["source"], "selection"), validateResponseDefinition({ type: "selection", source: input.source });
5305
+ return keys(input, ["source", "options"], "selection"), validateResponseDefinition({ type: "selection", ...input });
5306
+ }
5307
+ function validateChoice(entry) {
5308
+ let option = object(entry, "choice");
5309
+ keys(option, ["value", "label", "description", "note"], "choice");
5310
+ let note;
5311
+ if (option.note !== void 0) {
5312
+ let declaration2 = object(option.note, "choice note");
5313
+ keys(declaration2, ["placeholder"], "choice note"), note = { placeholder: text(declaration2.placeholder, "note placeholder") };
5314
+ }
5315
+ return {
5316
+ value: id(option.value, "choice value"),
5317
+ label: text(option.label, "choice label"),
5318
+ ...option.description === void 0 ? {} : { description: text(option.description, "choice description") },
5319
+ ...note ? { note } : {}
5320
+ };
5306
5321
  }
5307
5322
  function validateAuthoredSource(value) {
5308
5323
  let source2 = object(value, "response definition");
5309
5324
  keys(source2, ["type", "options", "suggestions", "search"], "response definition"), source2.type !== "authored" && fail("Expected authored options");
5310
- let options = array(source2.options, "options").map((entry) => {
5311
- let option = object(entry, "choice");
5312
- keys(option, ["value", "label", "description", "note"], "choice");
5313
- let note;
5314
- if (option.note !== void 0) {
5315
- let declaration2 = object(option.note, "choice note");
5316
- keys(declaration2, ["placeholder"], "choice note"), note = { placeholder: text(declaration2.placeholder, "note placeholder") };
5317
- }
5318
- return {
5319
- value: id(option.value, "choice value"),
5320
- label: text(option.label, "choice label"),
5321
- ...option.description === void 0 ? {} : { description: text(option.description, "choice description") },
5322
- ...note ? { note } : {}
5323
- };
5324
- });
5325
+ let options = array(source2.options, "options").map(validateChoice);
5325
5326
  if (options.length || fail("Choices require at least one option"), new Set(options.map((option) => option.value)).size !== options.length && fail("Duplicate choice value"), Object.hasOwn(source2, "search") || Object.hasOwn(source2, "suggestions")) {
5326
5327
  let labels = object(source2.search, "choice search");
5327
5328
  keys(labels, ["triggerLabel", "placeholder", "emptyLabel"], "choice search");
@@ -5340,10 +5341,8 @@ function validateRecordReference(value) {
5340
5341
  let repository = id(row.repository, "repository"), ref = id(row.ref, "Record reference");
5341
5342
  return (!/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(repository) || /\.\.|\/\//.test(repository) || ref.length > 512 || !/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(ref)) && fail("Invalid Record identity"), { repository, ref };
5342
5343
  }
5343
- function validateRecordSource(value) {
5344
- let source2 = object(value, "Record selection");
5345
- keys(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], "Record selection"), source2.type !== "records" && fail("Expected Record options");
5346
- let collection = object(source2.collection, "collection");
5344
+ function recordPickerSource(value) {
5345
+ let source2 = object(value, "Record selection"), collection = object(source2.collection, "collection");
5347
5346
  keys(collection, ["repository", "name"], "collection");
5348
5347
  let repository = validateRecordReference({ repository: collection.repository, ref: "records/example" }).repository, name2 = id(collection.name, "collection name");
5349
5348
  /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(name2) || fail("Invalid collection name");
@@ -5352,10 +5351,23 @@ function validateRecordSource(value) {
5352
5351
  let where = object(source2.where ?? {}, "Record filter"), fieldName = (name3) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name3) && !["constructor", "prototype"].includes(name3);
5353
5352
  for (let [name3, value2] of Object.entries(where))
5354
5353
  (!fieldName(name3) || !(value2 === null || ["string", "number", "boolean"].includes(typeof value2)) || typeof value2 == "number" && !Number.isFinite(value2)) && fail("Record filters require scalar equality");
5355
- let display = object(source2.display, "Record display");
5354
+ return {
5355
+ collection: { repository, name: name2 },
5356
+ ...refPrefix ? { refPrefix } : {},
5357
+ ...source2.where === void 0 ? {} : { where: { ...where } }
5358
+ };
5359
+ }
5360
+ function validateRecordPickerSource(value) {
5361
+ let source2 = object(value, "Record picker source");
5362
+ return keys(source2, ["collection", "refPrefix", "where"], "Record picker source"), Object.hasOwn(source2, "where") && object(source2.where, "Record filter"), recordPickerSource(source2);
5363
+ }
5364
+ function validateRecordSource(value) {
5365
+ let source2 = object(value, "Record selection");
5366
+ keys(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], "Record selection"), source2.type !== "records" && fail("Expected Record options");
5367
+ let bounded3 = recordPickerSource(source2), { repository } = bounded3.collection, fieldName = (name2) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2) && !["constructor", "prototype"].includes(name2), display = object(source2.display, "Record display");
5356
5368
  keys(display, ["labelFields"], "Record display");
5357
5369
  let labelFields = distinctIds(display.labelFields, "label fields");
5358
- (labelFields.length > 2 || labelFields.some((name3) => !fieldName(name3))) && fail("Select one or two scalar label fields");
5370
+ (labelFields.length > 2 || labelFields.some((name2) => !fieldName(name2))) && fail("Select one or two scalar label fields");
5359
5371
  let suggestions = array(source2.suggestions ?? [], "suggestions").map((value2) => {
5360
5372
  let entry = object(value2, "suggestion");
5361
5373
  keys(entry, ["record", "reason"], "suggestion");
@@ -5364,14 +5376,13 @@ function validateRecordSource(value) {
5364
5376
  });
5365
5377
  return (suggestions.length > 8 || new Set(suggestions.map((entry) => entry.record.ref)).size !== suggestions.length) && fail("Record selection permits at most eight unique suggestions"), {
5366
5378
  type: "records",
5367
- collection: { repository, name: name2 },
5368
- ...refPrefix ? { refPrefix } : {},
5369
- where: { ...where },
5379
+ ...bounded3,
5380
+ where: bounded3.where ?? {},
5370
5381
  display: { labelFields },
5371
5382
  suggestions
5372
5383
  };
5373
5384
  }
5374
- function validateResponseDefinition(value) {
5385
+ function validateLegacyResponseDefinition(value) {
5375
5386
  let definition = object(value, "response definition");
5376
5387
  keys(definition, ["type", "source"], "response definition"), definition.type !== "selection" && fail("Expected a selection definition");
5377
5388
  let source2 = object(definition.source, "option source");
@@ -5384,6 +5395,41 @@ function validateResponseDefinition(value) {
5384
5395
  return fail("Unsupported option source");
5385
5396
  }
5386
5397
  }
5398
+ function selectionOptions(value, published) {
5399
+ let options = array(value, "options");
5400
+ return (!options.length || options.length > 9) && fail("Selections require one to nine options"), options.map((value2, index) => {
5401
+ let option = object(value2, "option"), common = published ? ["type", "id"] : ["type"];
5402
+ published && option.id !== index + 1 && fail("Published option IDs must be consecutive from one");
5403
+ let numbered = published ? { id: index + 1 } : {};
5404
+ switch (option.type) {
5405
+ case "choice":
5406
+ return keys(option, [...common, "value", "label", "description", "note"], "choice"), { type: "choice", ...validateChoice(
5407
+ Object.fromEntries(Object.entries(option).filter(([key]) => !["type", "id"].includes(key)))
5408
+ ), ...numbered };
5409
+ case "record":
5410
+ return keys(option, [...common, "value", "label", "description"], "Record option"), {
5411
+ type: "record",
5412
+ value: validateRecordReference(option.value),
5413
+ label: text(option.label, "Record label"),
5414
+ ...option.description === void 0 ? {} : { description: text(option.description, "Record description") },
5415
+ ...numbered
5416
+ };
5417
+ case "record-picker":
5418
+ return keys(option, [...common, "label", "source"], "Record picker option"), {
5419
+ type: "record-picker",
5420
+ label: text(option.label, "picker label"),
5421
+ source: validateRecordPickerSource(option.source),
5422
+ ...numbered
5423
+ };
5424
+ default:
5425
+ return fail("Unsupported option kind");
5426
+ }
5427
+ });
5428
+ }
5429
+ function validateResponseDefinition(value) {
5430
+ let definition = object(value, "response definition");
5431
+ return Object.hasOwn(definition, "options") ? (keys(definition, ["type", "options"], "response definition"), definition.type !== "selection" && fail("Expected a selection definition"), { type: "selection", options: selectionOptions(definition.options, !1) }) : validateLegacyResponseDefinition(definition);
5432
+ }
5387
5433
  function handlerReference(value) {
5388
5434
  let source2 = object(value, "handler reference");
5389
5435
  return keys(source2, ["id", "input"], "handler reference"), { id: id(source2.id, "handler ID"), input: serializable(source2.input) };
@@ -5528,11 +5574,11 @@ var RecordSelectionError = class extends InboxContractError {
5528
5574
  constructor(problem, source2) {
5529
5575
  let collection = `${source2.collection.repository}/${source2.collection.name}`, messages = {
5530
5576
  collection_unavailable: `The ${collection} collection is unavailable. Check the collection name and its schema.`,
5531
- display_fields_invalid: `The label fields for ${collection} must be scalar fields in its schema. Check display.labelFields.`,
5577
+ display_fields_invalid: "display" in source2 ? `The label fields for ${collection} must be scalar fields in its schema. Check display.labelFields.` : `The ${collection} schema must declare one or two scalar title fields. Check display.title.`,
5532
5578
  filter_fields_invalid: `The filters for ${collection} must use scalar schema fields and matching values. Check the Question\u2019s where fields.`,
5533
5579
  ref_prefix_invalid: `The record reference prefix does not belong to ${collection}. Check refPrefix against the collection\u2019s record references.`,
5534
5580
  suggestion_unavailable: `A suggested record is missing or isn\u2019t eligible for ${collection}. Update the suggestions and try again.`,
5535
- label_unavailable: `A record in ${collection} has no value in the configured label fields. Update display.labelFields or the record.`
5581
+ label_unavailable: "display" in source2 ? `A record in ${collection} has no value in the configured label fields. Update display.labelFields or the record.` : `A record in ${collection} has no value in the declared title fields. Update display.title or the record.`
5536
5582
  };
5537
5583
  super(messages[problem]);
5538
5584
  this.problem = problem;
@@ -8769,7 +8815,10 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8769
8815
  headers: { ...authority2.headers, "content-type": "application/json" },
8770
8816
  body: JSON.stringify(body)
8771
8817
  });
8772
- if (!response2.ok) throw dataTransportError(response2.status, await response2.json());
8818
+ if (!response2.ok) {
8819
+ let failure = dataTransportError(response2.status, await response2.json());
8820
+ throw publication && failure.effect === "unapplied" && (publication.id = crypto.randomUUID()), failure;
8821
+ }
8773
8822
  applied = !0;
8774
8823
  let value = await response2.json(), mutation;
8775
8824
  if (kind === "discard") {
@@ -8791,15 +8840,15 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8791
8840
  let update = snapshotDifference(before, await store.changes(installation));
8792
8841
  return kind === "publish" && (update.records = !0), assertAccess(), publication && (publication.complete = !0), live2.notify(update), assertAccess(), structuredClone(mutation.changes ?? []);
8793
8842
  } catch (error) {
8794
- let failure = error instanceof DataOperationError ? error : new DataOperationError("unavailable"), effect = applied ? "applied" : dispatched ? failure.effect ?? "uncertain" : "unapplied";
8843
+ let failure = error instanceof DataOperationError ? error : new DataOperationError("unavailable", dispatched && kind === "publish"), effect = applied ? "applied" : dispatched ? failure.effect ?? "uncertain" : "unapplied";
8795
8844
  throw effect !== "unapplied" && (kind !== "publish" || effect === "applied") && (invalidated = !0, live2.stop(), await store?.invalidate(installation).catch(() => {
8796
- })), new DataOperationError(
8845
+ })), explainDataValidation(new DataOperationError(
8797
8846
  failure.code,
8798
- effect === "uncertain" ? kind === "publish" : effect === "applied" ? !1 : failure.retryable,
8847
+ effect === "uncertain" ? kind === "publish" && failure.retryable : effect === "applied" ? !1 : failure.retryable,
8799
8848
  effect,
8800
8849
  failure.component,
8801
8850
  failure.detail
8802
- );
8851
+ ), failure.message, failure.detail);
8803
8852
  } finally {
8804
8853
  store?.close();
8805
8854
  }
@@ -9445,7 +9494,8 @@ var files = {
9445
9494
  } finally {
9446
9495
  release();
9447
9496
  }
9448
- return metadata.size > MAX_BYTES ? multipartCreate(input, metadata, (suffix, init2, kind, signal) => kind === !0 ? send(suffix, init2, !0, context, signal) : send(suffix, init2, "control", context, signal), release) : timed(async (signal) => {
9497
+ if (metadata.size > MAX_BYTES) return multipartCreate(input, metadata, (suffix, init2, kind, signal) => kind === !0 ? send(suffix, init2, !0, context, signal) : send(suffix, init2, "control", context, signal), release);
9498
+ let execute = async (signal) => {
9449
9499
  try {
9450
9500
  let bytes = array3 ? new Uint8Array(input.file) : await boundedBytes(
9451
9501
  blob ? input.file.stream() : input.file,
@@ -9467,7 +9517,8 @@ var files = {
9467
9517
  } finally {
9468
9518
  release();
9469
9519
  }
9470
- }, context.signal).catch((error) => {
9520
+ };
9521
+ return (context.localFiles ? execute(context.signal ?? new AbortController().signal) : timed(execute, context.signal)).catch((error) => {
9471
9522
  throw error instanceof FileOperationError ? error : unavailable4();
9472
9523
  });
9473
9524
  },
@@ -10037,9 +10088,10 @@ function parseInboxRecordRefs(value) {
10037
10088
  }
10038
10089
  var recordKey = ({ repository, ref }) => JSON.stringify([repository, ref]);
10039
10090
  function parseInboxRecords(value) {
10040
- let result2 = serializable(value);
10041
- if (!result2 || Object.keys(result2).join() !== "records" || !Array.isArray(result2.records) || result2.records.length > 100) throw new Error("Invalid Record result");
10091
+ let result2 = serializable(value), keys7 = result2 ? Object.keys(result2).sort().join() : "";
10092
+ if (!result2 || !["records", "links,records"].includes(keys7) || !Array.isArray(result2.records) || result2.records.length > 100) throw new Error("Invalid Record result");
10042
10093
  for (let entry of result2.records) {
10094
+ if (!entry || typeof entry != "object") throw new Error("Invalid current Record");
10043
10095
  if (validateQualifiedRecordRef({ repository: entry.repository, ref: entry.ref }), Object.keys(entry).sort().join() !== "record,ref,repository,schema" || (entry.record === null ? entry.schema !== null : !entry.schema || entry.record.$ref !== entry.ref || typeof entry.record.$version != "string" || !Array.isArray(entry.schema.fields) || typeof entry.schema.name != "string"))
10044
10096
  throw new Error("Invalid current Record");
10045
10097
  if (entry.schema)
@@ -10051,7 +10103,14 @@ function parseInboxRecords(value) {
10051
10103
  }
10052
10104
  }
10053
10105
  if (new Set(result2.records.map(recordKey)).size !== result2.records.length) throw new Error("Duplicate current Record");
10054
- return result2;
10106
+ let links = keys7 === "records" ? [] : result2.links;
10107
+ if (!Array.isArray(links)) throw new Error("Invalid Record links");
10108
+ for (let link of links) {
10109
+ if (!link || typeof link != "object" || Object.keys(link).sort().join() !== "ref,repository,title" || typeof link.title != "string" || !link.title.trim()) throw new Error("Invalid Record link");
10110
+ validateQualifiedRecordRef({ repository: link.repository, ref: link.ref });
10111
+ }
10112
+ if (new Set(links.map(recordKey)).size !== links.length) throw new Error("Duplicate Record link");
10113
+ return { records: result2.records, links };
10055
10114
  }
10056
10115
 
10057
10116
  var InboxOperationError = class extends Error {
@@ -10096,7 +10155,7 @@ function parseInboxUnavailableFailure(value, status) {
10096
10155
  return;
10097
10156
  }
10098
10157
  }
10099
- var INBOX_RESULT_BYTES = 8 * 1024 * 1024, INBOX_INPUT_BYTES = 8192, INBOX_LOCAL_INPUT_BYTES = 256 * 1024, INBOX_QUESTION_CONTRACT = "question-work-v1", INBOX_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10158
+ var INBOX_RESULT_BYTES = 8 * 1024 * 1024, INBOX_INPUT_BYTES = 8192, INBOX_LOCAL_INPUT_BYTES = 256 * 1024, INBOX_QUESTION_CONTRACT = "question-work-v2", INBOX_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10100
10159
  function isAppQuestionOperation(operation2) {
10101
10160
  return operation2 === "questions.list" || operation2 === "questions.answer" || operation2 === "questions.listRecordOptions";
10102
10161
  }
@@ -10161,21 +10220,58 @@ function recordReference(value) {
10161
10220
  let record4 = object8(value);
10162
10221
  return keys6(record4, ["repository", "ref"]), assert(text4(record4.repository) && record4.repository === record4.repository.trim() && /^[a-z0-9][a-z0-9._/-]{0,127}$/.test(record4.repository) && !/\.\.|\/\//.test(record4.repository) && text4(record4.ref) && record4.ref === record4.ref.trim() && record4.ref.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(record4.ref)), record4;
10163
10222
  }
10223
+ function choiceValue(value) {
10224
+ assert(text4(value) && value === value.trim());
10225
+ }
10226
+ function choiceDetails(option) {
10227
+ if ("description" in option && assert(text4(option.description)), "note" in option) {
10228
+ let note = object8(option.note);
10229
+ keys6(note, ["placeholder"]), assert(text4(note.placeholder));
10230
+ }
10231
+ }
10232
+ function pickerSource(value) {
10233
+ let source2 = object8(value), collection = object8(source2.collection);
10234
+ keys6(collection, ["repository", "name"]), recordReference({ repository: collection.repository, ref: "records/example" }), assert(text4(collection.name) && /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(collection.name)), "refPrefix" in source2 && assert(text4(source2.refPrefix) && source2.refPrefix.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(source2.refPrefix));
10235
+ let where = object8(source2.where ?? {});
10236
+ return assert(Object.entries(where).every(([name2, value2]) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2) && !["constructor", "prototype"].includes(name2) && (value2 === null || typeof value2 == "string" || typeof value2 == "boolean" || typeof value2 == "number" && Number.isFinite(value2)))), collection;
10237
+ }
10164
10238
  function responseDefinition(value) {
10165
10239
  let definition = object8(value);
10166
- keys6(definition, ["type", "source"]), assert(definition.type === "selection");
10240
+ if (assert(definition.type === "selection"), "options" in definition) {
10241
+ keys6(definition, ["type", "options"]);
10242
+ let options = array2(definition.options);
10243
+ assert(options.length > 0 && options.length <= 9), options.forEach((value2, index) => {
10244
+ let option = object8(value2);
10245
+ switch (assert(option.id === index + 1 && text4(option.label)), option.type) {
10246
+ case "choice":
10247
+ case "record":
10248
+ keys6(
10249
+ option,
10250
+ ["id", "type", "value", "label", "description", ...option.type === "choice" ? ["note"] : []],
10251
+ []
10252
+ ), option.type === "choice" ? choiceValue(option.value) : recordReference(option.value), choiceDetails(option);
10253
+ break;
10254
+ case "record-picker": {
10255
+ keys6(option, ["id", "type", "label", "source"]);
10256
+ let source3 = object8(option.source);
10257
+ keys6(source3, ["collection", "where", "refPrefix"], []), "where" in source3 && object8(source3.where), pickerSource(source3);
10258
+ break;
10259
+ }
10260
+ default:
10261
+ assert(!1);
10262
+ }
10263
+ });
10264
+ return;
10265
+ }
10266
+ keys6(definition, ["type", "source"]);
10167
10267
  let source2 = object8(definition.source);
10168
10268
  if (source2.type === "authored") {
10169
- keys6(source2, ["type", "options", "suggestions", "search"], ["type", "options"]);
10269
+ keys6(source2, ["type", "options", "suggestions", "search"], []);
10170
10270
  let options = array2(source2.options);
10171
10271
  assert(options.length > 0);
10172
10272
  let values = options.map((value2) => {
10173
10273
  let option = object8(value2);
10174
- if (keys6(option, ["value", "label", "description", "note"], ["value", "label"]), assert(text4(option.value) && option.value === option.value.trim() && text4(option.label)), "description" in option && assert(text4(option.description)), "note" in option) {
10175
- let note = object8(option.note);
10176
- keys6(note, ["placeholder"]), assert(text4(note.placeholder));
10177
- }
10178
- return option.value;
10274
+ return keys6(option, ["value", "label", "description", "note"], []), choiceValue(option.value), assert(text4(option.label)), choiceDetails(option), option.value;
10179
10275
  });
10180
10276
  if (assert(new Set(values).size === values.length), "search" in source2 || "suggestions" in source2) {
10181
10277
  let search = object8(source2.search);
@@ -10186,11 +10282,7 @@ function responseDefinition(value) {
10186
10282
  return;
10187
10283
  }
10188
10284
  assert(source2.type === "records"), keys6(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], ["type", "collection", "display"]);
10189
- let collection = object8(source2.collection);
10190
- keys6(collection, ["repository", "name"]), recordReference({ repository: collection.repository, ref: "records/example" }), assert(text4(collection.name) && /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(collection.name)), "refPrefix" in source2 && assert(text4(source2.refPrefix) && source2.refPrefix.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(source2.refPrefix));
10191
- let where = object8(source2.where ?? {});
10192
- assert(Object.entries(where).every(([name2, value2]) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2) && !["constructor", "prototype"].includes(name2) && (value2 === null || typeof value2 == "string" || typeof value2 == "boolean" || typeof value2 == "number" && Number.isFinite(value2))));
10193
- let display = object8(source2.display);
10285
+ let collection = pickerSource(source2), display = object8(source2.display);
10194
10286
  keys6(display, ["labelFields"]);
10195
10287
  let labels = array2(display.labelFields);
10196
10288
  assert(labels.length > 0 && labels.length <= 2 && new Set(labels).size === labels.length && labels.every((value2) => text4(value2) && /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value2)));
@@ -10202,22 +10294,32 @@ function responseDefinition(value) {
10202
10294
  });
10203
10295
  assert(suggestions.length <= 8 && new Set(refs).size === refs.length);
10204
10296
  }
10205
- function response(value) {
10206
- let answer = object8(value);
10207
- return assert(Object.keys(answer).every((key) => ["selection", "note"].includes(key))), typeof answer.selection == "string" ? assert(text4(answer.selection) && answer.selection === answer.selection.trim()) : recordReference(answer.selection), Object.hasOwn(answer, "note") && assert(text4(answer.note)), answer;
10297
+ function response(value, definition, numbered = !1) {
10298
+ let answer = object8(value), options = definition && "options" in definition ? array2(definition.options) : void 0, selected = options || numbered ? answer.value : answer.selection;
10299
+ if (typeof selected == "string" ? choiceValue(selected) : recordReference(selected), options || numbered) {
10300
+ if (keys6(answer, ["option", "value", "note"], []), assert(integer(answer.option) && answer.option <= (options?.length ?? 9)), options) {
10301
+ let option = object8(options[answer.option - 1]);
10302
+ assert(option.type === "choice" == (typeof selected == "string")), assert("note" in answer == (option.type === "choice" && "note" in option));
10303
+ }
10304
+ } else assert(Object.keys(answer).every((key) => ["selection", "note"].includes(key)));
10305
+ return Object.hasOwn(answer, "note") && assert(text4(answer.note)), answer;
10208
10306
  }
10209
10307
  function parseInboxRequest(value) {
10210
10308
  try {
10211
10309
  let envelope = object8(value);
10212
10310
  assert(typeof envelope.operation == "string" && Object.hasOwn(operations, envelope.operation));
10213
10311
  let operation2 = envelope.operation, questionOperation = isAppQuestionOperation(operation2);
10214
- if (questionOperation && envelope.contract !== INBOX_QUESTION_CONTRACT)
10312
+ if (questionOperation && envelope.contract !== INBOX_QUESTION_CONTRACT && envelope.contract !== "question-work-v1")
10215
10313
  throw new InboxOperationError(426, "client_update_required");
10216
10314
  keys6(envelope, questionOperation ? ["contract", "input", "operation"] : ["input", "operation"]);
10217
10315
  let input = { ...object8(envelope.input) }, required = operations[operation2];
10218
- assert(required.every((key) => Object.hasOwn(input, key)) && Object.keys(input).every((key) => required.includes(key) || operation2 === "questions.answer" && key === "label" || (operation2 === "items.list" || operation2 === "questions.list") && key === "beforeNumber" || operation2 === "questions.list" && key === "routines")), operation2 === "questions.list" && (assert(Object.hasOwn(input, "routines")), assert(array2(input.routines).every(isAppRoutineName)));
10316
+ assert(required.every((key) => Object.hasOwn(input, key)) && Object.keys(input).every((key) => required.includes(key) || operation2 === "questions.answer" && key === "label" || operation2 === "questions.listRecordOptions" && envelope.contract === INBOX_QUESTION_CONTRACT && key === "option" || (operation2 === "items.list" || operation2 === "questions.list") && key === "beforeNumber" || operation2 === "questions.list" && key === "routines")), operation2 === "questions.list" && (assert(Object.hasOwn(input, "routines")), assert(array2(input.routines).every(isAppRoutineName)));
10219
10317
  for (let key of ["itemId", "personId", "fileId"]) key in input && assert(id2(input[key]));
10220
- return "revision" in input && assert(integer(input.revision)), "beforeNumber" in input && assert(integer(input.beforeNumber)), "questionId" in input && assert(text4(input.questionId) && input.questionId === input.questionId.trim()), "submissionKey" in input && assert(text4(input.submissionKey) && input.submissionKey.length <= 128 && input.submissionKey === input.submissionKey.trim()), "title" in input && assert(text4(input.title)), "lifecycle" in input && assert(input.lifecycle === "open" || input.lifecycle === "closed"), "records" in input && (input.records = parseInboxRecordRefs(input.records)), "response" in input && response(input.response), "label" in input && assert(text4(input.label) && typeof input.response?.selection == "object"), assert(new TextEncoder().encode(JSON.stringify(envelope)).byteLength <= INBOX_INPUT_BYTES), "routines" in input && (input.routines = [...new Set(input.routines)]), { operation: operation2, input, ...isAppQuestionOperation(operation2) ? { contract: INBOX_QUESTION_CONTRACT } : {} };
10318
+ if ("revision" in input && assert(integer(input.revision)), "beforeNumber" in input && assert(integer(input.beforeNumber)), "questionId" in input && assert(text4(input.questionId) && input.questionId === input.questionId.trim()), "submissionKey" in input && assert(text4(input.submissionKey) && input.submissionKey.length <= 128 && input.submissionKey === input.submissionKey.trim()), "title" in input && assert(text4(input.title)), "lifecycle" in input && assert(input.lifecycle === "open" || input.lifecycle === "closed"), "records" in input && (input.records = parseInboxRecordRefs(input.records)), "option" in input && assert(integer(input.option) && input.option <= 9), "response" in input && response(input.response, void 0, envelope.contract === INBOX_QUESTION_CONTRACT && "option" in object8(input.response)), "label" in input) {
10319
+ let answer = object8(input.response);
10320
+ assert(text4(input.label) && typeof ("option" in answer ? answer.value : answer.selection) == "object");
10321
+ }
10322
+ return assert(new TextEncoder().encode(JSON.stringify(envelope)).byteLength <= INBOX_INPUT_BYTES), "routines" in input && (input.routines = [...new Set(input.routines)]), { operation: operation2, input, ...isAppQuestionOperation(operation2) ? { contract: envelope.contract } : {} };
10221
10323
  } catch (error) {
10222
10324
  throw error instanceof InboxOperationError ? error : new InboxOperationError(400, "invalid_input");
10223
10325
  }
@@ -10241,7 +10343,7 @@ function parseInboxItem(value) {
10241
10343
  let question2 = object8(value2);
10242
10344
  if (assert(text4(question2.id) && id2(question2.to) && text4(question2.prompt) && (question2.instructions === null || text4(question2.instructions, !0)) && typeof question2.available == "boolean"), questionAvailability(question2, question2.available), parseQuestionStatus(question2.status), assert(!("requirements" in question2) && !("requirementsRepository" in question2) && !("handler" in question2)), responseDefinition(question2.response), assert(array2(question2.allowedResponders).every(id2)), question2.acceptedResponse !== null) {
10243
10345
  let accepted = object8(question2.acceptedResponse);
10244
- assert(id2(accepted.id) && id2(accepted.userId) && date(accepted.acceptedAt)), response(accepted.response), accepted.label === null ? delete accepted.label : "label" in accepted && assert(text4(accepted.label)), "acceptanceOrder" in accepted && assert(integer(accepted.acceptanceOrder));
10346
+ assert(id2(accepted.id) && id2(accepted.userId) && date(accepted.acceptedAt)), response(accepted.response, object8(question2.response)), accepted.label === null ? delete accepted.label : "label" in accepted && assert(text4(accepted.label)), "acceptanceOrder" in accepted && assert(integer(accepted.acceptanceOrder));
10245
10347
  }
10246
10348
  if (question2.execution !== null) {
10247
10349
  let execution = object8(question2.execution);
@@ -10273,7 +10375,7 @@ function parseInboxItem(value) {
10273
10375
  assert(id2(work.id) && text4(work.questionId) && text4(work.reason) && optionalDate(work.settledAt));
10274
10376
  }), item;
10275
10377
  }
10276
- function parseQuestionWork(value) {
10378
+ function parseQuestionWork(value, contract = INBOX_QUESTION_CONTRACT) {
10277
10379
  let entry = object8(json2(value));
10278
10380
  keys6(
10279
10381
  entry,
@@ -10285,7 +10387,9 @@ function parseQuestionWork(value) {
10285
10387
  let assignee = object8(entry.assignee);
10286
10388
  keys6(assignee, ["id", "name"]), assert(id2(assignee.id) && text4(assignee.name));
10287
10389
  let status = parseQuestionStatus(entry.status);
10288
- return assert(status.code !== "completed" && (!entry.canAnswer || status.code === "awaiting_answer") && (!("unavailableReason" in entry) || status.code === "awaiting_answer")), status.code === "awaiting_answer" && assert(status.label === "Needs your answer" || !entry.canAnswer && status.label === `Waiting for ${assignee.name}`), responseDefinition(entry.response), askMetadata(entry), entry;
10390
+ if (assert(status.code !== "completed" && (!entry.canAnswer || status.code === "awaiting_answer") && (!("unavailableReason" in entry) || status.code === "awaiting_answer")), status.code === "awaiting_answer" && assert(status.label === "Needs your answer" || !entry.canAnswer && status.label === `Waiting for ${assignee.name}`), contract === "question-work-v1" && "options" in object8(entry.response))
10391
+ throw new InboxOperationError(426, "client_update_required");
10392
+ return responseDefinition(entry.response), askMetadata(entry), entry;
10289
10393
  }
10290
10394
  function parseQuestionStatus(value) {
10291
10395
  let status = object8(value), code = status.code;
@@ -10313,12 +10417,12 @@ function parseInboxAcceptance(value) {
10313
10417
  let accepted = object8(value);
10314
10418
  return assert(id2(accepted.responseId) && date(accepted.acceptedAt)), "executionId" in accepted && assert(id2(accepted.executionId)), "acceptanceOrder" in accepted && assert(integer(accepted.acceptanceOrder)), "label" in accepted && assert(text4(accepted.label)), accepted;
10315
10419
  }
10316
- function parseInboxResult(operation2, value) {
10420
+ function parseInboxResult(operation2, value, contract = INBOX_QUESTION_CONTRACT) {
10317
10421
  if (operation2 === "current") return parseInboxCurrent(value);
10318
10422
  if (operation2 === "questions.list") {
10319
10423
  let page = object8(value);
10320
10424
  keys6(page, ["questions", "nextBeforeNumber"]);
10321
- let questions = array2(page.questions).map(parseQuestionWork);
10425
+ let questions = array2(page.questions).map((value2) => parseQuestionWork(value2, contract));
10322
10426
  return assert(page.nextBeforeNumber === null || integer(page.nextBeforeNumber)), { questions, nextBeforeNumber: page.nextBeforeNumber };
10323
10427
  }
10324
10428
  if (operation2 === "items.readRecords") return parseInboxRecords(value);
@@ -10423,9 +10527,9 @@ function hostedInboxContext() {
10423
10527
  };
10424
10528
  check();
10425
10529
  let matches2 = (entry2) => entry2.endpoint === host.endpoint && entry2.memberId === host.memberId && entry2.valid();
10426
- if (mode === "list" && denied && matches2(denied)) throw new InboxContextError(denied.status);
10530
+ if (mode === "member" && denied && matches2(denied)) throw new InboxContextError(denied.status);
10427
10531
  let bind = (value) => ({ ...value, isCurrent: () => host.isCurrent() && host.expiresAt > Date.now() && value.isCurrent() });
10428
- if (mode === "list" && retained && matches2(retained)) return bind(retained.value);
10532
+ if (mode === "member" && retained && matches2(retained)) return bind(retained.value);
10429
10533
  if (mode !== "fresh" && pending && matches2(pending)) {
10430
10534
  let value = await pending.result;
10431
10535
  return check(), bind(value);
@@ -10924,7 +11028,7 @@ async function send2(operation2, input, resolved, admitted) {
10924
11028
  ...isAppQuestionOperation(operation2) ? { contract: INBOX_QUESTION_CONTRACT } : {}
10925
11029
  }), context;
10926
11030
  try {
10927
- context = resolved ?? await resolveAppContext();
11031
+ context = resolved ?? await resolveAppContext(!1, !isAppQuestionOperation(operation2));
10928
11032
  } catch (error) {
10929
11033
  throw contextFailure(error);
10930
11034
  }
@@ -10950,7 +11054,7 @@ async function send2(operation2, input, resolved, admitted) {
10950
11054
  let host;
10951
11055
  if (!isAppQuestionOperation(operation2)) {
10952
11056
  try {
10953
- host = admitted ?? await resolveHostedInboxContext(context);
11057
+ host = admitted ?? await resolveHostedInboxContext(context, "member");
10954
11058
  } catch (error) {
10955
11059
  throw hostFailure(error, context);
10956
11060
  }
@@ -10964,7 +11068,11 @@ async function send2(operation2, input, resolved, admitted) {
10964
11068
  try {
10965
11069
  let response2 = await fetch(`${context.endpoint}/api/inbox`, {
10966
11070
  method: "POST",
10967
- headers: { authorization: `Bearer ${context.accessToken}`, "content-type": "application/json" },
11071
+ headers: {
11072
+ authorization: `Bearer ${context.accessToken}`,
11073
+ "content-type": "application/json",
11074
+ ...operation2 === "items.readRecords" ? { "x-os-inbox-records": "links-v1" } : {}
11075
+ },
10968
11076
  body: JSON.stringify(envelope),
10969
11077
  redirect: "error",
10970
11078
  cache: "no-store",
@@ -11037,7 +11145,7 @@ var inbox = {
11037
11145
  }
11038
11146
  let host;
11039
11147
  try {
11040
- host = initial.kind !== "local" && await resolveHostedInboxContext(initial, "list");
11148
+ host = initial.kind !== "local" && await resolveHostedInboxContext(initial, "member");
11041
11149
  } catch (error) {
11042
11150
  throw hostFailure(error, initial);
11043
11151
  }