@composable-os/cli 0.1.0-beta.8 → 0.1.0-beta.9

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 (63) hide show
  1. package/dist/accounts-D6N77JGP.js +44 -0
  2. package/dist/{blocks-DEELKGDC.js → blocks-4CA4PP3P.js} +4 -4
  3. package/dist/{chunk-X6I2LWB3.js → chunk-2MLAPQU7.js} +1471 -359
  4. package/dist/{chunk-2S7375SC.js → chunk-3MIEYXRY.js} +3 -301
  5. package/dist/chunk-56A6RJIU.js +1040 -0
  6. package/dist/chunk-7CQGMVDO.js +63 -0
  7. package/dist/{chunk-STJZJIRA.js → chunk-7O4F3NU4.js} +1039 -1380
  8. package/dist/chunk-7U3OZLTK.js +1370 -0
  9. package/dist/{chunk-ZRWF6QZS.js → chunk-DU6OIFOU.js} +1 -0
  10. package/dist/chunk-E4WCYTCT.js +347 -0
  11. package/dist/{chunk-E5JLTLRM.js → chunk-GYTEW66E.js} +1 -1
  12. package/dist/chunk-LPD2VR5M.js +284 -0
  13. package/dist/chunk-NDKVIG23.js +2641 -0
  14. package/dist/chunk-NSSUOI3Z.js +333 -0
  15. package/dist/chunk-OV3OFYPI.js +746 -0
  16. package/dist/{chunk-KTXGEXTY.js → chunk-P6YZMS3F.js} +11 -5
  17. package/dist/{chunk-G3ORKXVP.js → chunk-RFJOPI42.js} +138 -14
  18. package/dist/{chunk-KOKYDJ7Z.js → chunk-RXRD34QW.js} +10 -8
  19. package/dist/{chunk-XDDBLYKW.js → chunk-STBMGUTM.js} +4613 -2307
  20. package/dist/chunk-VTQNOQGA.js +150 -0
  21. package/dist/chunk-XSE37HK5.js +426 -0
  22. package/dist/{chunk-LTQDLCP7.js → chunk-Z52IX5WL.js} +257 -845
  23. package/dist/chunk-ZSR5H4O7.js +552 -0
  24. package/dist/{cli-DTMGNDXN.js → cli-7A5XHYML.js} +16 -9
  25. package/dist/{cli-BRSACHSG.js → cli-T6MJM7TU.js} +20 -8
  26. package/dist/cli.js +4 -4
  27. package/dist/{client-repo-ZVZ6KW5S.js → client-repo-PC4ISVEZ.js} +4 -4
  28. package/dist/create.js +4 -4
  29. package/dist/{fields-64BQJA62.js → fields-L24XAIOA.js} +13 -11
  30. package/dist/invoke-TLYT6CFI.js +33 -0
  31. package/dist/order-IKQBUFCV.js +19 -0
  32. package/dist/{person-WMWRF2HV.js → person-DXEOOH2A.js} +9 -5
  33. package/dist/plan-on-sale-LRCK5MJG.js +24 -0
  34. package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
  35. package/dist/platform/migrations/0516_order_tax.sql +63 -0
  36. package/dist/platform/migrations/0530_subscriptions.sql +173 -0
  37. package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
  38. package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
  39. package/dist/platform/migrations/0533_allowances.sql +262 -0
  40. package/dist/platform/migrations/0560_recurring.sql +75 -0
  41. package/dist/platform/sdk/allowance.ts +508 -0
  42. package/dist/platform/sdk/capacity.ts +89 -0
  43. package/dist/platform/sdk/contract.ts +97 -1
  44. package/dist/platform/sdk/document.ts +161 -14
  45. package/dist/platform/sdk/field-types.ts +5 -0
  46. package/dist/platform/sdk/index.ts +3 -0
  47. package/dist/platform/sdk/manifest.ts +206 -5
  48. package/dist/platform/sdk/media.ts +62 -0
  49. package/dist/platform/sdk/recurring.ts +314 -0
  50. package/dist/platform/sdk/rich-text.ts +52 -4
  51. package/dist/platform/sdk/sellable.ts +120 -0
  52. package/dist/platform/sdk/states.ts +162 -1
  53. package/dist/platform/sdk/unique.ts +81 -0
  54. package/dist/run-BMSZKTN3.js +648 -0
  55. package/dist/run-GMQBAV6H.js +309 -0
  56. package/dist/{run-4JNFLYXV.js → run-TNHMG5RI.js} +51 -390
  57. package/dist/src-7DXXGZG2.js +38 -0
  58. package/dist/{src-J27WXNLY.js → src-BDG7PERB.js} +73 -1
  59. package/dist/visibility-XSBZTO66.js +33 -0
  60. package/package.json +2 -2
  61. package/dist/chunk-MAXLUQKB.js +0 -1287
  62. package/dist/invoke-NHHOLLF6.js +0 -26
  63. package/dist/src-G6OF5SKW.js +0 -31
@@ -1,21 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- PROVIDERS,
4
- parseRoleLayer
5
- } from "./chunk-KGHA67HG.js";
6
2
  import {
7
3
  CORE_OBJECTS,
8
- getField,
9
4
  getObject,
5
+ isCoreObject,
10
6
  setExtensionObjects
11
- } from "./chunk-2S7375SC.js";
7
+ } from "./chunk-3MIEYXRY.js";
8
+ import {
9
+ BASE_TABLES
10
+ } from "./chunk-ZSR5H4O7.js";
12
11
  import {
13
12
  EXTENSION_ID_RE,
14
13
  FIELD_NAME_RE,
15
14
  FormulaError,
16
15
  OBJECT_NAME_RE,
16
+ RECURRING_HORIZON_DAYS,
17
17
  SLUG_RE,
18
- automationManifestSchema,
19
18
  compileFormula,
20
19
  documentJsonPath,
21
20
  documentMaxBytesOf,
@@ -25,172 +24,9 @@ import {
25
24
  formulaTypeOf,
26
25
  isDocumentType,
27
26
  onStep,
27
+ spendsOnList,
28
28
  validateDocument
29
- } from "./chunk-X6I2LWB3.js";
30
-
31
- // ../core/src/errors.ts
32
- var OperationError = class extends Error {
33
- constructor(code, message, details) {
34
- super(message);
35
- this.code = code;
36
- this.details = details;
37
- }
38
- code;
39
- details;
40
- name = "OperationError";
41
- toJSON() {
42
- return {
43
- code: this.code,
44
- message: this.message,
45
- ...this.details === void 0 ? {} : { details: this.details }
46
- };
47
- }
48
- };
49
- var UnknownOperationError = class extends OperationError {
50
- name = "UnknownOperationError";
51
- constructor(name) {
52
- super("unknown_operation", `No operation named "${name}"`);
53
- }
54
- };
55
- var ValidationError = class extends OperationError {
56
- name = "ValidationError";
57
- constructor(message, details) {
58
- super("invalid_input", message, details);
59
- }
60
- };
61
- var ForbiddenError = class extends OperationError {
62
- name = "ForbiddenError";
63
- constructor(message, details) {
64
- super("forbidden", message, details);
65
- }
66
- };
67
- var GateDeniedError = class extends OperationError {
68
- name = "GateDeniedError";
69
- constructor(message, details) {
70
- super("denied", message, details);
71
- }
72
- };
73
- var PendingApprovalError = class extends OperationError {
74
- name = "PendingApprovalError";
75
- pending;
76
- constructor(pending) {
77
- super("pending_approval", pending.message, pending);
78
- this.pending = pending;
79
- }
80
- };
81
- var RateLimitedError = class extends OperationError {
82
- name = "RateLimitedError";
83
- constructor(message, details) {
84
- super("rate_limited", message, details);
85
- }
86
- };
87
- var PlanLimitError = class extends OperationError {
88
- name = "PlanLimitError";
89
- constructor(message, details) {
90
- super("plan_limit", message, details);
91
- }
92
- };
93
- var NotFoundError = class extends OperationError {
94
- name = "NotFoundError";
95
- constructor(object, id) {
96
- super("not_found", `No ${object} with id ${id}`, { object, id });
97
- }
98
- };
99
- var ConflictError = class extends OperationError {
100
- name = "ConflictError";
101
- constructor(message, details) {
102
- super("conflict", message, details);
103
- }
104
- };
105
- var ConfigError = class extends OperationError {
106
- name = "ConfigError";
107
- constructor(message) {
108
- super("config", message);
109
- }
110
- };
111
- function toOperationError(error) {
112
- if (error instanceof OperationError) return error;
113
- if (error instanceof Error && error.name === "AiAllowanceError") {
114
- return new PlanLimitError(error.message, { reason: "platform_ai" });
115
- }
116
- const capacity = capacityRefusal(error);
117
- if (capacity) return capacity;
118
- const message = error instanceof Error ? error.message : String(error);
119
- if (message.includes("core_order_stale")) {
120
- return new ConflictError("The order changed while this was being applied. Try again.", {
121
- reason: "order_stale"
122
- });
123
- }
124
- if (message.includes(
125
- "UNIQUE constraint failed: core_transition_history.object_type, core_transition_history.record_id"
126
- )) {
127
- return new ConflictError(
128
- "The record was moved by another change while this one was being made, so nothing was changed. Read it again: it may already be where you wanted it.",
129
- { reason: "moved_meanwhile" }
130
- );
131
- }
132
- if (message.includes("UNIQUE constraint failed: core_publish_version")) {
133
- return new ConflictError(
134
- "Another version of this record was published at the same moment, so this one was not. Read its versions again before publishing.",
135
- { reason: "published_meanwhile" }
136
- );
137
- }
138
- const unique = /UNIQUE constraint failed: ([\w.]+(?:, [\w.]+)*)/.exec(message);
139
- if (unique) {
140
- return new ConflictError("A record with that value already exists", {
141
- constraint: unique[1]
142
- });
143
- }
144
- if (/FOREIGN KEY constraint failed/.test(message)) {
145
- return new ValidationError("A referenced record does not exist");
146
- }
147
- if (/CHECK constraint failed/.test(message)) {
148
- return new ValidationError("A value is not allowed", { reason: message });
149
- }
150
- return new OperationError("internal", "Internal error", { reason: message });
151
- }
152
- var CAPACITY_REFUSED = /core_capacity_refused (\{[^{}]*\})/;
153
- function capacityRefusal(error) {
154
- const message = error instanceof Error ? error.message : String(error);
155
- const match = CAPACITY_REFUSED.exec(message);
156
- if (match) {
157
- let payload;
158
- try {
159
- payload = JSON.parse(match[1]);
160
- } catch {
161
- return new ValidationError("Not enough places", { rule: "capacity" });
162
- }
163
- if (payload.asked > 0) {
164
- const details2 = {
165
- rule: "capacity",
166
- object: payload.object,
167
- record: payload.record,
168
- asked: payload.asked,
169
- available: payload.available
170
- };
171
- return new ValidationError(
172
- `Not enough places: asked for ${payload.asked}, ${payload.available} left`,
173
- details2
174
- );
175
- }
176
- const details = {
177
- rule: "capacity",
178
- object: payload.object,
179
- record: payload.record,
180
- places: payload.places,
181
- held: payload.held,
182
- taken: payload.taken
183
- };
184
- return new ValidationError(
185
- `Places cannot be fewer than are claimed: ${payload.held} held and ${payload.taken} taken`,
186
- details
187
- );
188
- }
189
- if (message.includes("core_capacity_within_places")) {
190
- return new ValidationError("Not enough places", { rule: "capacity" });
191
- }
192
- return null;
193
- }
29
+ } from "./chunk-2MLAPQU7.js";
194
30
 
195
31
  // ../../node_modules/.pnpm/kysely@0.29.8/node_modules/kysely/dist/util/object-utils.js
196
32
  function isUndefined(obj) {
@@ -1053,16 +889,16 @@ function parseReferentialBinaryOperation(left, operator, right) {
1053
889
  function parseFilterObject(obj, combinator) {
1054
890
  return parseFilterList(Object.entries(obj).filter(([, v]) => !isUndefined(v)).map(([k, v]) => parseValueBinaryOperation(k, needsIsOperator(v) ? "is" : "=", v)), combinator);
1055
891
  }
1056
- function parseFilterList(list2, combinator, withParens = true) {
892
+ function parseFilterList(list, combinator, withParens = true) {
1057
893
  const combine = combinator === "and" ? AndNode.create : OrNode.create;
1058
- if (list2.length === 0) {
894
+ if (list.length === 0) {
1059
895
  return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create("="), ValueNode.createImmediate(combinator === "and" ? 1 : 0));
1060
896
  }
1061
- let node = toOperationNode(list2[0]);
1062
- for (let i = 1; i < list2.length; ++i) {
1063
- node = combine(node, toOperationNode(list2[i]));
897
+ let node = toOperationNode(list[0]);
898
+ for (let i = 1; i < list.length; ++i) {
899
+ node = combine(node, toOperationNode(list[i]));
1064
900
  }
1065
- if (list2.length > 1 && withParens) {
901
+ if (list.length > 1 && withParens) {
1066
902
  return ParensNode.create(node);
1067
903
  }
1068
904
  return node;
@@ -1834,8 +1670,8 @@ var DefaultInsertValueNode = freeze({
1834
1670
  // ../../node_modules/.pnpm/kysely@0.29.8/node_modules/kysely/dist/parser/insert-values-parser.js
1835
1671
  function parseInsertExpression(arg) {
1836
1672
  const objectOrList = isFunction(arg) ? arg(expressionBuilder()) : arg;
1837
- const list2 = isReadonlyArray(objectOrList) ? objectOrList : freeze([objectOrList]);
1838
- return parseInsertColumnsAndValues(list2);
1673
+ const list = isReadonlyArray(objectOrList) ? objectOrList : freeze([objectOrList]);
1674
+ return parseInsertColumnsAndValues(list);
1839
1675
  }
1840
1676
  function parseInsertColumnsAndValues(rows) {
1841
1677
  const columns = parseColumnNamesAndIndexes(rows);
@@ -4770,11 +4606,11 @@ var OperationNodeTransformer = class {
4770
4606
  transformNodeImpl(node, queryId) {
4771
4607
  return this.#transformers[node.kind](node, queryId);
4772
4608
  }
4773
- transformNodeList(list2, queryId) {
4774
- if (!list2) {
4775
- return list2;
4609
+ transformNodeList(list, queryId) {
4610
+ if (!list) {
4611
+ return list;
4776
4612
  }
4777
- return freeze(list2.map((node) => this.transformNode(node, queryId)));
4613
+ return freeze(list.map((node) => this.transformNode(node, queryId)));
4778
4614
  }
4779
4615
  transformSelectQuery(node, queryId) {
4780
4616
  return {
@@ -5805,9 +5641,9 @@ var Deferred = class {
5805
5641
  #resolve;
5806
5642
  #reject;
5807
5643
  constructor() {
5808
- this.#promise = new Promise((resolve, reject) => {
5644
+ this.#promise = new Promise((resolve2, reject) => {
5809
5645
  this.#reject = reject;
5810
- this.#resolve = resolve;
5646
+ this.#resolve = resolve2;
5811
5647
  });
5812
5648
  }
5813
5649
  get promise() {
@@ -5880,8 +5716,8 @@ async function waitOrAbort(promise, signal, name, onAbort) {
5880
5716
  return promise;
5881
5717
  }
5882
5718
  assertNotAborted(signal, `before ${name}`, onAbort);
5883
- const { promise: abortPromise, resolve } = new Deferred();
5884
- const abortListener = () => resolve(ABORTED);
5719
+ const { promise: abortPromise, resolve: resolve2 } = new Deferred();
5720
+ const abortListener = () => resolve2(ABORTED);
5885
5721
  signal.addEventListener("abort", abortListener);
5886
5722
  try {
5887
5723
  assertNotAborted(signal, `before ${name}`, onAbort);
@@ -5893,7 +5729,7 @@ async function waitOrAbort(promise, signal, name, onAbort) {
5893
5729
  throwReasonWithTiming(signal.reason, `during ${name}`);
5894
5730
  } finally {
5895
5731
  signal.removeEventListener("abort", abortListener);
5896
- resolve(ABORTED);
5732
+ resolve2(ABORTED);
5897
5733
  }
5898
5734
  }
5899
5735
  function printBackgroundFail(name) {
@@ -5948,8 +5784,8 @@ var QueryExecutorBase = class {
5948
5784
  options = freeze({ signal });
5949
5785
  const { connection, release } = await provideControlledConnection(this, options);
5950
5786
  const controlConnectionProvider = this.provideConnection.bind(this);
5951
- const { promise: abortPromise, resolve } = new Deferred();
5952
- const abortListener = () => resolve(ABORTED);
5787
+ const { promise: abortPromise, resolve: resolve2 } = new Deferred();
5788
+ const abortListener = () => resolve2(ABORTED);
5953
5789
  signal.addEventListener("abort", abortListener, { once: true });
5954
5790
  try {
5955
5791
  assertNotAborted(signal, "before query execution", release);
@@ -5991,7 +5827,7 @@ var QueryExecutorBase = class {
5991
5827
  }
5992
5828
  return transformedResult;
5993
5829
  } finally {
5994
- resolve(ABORTED);
5830
+ resolve2(ABORTED);
5995
5831
  signal.removeEventListener("abort", abortListener);
5996
5832
  }
5997
5833
  }
@@ -6011,8 +5847,8 @@ var QueryExecutorBase = class {
6011
5847
  options = freeze({ signal });
6012
5848
  assertNotAborted(signal, "before connection acquisition");
6013
5849
  const { connection, release } = await provideControlledConnection(this, options);
6014
- const { promise: abortPromise, resolve } = new Deferred();
6015
- const abortListener = () => resolve(ABORTED);
5850
+ const { promise: abortPromise, resolve: resolve2 } = new Deferred();
5851
+ const abortListener = () => resolve2(ABORTED);
6016
5852
  signal.addEventListener("abort", abortListener, { once: true });
6017
5853
  let asyncIterator;
6018
5854
  let releasePrerequisite;
@@ -6043,7 +5879,7 @@ var QueryExecutorBase = class {
6043
5879
  yield transformedResult;
6044
5880
  }
6045
5881
  } finally {
6046
- resolve(ABORTED);
5882
+ resolve2(ABORTED);
6047
5883
  signal.removeEventListener("abort", abortListener);
6048
5884
  const cleanup = (asyncIterator?.return?.() || Promise.resolve()).finally(() => releasePrerequisite).finally(release);
6049
5885
  if (!releasePrerequisite) {
@@ -9045,612 +8881,24 @@ function parseParameter(param) {
9045
8881
  return parseValueExpression(param);
9046
8882
  }
9047
8883
 
9048
- // ../../node_modules/.pnpm/kysely@0.29.8/node_modules/kysely/dist/query-compiler/compiled-query.js
9049
- var CompiledQuery = freeze({
9050
- raw(sql2, parameters = []) {
9051
- return freeze({
9052
- sql: sql2,
9053
- query: RawNode.createWithSql(sql2),
9054
- parameters: freeze(parameters),
9055
- queryId: createQueryId()
9056
- });
9057
- }
9058
- });
9059
-
9060
- // ../core/src/records/common.ts
9061
- var TRASH_RETENTION_DAYS = 30;
9062
- var DAY_MS = 864e5;
9063
- function restorableUntil(deletedAt) {
9064
- return new Date(Date.parse(deletedAt) + TRASH_RETENTION_DAYS * DAY_MS).toISOString();
9065
- }
9066
- function purgeCutoff(now) {
9067
- return new Date(Date.parse(now) - TRASH_RETENTION_DAYS * DAY_MS).toISOString();
9068
- }
9069
- var BATCH_MAX = 100;
9070
- var IN_LIST_CHUNK = 50;
9071
- function jsonList(values) {
9072
- return sql`(SELECT value FROM json_each(${JSON.stringify(values)}))`;
9073
- }
9074
- function chunk(items, size = IN_LIST_CHUNK) {
9075
- const chunks = [];
9076
- for (let i = 0; i < items.length; i += size) chunks.push(items.slice(i, i + size));
9077
- return chunks;
9078
- }
9079
- var blankToNull = (value) => value === void 0 ? void 0 : value === null || value === "" ? null : value;
9080
- async function assertUserExists(db, id, field = "ownerId") {
9081
- if (!id) return;
9082
- const user = await db.selectFrom("core_user").select("id").where("id", "=", id).executeTakeFirst();
9083
- if (!user) throw new ValidationError(`No user with id ${id}`, { field });
9084
- }
9085
- function withPrimary(items, what) {
9086
- const flagged = items.filter((item) => item.primary).length;
9087
- if (flagged > 1) throw new ValidationError(`Only one ${what} can be primary`);
9088
- return items.map((item, i) => ({ ...item, primary: flagged ? Boolean(item.primary) : i === 0 }));
9089
- }
9090
- function uniqueIds(ids) {
9091
- const unique = [...new Set(ids)];
9092
- if (unique.length !== ids.length) throw new ValidationError("An id is listed twice");
9093
- return unique;
9094
- }
9095
-
9096
- // ../core/src/ids.ts
9097
- var ID_PREFIXES = {
9098
- person: "per",
9099
- organisation: "org",
9100
- affiliation: "aff",
9101
- activity: "act",
9102
- task: "tsk",
9103
- user: "usr",
9104
- view: "vw",
9105
- audit: "aud",
9106
- tag: "tag",
9107
- email: "eml",
9108
- phone: "phn",
9109
- domain: "dom",
9110
- address: "adr",
9111
- /** Records of extension objects (stage 3). */
9112
- record: "rec",
9113
- /** Extension run history rows. */
9114
- extensionRun: "xrn",
9115
- changeSet: "chs",
9116
- pendingAction: "pac",
9117
- connectedApp: "cap",
9118
- /** Integration connections (stage 6, ADR 0050). */
9119
- connection: "con",
9120
- integrationEvent: "iev",
9121
- jobChange: "jcs",
9122
- /** Stage history rows (ADR 0100). */
9123
- stageHistory: "sth",
9124
- dashboard: "dsh",
9125
- /** Automation runs (ADR 0130). */
9126
- automationRun: "arn",
9127
- /** Notifications (ADR 0132). */
9128
- notification: "ntf",
9129
- /** Automation events outbox rows (ADR 0171). */
9130
- outbox: "obx",
9131
- /** Admin notification channel routes (ADR 0172). */
9132
- notificationRoute: "nrt",
9133
- /** In-app assistant conversations (ADR 0200). */
9134
- assistantConversation: "asc",
9135
- /** A person's one assistant thread (ADR 0340). */
9136
- assistantThread: "ath",
9137
- /** A memory line (ADR 0342). */
9138
- memory: "mem",
9139
- /** A personal routine (ADR 0343). */
9140
- routine: "rtn",
9141
- /** Policy adjudicator verdicts (ADR 0204). */
9142
- adjudication: "adj",
9143
- /** Assignment rules (ADR 0246). */
9144
- assignmentRule: "asr",
9145
- /** An agent (ADR 0344). */
9146
- agentJob: "job",
9147
- /** One approval's claim on the actions it applies (ADR 0345). */
9148
- execution: "exe",
9149
- /** A customer account (stage 22, ADR 0402): a Person who can sign in. Never a core_user. */
9150
- customer: "cus",
9151
- /** A request to erase a Person, made when a customer deletes their account (stage 22). */
9152
- eraseRequest: "erq",
9153
- /** An order and one of its lines (stage 25, ADR 0426). */
9154
- order: "ord",
9155
- orderLine: "orl",
9156
- /** A refund of an order's payment (stage 25, ADR 0429). */
9157
- refund: "rfd",
9158
- /** A native app's signed-in session on the HTTP surface (stage 23, ADR 0419). */
9159
- deviceSession: "dvs",
9160
- /** Places claimed from a record's capacity (stage 26, ADR 0430). */
9161
- capacityClaim: "clm",
9162
- /** An invite for a staff account (ADR 0455). */
9163
- userInvite: "uin",
9164
- // Stage 28 (ADR 0444): a picture of the media library.
9165
- media: "med"
9166
- };
9167
- var ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
9168
- var lastTime = -1;
9169
- var lastRandom = [];
9170
- function randomDigits() {
9171
- const bytes = crypto.getRandomValues(new Uint8Array(16));
9172
- return Array.from(bytes, (byte) => byte & 31);
9173
- }
9174
- function increment(digits) {
9175
- const next = [...digits];
9176
- for (let i = next.length - 1; i >= 0; i--) {
9177
- const digit = next[i] ?? 0;
9178
- if (digit < 31) {
9179
- next[i] = digit + 1;
9180
- return next;
9181
- }
9182
- next[i] = 0;
9183
- }
9184
- throw new Error("ULID random component overflowed within one millisecond");
9185
- }
9186
- function ulid(now = Date.now()) {
9187
- let random;
9188
- if (now <= lastTime) {
9189
- random = increment(lastRandom);
9190
- now = lastTime;
9191
- } else {
9192
- random = randomDigits();
9193
- lastTime = now;
9194
- }
9195
- lastRandom = random;
9196
- let time = "";
9197
- let t = now;
9198
- for (let i = 0; i < 10; i++) {
9199
- time = ALPHABET[t % 32] + time;
9200
- t = Math.floor(t / 32);
9201
- }
9202
- return time + random.map((digit) => ALPHABET[digit]).join("");
9203
- }
9204
- function newId(kind, now) {
9205
- return `${ID_PREFIXES[kind]}_${ulid(now)}`;
9206
- }
9207
- var PROVISIONAL_ID_RE = /^[a-z]{2,4}_pending_[0-9A-HJKMNP-TV-Z]{26}$/;
9208
- var PROVISIONAL_ANYWHERE_RE = /[a-z]{2,4}_pending_[0-9A-HJKMNP-TV-Z]{26}/g;
9209
- var ANY_ID_RE = /[a-z]{2,4}_(?:pending_)?[0-9A-HJKMNP-TV-Z]{26}/g;
9210
- function toProvisionalId(id) {
9211
- const at = id.indexOf("_");
9212
- return at < 0 ? id : `${id.slice(0, at)}_pending_${id.slice(at + 1)}`;
9213
- }
9214
- function isProvisionalId(value) {
9215
- return typeof value === "string" && PROVISIONAL_ID_RE.test(value);
9216
- }
9217
- function findProvisionalIds(value) {
9218
- const text2 = JSON.stringify(value ?? null);
9219
- return [...new Set(text2.match(PROVISIONAL_ANYWHERE_RE) ?? [])];
9220
- }
9221
- function findIds(value) {
9222
- const text2 = JSON.stringify(value ?? null);
9223
- return [...new Set(text2.match(ANY_ID_RE) ?? [])];
9224
- }
9225
- function replaceIds(value, map) {
9226
- if (!map.size) return value;
9227
- const inString = (text2) => text2.replace(ANY_ID_RE, (id) => map.get(id) ?? id);
9228
- const walk = (v) => {
9229
- if (typeof v === "string") return inString(v);
9230
- if (Array.isArray(v)) return v.map(walk);
9231
- if (v && typeof v === "object") {
9232
- return Object.fromEntries(
9233
- Object.entries(v).map(([k, x]) => [inString(k), walk(x)])
9234
- );
9235
- }
9236
- return v;
9237
- };
9238
- return walk(value);
8884
+ // ../core/src/extensions/naming.ts
8885
+ var IDENT_RE = /^[a-z][a-z0-9_]{0,120}$/;
8886
+ function ident(name) {
8887
+ if (!IDENT_RE.test(name)) throw new Error(`Unsafe SQL identifier: ${JSON.stringify(name)}`);
8888
+ return name;
9239
8889
  }
9240
-
9241
- // ../core/src/principals.ts
9242
- var RISK_CLASSES = [
9243
- "read",
9244
- "write",
9245
- "bulk-write",
9246
- "destructive",
9247
- "schema",
9248
- "extension",
9249
- "outbound"
9250
- ];
9251
- var ACTORS = ["human", "assistant", "mcp", "automation", "extension"];
9252
- var originSchema = external_exports.object({
9253
- // `client`: a client app or site: a customer or the public (stage 22), or any caller of the
9254
- // HTTP surface (stage 23).
9255
- surface: external_exports.enum(["ui", "mcp", "automation", "system", "extension", "assistant", "client"]),
9256
- /** The MCP client id (OAuth client_id). */
9257
- clientId: external_exports.string().optional(),
9258
- /** The MCP client's display name, as registered (self-asserted). */
9259
- clientName: external_exports.string().optional(),
9260
- /**
9261
- * The MCP session: the connected app (cap_…) the token belongs to (ADR 0032). Pending actions
9262
- * group by it, and only it sees their simulated state.
9263
- */
9264
- // For the in-app assistant (surface `assistant`, ADR 0340) the session is the thread (ath_…).
9265
- sessionId: external_exports.string().optional(),
9266
- /** The automation id (`<extension>.<key>`, or a system job such as `trash.purge`). */
9267
- automationId: external_exports.string().optional(),
9268
- /** An automation run (arn_…): its pending actions go in one change set per run (ADR 0130). */
9269
- runId: external_exports.string().optional(),
9270
- /** Cascade tags (ADR 0130): how deep in an automation cascade this call is, and its chain. */
9271
- depth: external_exports.number().int().min(0).optional(),
9272
- chain: external_exports.array(external_exports.string()).max(10).optional(),
9273
- rootEventId: external_exports.string().optional(),
9274
- /** Test mode: the call is simulated, nothing is written (ADR 0133). */
9275
- test: external_exports.boolean().optional(),
9276
- /** The extension whose code made the call (actor `extension`). */
9277
- extensionId: external_exports.string().optional(),
9278
- /** The agent that made the call (job_…, ADR 0344). Its session is `job:<id>`. */
9279
- jobId: external_exports.string().optional()
9280
- });
9281
- var ROLES = ["admin", "member", "viewer"];
9282
- var PERMISSIONS = [
9283
- "records:read",
9284
- "records:write",
9285
- "records:erase",
9286
- "audit:read",
9287
- "users:manage",
9288
- "policy:manage",
9289
- "extensions:manage",
9290
- "integrations:manage",
9291
- "settings:manage",
9292
- "orders:refund",
9293
- "records:publish"
9294
- ];
9295
- var ROLE_PERMISSIONS = {
9296
- viewer: ["records:read"],
9297
- member: ["records:read", "records:write"],
9298
- admin: PERMISSIONS
8890
+ var CORE_TARGETS = {
8891
+ person: { base: "core_base_people", view: "rec_person" },
8892
+ organisation: { base: "core_base_organisations", view: "rec_organisation" },
8893
+ activity: { base: "core_base_activities", view: "rec_activity" },
8894
+ task: { base: "core_base_tasks", view: "rec_task" }
9299
8895
  };
9300
- function roleHasPermission(role, permission) {
9301
- return ROLE_PERMISSIONS[role].includes(permission);
8896
+ function isCoreTarget(object) {
8897
+ return Object.hasOwn(CORE_TARGETS, object);
9302
8898
  }
9303
- var GRANTABLE_PERMISSIONS = ["records:publish", "orders:refund"];
9304
- function holdsPermission(user, grants, permission) {
9305
- return roleHasPermission(user.role, permission) || GRANTABLE_PERMISSIONS.includes(permission) && (grants ?? []).includes(permission);
9306
- }
9307
- var MCP_SCOPES = ["read", "write", "admin"];
9308
- function grantableScopes(role) {
9309
- return role === "admin" ? [...MCP_SCOPES] : ["read", "write"];
9310
- }
9311
- function staffPrincipal(user) {
9312
- return Object.freeze({ kind: "staff", userId: user.id, role: user.role });
9313
- }
9314
- var OUTSIDE_ACTORS = ["customer", "public"];
9315
- var ALL_ACTORS = [...ACTORS, ...OUTSIDE_ACTORS];
9316
-
9317
- // ../core/src/records/columns.ts
9318
- function viewColumnOf(field) {
9319
- if (field.column) return field.column;
9320
- const match = /json_each\(r2\.([a-z0-9_]+)\)/.exec(field.related?.from ?? "");
9321
- return match?.[1] ?? null;
9322
- }
9323
-
9324
- // ../core/src/notifications/send.ts
9325
- var CORE_USER_FIELDS = /* @__PURE__ */ new Set(["ownerId", "assigneeId", "authorUserId", "createdBy"]);
9326
- var NO_MANAGER_NOTE = "Users have no manager field: sent to the admins instead";
9327
- async function adminUserIds(db) {
9328
- const rows = await db.selectFrom("core_user").select("id").where("role", "=", "admin").where("kind", "=", "human").orderBy("id").execute();
9329
- return rows.map((row) => row.id);
9330
- }
9331
- async function recordUser(db, record, fieldName, options) {
9332
- const object = getObject(record.object);
9333
- if (!object) {
9334
- throw new ValidationError(`Unknown object "${record.object}"`, { field: "to" });
9335
- }
9336
- const field = getField(object, fieldName);
9337
- const isUserField = field && (field.fieldType === "user" || !field.extension && CORE_USER_FIELDS.has(field.name));
9338
- if (!field || !isUserField) {
9339
- throw new ValidationError(
9340
- `${object.label} has no user field "${fieldName}" (recipients name a user field of the record)`,
9341
- { field: "to", object: record.object, recordField: fieldName }
9342
- );
9343
- }
9344
- const simulated = options.simulation?.record(record.object, record.id);
9345
- if (simulated) {
9346
- if (simulated.state === "deleted" || !simulated.record) {
9347
- return { userId: null, reason: `${object.label} ${record.id} is deleted` };
9348
- }
9349
- const values = simulated.record.values ?? simulated.record;
9350
- const value = values[field.name];
9351
- return typeof value === "string" && value ? { userId: value } : {
9352
- userId: null,
9353
- reason: `${object.label} ${record.id} has no ${field.label.toLowerCase()}`
9354
- };
9355
- }
9356
- const column = viewColumnOf(field);
9357
- if (!column) throw new ValidationError(`${object.label}.${field.name} cannot be read`);
9358
- const result = await sql`SELECT ${sql.ref(column)} AS v FROM ${sql.table(
9359
- object.source
9360
- )} WHERE id = ${record.id}`.execute(db);
9361
- const row = result.rows[0];
9362
- if (!row) return { userId: null, reason: `No ${object.label} with id ${record.id}` };
9363
- return typeof row.v === "string" && row.v ? { userId: row.v } : { userId: null, reason: `${object.label} ${record.id} has no ${field.label.toLowerCase()}` };
9364
- }
9365
- async function resolveRecipients(db, to, options = {}) {
9366
- const ids = [];
9367
- const notes = [];
9368
- let admins = null;
9369
- const loadAdmins = async () => {
9370
- admins ??= await adminUserIds(db);
9371
- return admins;
9372
- };
9373
- for (const recipient of to) {
9374
- if ("userId" in recipient) {
9375
- ids.push(recipient.userId);
9376
- } else if ("role" in recipient) {
9377
- ids.push(...await loadAdmins());
9378
- } else if ("field" in recipient) {
9379
- const found = await recordUser(db, recipient.record, recipient.field, options);
9380
- if (found.userId) ids.push(found.userId);
9381
- else notes.push(`${found.reason}: nobody to notify`);
9382
- } else {
9383
- const found = await recordUser(db, recipient.record, recipient.managerOf, options);
9384
- if (!found.userId) notes.push(`${found.reason}`);
9385
- notes.push(NO_MANAGER_NOTE);
9386
- ids.push(...await loadAdmins());
9387
- }
9388
- }
9389
- const unique = [...new Set(ids)];
9390
- const people = unique.length ? await db.selectFrom("core_user").select("id").where("id", "in", jsonList(unique)).where("kind", "=", "human").execute() : [];
9391
- const known = new Set(people.map((p) => p.id));
9392
- const explicit = new Set(
9393
- to.flatMap((r) => "userId" in r ? [r.userId] : [])
9394
- );
9395
- for (const id of unique) {
9396
- if (known.has(id)) continue;
9397
- if (explicit.has(id)) {
9398
- throw new ValidationError(`No user with id ${id}`, { field: "to", userId: id });
9399
- }
9400
- notes.push(`User ${id} no longer exists: skipped`);
9401
- }
9402
- if (!to.length) notes.push("No recipients");
9403
- return { userIds: unique.filter((id) => known.has(id)), notes };
9404
- }
9405
- async function notifyStatements(db, input, now, options = {}) {
9406
- const { userIds, notes } = await resolveRecipients(db, input.to, options);
9407
- const source = JSON.stringify(
9408
- Object.fromEntries(Object.entries(input.source).filter(([, v]) => v !== void 0))
9409
- );
9410
- const link = input.link ? JSON.stringify(input.link) : null;
9411
- const statements = userIds.map(
9412
- (userId) => db.insertInto("core_notifications").orIgnore().values({
9413
- id: newId("notification"),
9414
- user_id: userId,
9415
- type: input.type,
9416
- title: input.title,
9417
- body: input.body ?? null,
9418
- link,
9419
- source,
9420
- dedupe_key: input.dedupeKey ?? null,
9421
- read_at: null,
9422
- created_at: now
9423
- })
9424
- );
9425
- return { statements, userIds, notes };
9426
- }
9427
-
9428
- // ../core/src/filter.ts
9429
- var FILTER_OPS = [
9430
- "eq",
9431
- "neq",
9432
- "lt",
9433
- "lte",
9434
- "gt",
9435
- "gte",
9436
- "between",
9437
- "in",
9438
- "not_in",
9439
- "contains",
9440
- "not_contains",
9441
- "starts_with",
9442
- "ends_with",
9443
- "is_null",
9444
- "is_not_null"
9445
- ];
9446
- var FILTER_LIMITS = { maxDepth: 5, maxConditions: 100, maxListValues: 500 };
9447
- var conditionSchema = external_exports.object({
9448
- field: external_exports.string().min(1).max(64),
9449
- op: external_exports.enum(FILTER_OPS),
9450
- value: external_exports.unknown().optional()
9451
- }).strict();
9452
- var filterSchema = external_exports.lazy(
9453
- () => external_exports.union([
9454
- conditionSchema,
9455
- external_exports.object({ and: external_exports.array(filterSchema).max(FILTER_LIMITS.maxConditions) }).strict(),
9456
- external_exports.object({ or: external_exports.array(filterSchema).max(FILTER_LIMITS.maxConditions) }).strict()
9457
- ])
9458
- );
9459
- var COMPARABLE = ["eq", "neq", "lt", "lte", "gt", "gte", "between", "in", "not_in"];
9460
- var NULLS = ["is_null", "is_not_null"];
9461
- var TEXT = [
9462
- "eq",
9463
- "neq",
9464
- "in",
9465
- "not_in",
9466
- "contains",
9467
- "not_contains",
9468
- "starts_with",
9469
- "ends_with"
9470
- ];
9471
- var OPS_BY_TYPE = {
9472
- text: [...TEXT, ...NULLS],
9473
- number: [...COMPARABLE, ...NULLS],
9474
- date: [...COMPARABLE, ...NULLS],
9475
- datetime: [...COMPARABLE, ...NULLS],
9476
- boolean: ["eq", "neq", ...NULLS],
9477
- id: ["eq", "neq", "in", "not_in", ...NULLS],
9478
- enum: ["eq", "neq", "in", "not_in", ...NULLS],
9479
- json: []
9480
- };
9481
- var RELATED_OPS = [
9482
- "eq",
9483
- "neq",
9484
- "in",
9485
- "not_in",
9486
- "contains",
9487
- "not_contains",
9488
- "starts_with",
9489
- "ends_with",
9490
- ...NULLS
9491
- ];
9492
- var NEGATED = {
9493
- neq: "eq",
9494
- not_in: "in",
9495
- not_contains: "contains"
9496
- };
9497
- var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
9498
- var DATETIME_RE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})?)?$/;
9499
- function fail(path, reason) {
9500
- throw new ValidationError(`Invalid filter at ${path}: ${reason}`, { path, reason });
9501
- }
9502
- function scalar(field, value, path) {
9503
- switch (field.type) {
9504
- case "text":
9505
- if (typeof value !== "string") fail(path, `${field.name} needs a string`);
9506
- if (value.length > 1e3) fail(path, "value is too long");
9507
- return value;
9508
- case "id":
9509
- if (typeof value !== "string" || value.length > 100) fail(path, `${field.name} needs an id`);
9510
- return value;
9511
- case "number":
9512
- if (typeof value !== "number" || !Number.isFinite(value)) {
9513
- fail(path, `${field.name} needs a number`);
9514
- }
9515
- return value;
9516
- case "boolean":
9517
- if (typeof value !== "boolean") fail(path, `${field.name} needs true or false`);
9518
- return value ? 1 : 0;
9519
- case "date":
9520
- if (typeof value !== "string" || !DATE_RE.test(value)) {
9521
- fail(path, `${field.name} needs a YYYY-MM-DD date`);
9522
- }
9523
- return value;
9524
- case "datetime":
9525
- if (typeof value !== "string" || !DATETIME_RE.test(value)) {
9526
- fail(path, `${field.name} needs an ISO-8601 date or timestamp`);
9527
- }
9528
- return value;
9529
- case "enum":
9530
- if (typeof value !== "string" || !field.enumValues?.includes(value)) {
9531
- fail(path, `${field.name} must be one of ${field.enumValues?.join(", ")}`);
9532
- }
9533
- return value;
9534
- case "json":
9535
- return fail(path, `${field.name} cannot be filtered`);
9536
- }
9537
- }
9538
- function list(field, value, path) {
9539
- if (!Array.isArray(value) || value.length === 0) fail(path, "needs a non-empty array");
9540
- if (value.length > FILTER_LIMITS.maxListValues) fail(path, "too many values");
9541
- return value.map((item, i) => scalar(field, item, `${path}[${i}]`));
9542
- }
9543
- function escapeLike(value) {
9544
- return value.replace(/[\\%_]/g, (char) => `\\${char}`);
9545
- }
9546
- function comparison(field, col, op, value, path) {
9547
- const nocase = field.type === "text" ? sql` COLLATE NOCASE` : sql``;
9548
- switch (op) {
9549
- case "is_null":
9550
- return sql`${col} IS NULL`;
9551
- case "is_not_null":
9552
- return sql`${col} IS NOT NULL`;
9553
- case "eq":
9554
- return sql`${col} = ${scalar(field, value, path)}${nocase}`;
9555
- case "neq":
9556
- return sql`(${col} IS NULL OR ${col} <> ${scalar(field, value, path)}${nocase})`;
9557
- case "lt":
9558
- return sql`${col} < ${scalar(field, value, path)}`;
9559
- case "lte":
9560
- return sql`${col} <= ${scalar(field, value, path)}`;
9561
- case "gt":
9562
- return sql`${col} > ${scalar(field, value, path)}`;
9563
- case "gte":
9564
- return sql`${col} >= ${scalar(field, value, path)}`;
9565
- case "between": {
9566
- if (!Array.isArray(value) || value.length !== 2) fail(path, "between needs [low, high]");
9567
- const [low, high] = list(field, value, path);
9568
- return sql`${col} BETWEEN ${low ?? null} AND ${high ?? null}`;
9569
- }
9570
- case "in":
9571
- return sql`${col}${nocase} IN (${sql.join(list(field, value, path))})`;
9572
- case "not_in":
9573
- return sql`(${col} IS NULL OR ${col}${nocase} NOT IN (${sql.join(list(field, value, path))}))`;
9574
- case "contains":
9575
- case "not_contains":
9576
- case "starts_with":
9577
- case "ends_with": {
9578
- const text2 = scalar(field, value, path);
9579
- if (typeof text2 !== "string") fail(path, `${op} needs a string`);
9580
- const escaped = escapeLike(text2);
9581
- const pattern = op === "starts_with" ? `${escaped}%` : op === "ends_with" ? `%${escaped}` : `%${escaped}%`;
9582
- const like = sql`${col} LIKE ${pattern} ESCAPE '\\'`;
9583
- return op === "not_contains" ? sql`(${col} IS NULL OR NOT (${like}))` : like;
9584
- }
9585
- }
9586
- }
9587
- function compileNode(object, node, alias, path, depth, state) {
9588
- if (depth > FILTER_LIMITS.maxDepth) fail(path, "filter is nested too deeply");
9589
- if ("and" in node || "or" in node) {
9590
- const isAnd = "and" in node;
9591
- const children = isAnd ? node.and : node.or;
9592
- const key = isAnd ? "and" : "or";
9593
- if (children.length === 0) return isAnd ? sql`1 = 1` : sql`1 = 0`;
9594
- const parts = children.map(
9595
- (child, i) => compileNode(object, child, alias, `${path}.${key}[${i}]`, depth + 1, state)
9596
- );
9597
- return sql`(${sql.join(parts, sql.raw(isAnd ? " AND " : " OR "))})`;
9598
- }
9599
- state.conditions += 1;
9600
- if (state.conditions > FILTER_LIMITS.maxConditions) fail(path, "too many conditions");
9601
- const { field: name, op, value } = node;
9602
- const field = object.fields.find((f) => f.name === name);
9603
- if (!field) fail(path, `unknown field "${name}" on ${object.name}`);
9604
- if (!field.filterable) fail(path, `${object.name}.${name} is not filterable`);
9605
- if (field.related) {
9606
- if (!RELATED_OPS.includes(op) || !OPS_BY_TYPE[field.type].includes(op)) {
9607
- fail(path, `${op} is not supported on ${object.name}.${name}`);
9608
- }
9609
- const r = field.related;
9610
- const extra = r.where ? sql` AND ${sql.raw(r.where)}` : sql``;
9611
- const exists = (condition) => sql`EXISTS (SELECT 1 FROM ${sql.raw(r.from)} WHERE ${sql.raw(r.link)} = ${sql.ref(`${alias}.id`)}${extra}${condition ? sql` AND ${condition}` : sql``})`;
9612
- if (op === "is_not_null") return exists(null);
9613
- if (op === "is_null") return sql`NOT ${exists(null)}`;
9614
- const positive = NEGATED[op];
9615
- const col = sql.raw(r.column);
9616
- if (positive) {
9617
- return sql`NOT ${exists(comparison(field, col, positive, value, path))}`;
9618
- }
9619
- return exists(comparison(field, col, op, value, path));
9620
- }
9621
- if (!OPS_BY_TYPE[field.type].includes(op)) {
9622
- fail(path, `${op} is not supported on ${field.type} field ${object.name}.${name}`);
9623
- }
9624
- if (!field.column) fail(path, `${object.name}.${name} has no column`);
9625
- if (!NULLS.includes(op) && value === void 0) fail(path, `${op} needs a value`);
9626
- return comparison(field, sql.ref(`${alias}.${field.column}`), op, value, path);
9627
- }
9628
- function compileFilter(object, filter, alias = object.source) {
9629
- const parsed = filterSchema.safeParse(filter);
9630
- if (!parsed.success) {
9631
- throw new ValidationError("Invalid filter", { issues: parsed.error.issues });
9632
- }
9633
- return compileNode(object, parsed.data, alias, "filter", 1, { conditions: 0 });
9634
- }
9635
-
9636
- // ../core/src/extensions/naming.ts
9637
- var IDENT_RE = /^[a-z][a-z0-9_]{0,120}$/;
9638
- function ident(name) {
9639
- if (!IDENT_RE.test(name)) throw new Error(`Unsafe SQL identifier: ${JSON.stringify(name)}`);
9640
- return name;
9641
- }
9642
- var CORE_TARGETS = {
9643
- person: { base: "core_base_people", view: "rec_person" },
9644
- organisation: { base: "core_base_organisations", view: "rec_organisation" },
9645
- activity: { base: "core_base_activities", view: "rec_activity" },
9646
- task: { base: "core_base_tasks", view: "rec_task" }
9647
- };
9648
- function isCoreTarget(object) {
9649
- return Object.hasOwn(CORE_TARGETS, object);
9650
- }
9651
- function assertExtensionId(id) {
9652
- if (!EXTENSION_ID_RE.test(id)) throw new Error(`Invalid extension id ${JSON.stringify(id)}`);
9653
- return id;
8899
+ function assertExtensionId(id) {
8900
+ if (!EXTENSION_ID_RE.test(id)) throw new Error(`Invalid extension id ${JSON.stringify(id)}`);
8901
+ return id;
9654
8902
  }
9655
8903
  function splitObjectName(name) {
9656
8904
  const [extension, object, ...rest] = name.split(".");
@@ -9753,235 +9001,289 @@ function viewColumnName(extension, target, local) {
9753
9001
  return target.startsWith(`${extension}.`) ? column : ident(`${extension}__${column}`);
9754
9002
  }
9755
9003
 
9756
- // ../core/src/gate.ts
9757
- var GATE_DECISIONS = ["auto", "review", "deny"];
9758
- var POLICY_PRESETS = ["cautious", "balanced", "autonomous"];
9759
- var approvalPolicySchema = external_exports.object({ preset: external_exports.enum(POLICY_PRESETS) });
9760
- var APPROVAL_POLICY_SETTING = "approval_policy";
9761
- var HUMAN_ALL_AUTO = {
9762
- read: "auto",
9763
- write: "auto",
9764
- "bulk-write": "auto",
9765
- destructive: "auto",
9766
- schema: "auto",
9767
- extension: "auto",
9768
- outbound: "auto"
9004
+ // ../core/src/errors.ts
9005
+ var OperationError = class extends Error {
9006
+ constructor(code, message, details) {
9007
+ super(message);
9008
+ this.code = code;
9009
+ this.details = details;
9010
+ }
9011
+ code;
9012
+ details;
9013
+ name = "OperationError";
9014
+ toJSON() {
9015
+ return {
9016
+ code: this.code,
9017
+ message: this.message,
9018
+ ...this.details === void 0 ? {} : { details: this.details }
9019
+ };
9020
+ }
9769
9021
  };
9770
- var cautiousAi = {
9771
- read: "auto",
9772
- write: "review",
9773
- "bulk-write": "review",
9774
- destructive: "review",
9775
- schema: "review",
9776
- extension: "review",
9777
- outbound: "review"
9022
+ var UnknownOperationError = class extends OperationError {
9023
+ name = "UnknownOperationError";
9024
+ constructor(name) {
9025
+ super("unknown_operation", `No operation named "${name}"`);
9026
+ }
9778
9027
  };
9779
- var balancedAi = {
9780
- read: "auto",
9781
- write: "auto",
9782
- "bulk-write": { autoUpTo: 25, above: "review" },
9783
- destructive: "review",
9784
- schema: "review",
9785
- extension: "review",
9786
- outbound: "review"
9028
+ var ValidationError = class extends OperationError {
9029
+ name = "ValidationError";
9030
+ constructor(message, details) {
9031
+ super("invalid_input", message, details);
9032
+ }
9787
9033
  };
9788
- var balancedMcp = { ...balancedAi, "bulk-write": "review" };
9789
- var autonomousAi = {
9790
- read: "auto",
9791
- write: "auto",
9792
- "bulk-write": "auto",
9793
- destructive: { autoUpTo: 10, above: "review" },
9794
- schema: "review",
9795
- extension: "review",
9796
- outbound: "auto"
9034
+ var ForbiddenError = class extends OperationError {
9035
+ name = "ForbiddenError";
9036
+ constructor(message, details) {
9037
+ super("forbidden", message, details);
9038
+ }
9797
9039
  };
9798
- var extensionRow = (bulk, destructive) => ({
9799
- read: "auto",
9800
- write: "auto",
9801
- "bulk-write": bulk,
9802
- destructive,
9803
- schema: "deny",
9804
- extension: "deny",
9805
- outbound: "review"
9806
- });
9807
- var PRESET_MATRICES = {
9808
- cautious: {
9809
- human: HUMAN_ALL_AUTO,
9810
- assistant: cautiousAi,
9811
- mcp: cautiousAi,
9812
- automation: {
9813
- read: "auto",
9814
- write: "auto",
9815
- "bulk-write": "review",
9816
- destructive: "review",
9817
- schema: "deny",
9818
- extension: "deny",
9819
- outbound: "review"
9820
- },
9821
- extension: extensionRow("review", "review")
9822
- },
9823
- balanced: {
9824
- human: HUMAN_ALL_AUTO,
9825
- assistant: balancedAi,
9826
- mcp: balancedMcp,
9827
- automation: {
9828
- read: "auto",
9829
- write: "auto",
9830
- "bulk-write": { autoUpTo: 100, above: "review" },
9831
- destructive: "review",
9832
- schema: "deny",
9833
- extension: "deny",
9834
- outbound: "review"
9835
- },
9836
- extension: extensionRow({ autoUpTo: 100, above: "review" }, "review")
9837
- },
9838
- autonomous: {
9839
- human: HUMAN_ALL_AUTO,
9840
- assistant: autonomousAi,
9841
- mcp: autonomousAi,
9842
- automation: { ...autonomousAi, schema: "deny", extension: "deny" },
9843
- extension: extensionRow("auto", { autoUpTo: 10, above: "review" })
9040
+ var GateDeniedError = class extends OperationError {
9041
+ name = "GateDeniedError";
9042
+ constructor(message, details) {
9043
+ super("denied", message, details);
9844
9044
  }
9845
9045
  };
9846
- var ruleSchema = external_exports.union([
9847
- external_exports.enum(GATE_DECISIONS),
9848
- external_exports.object({ autoUpTo: external_exports.number().int().min(0), above: external_exports.enum(["review", "deny"]) }).strict()
9849
- ]);
9850
- var floorSchema = external_exports.partialRecord(
9851
- external_exports.enum([...ACTORS, "*"]),
9852
- external_exports.partialRecord(external_exports.enum([...RISK_CLASSES, "*"]), ruleSchema)
9853
- );
9854
- var STRICTNESS = { auto: 0, review: 1, deny: 2 };
9855
- function stricter(a, b) {
9856
- return STRICTNESS[a] >= STRICTNESS[b] ? a : b;
9857
- }
9858
- function applyRule(rule, bulkSize) {
9859
- if (typeof rule === "string") return rule;
9860
- return bulkSize <= rule.autoUpTo ? "auto" : rule.above;
9861
- }
9862
- function evaluateGate(request, policy, floor = {}) {
9863
- const bulkSize = Math.max(1, request.bulkSize ?? 1);
9864
- let policyDecision = applyRule(
9865
- PRESET_MATRICES[policy.preset][request.actor][request.risk],
9866
- bulkSize
9867
- );
9868
- if (request.risk === "outbound" && policyDecision === "review" && policy.preset === "balanced" && request.outbound?.autoApprovable && request.outbound.enabled) {
9869
- policyDecision = "auto";
9870
- }
9871
- const floorRules = [
9872
- floor[request.actor]?.[request.risk],
9873
- floor[request.actor]?.["*"],
9874
- floor["*"]?.[request.risk],
9875
- floor["*"]?.["*"]
9876
- ].filter((rule) => rule !== void 0);
9877
- let decision = policyDecision;
9878
- let floorDecision;
9879
- for (const rule of floorRules) {
9880
- const fromFloor = applyRule(rule, bulkSize);
9881
- floorDecision = floorDecision ? stricter(floorDecision, fromFloor) : fromFloor;
9882
- decision = stricter(decision, fromFloor);
9046
+ var PendingApprovalError = class extends OperationError {
9047
+ name = "PendingApprovalError";
9048
+ pending;
9049
+ constructor(pending) {
9050
+ super("pending_approval", pending.message, pending);
9051
+ this.pending = pending;
9883
9052
  }
9884
- return {
9885
- decision,
9886
- policyDecision,
9887
- ...floorDecision ? { floorDecision } : {},
9888
- preset: policy.preset
9889
- };
9053
+ };
9054
+ var RateLimitedError = class extends OperationError {
9055
+ name = "RateLimitedError";
9056
+ constructor(message, details) {
9057
+ super("rate_limited", message, details);
9058
+ }
9059
+ };
9060
+ var PlanLimitError = class extends OperationError {
9061
+ name = "PlanLimitError";
9062
+ constructor(message, details) {
9063
+ super("plan_limit", message, details);
9064
+ }
9065
+ };
9066
+ var NotFoundError = class extends OperationError {
9067
+ name = "NotFoundError";
9068
+ constructor(object, id) {
9069
+ super("not_found", `No ${object} with id ${id}`, { object, id });
9070
+ }
9071
+ };
9072
+ var ConflictError = class extends OperationError {
9073
+ name = "ConflictError";
9074
+ constructor(message, details) {
9075
+ super("conflict", message, details);
9076
+ }
9077
+ };
9078
+ var ConfigError = class extends OperationError {
9079
+ name = "ConfigError";
9080
+ constructor(message) {
9081
+ super("config", message);
9082
+ }
9083
+ };
9084
+ var declaredUniqueKeys = /* @__PURE__ */ new Set();
9085
+ function setDeclaredUniqueKeys(keys) {
9086
+ declaredUniqueKeys = keys;
9890
9087
  }
9891
- function evaluateOutsideGate(risk, floor = {}) {
9892
- if (risk !== "read" && risk !== "write") return "deny";
9893
- const rules = [floor["*"]?.[risk], floor["*"]?.["*"]].filter(
9894
- (rule) => rule !== void 0
9895
- );
9896
- return rules.some((rule) => applyRule(rule, 1) === "deny") ? "deny" : "auto";
9897
- }
9898
- function isLoosening(from, to) {
9899
- const a = PRESET_MATRICES[from];
9900
- const b = PRESET_MATRICES[to];
9901
- for (const actor of ACTORS) {
9902
- for (const risk of RISK_CLASSES) {
9903
- for (const size of [1, 10, 11, 25, 26, 100, 101, 1e4]) {
9904
- if (STRICTNESS[applyRule(b[actor][risk], size)] < STRICTNESS[applyRule(a[actor][risk], size)])
9905
- return true;
9088
+ function toOperationError(error) {
9089
+ if (error instanceof OperationError) return error;
9090
+ if (error instanceof Error && error.name === "AiAllowanceError") {
9091
+ return new PlanLimitError(error.message, { reason: "platform_ai" });
9092
+ }
9093
+ const capacity = capacityRefusal(error);
9094
+ if (capacity) return capacity;
9095
+ const allowance = allowanceRefusal(error);
9096
+ if (allowance) return allowance;
9097
+ const message = error instanceof Error ? error.message : String(error);
9098
+ if (message.includes("core_order_stale")) {
9099
+ return new ConflictError("The order changed while this was being applied. Try again.", {
9100
+ reason: "order_stale"
9101
+ });
9102
+ }
9103
+ if (message.includes("core_subscription_stale")) {
9104
+ return new ConflictError("The subscription changed while this was being applied. Try again.", {
9105
+ reason: "subscription_stale"
9106
+ });
9107
+ }
9108
+ if (message.includes("core_subscription_trial_taken")) {
9109
+ return new ConflictError(
9110
+ "A checkout with this free trial was opened at the same moment. Start again to get it.",
9111
+ { rule: "trial_held" }
9112
+ );
9113
+ }
9114
+ if (message.includes("core_subscription_offer_held")) {
9115
+ return new ConflictError(
9116
+ "A checkout for this offer was opened at the same moment, or the offer was taken or withdrawn. Start again.",
9117
+ { rule: "offer_held" }
9118
+ );
9119
+ }
9120
+ if (message.includes("core_subscription_offer_stale")) {
9121
+ return new ConflictError(
9122
+ "The offer changed while this was being done, so nothing was changed. Try again.",
9123
+ { rule: "offer_changed" }
9124
+ );
9125
+ }
9126
+ if (message.includes("UNIQUE constraint failed: core_subscription_offer")) {
9127
+ return new ConflictError(
9128
+ "Another import wrote one of these offers at the same moment. Run the import again.",
9129
+ { rule: "offer_key" }
9130
+ );
9131
+ }
9132
+ if (message.includes(
9133
+ "UNIQUE constraint failed: core_transition_history.object_type, core_transition_history.record_id"
9134
+ )) {
9135
+ return new ConflictError(
9136
+ "The record was moved by another change while this one was being made, so nothing was changed. Read it again: it may already be where you wanted it.",
9137
+ { reason: "moved_meanwhile" }
9138
+ );
9139
+ }
9140
+ if (message.includes("UNIQUE constraint failed: core_publish_version")) {
9141
+ return new ConflictError(
9142
+ "Another version of this record was published at the same moment, so this one was not. Read its versions again before publishing.",
9143
+ { reason: "published_meanwhile" }
9144
+ );
9145
+ }
9146
+ if (message.includes("core_recurrence_stale")) {
9147
+ return new ConflictError(
9148
+ "The schedule or a booking changed while this was being done, so nothing was changed. Try again.",
9149
+ { rule: "recurring_stale" }
9150
+ );
9151
+ }
9152
+ if (message.includes("core_claim_live")) {
9153
+ return new ConflictError(
9154
+ "This record took a place while it was being deleted, so it was not. Move it out first.",
9155
+ { rule: "capacity", reason: "claim_live" }
9156
+ );
9157
+ }
9158
+ if (message.includes("UNIQUE constraint failed: core_recurrence_occurrence")) {
9159
+ return new ConflictError(
9160
+ "Another run made these records at the same moment. Nothing was changed.",
9161
+ {
9162
+ rule: "recurring_occurrence"
9906
9163
  }
9907
- }
9164
+ );
9908
9165
  }
9909
- return false;
9910
- }
9911
-
9912
- // ../core/src/settings.ts
9913
- async function loadApprovalPolicy(db) {
9914
- const row = await db.selectFrom("core_settings").select("value").where("key", "=", APPROVAL_POLICY_SETTING).executeTakeFirst();
9915
- if (!row) return { preset: "cautious" };
9916
- try {
9917
- const parsed = approvalPolicySchema.safeParse(JSON.parse(row.value));
9918
- return parsed.success ? parsed.data : { preset: "cautious" };
9919
- } catch {
9920
- return { preset: "cautious" };
9921
- }
9922
- }
9923
- var BASE_CURRENCY_SETTING = "base_currency";
9924
- var ORG_NAME_SETTING = "org_name";
9925
- var ORG_LOGO_SETTING = "org_logo";
9926
- var ORG_TIMEZONE_SETTING = "org_timezone";
9927
- var ASSISTANT_NAME_SETTING = "assistant_name";
9928
- var DEFAULT_ASSISTANT_NAME = "Assistant";
9929
- function parseJson(value) {
9930
- if (value === void 0) return null;
9931
- try {
9932
- return JSON.parse(value);
9933
- } catch {
9934
- return null;
9166
+ const unique = /UNIQUE constraint failed: ([\w.]+(?:, [\w.]+)*)/.exec(message);
9167
+ if (unique?.[1] && declaredUniqueKeys.has(unique[1])) {
9168
+ return new ConflictError(
9169
+ "A record like this one was made at the same moment, so this one was not",
9170
+ {
9171
+ rule: "unique",
9172
+ constraint: unique[1]
9173
+ }
9174
+ );
9935
9175
  }
9176
+ if (unique) {
9177
+ return new ConflictError("A record with that value already exists", {
9178
+ constraint: unique[1]
9179
+ });
9180
+ }
9181
+ if (/FOREIGN KEY constraint failed/.test(message)) {
9182
+ return new ValidationError("A referenced record does not exist");
9183
+ }
9184
+ if (/CHECK constraint failed/.test(message)) {
9185
+ return new ValidationError("A value is not allowed", { reason: message });
9186
+ }
9187
+ return new OperationError("internal", "Internal error", { reason: message });
9936
9188
  }
9937
- function isTimezone(tz) {
9938
- try {
9939
- new Intl.DateTimeFormat("en", { timeZone: tz });
9940
- return true;
9941
- } catch {
9942
- return false;
9943
- }
9944
- }
9945
- async function loadGeneralSettings(db) {
9946
- const rows = await db.selectFrom("core_settings").select(["key", "value"]).where("key", "in", [
9947
- BASE_CURRENCY_SETTING,
9948
- ORG_NAME_SETTING,
9949
- ORG_LOGO_SETTING,
9950
- ORG_TIMEZONE_SETTING,
9951
- ASSISTANT_NAME_SETTING
9952
- ]).execute();
9953
- const get = (key) => parseJson(rows.find((r) => r.key === key)?.value);
9954
- const currency = get(BASE_CURRENCY_SETTING);
9955
- const name = get(ORG_NAME_SETTING);
9956
- const logo = get(ORG_LOGO_SETTING);
9957
- const timezone = get(ORG_TIMEZONE_SETTING);
9958
- const assistantName = get(ASSISTANT_NAME_SETTING);
9959
- return {
9960
- baseCurrency: typeof currency === "string" && /^[A-Z]{3}$/.test(currency) ? currency : "USD",
9961
- orgName: typeof name === "string" && name.trim() ? name : null,
9962
- logo: typeof logo === "string" && logo.startsWith("data:image/") ? logo : null,
9963
- timezone: typeof timezone === "string" && isTimezone(timezone) ? timezone : "UTC",
9964
- assistantName: typeof assistantName === "string" && assistantName.trim() ? assistantName.trim() : DEFAULT_ASSISTANT_NAME
9965
- };
9189
+ var ALLOWANCE_REFUSED = /core_allowance_refused (\{[^{}]*\})/;
9190
+ var ALLOWANCE_MESSAGES = {
9191
+ no_uses_left: "No uses left in this period",
9192
+ spent_meanwhile: "Another booking took the last use at the same moment. Try again",
9193
+ not_theirs: "That pass or membership is not this person's",
9194
+ not_live: "That pass or membership cannot be used now (paused, ended or void)",
9195
+ not_yet_valid: "That pass or membership is not valid yet at this time",
9196
+ ended: "That pass or membership has ended by this time",
9197
+ no_holder: "Nothing this person holds can pay for this",
9198
+ not_covered: "That pass or membership does not cover this"
9199
+ };
9200
+ function allowanceMessage(details) {
9201
+ const base = ALLOWANCE_MESSAGES[details.reason] ?? "The allowance refused this";
9202
+ return details.reason === "no_uses_left" && details.uses !== void 0 ? `${base}: ${details.used ?? details.uses} of ${details.uses} spent` : base;
9966
9203
  }
9967
- var AI_SETTINGS = "ai_settings";
9968
- async function loadAiSettings(db) {
9969
- const row = await db.selectFrom("core_settings").select("value").where("key", "=", AI_SETTINGS).executeTakeFirst();
9970
- if (!row) return { roles: {}, byok: [] };
9971
- try {
9972
- const value = JSON.parse(row.value);
9973
- return {
9974
- roles: parseRoleLayer(JSON.stringify(value.roles ?? {}), "Settings \u2192 AI (ai_settings)"),
9975
- byok: Array.isArray(value.byok) ? value.byok.filter((p) => PROVIDERS.includes(p)) : []
9204
+ function allowanceRefusal(error) {
9205
+ if (error instanceof OperationError) return null;
9206
+ const message = error instanceof Error ? error.message : String(error);
9207
+ const match = ALLOWANCE_REFUSED.exec(message);
9208
+ if (match) {
9209
+ let payload;
9210
+ try {
9211
+ payload = JSON.parse(match[1]);
9212
+ } catch {
9213
+ return new ValidationError("The allowance refused this", { rule: "allowance" });
9214
+ }
9215
+ const details = {
9216
+ rule: "allowance",
9217
+ reason: String(payload.reason),
9218
+ ...typeof payload.object === "string" ? { object: payload.object } : {},
9219
+ ...typeof payload.record === "string" ? { record: payload.record } : {},
9220
+ ...typeof payload.period === "string" ? { period: payload.period } : {},
9221
+ ...typeof payload.uses === "number" ? { uses: payload.uses } : {},
9222
+ ...typeof payload.used === "number" ? { used: payload.used } : {},
9223
+ ...typeof payload.at === "string" ? { at: payload.at } : {}
9976
9224
  };
9977
- } catch {
9978
- return { roles: {}, byok: [] };
9225
+ if (details.reason === "no_uses_left") {
9226
+ return new ConflictError(
9227
+ "Another booking took the last use at the same moment, so nothing was changed. Try again.",
9228
+ { ...details, reason: "spent_meanwhile" }
9229
+ );
9230
+ }
9231
+ return new ValidationError(allowanceMessage(details), { ...details });
9979
9232
  }
9233
+ if (message.includes("UNIQUE constraint failed: core_allowance_use.spender_type")) {
9234
+ return new ConflictError(
9235
+ "This record spent a use at the same moment in another change, so nothing was changed.",
9236
+ { rule: "allowance", reason: "spent_meanwhile" }
9237
+ );
9238
+ }
9239
+ return null;
9240
+ }
9241
+ var CAPACITY_REFUSED = /core_capacity_refused (\{[^{}]*\})/;
9242
+ function capacityRefusal(error) {
9243
+ const message = error instanceof Error ? error.message : String(error);
9244
+ const match = CAPACITY_REFUSED.exec(message);
9245
+ if (match) {
9246
+ let payload;
9247
+ try {
9248
+ payload = JSON.parse(match[1]);
9249
+ } catch {
9250
+ return new ValidationError("Not enough places", { rule: "capacity" });
9251
+ }
9252
+ if (payload.asked > 0) {
9253
+ const details2 = {
9254
+ rule: "capacity",
9255
+ object: payload.object,
9256
+ record: payload.record,
9257
+ asked: payload.asked,
9258
+ available: payload.available
9259
+ };
9260
+ return new ValidationError(
9261
+ `Not enough places: asked for ${payload.asked}, ${payload.available} left`,
9262
+ details2
9263
+ );
9264
+ }
9265
+ const details = {
9266
+ rule: "capacity",
9267
+ object: payload.object,
9268
+ record: payload.record,
9269
+ places: payload.places,
9270
+ held: payload.held,
9271
+ taken: payload.taken
9272
+ };
9273
+ return new ValidationError(
9274
+ `Places cannot be fewer than are claimed: ${payload.held} held and ${payload.taken} taken`,
9275
+ details
9276
+ );
9277
+ }
9278
+ if (message.includes("core_capacity_within_places")) {
9279
+ return new ValidationError("Not enough places", { rule: "capacity" });
9280
+ }
9281
+ return null;
9980
9282
  }
9981
9283
 
9982
9284
  // ../core/src/fields/field-types.ts
9983
- var DATE_RE2 = /^\d{4}-\d{2}-\d{2}$/;
9984
- var DATETIME_RE2 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})$/;
9285
+ var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
9286
+ var DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})$/;
9985
9287
  var nullable = (schema) => schema.nullable();
9986
9288
  var text = (max) => external_exports.string().max(max);
9987
9289
  var identity = (value) => value === void 0 ? null : value;
@@ -10107,13 +9409,13 @@ var FIELD_TYPE_REGISTRY = {
10107
9409
  filterType: () => "date",
10108
9410
  multi: () => false,
10109
9411
  sortable: () => true,
10110
- schema: () => nullable(external_exports.string().regex(DATE_RE2, "Expected YYYY-MM-DD")),
9412
+ schema: () => nullable(external_exports.string().regex(DATE_RE, "Expected YYYY-MM-DD")),
10111
9413
  toStorage: identity,
10112
9414
  fromStorage: identity,
10113
9415
  csv: {
10114
9416
  parse: (cell) => {
10115
9417
  if (cell.trim() === "") return null;
10116
- if (!DATE_RE2.test(cell.trim())) throw new Error(`"${cell}" is not a YYYY-MM-DD date`);
9418
+ if (!DATE_RE.test(cell.trim())) throw new Error(`"${cell}" is not a YYYY-MM-DD date`);
10117
9419
  return cell.trim();
10118
9420
  },
10119
9421
  format: csvText.format
@@ -10125,7 +9427,7 @@ var FIELD_TYPE_REGISTRY = {
10125
9427
  filterType: () => "datetime",
10126
9428
  multi: () => false,
10127
9429
  sortable: () => true,
10128
- schema: () => nullable(external_exports.string().regex(DATETIME_RE2, "Expected an ISO-8601 timestamp")),
9430
+ schema: () => nullable(external_exports.string().regex(DATETIME_RE, "Expected an ISO-8601 timestamp")),
10129
9431
  toStorage: identity,
10130
9432
  fromStorage: identity,
10131
9433
  csv: {
@@ -10215,6 +9517,8 @@ var FIELD_TYPE_REGISTRY = {
10215
9517
  richText: { ...documentType, widget: { display: "richText", edit: "richText" } },
10216
9518
  // A picture from the media library (stage 28, ADR 0444): a document with the image schema.
10217
9519
  image: { ...documentType, widget: { display: "image", edit: "image" } },
9520
+ // A video from the media library (stage 42, ADR 0475): a document with the video schema.
9521
+ video: { ...documentType, widget: { display: "video", edit: "video" } },
10218
9522
  // A record's address (stage 28, ADR 0442). Unique among live records by an index the
10219
9523
  // reconciler makes; made from the title when left empty (records/slug.ts).
10220
9524
  slug: textType(
@@ -10433,6 +9737,12 @@ function buildViews(state) {
10433
9737
  columns.push(...published.columns);
10434
9738
  joins.push(...published.joins);
10435
9739
  }
9740
+ const allowance = object.definition.allowance;
9741
+ if (allowance && "holds" in allowance) {
9742
+ const held = allowanceView(object.name);
9743
+ columns.push(...held.columns);
9744
+ joins.push(...held.joins);
9745
+ }
10436
9746
  build.creates.push(
10437
9747
  `CREATE VIEW ${view} AS SELECT ${columns.join(", ")} FROM ${ident(object.tableName)} t${joins.length ? ` ${joins.join(" ")}` : ""} WHERE t.deleted_at IS NULL`
10438
9748
  );
@@ -10506,6 +9816,17 @@ function capacityView(object) {
10506
9816
  ]
10507
9817
  };
10508
9818
  }
9819
+ function allowanceView(object) {
9820
+ const name = `'${object.replaceAll("'", "''")}'`;
9821
+ return {
9822
+ joins: [`LEFT JOIN rec_allowance alw ON alw.object_type = ${name} AND alw.record_id = t.id`],
9823
+ columns: [
9824
+ `coalesce(alw.used, 0) AS ${ALLOWANCE_COLUMNS.used}`,
9825
+ // No terms row (never written since a reconcile's backfill): nothing can be spent yet.
9826
+ `CASE WHEN alw.record_id IS NULL THEN 0 ELSE alw."left" END AS ${ALLOWANCE_COLUMNS.left}`
9827
+ ]
9828
+ };
9829
+ }
10509
9830
  function documentPathColumns(field, alias, object) {
10510
9831
  if (field.type !== "document" || !field.columnName) return [];
10511
9832
  const column = `${alias}.${ident(field.columnName)}`;
@@ -10627,23 +9948,82 @@ var CAPACITY_FIELDS = [
10627
9948
  name: "taken",
10628
9949
  label: "Taken",
10629
9950
  type: "number",
10630
- column: CAPACITY_COLUMNS.taken,
9951
+ column: CAPACITY_COLUMNS.taken,
9952
+ filterable: true,
9953
+ sortable: true,
9954
+ readOnly: true,
9955
+ description: "Places taken by paid orders."
9956
+ },
9957
+ {
9958
+ name: "available",
9959
+ label: "Available",
9960
+ type: "number",
9961
+ column: CAPACITY_COLUMNS.available,
9962
+ filterable: true,
9963
+ sortable: true,
9964
+ readOnly: true,
9965
+ description: "Places left (the record's and its pool's, whichever is fewer). Empty: unlimited."
9966
+ }
9967
+ ];
9968
+ var ALLOWANCE_COLUMNS = { used: "_alw_used", left: "_alw_left" };
9969
+ var ALLOWANCE_FIELDS = [
9970
+ {
9971
+ name: "used",
9972
+ label: "Used",
9973
+ type: "number",
9974
+ column: ALLOWANCE_COLUMNS.used,
10631
9975
  filterable: true,
10632
9976
  sortable: true,
10633
9977
  readOnly: true,
10634
- description: "Places taken by paid orders."
9978
+ description: "Uses spent in the current period (this week, this month, or in all)."
10635
9979
  },
10636
9980
  {
10637
- name: "available",
10638
- label: "Available",
9981
+ name: "left",
9982
+ label: "Left",
10639
9983
  type: "number",
10640
- column: CAPACITY_COLUMNS.available,
9984
+ column: ALLOWANCE_COLUMNS.left,
10641
9985
  filterable: true,
10642
9986
  sortable: true,
10643
9987
  readOnly: true,
10644
- description: "Places left (the record's and its pool's, whichever is fewer). Empty: unlimited."
9988
+ description: "Uses that can be spent now in the current period. Empty: unlimited."
10645
9989
  }
10646
9990
  ];
9991
+ function allowanceDefinition(object) {
9992
+ const declared = object.definition.allowance;
9993
+ if (!declared) return void 0;
9994
+ const qualify = (target) => target.includes(".") ? target : `${object.extensionId}.${target}`;
9995
+ if ("holds" in declared) {
9996
+ const h = declared.holds;
9997
+ return {
9998
+ kind: "holder",
9999
+ person: h.person,
10000
+ uses: h.uses,
10001
+ per: typeof h.per === "string" ? { fixed: h.per } : { field: h.per.field },
10002
+ spendsOn: spendsOnList(h).map((s) => ({
10003
+ object: qualify(s.object),
10004
+ when: (s.when ?? []).map((c) => ({ ...c }))
10005
+ })),
10006
+ ...h.from ? { from: h.from } : {},
10007
+ ...h.until ? { until: h.until } : {},
10008
+ live: h.live ? [...h.live] : null,
10009
+ ...h.zone ? { zone: h.zone } : {},
10010
+ emptyIsUnlimited: h.emptyIsUnlimited === true
10011
+ };
10012
+ }
10013
+ const sp = declared.spends;
10014
+ return {
10015
+ kind: "spender",
10016
+ person: sp.person,
10017
+ holder: sp.holder,
10018
+ spendIn: [...sp.spendIn],
10019
+ returnIn: [...sp.returnIn],
10020
+ ...sp.at ? { at: sp.at } : {},
10021
+ copy: { ...sp.copy ?? {} },
10022
+ local: { ...sp.local ?? {} },
10023
+ ...sp.movedFrom ? { movedFrom: { ...sp.movedFrom } } : {},
10024
+ paidBy: [...sp.paidBy ?? []]
10025
+ };
10026
+ }
10647
10027
  function capacityDefinition(object, own) {
10648
10028
  const declared = object.definition.capacity;
10649
10029
  if (!declared) return void 0;
@@ -10657,6 +10037,44 @@ function capacityDefinition(object, own) {
10657
10037
  releaseOnRefund: declared.releaseOnRefund ?? true
10658
10038
  };
10659
10039
  }
10040
+ function claimsDefinition(object, own) {
10041
+ const declared = object.definition.claims;
10042
+ if (!declared) return {};
10043
+ const on = own.find((f) => f.localName === declared.on);
10044
+ if (!on?.definition.to) return {};
10045
+ return {
10046
+ claims: {
10047
+ on: on.name,
10048
+ object: on.definition.to,
10049
+ held: [...declared.held ?? []],
10050
+ confirmed: [...declared.confirmed ?? []]
10051
+ }
10052
+ };
10053
+ }
10054
+ function recurringDefinition(object) {
10055
+ const declared = object.definition.recurring;
10056
+ if (!declared) return {};
10057
+ const named = (local) => `${object.extensionId}.${local}`;
10058
+ return {
10059
+ recurring: {
10060
+ generates: named(declared.generates),
10061
+ link: declared.link,
10062
+ rule: { ...declared.rule },
10063
+ into: { ...declared.into },
10064
+ copy: { ...declared.copy ?? {} },
10065
+ cancel: declared.cancel,
10066
+ ...declared.ended ? { ended: { field: declared.ended.field, in: [...declared.ended.in] } } : {},
10067
+ ...declared.closures ? { closures: { ...declared.closures, object: named(declared.closures.object) } } : {},
10068
+ horizonDays: declared.horizonDays ?? RECURRING_HORIZON_DAYS,
10069
+ ...declared.horizonAtLeast ? {
10070
+ horizonAtLeast: {
10071
+ object: named(declared.horizonAtLeast.object),
10072
+ field: declared.horizonAtLeast.field
10073
+ }
10074
+ } : {}
10075
+ }
10076
+ };
10077
+ }
10660
10078
  function sellableDefinition(object, own) {
10661
10079
  const declared = object.definition.sellable;
10662
10080
  if (!declared) return void 0;
@@ -10683,6 +10101,31 @@ function sellableDefinition(object, own) {
10683
10101
  set: { ...grants.set },
10684
10102
  void: grants.void
10685
10103
  }
10104
+ } : {},
10105
+ ...declared.tax ? {
10106
+ tax: {
10107
+ code: declared.tax.code,
10108
+ ...declared.tax.place ? {
10109
+ place: {
10110
+ ...declared.tax.place,
10111
+ // Fields of the object itself are named by their registry names; a related
10112
+ // record's own fields are named by their local names, which are the same.
10113
+ ...declared.tax.place.via ? { via: nameOf(declared.tax.place.via) } : {
10114
+ country: nameOf(declared.tax.place.country),
10115
+ region: opt(declared.tax.place.region),
10116
+ postcode: opt(declared.tax.place.postcode),
10117
+ city: opt(declared.tax.place.city),
10118
+ line1: opt(declared.tax.place.line1)
10119
+ }
10120
+ }
10121
+ } : {}
10122
+ }
10123
+ } : {},
10124
+ ...declared.recurring ? {
10125
+ recurring: {
10126
+ interval: declared.recurring.interval,
10127
+ trialDays: opt(declared.recurring.trialDays)
10128
+ }
10686
10129
  } : {}
10687
10130
  };
10688
10131
  }
@@ -10708,7 +10151,7 @@ function registryField(field, object) {
10708
10151
  ...def.step !== void 0 ? { step: def.step } : {},
10709
10152
  ...field.type === "document" && def.schema ? { document: { schema: def.schema, maxBytes: def.maxBytes } } : {},
10710
10153
  // Rich text is a document with the platform's schema (ADR 0440).
10711
- ...field.type === "richText" || field.type === "image" ? {
10154
+ ...field.type === "richText" || field.type === "image" || field.type === "video" ? {
10712
10155
  document: {
10713
10156
  schema: documentSchemaOf(def),
10714
10157
  maxBytes: documentMaxBytesOf(def)
@@ -10788,6 +10231,7 @@ function buildRegistry(state) {
10788
10231
  );
10789
10232
  const capacity = capacityDefinition(object, own);
10790
10233
  const sellable = sellableDefinition(object, own);
10234
+ const allowance = allowanceDefinition(object);
10791
10235
  const publishable = object.definition.publishable;
10792
10236
  const fields = [
10793
10237
  ...SYSTEM_FIELDS,
@@ -10795,6 +10239,7 @@ function buildRegistry(state) {
10795
10239
  ...foreign.map((f) => registryField(f, object.name)),
10796
10240
  ...[...own, ...foreign].flatMap((f) => documentPathFields(f, object.name)),
10797
10241
  ...capacity ? CAPACITY_FIELDS : [],
10242
+ ...allowance?.kind === "holder" ? ALLOWANCE_FIELDS : [],
10798
10243
  ...publishable ? PUBLISHED_FIELDS : []
10799
10244
  ];
10800
10245
  map.set(object.name, {
@@ -10813,12 +10258,17 @@ function buildRegistry(state) {
10813
10258
  ...object.definition.stages ? { stages: object.definition.stages } : {},
10814
10259
  ...capacity ? { capacity } : {},
10815
10260
  ...sellable ? { sellable } : {},
10261
+ ...allowance ? { allowance } : {},
10816
10262
  ...object.definition.states ? { states: object.definition.states } : {},
10263
+ ...claimsDefinition(object, own),
10264
+ ...object.definition.unique?.length ? { unique: object.definition.unique } : {},
10265
+ ...recurringDefinition(object),
10817
10266
  ...object.definition.owner ? { ownerField: object.definition.owner } : {},
10818
10267
  ...object.definition.customer ? { customer: object.definition.customer } : {},
10819
10268
  ...object.definition.public ? { public: object.definition.public } : {},
10820
10269
  ...object.definition.signedIn ? { signedIn: object.definition.signedIn } : {},
10821
10270
  ...object.definition.customerVia ? { customerVia: object.definition.customerVia } : {},
10271
+ ...object.definition.access ? { access: object.definition.access } : {},
10822
10272
  ...publishable ? {
10823
10273
  publishable: {
10824
10274
  content: [...publishable.content],
@@ -10870,6 +10320,21 @@ async function refreshSchemaRegistry(db) {
10870
10320
  );
10871
10321
  cached = { stamp, objects, storage, tables };
10872
10322
  setExtensionObjects(objects);
10323
+ const keys = /* @__PURE__ */ new Set();
10324
+ for (const object of state.objects) {
10325
+ if (object.status !== "active") continue;
10326
+ for (const rule of object.definition.unique ?? []) {
10327
+ const columns = rule.fields.map(
10328
+ (local) => state.fields.find(
10329
+ (f) => f.object === object.name && f.extensionId === object.extensionId && f.localName === local && f.status === "active"
10330
+ )?.columnName
10331
+ );
10332
+ if (columns.every(Boolean)) {
10333
+ keys.add(columns.map((c) => `${object.tableName}.${c}`).join(", "));
10334
+ }
10335
+ }
10336
+ }
10337
+ setDeclaredUniqueKeys(keys);
10873
10338
  }
10874
10339
  function mergeOptions(declared, edited) {
10875
10340
  if (!edited) return [...declared];
@@ -10908,320 +10373,559 @@ function withEditedOptions(state, overrides) {
10908
10373
  };
10909
10374
  }
10910
10375
 
10911
- // ../core/src/integrations/catalogue.ts
10912
- var CATALOGUE = [
10913
- {
10914
- vendor: "google",
10915
- title: "Google Workspace",
10916
- description: "Gmail, Google Calendar and Drive. Syncs mail and meetings onto timelines.",
10917
- connect: "oauth",
10918
- scopes: ["personal", "org"],
10919
- sync: {
10920
- mail: ["https://mail.google.com/"],
10921
- calendar: ["https://calendar.google.com/"]
10376
+ // ../core/src/principals.ts
10377
+ var RISK_CLASSES = [
10378
+ "read",
10379
+ "write",
10380
+ "bulk-write",
10381
+ "destructive",
10382
+ "schema",
10383
+ "extension",
10384
+ "outbound"
10385
+ ];
10386
+ var ACTORS = ["human", "assistant", "mcp", "automation", "extension"];
10387
+ var originSchema = external_exports.object({
10388
+ // `client`: a client app or site: a customer or the public (stage 22), or any caller of the
10389
+ // HTTP surface (stage 23).
10390
+ surface: external_exports.enum(["ui", "mcp", "automation", "system", "extension", "assistant", "client"]),
10391
+ /** The MCP client id (OAuth client_id). */
10392
+ clientId: external_exports.string().optional(),
10393
+ /** The MCP client's display name, as registered (self-asserted). */
10394
+ clientName: external_exports.string().optional(),
10395
+ /**
10396
+ * The MCP session: the connected app (cap_…) the token belongs to (ADR 0032). Pending actions
10397
+ * group by it, and only it sees their simulated state.
10398
+ */
10399
+ // For the in-app assistant (surface `assistant`, ADR 0340) the session is the thread (ath_…).
10400
+ sessionId: external_exports.string().optional(),
10401
+ /** The automation id (`<extension>.<key>`, or a system job such as `trash.purge`). */
10402
+ automationId: external_exports.string().optional(),
10403
+ /** An automation run (arn_…): its pending actions go in one change set per run (ADR 0130). */
10404
+ runId: external_exports.string().optional(),
10405
+ /** Cascade tags (ADR 0130): how deep in an automation cascade this call is, and its chain. */
10406
+ depth: external_exports.number().int().min(0).optional(),
10407
+ chain: external_exports.array(external_exports.string()).max(10).optional(),
10408
+ rootEventId: external_exports.string().optional(),
10409
+ /** Test mode: the call is simulated, nothing is written (ADR 0133). */
10410
+ test: external_exports.boolean().optional(),
10411
+ /** The extension whose code made the call (actor `extension`). */
10412
+ extensionId: external_exports.string().optional(),
10413
+ /** The agent that made the call (job_…, ADR 0344). Its session is `job:<id>`. */
10414
+ jobId: external_exports.string().optional()
10415
+ });
10416
+ var ROLES = ["admin", "member", "viewer"];
10417
+ var PERMISSIONS = [
10418
+ "records:read",
10419
+ "records:write",
10420
+ "records:erase",
10421
+ "audit:read",
10422
+ "users:manage",
10423
+ "policy:manage",
10424
+ "extensions:manage",
10425
+ "integrations:manage",
10426
+ "settings:manage",
10427
+ "orders:refund",
10428
+ "records:publish",
10429
+ "subscriptions:manage"
10430
+ ];
10431
+ var ROLE_PERMISSIONS = {
10432
+ viewer: ["records:read"],
10433
+ member: ["records:read", "records:write"],
10434
+ admin: PERMISSIONS
10435
+ };
10436
+ function roleHasPermission(role, permission) {
10437
+ return ROLE_PERMISSIONS[role].includes(permission);
10438
+ }
10439
+ var GRANTABLE_PERMISSIONS = [
10440
+ "records:publish",
10441
+ "orders:refund",
10442
+ "subscriptions:manage"
10443
+ ];
10444
+ function holdsPermission(user, grants, permission) {
10445
+ return roleHasPermission(user.role, permission) || GRANTABLE_PERMISSIONS.includes(permission) && (grants ?? []).includes(permission);
10446
+ }
10447
+ var MCP_SCOPES = ["read", "write", "admin"];
10448
+ function grantableScopes(role) {
10449
+ return role === "admin" ? [...MCP_SCOPES] : ["read", "write"];
10450
+ }
10451
+ function staffPrincipal(user) {
10452
+ return Object.freeze({ kind: "staff", userId: user.id, role: user.role });
10453
+ }
10454
+ var OUTSIDE_ACTORS = ["customer", "public"];
10455
+ var ALL_ACTORS = [...ACTORS, ...OUTSIDE_ACTORS];
10456
+
10457
+ // ../core/src/records/columns.ts
10458
+ function viewColumnOf(field) {
10459
+ if (field.column) return field.column;
10460
+ const match = /json_each\(r2\.([a-z0-9_]+)\)/.exec(field.related?.from ?? "");
10461
+ return match?.[1] ?? null;
10462
+ }
10463
+
10464
+ // ../core/src/visibility/public.ts
10465
+ function publicProblems(object) {
10466
+ const problems = readProblems(object, "public");
10467
+ if (object.public && object.customer) {
10468
+ problems.unshift("an object declares customer or public, not both");
10469
+ }
10470
+ if (object.public && object.publishable) problems.push(...contentProblems(object));
10471
+ return problems;
10472
+ }
10473
+ function contentProblems(object) {
10474
+ const declared = object.public;
10475
+ const publishable = object.publishable;
10476
+ if (!declared || !publishable) return [];
10477
+ const problems = [];
10478
+ if (!publishable.slug) {
10479
+ problems.push("a publishable object the public reads names its slug (publishable.slug)");
10480
+ } else if (!declared.read.includes(publishable.slug)) {
10481
+ problems.push(`public.read lists the slug "${publishable.slug}": it is how the public reads`);
10482
+ }
10483
+ const content = new Set(publishable.content);
10484
+ for (const name of declared.read) {
10485
+ const field = object.fields.find((f) => f.name === name);
10486
+ if (field?.fieldType === "formula") {
10487
+ problems.push(`public.read lists "${name}", a formula of the working copy`);
10922
10488
  }
10923
- },
10924
- {
10925
- vendor: "microsoft",
10926
- title: "Microsoft 365",
10927
- description: "Outlook mail, Outlook Calendar and SharePoint. Syncs mail and meetings.",
10928
- connect: "oauth",
10929
- scopes: ["personal", "org"],
10930
- sync: {
10931
- mail: ["https://outlook.office.com/"],
10932
- calendar: ["https://outlook.office.com/calendar"]
10489
+ const path = field?.options?.documentPath;
10490
+ if (path && !content.has(path.field)) {
10491
+ problems.push(`public.read lists "${name}", a path of a document that is not content`);
10933
10492
  }
10934
- },
10935
- {
10936
- vendor: "slack",
10937
- title: "Slack",
10938
- description: "Read channels and threads, and post messages and DMs (with the Slack posting gatekeeper, through the same Slack app).",
10939
- connect: "oauth",
10940
- scopes: ["personal", "org"],
10941
- companion: "slack-post"
10942
- },
10943
- {
10944
- vendor: "slack-post",
10945
- title: "Slack (post messages)",
10946
- description: "Post to channels and send DMs as the CRM's Slack bot.",
10947
- connect: "oauth",
10948
- scopes: ["org"]
10949
- },
10950
- {
10951
- vendor: "mcp",
10952
- title: "MCP server",
10953
- description: "Connect any remote MCP server and use its tools through a gatekeeper.",
10954
- connect: "oauth",
10955
- scopes: ["personal", "org"]
10956
- },
10957
- {
10958
- vendor: "email",
10959
- title: "Inbound email",
10960
- description: "Receive mail at a CRM address (Cloudflare Email Routing).",
10961
- connect: "oauth",
10962
- scopes: ["org"]
10963
- },
10964
- {
10965
- vendor: "email-send",
10966
- title: "Email sending",
10967
- description: "Send email from the CRM's own addresses (Cloudflare Email Service).",
10968
- connect: "auto",
10969
- scopes: ["org"]
10970
- },
10971
- {
10972
- vendor: "zoominfo",
10973
- title: "ZoomInfo",
10974
- description: "Manual, approved 'Enrich now' on people and organisations. No polling.",
10975
- connect: "oauth",
10976
- scopes: ["org"]
10977
- },
10978
- {
10979
- vendor: "websearch",
10980
- title: "Web search",
10981
- description: "Search the public web (Cloudflare Web Search). Searches are observations.",
10982
- connect: "auto",
10983
- scopes: ["personal", "org"],
10984
- singleton: true
10985
- },
10986
- {
10987
- vendor: "webhook",
10988
- title: "Inbound webhooks",
10989
- description: "External systems post signed events to the CRM. Bad signatures are rejected; good ones become typed events for automations.",
10990
- connect: "auto",
10991
- scopes: ["org"]
10992
- },
10993
- {
10994
- vendor: "payments",
10995
- title: "Payments",
10996
- description: "Take payment for orders on the provider's own page (Stripe), into your own account. Keys stay in the gatekeeper; card details never reach the CRM.",
10997
- connect: "auto",
10998
- scopes: ["org"]
10999
- },
11000
- {
11001
- vendor: "fake",
11002
- title: "Fake provider (development)",
11003
- description: "A fake OAuth provider with a mailbox and calendar, for development and tests.",
11004
- connect: "oauth",
11005
- scopes: ["personal", "org"],
11006
- sync: { mail: ["fake://mailbox/"], calendar: ["fake://calendar/"] },
11007
- devOnly: true
11008
10493
  }
11009
- ];
11010
- function catalogueEntry(vendor) {
11011
- return CATALOGUE.find((entry) => entry.vendor === vendor);
11012
- }
11013
- function syncKindOf(vendor, url) {
11014
- const entry = catalogueEntry(vendor);
11015
- for (const kind of ["calendar", "mail"]) {
11016
- if (entry?.sync?.[kind]?.some((prefix) => url.startsWith(prefix))) return kind;
10494
+ if (object.customer || object.customerVia) {
10495
+ problems.push("a publishable object the public reads declares no customer or customerVia");
11017
10496
  }
11018
- return null;
10497
+ return problems;
11019
10498
  }
11020
-
11021
- // ../core/src/automations/bindings.ts
11022
- var WAITING_FOR_CONNECTIONS = "Waiting for connections";
11023
- var CONNECTION_REVOKED_PREFIX = "Connection revoked";
11024
- function toBinding(row) {
10499
+ function signedInProblems(object) {
10500
+ const declared = object.signedIn;
10501
+ if (!declared) return [];
10502
+ const problems = readProblems(object, "signedIn");
10503
+ if (object.public) problems.unshift("an object declares public or signedIn, not both");
10504
+ if (object.customer) {
10505
+ for (const name of declared.read) {
10506
+ if (!object.customer.read.includes(name)) {
10507
+ problems.push(`signedIn.read lists "${name}", which customer.read does not`);
10508
+ }
10509
+ }
10510
+ }
10511
+ return problems;
10512
+ }
10513
+ function readProblems(object, key) {
10514
+ const declared = object[key];
10515
+ if (!declared) return [];
10516
+ const problems = [];
10517
+ const field = (o, name) => o.fields.find((f) => f.name === name);
10518
+ if (new Set(declared.read).size !== declared.read.length) {
10519
+ problems.push(`${key}.read lists a field twice`);
10520
+ }
10521
+ for (const name of declared.read) {
10522
+ const f = field(object, name);
10523
+ if (!f) problems.push(`${key}.read lists "${name}", which is not a field`);
10524
+ else if (!viewColumnOf(f)) problems.push(`${key}.read lists "${name}", which has no column`);
10525
+ }
10526
+ const condition = resolveCondition(object, declared, key);
10527
+ if (typeof condition === "string") problems.push(condition);
10528
+ return problems;
10529
+ }
10530
+ function resolveCondition(object, declared, key = "public") {
10531
+ const { when } = declared;
10532
+ if (!when) return null;
10533
+ const fieldOf = (o, name) => o.fields.find((f) => f.name === name);
10534
+ if (when.via === void 0) {
10535
+ const own = fieldOf(object, when.field);
10536
+ if (!own || own.fieldType !== "select" || !own.column) {
10537
+ return `${key}.when.field "${when.field}" must be a select field`;
10538
+ }
10539
+ return { column: own.column, values: [...when.in] };
10540
+ }
10541
+ const via = fieldOf(object, when.via);
10542
+ const to = via?.options?.to;
10543
+ const target = to ? getObject(to) : void 0;
10544
+ if (!via || via.fieldType !== "relation" || via.options?.many || !via.column || !target) {
10545
+ return `${key}.when.via "${when.via}" must be a relation to one record`;
10546
+ }
10547
+ const tested = fieldOf(target, when.field);
10548
+ if (!tested || tested.fieldType !== "select" || !tested.column) {
10549
+ return `${key}.when.field "${when.field}" must be a select field of ${target.name}`;
10550
+ }
11025
10551
  return {
11026
- automationId: row.automation_id,
11027
- slot: row.slot,
11028
- gatekeeper: row.gatekeeper,
11029
- purpose: row.purpose,
11030
- connectionId: row.connection_id,
11031
- boundBy: row.bound_by,
11032
- boundAt: row.bound_at,
11033
- revokedAt: row.revoked_at,
11034
- revokedBy: row.revoked_by,
11035
- revokeReason: row.revoke_reason
10552
+ column: via.column,
10553
+ values: [...when.in],
10554
+ via: { source: target.source, column: tested.column }
11036
10555
  };
11037
10556
  }
11038
- function declaredConnections(spec) {
11039
- return spec.connections ?? [];
10557
+ function publicScope(object) {
10558
+ return readScope(object, "public");
11040
10559
  }
11041
- function connectionServes(vendor, gatekeeper) {
11042
- return vendor === gatekeeper || catalogueEntry(vendor)?.companion === gatekeeper;
10560
+ function signedInScope(object) {
10561
+ return readScope(object, "signedIn");
11043
10562
  }
11044
- async function loadBindings(db, automationIds) {
11045
- if (!automationIds.length) return [];
11046
- const rows = await db.selectFrom("core_automation_binding").selectAll().where("automation_id", "in", jsonList([...new Set(automationIds)])).execute();
11047
- return rows.map(toBinding);
10563
+ function readScope(object, key) {
10564
+ const declared = object[key];
10565
+ if (!declared) return null;
10566
+ const problems = key === "public" ? publicProblems(object) : signedInProblems(object);
10567
+ if (problems.length) {
10568
+ throw new Error(`${object.name}: invalid ${key} declaration: ${problems.join("; ")}`);
10569
+ }
10570
+ const readable = /* @__PURE__ */ new Set(["id", ...declared.read]);
10571
+ const fields = object.fields.filter((f) => readable.has(f.name));
10572
+ const columns = [...new Set(fields.map((f) => viewColumnOf(f)))];
10573
+ return {
10574
+ kind: "public",
10575
+ from: key,
10576
+ fields,
10577
+ columns,
10578
+ condition: resolveCondition(object, declared, key),
10579
+ declaration: declared,
10580
+ source: key === "public" && object.publishable ? liveViewOf(object.name) : object.source
10581
+ };
11048
10582
  }
11049
- function unboundSlots(spec, bindings) {
11050
- return declaredConnections(spec).filter(
11051
- (c) => !bindings.some((b) => b.slot === c.id && b.revokedAt === null)
11052
- );
10583
+ function publicObject(object, scope) {
10584
+ const names = new Set(scope.fields.map((f) => f.name));
10585
+ const sort = names.has(object.defaultSort.field) ? object.defaultSort : { field: "id", direction: "asc" };
10586
+ return {
10587
+ name: object.name,
10588
+ label: object.label,
10589
+ source: object.source,
10590
+ fields: scope.fields,
10591
+ defaultSort: sort,
10592
+ ...object.plural ? { plural: object.plural } : {},
10593
+ ...object.extension ? { extension: object.extension } : {},
10594
+ ...object.titleField && names.has(object.titleField) ? { titleField: object.titleField } : {},
10595
+ ...scope.from === "public" ? { public: scope.declaration } : { signedIn: scope.declaration }
10596
+ };
11053
10597
  }
11054
- async function revokeBindingsPlan(db, target, input) {
11055
- let connectionIds;
11056
- if ("connectionId" in target) {
11057
- connectionIds = [target.connectionId];
11058
- } else {
11059
- const owned = await db.selectFrom("core_integration_connection").select("id").where("owner_user_id", "=", target.ownerUserId).execute();
11060
- connectionIds = owned.map((r) => r.id);
11061
- }
11062
- if (!connectionIds.length) return { statements: [], automationIds: [], revoked: 0 };
11063
- const live = await db.selectFrom("core_automation_binding as b").innerJoin("core_automations as a", "a.id", "b.automation_id").select(["b.automation_id", "b.slot", "a.label", "a.paused_reason"]).where("b.connection_id", "in", jsonList(connectionIds)).where("b.revoked_at", "is", null).execute();
11064
- if (!live.length) return { statements: [], automationIds: [], revoked: 0 };
11065
- const statements = [
11066
- db.updateTable("core_automation_binding").set({ revoked_at: input.now, revoked_by: input.by, revoke_reason: input.reason }).where("connection_id", "in", jsonList(connectionIds)).where("revoked_at", "is", null)
11067
- ];
11068
- const automations = /* @__PURE__ */ new Map();
11069
- for (const row of live) {
11070
- automations.set(row.automation_id, { label: row.label, paused: row.paused_reason !== null });
10598
+
10599
+ // ../core/src/visibility/customer.ts
10600
+ function customerProblems(object) {
10601
+ const declared = object.customer;
10602
+ if (!declared) return [];
10603
+ const problems = [];
10604
+ const field = (name) => object.fields.find((f) => f.name === name);
10605
+ const owner = field(declared.field);
10606
+ if (!owner?.column) {
10607
+ problems.push(`customer.field "${declared.field}" is not a single-valued field`);
10608
+ } else if (object.name === "person") {
10609
+ if (declared.field !== "id")
10610
+ problems.push("a person is their own customer: customer.field is id");
10611
+ } else if (owner.fieldType !== "relation" || owner.options?.to !== "person" || owner.options.many) {
10612
+ problems.push(`customer.field "${declared.field}" must be a relation to one person`);
10613
+ }
10614
+ for (const [key, names] of [
10615
+ ["read", declared.read],
10616
+ ["write", declared.write]
10617
+ ]) {
10618
+ if (new Set(names).size !== names.length) problems.push(`customer.${key} lists a field twice`);
10619
+ for (const name of names) {
10620
+ const f = field(name);
10621
+ if (!f) problems.push(`customer.${key} lists "${name}", which is not a field`);
10622
+ else if (!viewColumnOf(f))
10623
+ problems.push(`customer.${key} lists "${name}", which has no column`);
10624
+ }
11071
10625
  }
11072
- const pauseReason = `${CONNECTION_REVOKED_PREFIX}: ${input.reason}`;
11073
- statements.push(
11074
- db.updateTable("core_automations").set({ paused_reason: pauseReason, paused_at: input.now, updated_at: input.now }).where("id", "in", jsonList([...automations.keys()])).where(sql`(paused_reason IS NULL OR paused_reason = ${WAITING_FOR_CONNECTIONS})`)
11075
- );
11076
- for (const [id, a] of automations) {
11077
- const plan = await notifyStatements(
11078
- db,
11079
- {
11080
- to: [{ role: "admin" }],
11081
- type: "automation.paused",
11082
- title: `\u201C${a.label}\u201D was paused`,
11083
- body: `${input.reason}. Bind another connection on the automation page, then enable it again.`,
11084
- link: { kind: "automation", automationId: id },
11085
- dedupeKey: `revoked:${id}:${input.now}`,
11086
- source: { actor: "automation", automationId: id }
11087
- },
11088
- input.now
11089
- );
11090
- statements.push(...plan.statements);
11091
- }
11092
- return { statements, automationIds: [...automations.keys()], revoked: live.length };
11093
- }
11094
-
11095
- // ../core/src/automations/types.ts
11096
- var MAX_CASCADE_DEPTH = 3;
11097
- var EVENT_CHANGES_PER_MESSAGE = 100;
11098
- var QUEUE_MESSAGE_MAX_BYTES = 12e4;
11099
- var AUTOMATION_SETTINGS = {
11100
- /** boolean. Human admins only (automation.killSwitch). Pauses every automation at once. */
11101
- killSwitch: "automations_kill_switch",
11102
- /** IANA timezone schedules and date-relative triggers are evaluated in. Default "UTC". */
11103
- timezone: "automation_timezone",
11104
- /** Seconds within which `updated` events for one record coalesce. Default 30. */
11105
- debounceSeconds: "automation_debounce_seconds"
11106
- };
11107
- var DEFAULT_RAILS = {
11108
- maxRunsPerMinute: 60,
11109
- maxWritesPerHour: 500,
11110
- debounceSeconds: 30
11111
- };
11112
- var RUN_STATUSES = [
11113
- /** Row written, Workflow not yet running. */
11114
- "queued",
11115
- "running",
11116
- /** In a step.sleep or step.waitForEvent. */
11117
- "waiting",
11118
- /** Paused on a pending action (review) until a person decides. */
11119
- "review",
11120
- "completed",
11121
- "failed",
11122
- /** Stopped: rejected (onRejected stop), cancelled by a person, or the kill switch. */
11123
- "cancelled",
11124
- /** Its pending action expired. */
11125
- "expired",
11126
- /** Not started: a rail dropped it (depth, cycle, budget, rate, paused, kill switch). */
11127
- "skipped"
11128
- ];
11129
- var DRAFT_TARGET_ERRORS = ["unknown_automation", "evaluate_failed"];
11130
-
11131
- // ../core/src/automations/registry.ts
11132
- function triggerObject(spec) {
11133
- const t = spec.trigger;
11134
- return "object" in t && typeof t.object === "string" ? t.object : null;
11135
- }
11136
- function automationSyncStatements(db, input) {
11137
- const statements = [];
11138
- const ids = [];
11139
- for (const [key, spec] of Object.entries(input.automations)) {
11140
- const id = `${input.extensionId}.${key}`;
11141
- ids.push(id);
11142
- const values = {
11143
- label: spec.label,
11144
- trigger_type: spec.trigger.type,
11145
- trigger_object: triggerObject(spec),
11146
- spec: JSON.stringify(spec),
11147
- commit_oid: input.commit,
11148
- removed_at: null,
11149
- updated_at: input.now
11150
- };
11151
- statements.push(
11152
- db.insertInto("core_automations").values({
11153
- id,
11154
- extension_id: input.extensionId,
11155
- key,
11156
- ...values,
11157
- // Shipped turned off (ADR 0246) until a person turns it on.
11158
- enabled: spec.enabled === false ? 0 : 1,
11159
- // An automation that needs connections waits until a person binds them (ADR 0170).
11160
- paused_reason: spec.connections?.length ? WAITING_FOR_CONNECTIONS : null,
11161
- paused_at: spec.connections?.length ? input.now : null,
11162
- created_at: input.now
11163
- }).onConflict((oc) => oc.column("id").doUpdateSet(values))
11164
- );
10626
+ for (const name of declared.write) {
10627
+ if (name === declared.field) {
10628
+ problems.push("customer.write may not list the customer field: it is always the caller");
10629
+ }
10630
+ if (name === "id") problems.push("customer.write may not list id");
10631
+ if (field(name)?.readOnly) problems.push(`customer.write lists "${name}", which is read-only`);
10632
+ if (!declared.read.includes(name)) {
10633
+ problems.push(`customer.write lists "${name}", which customer.read does not`);
10634
+ }
11165
10635
  }
11166
- let removed = db.updateTable("core_automations").set({ removed_at: input.now, updated_at: input.now }).where("extension_id", "=", input.extensionId).where("removed_at", "is", null);
11167
- if (ids.length) removed = removed.where("id", "not in", jsonList(ids));
11168
- statements.push(removed);
11169
- return statements;
10636
+ return problems;
11170
10637
  }
11171
- function parseSpec(json) {
11172
- try {
11173
- const parsed = automationManifestSchema.safeParse(JSON.parse(json));
11174
- return parsed.success ? parsed.data : null;
11175
- } catch {
11176
- return null;
11177
- }
11178
- }
11179
- async function loadAutomationSettings(db) {
11180
- const rows = await db.selectFrom("core_settings").select(["key", "value"]).where("key", "in", [
11181
- AUTOMATION_SETTINGS.killSwitch,
11182
- AUTOMATION_SETTINGS.timezone,
11183
- AUTOMATION_SETTINGS.debounceSeconds
11184
- ]).execute();
11185
- const value = (key) => {
11186
- const row = rows.find((r) => r.key === key);
11187
- if (!row) return void 0;
11188
- try {
11189
- return JSON.parse(row.value);
11190
- } catch {
11191
- return void 0;
11192
- }
10638
+ function customerScope(object, personId) {
10639
+ const declared = object.customer;
10640
+ if (!declared) return null;
10641
+ const problems = customerProblems(object);
10642
+ if (problems.length) {
10643
+ throw new Error(`${object.name}: invalid customer declaration: ${problems.join("; ")}`);
10644
+ }
10645
+ const owner = object.fields.find((f) => f.name === declared.field);
10646
+ const readable = /* @__PURE__ */ new Set(["id", ...declared.read]);
10647
+ const fields = object.fields.filter((f) => readable.has(f.name));
10648
+ const columns = [...new Set(fields.map((f) => viewColumnOf(f)))];
10649
+ const shared = sharedPart(object);
10650
+ return {
10651
+ kind: "customer",
10652
+ personId,
10653
+ column: owner.column,
10654
+ fields,
10655
+ columns,
10656
+ writable: new Set(declared.write),
10657
+ declaration: declared,
10658
+ ...shared ? { shared } : {}
10659
+ };
10660
+ }
10661
+ function sharedPart(object) {
10662
+ const declared = object.signedIn;
10663
+ if (!declared) return void 0;
10664
+ const problems = signedInProblems(object);
10665
+ if (problems.length) {
10666
+ throw new Error(`${object.name}: invalid signedIn declaration: ${problems.join("; ")}`);
10667
+ }
10668
+ const readable = /* @__PURE__ */ new Set(["id", ...declared.read]);
10669
+ const columns = new Set(
10670
+ object.fields.filter((f) => readable.has(f.name)).map((f) => viewColumnOf(f))
10671
+ );
10672
+ return {
10673
+ condition: resolveCondition(object, declared, "signedIn"),
10674
+ columns
11193
10675
  };
11194
- const tz = value(AUTOMATION_SETTINGS.timezone);
11195
- const debounce = value(AUTOMATION_SETTINGS.debounceSeconds);
10676
+ }
10677
+ function customerObject(object, scope) {
10678
+ const names = new Set(scope.fields.map((f) => f.name));
10679
+ const sort = names.has(object.defaultSort.field) ? object.defaultSort : { field: "id", direction: "asc" };
11196
10680
  return {
11197
- // Engaged only when the stored value is exactly true.
11198
- killSwitch: value(AUTOMATION_SETTINGS.killSwitch) === true,
11199
- timezone: typeof tz === "string" && isTimeZone(tz) ? tz : "UTC",
11200
- debounceSeconds: typeof debounce === "number" && debounce >= 0 ? debounce : DEFAULT_RAILS.debounceSeconds
10681
+ name: object.name,
10682
+ label: object.label,
10683
+ source: object.source,
10684
+ fields: scope.fields,
10685
+ defaultSort: sort,
10686
+ ...object.plural ? { plural: object.plural } : {},
10687
+ ...object.extension ? { extension: object.extension } : {},
10688
+ ...object.titleField && names.has(object.titleField) ? { titleField: object.titleField } : {},
10689
+ customer: scope.declaration
11201
10690
  };
11202
10691
  }
11203
- function isTimeZone(tz) {
11204
- try {
11205
- new Intl.DateTimeFormat("en-US", { timeZone: tz });
11206
- return true;
11207
- } catch {
11208
- return false;
10692
+ function unknownObject(name) {
10693
+ return new ValidationError(`Unknown object "${name}"`, { object: name });
10694
+ }
10695
+
10696
+ // ../core/src/visibility/via.ts
10697
+ function customerViaProblems(object) {
10698
+ const declared = object.customerVia;
10699
+ if (!declared) return [];
10700
+ const problems = [];
10701
+ if (object.customer) {
10702
+ problems.push("an object that declares a customer cannot also declare customerVia");
11209
10703
  }
10704
+ if (new Set(declared.read).size !== declared.read.length) {
10705
+ problems.push("customerVia.read lists a field twice");
10706
+ }
10707
+ for (const name of declared.read) {
10708
+ const f = object.fields.find((field) => field.name === name);
10709
+ if (!f) problems.push(`customerVia.read lists "${name}", which is not a field`);
10710
+ else if (!viewColumnOf(f)) {
10711
+ problems.push(`customerVia.read lists "${name}", which has no column`);
10712
+ }
10713
+ }
10714
+ const link = resolveLink(object, declared);
10715
+ if (typeof link === "string") problems.push(link);
10716
+ return problems;
10717
+ }
10718
+ function resolveLink(object, declared) {
10719
+ const from = getObject(declared.from);
10720
+ if (!from || from.name === object.name || !object.extension) {
10721
+ return `customerVia.from "${declared.from}" must be another object of the same extension`;
10722
+ }
10723
+ if (from.extension !== object.extension) {
10724
+ return `customerVia.from "${declared.from}" must be an object of the same extension`;
10725
+ }
10726
+ const owner = from.customer ? from.fields.find((field) => field.name === from.customer?.field) : void 0;
10727
+ if (!from.customer || !owner?.column) {
10728
+ return `customerVia.from "${declared.from}" must declare a customer`;
10729
+ }
10730
+ const pointer = from.fields.find((field) => field.name === declared.field);
10731
+ if (!pointer?.column || pointer.fieldType !== "relation" || pointer.options?.many || pointer.options?.to !== object.name) {
10732
+ return `customerVia.field "${declared.field}" must be a relation of ${from.name} to one ${object.name}`;
10733
+ }
10734
+ if (!from.customer.read.includes(declared.field)) {
10735
+ return `customerVia.field "${declared.field}" must be one the customer of ${from.name} may read`;
10736
+ }
10737
+ return { source: from.source, pointer: pointer.column, owner: owner.column };
11210
10738
  }
11211
- function effectiveRails(spec, settings) {
10739
+ function customerViaScope(object, personId) {
10740
+ const declared = object.customerVia;
10741
+ if (!declared) return null;
10742
+ const problems = customerViaProblems(object);
10743
+ if (problems.length) {
10744
+ throw new Error(`${object.name}: invalid customerVia declaration: ${problems.join("; ")}`);
10745
+ }
10746
+ const shared = signedInScope(object) ?? publicScope(object);
10747
+ const reached = /* @__PURE__ */ new Set(["id", ...declared.read]);
10748
+ const open = new Set(shared ? ["id", ...shared.declaration.read] : []);
10749
+ const fields = object.fields.filter((f) => reached.has(f.name) || open.has(f.name));
10750
+ const columns = /* @__PURE__ */ new Map();
10751
+ for (const field of fields) {
10752
+ const column = viewColumnOf(field);
10753
+ const shownOn = !shared || reached.has(field.name) && open.has(field.name) ? "both" : reached.has(field.name) ? "reached" : "public";
10754
+ const before = columns.get(column);
10755
+ columns.set(column, before && before !== shownOn ? "both" : shownOn);
10756
+ }
11212
10757
  return {
11213
- maxRunsPerMinute: Math.min(
11214
- spec.rails?.maxRunsPerMinute ?? DEFAULT_RAILS.maxRunsPerMinute,
11215
- DEFAULT_RAILS.maxRunsPerMinute
11216
- ),
11217
- maxWritesPerHour: Math.min(
11218
- spec.rails?.maxWritesPerHour ?? DEFAULT_RAILS.maxWritesPerHour,
11219
- DEFAULT_RAILS.maxWritesPerHour
11220
- ),
11221
- debounceSeconds: spec.rails?.debounceSeconds ?? settings.debounceSeconds
10758
+ kind: "via",
10759
+ personId,
10760
+ fields,
10761
+ columns: [...columns].map(([column, shownOn]) => ({ column, shownOn })),
10762
+ link: resolveLink(object, declared),
10763
+ public: shared,
10764
+ declaration: declared
10765
+ };
10766
+ }
10767
+ function viaObject(object, scope) {
10768
+ const names = new Set(scope.fields.map((f) => f.name));
10769
+ const sort = names.has(object.defaultSort.field) ? object.defaultSort : { field: "id", direction: "asc" };
10770
+ return {
10771
+ name: object.name,
10772
+ label: object.label,
10773
+ source: object.source,
10774
+ fields: scope.fields,
10775
+ defaultSort: sort,
10776
+ ...object.plural ? { plural: object.plural } : {},
10777
+ ...object.extension ? { extension: object.extension } : {},
10778
+ ...object.titleField && names.has(object.titleField) ? { titleField: object.titleField } : {},
10779
+ customerVia: scope.declaration
11222
10780
  };
11223
10781
  }
11224
10782
 
10783
+ // ../core/src/visibility/index.ts
10784
+ var NONE = Object.freeze({ kind: "none" });
10785
+ function scopeOf(principal, given, throughOwnRecords = true) {
10786
+ const object = getObject(given.name) ?? given;
10787
+ switch (principal.kind) {
10788
+ case "staff":
10789
+ return { kind: "all" };
10790
+ case "customer":
10791
+ return customerScope(object, principal.personId) ?? (throughOwnRecords ? customerViaScope(object, principal.personId) : null) ?? signedInScope(object) ?? publicScope(object) ?? NONE;
10792
+ case "public":
10793
+ return publicScope(object) ?? NONE;
10794
+ default:
10795
+ return NONE;
10796
+ }
10797
+ }
10798
+ function visibleObject(ctx, object) {
10799
+ const definition = typeof object === "string" ? getObject(object) : object;
10800
+ if (!definition) throw unknownObject(String(object));
10801
+ const scope = scopeOf(ctx.principal, definition);
10802
+ switch (scope.kind) {
10803
+ case "all":
10804
+ return definition;
10805
+ case "customer":
10806
+ return customerObject(definition, scope);
10807
+ case "public":
10808
+ return publicObject(definition, scope);
10809
+ case "via":
10810
+ return viaObject(definition, scope);
10811
+ case "none":
10812
+ throw unknownObject(definition.name);
10813
+ }
10814
+ }
10815
+ var CORE_SOURCES = {
10816
+ person: { view: "rec_person", table: "core_person" },
10817
+ organisation: { view: "rec_organisation", table: "core_organisation" },
10818
+ activity: { view: "rec_activity", table: "core_activity" },
10819
+ task: { view: "rec_task", table: "core_task" }
10820
+ };
10821
+ function resolve(object) {
10822
+ if (typeof object !== "string") return object;
10823
+ const definition = getObject(object);
10824
+ if (!definition) throw new Error(`Unknown object ${object}`);
10825
+ return definition;
10826
+ }
10827
+ function visibleSource(ctx, object, alias) {
10828
+ const definition = resolve(object);
10829
+ return sourceOf(scopeOf(ctx.principal, definition), definition, alias ?? definition.source);
10830
+ }
10831
+ function buyableSource(ctx, object) {
10832
+ const definition = resolve(object);
10833
+ return sourceOf(scopeOf(ctx.principal, definition, false), definition, definition.source);
10834
+ }
10835
+ function reachedWhere(scope) {
10836
+ const { link } = scope;
10837
+ return sql`id IN (SELECT ${sql.ref(link.pointer)} FROM ${sql.table(link.source)} WHERE ${sql.ref(link.owner)} = ${scope.personId} AND ${sql.ref(link.pointer)} IS NOT NULL)`;
10838
+ }
10839
+ function sourceOf(scope, definition, name) {
10840
+ switch (scope.kind) {
10841
+ case "all":
10842
+ return sql`${sql.table(definition.source)}`.as(name);
10843
+ case "customer": {
10844
+ const own = sql`${sql.ref(scope.column)} = ${scope.personId}`;
10845
+ if (!scope.shared) {
10846
+ const columns2 = sql.join(scope.columns.map((column) => sql.ref(column)));
10847
+ return sql`(SELECT ${columns2} FROM ${sql.table(definition.source)} WHERE ${own})`.as(
10848
+ name
10849
+ );
10850
+ }
10851
+ const { shared } = scope;
10852
+ const columns = sql.join(
10853
+ scope.columns.map(
10854
+ (column) => shared.columns.has(column) ? sql.ref(column) : sql`CASE WHEN ${own} THEN ${sql.ref(column)} END AS ${sql.ref(column)}`
10855
+ )
10856
+ );
10857
+ return sql`(SELECT ${columns} FROM ${sql.table(definition.source)} WHERE ${own} OR ${conditionSql(shared.condition)})`.as(
10858
+ name
10859
+ );
10860
+ }
10861
+ case "public": {
10862
+ const columns = sql.join(scope.columns.map((column) => sql.ref(column)));
10863
+ return sql`(SELECT ${columns} FROM ${sql.table(scope.source)} WHERE ${conditionSql(scope.condition)})`.as(
10864
+ name
10865
+ );
10866
+ }
10867
+ case "via": {
10868
+ const reached = reachedWhere(scope);
10869
+ const shared = scope.public ? conditionSql(scope.public.condition) : null;
10870
+ const columns = sql.join(
10871
+ scope.columns.map(
10872
+ ({ column, shownOn }) => shownOn === "both" || !shared ? sql.ref(column) : sql`CASE WHEN ${shownOn === "reached" ? reached : shared} THEN ${sql.ref(column)} END AS ${sql.ref(column)}`
10873
+ )
10874
+ );
10875
+ const where = shared ? sql`(${reached}) OR (${shared})` : reached;
10876
+ return sql`(SELECT ${columns} FROM ${sql.table(definition.source)} WHERE ${where})`.as(
10877
+ name
10878
+ );
10879
+ }
10880
+ case "none":
10881
+ throw unknownObject(definition.name);
10882
+ }
10883
+ }
10884
+ function previewSource(object, id) {
10885
+ const definition = getObject(object.name) ?? object;
10886
+ const scope = publicScope(definition);
10887
+ if (!scope || !definition.publishable) throw unknownObject(definition.name);
10888
+ const columns = sql.join(scope.columns.map((column) => sql.ref(column)));
10889
+ return sql`(SELECT ${columns} FROM ${sql.table(definition.source)} WHERE id = ${id})`.as(
10890
+ definition.source
10891
+ );
10892
+ }
10893
+ function conditionSql(condition) {
10894
+ if (!condition) return sql`1 = 1`;
10895
+ const values = sql.join(condition.values.map((value) => sql`${value}`));
10896
+ return condition.via ? sql`${sql.ref(condition.column)} IN (SELECT id FROM ${sql.table(condition.via.source)} WHERE ${sql.ref(condition.via.column)} IN (${values}))` : sql`${sql.ref(condition.column)} IN (${values})`;
10897
+ }
10898
+ function ownedSource(ctx, object, alias) {
10899
+ const scope = scopeOf(ctx.principal, object);
10900
+ const name = alias ?? object.source;
10901
+ switch (scope.kind) {
10902
+ case "all":
10903
+ return sql`${sql.table(object.source)}`.as(name);
10904
+ case "customer":
10905
+ return sql`(SELECT id FROM ${sql.table(object.source)} WHERE ${sql.ref(scope.column)} = ${scope.personId})`.as(
10906
+ name
10907
+ );
10908
+ default:
10909
+ throw unknownObject(object.name);
10910
+ }
10911
+ }
10912
+ function visibleTable(ctx, object, alias) {
10913
+ const definition = resolve(object);
10914
+ const table = isCoreObject(definition.name) ? CORE_SOURCES[definition.name].table : Object.hasOwn(BASE_TABLES, definition.name) ? BASE_TABLES[definition.name] : objectTableOf(definition.name);
10915
+ if (!table) throw new Error(`${definition.name} has no record table`);
10916
+ const scope = scopeOf(ctx.principal, definition);
10917
+ switch (scope.kind) {
10918
+ case "all":
10919
+ return sql`${sql.table(ident(table))}`.as(alias ?? table);
10920
+ default:
10921
+ throw unknownObject(definition.name);
10922
+ }
10923
+ }
10924
+ function orgReader(db) {
10925
+ return { db, principal: ORG_PRINCIPAL };
10926
+ }
10927
+ var ORG_PRINCIPAL = staffPrincipal({ id: "system", role: "admin" });
10928
+
11225
10929
  export {
11226
10930
  isUndefined,
11227
10931
  isString,
@@ -11270,7 +10974,6 @@ export {
11270
10974
  DynamicTableBuilder,
11271
10975
  parseTable,
11272
10976
  sql,
11273
- CompiledQuery,
11274
10977
  OperationError,
11275
10978
  UnknownOperationError,
11276
10979
  ValidationError,
@@ -11283,49 +10986,10 @@ export {
11283
10986
  ConflictError,
11284
10987
  ConfigError,
11285
10988
  toOperationError,
11286
- TRASH_RETENTION_DAYS,
11287
- restorableUntil,
11288
- purgeCutoff,
11289
- BATCH_MAX,
11290
- jsonList,
11291
- chunk,
11292
- blankToNull,
11293
- assertUserExists,
11294
- withPrimary,
11295
- uniqueIds,
11296
- CATALOGUE,
11297
- catalogueEntry,
11298
- syncKindOf,
11299
- ID_PREFIXES,
11300
- newId,
11301
- toProvisionalId,
11302
- isProvisionalId,
11303
- findProvisionalIds,
11304
- findIds,
11305
- replaceIds,
10989
+ allowanceMessage,
11306
10990
  viewColumnOf,
11307
- notifyStatements,
11308
- WAITING_FOR_CONNECTIONS,
11309
- declaredConnections,
11310
- connectionServes,
11311
- loadBindings,
11312
- unboundSlots,
11313
- revokeBindingsPlan,
11314
- MAX_CASCADE_DEPTH,
11315
- EVENT_CHANGES_PER_MESSAGE,
11316
- QUEUE_MESSAGE_MAX_BYTES,
11317
- AUTOMATION_SETTINGS,
11318
- RUN_STATUSES,
11319
- DRAFT_TARGET_ERRORS,
11320
- triggerObject,
11321
- automationSyncStatements,
11322
- parseSpec,
11323
- loadAutomationSettings,
11324
- isTimeZone,
11325
- effectiveRails,
11326
- filterSchema,
11327
- OPS_BY_TYPE,
11328
- compileFilter,
10991
+ FIELD_TYPE_REGISTRY,
10992
+ formulaFromStorage,
11329
10993
  ident,
11330
10994
  isCoreTarget,
11331
10995
  splitObjectName,
@@ -11334,8 +10998,17 @@ export {
11334
10998
  sideTable,
11335
10999
  columnName,
11336
11000
  registryFieldName,
11337
- FIELD_TYPE_REGISTRY,
11338
- formulaFromStorage,
11001
+ loadSchemaState,
11002
+ coreFormulaFields,
11003
+ buildViews,
11004
+ liveViewOf,
11005
+ PUBLISHED_FIELDS,
11006
+ CAPACITY_FIELDS,
11007
+ ALLOWANCE_FIELDS,
11008
+ fieldStorage,
11009
+ objectTableOf,
11010
+ refreshSchemaRegistry,
11011
+ mergeOptions,
11339
11012
  RISK_CLASSES,
11340
11013
  ACTORS,
11341
11014
  originSchema,
@@ -11348,31 +11021,17 @@ export {
11348
11021
  grantableScopes,
11349
11022
  staffPrincipal,
11350
11023
  ALL_ACTORS,
11351
- POLICY_PRESETS,
11352
- approvalPolicySchema,
11353
- APPROVAL_POLICY_SETTING,
11354
- PRESET_MATRICES,
11355
- evaluateGate,
11356
- evaluateOutsideGate,
11357
- isLoosening,
11358
- loadApprovalPolicy,
11359
- BASE_CURRENCY_SETTING,
11360
- ORG_NAME_SETTING,
11361
- ORG_LOGO_SETTING,
11362
- ORG_TIMEZONE_SETTING,
11363
- ASSISTANT_NAME_SETTING,
11364
- isTimezone,
11365
- loadGeneralSettings,
11366
- AI_SETTINGS,
11367
- loadAiSettings,
11368
- loadSchemaState,
11369
- coreFormulaFields,
11370
- buildViews,
11371
- liveViewOf,
11372
- PUBLISHED_FIELDS,
11373
- CAPACITY_FIELDS,
11374
- fieldStorage,
11375
- objectTableOf,
11376
- refreshSchemaRegistry,
11377
- mergeOptions
11024
+ publicProblems,
11025
+ signedInProblems,
11026
+ customerProblems,
11027
+ unknownObject,
11028
+ customerViaProblems,
11029
+ scopeOf,
11030
+ visibleObject,
11031
+ visibleSource,
11032
+ buyableSource,
11033
+ previewSource,
11034
+ ownedSource,
11035
+ visibleTable,
11036
+ orgReader
11378
11037
  };