@composable-os/cli 0.1.0-beta.10 → 0.1.0-beta.13

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 (173) hide show
  1. package/dist/{accounts-X4CKM3HL.js → accounts-GOCNY6WI.js} +17 -14
  2. package/dist/app-RPRZMLU5.js +43 -0
  3. package/dist/app-upload-YJVEKZC6.js +198 -0
  4. package/dist/{blocks-YWDHEBOK.js → blocks-DE4RRWPJ.js} +207 -25
  5. package/dist/{chunk-VY64DMQO.js → chunk-2B6YUYZV.js} +23576 -11674
  6. package/dist/{run-RT2HVWMK.js → chunk-2CCHB37H.js} +9 -146
  7. package/dist/{chunk-DU6OIFOU.js → chunk-3OGDWKJ3.js} +530 -434
  8. package/dist/chunk-5D7BDF4Y.js +141 -0
  9. package/dist/{chunk-WO6D3XP3.js → chunk-6CM3WZG5.js} +13 -2470
  10. package/dist/chunk-CIBJGB5H.js +962 -0
  11. package/dist/chunk-EPDTPGZJ.js +330 -0
  12. package/dist/{chunk-LLULPZAJ.js → chunk-HAYF4G5V.js} +66 -23
  13. package/dist/chunk-HCG6T53D.js +61904 -0
  14. package/dist/chunk-JX4IFWNT.js +330 -0
  15. package/dist/{chunk-A4NTSYWV.js → chunk-KFHKNXGH.js} +786 -386
  16. package/dist/chunk-KMFMD52Z.js +13276 -0
  17. package/dist/{chunk-E4WCYTCT.js → chunk-LX2TTLVY.js} +174 -55
  18. package/dist/{chunk-GYTEW66E.js → chunk-O3R4FS2J.js} +1 -1
  19. package/dist/{chunk-LJFLENFC.js → chunk-Q6Y45DY6.js} +25 -2
  20. package/dist/{chunk-Y7JZFSTQ.js → chunk-QJZGYJVV.js} +823 -44
  21. package/dist/{chunk-6VXHPKGG.js → chunk-QQ3YSL5F.js} +172 -16
  22. package/dist/chunk-RGKJKC5T.js +876 -0
  23. package/dist/{chunk-IFG4FRW5.js → chunk-RSEWEFAV.js} +12 -2
  24. package/dist/{chunk-2ABSVMGB.js → chunk-SMJZIK2O.js} +1 -1
  25. package/dist/{chunk-CP6BXI6F.js → chunk-U72NEGCT.js} +8818 -3829
  26. package/dist/{chunk-WC5LHBBA.js → chunk-Z4IKF23A.js} +11 -7
  27. package/dist/chunk-Z7OVQ6BC.js +713 -0
  28. package/dist/{chunk-6UWRT4VM.js → chunk-ZJSFX4RD.js} +175 -3
  29. package/dist/{cli-2DFENR62.js → cli-OKQHHSOE.js} +17 -23
  30. package/dist/{cli-YIOVSKOD.js → cli-VYSD2S4Z.js} +231 -82
  31. package/dist/cli.js +5 -5
  32. package/dist/{client-repo-PRU3VCQQ.js → client-repo-NNUCHQ2Y.js} +7 -5
  33. package/dist/create.js +5 -5
  34. package/dist/{fields-2NC7LSYE.js → fields-GTHE6TTS.js} +27 -3
  35. package/dist/gateway-DPPEQZT4.js +25 -0
  36. package/dist/grants-6JY4XZO7.js +27 -0
  37. package/dist/invoke-MRONRZ5Q.js +33 -0
  38. package/dist/moves-UAUCMWL5.js +36 -0
  39. package/dist/{order-PUWD65BC.js → order-RKLGT74L.js} +2 -2
  40. package/dist/{person-WIQQ7ITU.js → person-YOZTFV4Q.js} +11 -11
  41. package/dist/plan-on-sale-H4F26YIN.js +26 -0
  42. package/dist/platform/migrations/0610_waitlists.sql +54 -0
  43. package/dist/platform/migrations/0630_subscription_changes.sql +122 -0
  44. package/dist/platform/migrations/0650_person_links.sql +90 -0
  45. package/dist/platform/migrations/0670_unmoved_guard.sql +52 -0
  46. package/dist/platform/migrations/0690_sellable_refund_due.sql +98 -0
  47. package/dist/platform/migrations/0730_practitioners.sql +79 -0
  48. package/dist/platform/migrations/0750_routine_mail.sql +98 -0
  49. package/dist/platform/migrations/0770_clear_fixed_role_grants.sql +64 -0
  50. package/dist/platform/migrations/0810_recurrence_exceptions.sql +66 -0
  51. package/dist/platform/migrations/0811_staff_time.sql +109 -0
  52. package/dist/platform/migrations/0812_staff_offers.sql +112 -0
  53. package/dist/platform/migrations/0813_pay_periods.sql +241 -0
  54. package/dist/platform/migrations/0814_staff_feed.sql +47 -0
  55. package/dist/platform/migrations/0815_checklists.sql +237 -0
  56. package/dist/platform/migrations/0816_checklist_schedules.sql +121 -0
  57. package/dist/platform/migrations/0817_checklist_day_window.sql +35 -0
  58. package/dist/platform/migrations/0850_agreements.sql +271 -0
  59. package/dist/platform/migrations/0851_agreement_acceptances.sql +387 -0
  60. package/dist/platform/migrations/0853_agreement_enforcement.sql +58 -0
  61. package/dist/platform/migrations/0854_agreement_copy.sql +149 -0
  62. package/dist/platform/migrations/0855_agreement_retention.sql +279 -0
  63. package/dist/platform/migrations/0856_subscription_cooling_off.sql +159 -0
  64. package/dist/platform/migrations/0857_agreement_copy_guardian.sql +337 -0
  65. package/dist/platform/migrations/0858_agreement_desk.sql +175 -0
  66. package/dist/platform/migrations/0910_routine_messages.sql +99 -0
  67. package/dist/platform/migrations/0911_texts.sql +60 -0
  68. package/dist/platform/migrations/0913_contact_consent.sql +93 -0
  69. package/dist/platform/migrations/0916_contact_mailbox_index.sql +29 -0
  70. package/dist/platform/migrations/0930_stock_movements.sql +95 -0
  71. package/dist/platform/migrations/0931_stock_low.sql +25 -0
  72. package/dist/platform/migrations/0932_order_delivery.sql +78 -0
  73. package/dist/platform/migrations/0950_order_adjustments.sql +111 -0
  74. package/dist/platform/migrations/0951_order_price_guards.sql +33 -0
  75. package/dist/platform/migrations/0952_order_paid_another_way.sql +194 -0
  76. package/dist/platform/migrations/0953_discount_uses.sql +183 -0
  77. package/dist/platform/migrations/0955_folded_addresses.sql +92 -0
  78. package/dist/platform/migrations/0970_published_text.sql +59 -0
  79. package/dist/platform/migrations/0971_publish_acks.sql +68 -0
  80. package/dist/platform/migrations/0990_customer_email_change.sql +65 -0
  81. package/dist/platform/migrations/1010_intake_links.sql +148 -0
  82. package/dist/platform/migrations/1030_invoices.sql +747 -0
  83. package/dist/platform/migrations/1031_invoice_orders.sql +327 -0
  84. package/dist/platform/migrations/1050_inbox_conversations.sql +83 -0
  85. package/dist/platform/migrations/1090_staff_hours.sql +43 -0
  86. package/dist/platform/migrations/1091_staff_time_margins.sql +12 -0
  87. package/dist/platform/migrations/1092_client_guard.sql +26 -0
  88. package/dist/platform/migrations/1095_thing_time.sql +70 -0
  89. package/dist/platform/migrations/1130_devices.sql +162 -0
  90. package/dist/platform/migrations/1135_person_codes.sql +88 -0
  91. package/dist/platform/migrations/1150_finance_periods.sql +316 -0
  92. package/dist/platform/migrations/1151_payouts.sql +202 -0
  93. package/dist/platform/migrations/1153_finance_money_dates.sql +18 -0
  94. package/dist/platform/migrations/1170_journeys.sql +318 -0
  95. package/dist/platform/migrations/1171_person_birthday.sql +52 -0
  96. package/dist/platform/migrations/1175_person_signals.sql +29 -0
  97. package/dist/platform/migrations/1190_restricted_values.sql +25 -0
  98. package/dist/platform/migrations/1230_note_levels.sql +113 -0
  99. package/dist/platform/migrations/1231_person_carers.sql +33 -0
  100. package/dist/platform/migrations/1232_note_kinds.sql +122 -0
  101. package/dist/platform/migrations/1270_time_entries.sql +145 -0
  102. package/dist/platform/migrations/1271_leave.sql +249 -0
  103. package/dist/platform/migrations/1273_time_entry_reopened.sql +21 -0
  104. package/dist/platform/migrations/1330_accounting.sql +260 -0
  105. package/dist/platform/migrations/1350_customer_feed.sql +24 -0
  106. package/dist/platform/migrations/1390_locations.sql +77 -0
  107. package/dist/platform/migrations/1410_outside_copy.sql +213 -0
  108. package/dist/platform/migrations/1430_inbox_activities.sql +231 -0
  109. package/dist/platform/migrations/1450_wrong_guesses.sql +23 -0
  110. package/dist/platform/sdk/acknowledge.ts +100 -0
  111. package/dist/platform/sdk/agreements.ts +185 -0
  112. package/dist/platform/sdk/allowance.ts +98 -8
  113. package/dist/platform/sdk/automation-check.ts +120 -9
  114. package/dist/platform/sdk/automation.ts +78 -10
  115. package/dist/platform/sdk/behaviour.ts +26 -6
  116. package/dist/platform/sdk/calendar-entry.ts +258 -0
  117. package/dist/platform/sdk/capacity.ts +103 -2
  118. package/dist/platform/sdk/checklists.ts +118 -0
  119. package/dist/platform/sdk/contract.ts +514 -27
  120. package/dist/platform/sdk/discount.ts +408 -0
  121. package/dist/platform/sdk/document.ts +4 -2
  122. package/dist/platform/sdk/field-types.ts +5 -0
  123. package/dist/platform/sdk/formula/compile.ts +10 -0
  124. package/dist/platform/sdk/index.ts +17 -0
  125. package/dist/platform/sdk/intake.ts +380 -0
  126. package/dist/platform/sdk/journey-signals.ts +215 -0
  127. package/dist/platform/sdk/manifest.ts +1313 -66
  128. package/dist/platform/sdk/mine.ts +161 -0
  129. package/dist/platform/sdk/occupies.ts +192 -0
  130. package/dist/platform/sdk/questions.ts +681 -0
  131. package/dist/platform/sdk/recurring.ts +90 -9
  132. package/dist/platform/sdk/restricted-fields.ts +129 -0
  133. package/dist/platform/sdk/rich-text.ts +112 -0
  134. package/dist/platform/sdk/routine-mail.ts +1272 -0
  135. package/dist/platform/sdk/runtime.ts +25 -12
  136. package/dist/platform/sdk/screens.ts +91 -0
  137. package/dist/platform/sdk/sellable.ts +595 -1
  138. package/dist/platform/sdk/slug.ts +7 -2
  139. package/dist/platform/sdk/staffed.ts +474 -0
  140. package/dist/platform/sdk/states.ts +220 -64
  141. package/dist/platform/sdk/stock.ts +332 -0
  142. package/dist/platform/sdk/team.ts +83 -0
  143. package/dist/platform/sdk/testing.ts +70 -6
  144. package/dist/platform/sdk/worked-on.ts +134 -0
  145. package/dist/{products-2H5DR232.js → products-GCQLSZ3U.js} +2 -2
  146. package/dist/run-7ID64RA6.js +65 -0
  147. package/dist/run-FH7OGGTV.js +131 -0
  148. package/dist/run-OYZIAP6M.js +3363 -0
  149. package/dist/{run-Y7T4TVOL.js → run-QOFRRSZV.js} +41 -60
  150. package/dist/{run-PZUCSDDL.js → run-TJAEWR5U.js} +21 -51
  151. package/dist/{src-XTOD7EXW.js → src-52VERUPK.js} +312 -4
  152. package/dist/src-PHRELWN5.js +40 -0
  153. package/dist/visibility-SZCINPP4.js +58 -0
  154. package/package.json +2 -2
  155. package/dist/chunk-6GDEDOV7.js +0 -157
  156. package/dist/chunk-6UPUF4ML.js +0 -29998
  157. package/dist/chunk-7CQGMVDO.js +0 -63
  158. package/dist/chunk-GYSGVT6R.js +0 -284
  159. package/dist/chunk-JJHHNV46.js +0 -227
  160. package/dist/chunk-K6T42YCH.js +0 -704
  161. package/dist/chunk-M7A6FR2Z.js +0 -2586
  162. package/dist/chunk-O2UIZHND.js +0 -249
  163. package/dist/chunk-Q4N55M2Z.js +0 -552
  164. package/dist/chunk-QGGJ2G6Z.js +0 -349
  165. package/dist/chunk-R4W5XAUD.js +0 -837
  166. package/dist/chunk-TQFGGSA4.js +0 -748
  167. package/dist/chunk-YJJHF65I.js +0 -759
  168. package/dist/chunk-Z3RMMB6S.js +0 -668
  169. package/dist/grants-QXMKYMGB.js +0 -32
  170. package/dist/invoke-I3NNNXVL.js +0 -39
  171. package/dist/plan-on-sale-NB774CQL.js +0 -26
  172. package/dist/src-GYS6NBQB.js +0 -44
  173. package/dist/visibility-DLGHU4YN.js +0 -33
@@ -1,52 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- callSubscriptionGatekeeper,
4
- paymentsTarget
5
- } from "./chunk-LJFLENFC.js";
6
- import {
7
- dropAllowanceStatements,
8
- dropRecurringStatements,
9
- termsSyncStatements
10
- } from "./chunk-JJHHNV46.js";
11
- import {
12
- loadOrderCurrency,
13
- realWallClock,
14
- zoneOffset
15
- } from "./chunk-O2UIZHND.js";
16
- import {
17
- automationSyncStatements
18
- } from "./chunk-QGGJ2G6Z.js";
19
- import {
20
- compileFilter,
21
- filterSchema,
22
- hasAccessSourceKind,
23
- holdsAccess,
24
- registerAccessSource,
25
- runListQuery
26
- } from "./chunk-K6T42YCH.js";
27
- import {
28
- CompiledQuery,
29
- ORG_TIMEZONE_SETTING,
30
- backfillCounters,
31
- dropCapacityStatements,
32
- loadGeneralSettings,
33
- newId,
34
- releaseAllClaimsStatements
35
- } from "./chunk-TQFGGSA4.js";
36
2
  import {
37
3
  CaseBuilder,
38
4
  CaseNode,
39
5
  ColumnNode,
40
- ConfigError,
41
- ConflictError,
42
6
  DynamicReferenceBuilder,
43
7
  DynamicTableBuilder,
44
- FIELD_TYPE_REGISTRY,
45
- ForbiddenError,
46
8
  IdentifierNode,
47
9
  InsertQueryNode,
48
- NotFoundError,
49
- OperationError,
50
10
  OperationNodeTransformer,
51
11
  OperatorNode,
52
12
  ParensNode,
@@ -57,23 +17,15 @@ import {
57
17
  SchemableIdentifierNode,
58
18
  SelectAllNode,
59
19
  SetOperationNode,
60
- ValidationError,
61
20
  ValueListNode,
62
21
  ValueNode,
63
22
  WhenNode,
64
23
  WithSchemaPlugin,
65
- buildViews,
66
- columnName,
67
- coreFormulaFields,
68
24
  createFunctionModule,
69
25
  createQueryId,
70
- formulaFromStorage,
71
26
  freeze,
72
- holdsPermission,
73
- ident,
74
27
  isBigInt,
75
28
  isBoolean,
76
- isCoreTarget,
77
29
  isDate,
78
30
  isFunction,
79
31
  isNull,
@@ -82,13 +34,8 @@ import {
82
34
  isOperationNodeSource,
83
35
  isString,
84
36
  isUndefined,
85
- liveViewOf,
86
- loadSchemaState,
87
37
  logOnce,
88
38
  noop,
89
- objectTable,
90
- objectView,
91
- orgReader,
92
39
  parseColumnName,
93
40
  parseDataTypeExpression,
94
41
  parseExpression,
@@ -96,34 +43,11 @@ import {
96
43
  parseStringReference,
97
44
  parseTable,
98
45
  parseValueBinaryOperationOrExpression,
99
- previewSource,
100
46
  printBackgroundFail,
101
47
  provideControlledConnection,
102
- registryFieldName,
103
- sideTable,
104
- splitObjectName,
105
48
  sql,
106
- unknownObject,
107
- viewColumnOf,
108
- visibleObject,
109
- visibleSource,
110
- visibleTable,
111
49
  waitOrAbort
112
- } from "./chunk-A4NTSYWV.js";
113
- import {
114
- getObject,
115
- listObjects
116
- } from "./chunk-IFG4FRW5.js";
117
- import {
118
- external_exports,
119
- hostFilledFields,
120
- isDocumentType,
121
- isLosslessChange,
122
- redactDocument,
123
- spenderAllows,
124
- spendsOnList,
125
- validateManifest
126
- } from "./chunk-CP6BXI6F.js";
50
+ } from "./chunk-KFHKNXGH.js";
127
51
 
128
52
  // ../../node_modules/.pnpm/kysely@0.29.8/node_modules/kysely/dist/operation-node/alter-table-node.js
129
53
  var AlterTableNode = freeze({
@@ -1748,15 +1672,15 @@ var AlterTableBuilder = class {
1748
1672
  node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn))
1749
1673
  });
1750
1674
  }
1751
- addColumn(columnName2, dataType, build = noop) {
1752
- const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName2, parseDataTypeExpression(dataType))));
1675
+ addColumn(columnName, dataType, build = noop) {
1676
+ const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
1753
1677
  return new AlterTableColumnAlteringBuilder({
1754
1678
  ...this.#props,
1755
1679
  node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode()))
1756
1680
  });
1757
1681
  }
1758
- modifyColumn(columnName2, dataType, build = noop) {
1759
- const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName2, parseDataTypeExpression(dataType))));
1682
+ modifyColumn(columnName, dataType, build = noop) {
1683
+ const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
1760
1684
  return new AlterTableColumnAlteringBuilder({
1761
1685
  ...this.#props,
1762
1686
  node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode()))
@@ -1914,15 +1838,15 @@ var AlterTableColumnAlteringBuilder = class _AlterTableColumnAlteringBuilder {
1914
1838
  node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn))
1915
1839
  });
1916
1840
  }
1917
- addColumn(columnName2, dataType, build = noop) {
1918
- const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName2, parseDataTypeExpression(dataType))));
1841
+ addColumn(columnName, dataType, build = noop) {
1842
+ const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
1919
1843
  return new _AlterTableColumnAlteringBuilder({
1920
1844
  ...this.#props,
1921
1845
  node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode()))
1922
1846
  });
1923
1847
  }
1924
- modifyColumn(columnName2, dataType, build = noop) {
1925
- const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName2, parseDataTypeExpression(dataType))));
1848
+ modifyColumn(columnName, dataType, build = noop) {
1849
+ const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
1926
1850
  return new _AlterTableColumnAlteringBuilder({
1927
1851
  ...this.#props,
1928
1852
  node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode()))
@@ -2286,8 +2210,8 @@ var CreateTableBuilder = class _CreateTableBuilder {
2286
2210
  * .execute()
2287
2211
  * ```
2288
2212
  */
2289
- addColumn(columnName2, dataType, build = noop) {
2290
- const columnBuilder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName2, parseDataTypeExpression(dataType))));
2213
+ addColumn(columnName, dataType, build = noop) {
2214
+ const columnBuilder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
2291
2215
  return new _CreateTableBuilder({
2292
2216
  ...this.#props,
2293
2217
  node: CreateTableNode.cloneWithColumn(this.#props.node, columnBuilder.toOperationNode())
@@ -6689,7 +6613,7 @@ var DefaultQueryCompiler = class extends OperationNodeVisitor {
6689
6613
  this.append("'");
6690
6614
  }
6691
6615
  sortSelectModifiers(arr) {
6692
- return freeze(arr.toSorted((left2, right) => left2.modifier && right.modifier ? SELECT_MODIFIER_PRIORITY[left2.modifier] - SELECT_MODIFIER_PRIORITY[right.modifier] : 1));
6616
+ return freeze(arr.toSorted((left, right) => left.modifier && right.modifier ? SELECT_MODIFIER_PRIORITY[left.modifier] - SELECT_MODIFIER_PRIORITY[right.modifier] : 1));
6693
6617
  }
6694
6618
  compileColumnAlterations(columnAlterations) {
6695
6619
  this.compileList(columnAlterations);
@@ -6876,2352 +6800,6 @@ var SqliteAdapter = class extends DialectAdapterBase {
6876
6800
  }
6877
6801
  };
6878
6802
 
6879
- // ../core/src/visibility/capacity.ts
6880
- var left = (places, held, taken) => places === null ? null : Math.max(places - held - taken, 0);
6881
- function capacityStatus(capacity, available) {
6882
- if (available === null) return "available";
6883
- if (available === 0) return "sold_out";
6884
- if (capacity.show === "low" && capacity.lowAt !== void 0 && available <= capacity.lowAt) {
6885
- return "low";
6886
- }
6887
- return "available";
6888
- }
6889
- function outsideView(object, id, available) {
6890
- const status = capacityStatus(object.capacity, available);
6891
- const base = { object: object.name, id, status };
6892
- switch (object.capacity.show) {
6893
- case "exact":
6894
- return { ...base, available };
6895
- case "low":
6896
- return status === "low" ? { ...base, available } : base;
6897
- default:
6898
- return base;
6899
- }
6900
- }
6901
- async function readableBy(reader, object, id) {
6902
- let source;
6903
- try {
6904
- source = visibleSource(reader, object);
6905
- } catch {
6906
- return false;
6907
- }
6908
- const row = await reader.db.selectFrom(source).select("id").where("id", "=", id).executeTakeFirst();
6909
- return Boolean(row);
6910
- }
6911
- async function readCapacity(reader, name, id) {
6912
- const object = getObject(name);
6913
- if (!object?.capacity) throw unknownObject(name);
6914
- const withCapacity = object;
6915
- const live = await orgReader(reader.db).db.selectFrom(visibleTable(orgReader(reader.db), object, "t")).select("t.deleted_at").where("t.id", "=", id).executeTakeFirst();
6916
- if (!live || live.deleted_at !== null) throw new NotFoundError(name, id);
6917
- if (reader.principal.kind !== "staff" && !await readableBy(reader, object, id)) {
6918
- throw new NotFoundError(name, id);
6919
- }
6920
- const row = await reader.db.selectFrom("core_capacity as c").leftJoin(
6921
- "core_capacity as p",
6922
- (join) => join.onRef("p.object_type", "=", "c.pool_object_type").onRef("p.record_id", "=", "c.pool_record_id")
6923
- ).select([
6924
- "c.places",
6925
- "c.held",
6926
- "c.taken",
6927
- "c.pool_object_type",
6928
- "c.pool_record_id",
6929
- "p.places as pool_places",
6930
- "p.held as pool_held",
6931
- "p.taken as pool_taken"
6932
- ]).where("c.object_type", "=", name).where("c.record_id", "=", id).executeTakeFirst();
6933
- const own = row ? left(row.places, row.held, row.taken) : null;
6934
- const pool = row?.pool_object_type && row.pool_record_id ? {
6935
- object: row.pool_object_type,
6936
- id: row.pool_record_id,
6937
- places: row.pool_places,
6938
- held: row.pool_held ?? 0,
6939
- taken: row.pool_taken ?? 0,
6940
- available: left(row.pool_places, row.pool_held ?? 0, row.pool_taken ?? 0)
6941
- } : null;
6942
- const available = own === null ? pool?.available ?? null : pool?.available == null ? own : Math.min(own, pool.available);
6943
- if (reader.principal.kind !== "staff") return outsideView(withCapacity, id, available);
6944
- return {
6945
- object: name,
6946
- id,
6947
- status: capacityStatus(object.capacity, available),
6948
- available,
6949
- places: row?.places ?? null,
6950
- held: row?.held ?? 0,
6951
- taken: row?.taken ?? 0,
6952
- show: object.capacity.show,
6953
- lowAt: object.capacity.lowAt ?? null,
6954
- pool
6955
- };
6956
- }
6957
-
6958
- // ../core/src/visibility/records.ts
6959
- async function currencyOf(ctx, object) {
6960
- if (!getObject(object.name)?.sellable) return {};
6961
- return { currency: await loadOrderCurrency(ctx.db) };
6962
- }
6963
- function fieldValue(field, row) {
6964
- const column = viewColumnOf(field);
6965
- const raw2 = column ? row[column] ?? null : null;
6966
- if (!field.extension || !field.fieldType) return raw2;
6967
- const type = field.fieldType;
6968
- return type === "formula" ? formulaFromStorage(field.options?.resultType, raw2) : FIELD_TYPE_REGISTRY[type].fromStorage(raw2);
6969
- }
6970
- function toRecord(object, row, viewer, held = NONE_HELD) {
6971
- const outsider = viewer.principal.kind !== "staff";
6972
- const holder = held.has(String(row.id));
6973
- const values = {};
6974
- for (const field of object.fields) {
6975
- if (field.name === "id") continue;
6976
- const value = fieldValue(field, row);
6977
- const schema = field.options?.document?.schema;
6978
- values[field.name] = outsider && isDocumentType(field.fieldType) ? schema ? redactDocument(schema, value, { holder }) : null : value;
6979
- }
6980
- return { object: object.name, id: String(row.id), values };
6981
- }
6982
- var NONE_HELD = /* @__PURE__ */ new Set();
6983
- async function heldOf(ctx, object, rows) {
6984
- const definition = getObject(object.name) ?? object;
6985
- if (ctx.principal.kind === "staff" || !definition.access || !rows.length) return NONE_HELD;
6986
- if (!object.fields.some((f) => isDocumentType(f.fieldType))) return NONE_HELD;
6987
- return holdsAccess(
6988
- ctx,
6989
- definition,
6990
- rows.map((row) => String(row.id))
6991
- );
6992
- }
6993
- async function listVisible(ctx, object, input) {
6994
- const visible = visibleObject(ctx, object);
6995
- const page = await runListQuery(ctx, visible, input);
6996
- const held = await heldOf(ctx, visible, page.rows);
6997
- return {
6998
- items: page.rows.map((row) => toRecord(visible, row, ctx, held)),
6999
- nextCursor: page.nextCursor,
7000
- ...await currencyOf(ctx, visible)
7001
- };
7002
- }
7003
- async function getVisible(ctx, object, id) {
7004
- const visible = visibleObject(ctx, object);
7005
- const row = await ctx.db.selectFrom(visibleSource(ctx, visible)).selectAll().where("id", "=", id).executeTakeFirst();
7006
- if (!row) throw new NotFoundError(visible.name, id);
7007
- const held = await heldOf(ctx, visible, [row]);
7008
- return {
7009
- ...toRecord(visible, row, ctx, held),
7010
- ...await currencyOf(ctx, visible)
7011
- };
7012
- }
7013
- async function previewVisible(ctx, object, id) {
7014
- const visible = visibleObject(ctx, object);
7015
- const row = await ctx.db.selectFrom(previewSource(object, id)).selectAll().executeTakeFirst();
7016
- return row ? toRecord(visible, row, ctx) : null;
7017
- }
7018
- var VISIBLE_COUNT_CAP = 1e4;
7019
- async function countVisible(ctx, object, filter) {
7020
- const visible = visibleObject(ctx, object);
7021
- const db = ctx.db;
7022
- let matching = db.selectFrom(visibleSource(ctx, visible)).select(sql`1`.as("one"));
7023
- if (filter) matching = matching.where(compileFilter(visible, filter, visible.source));
7024
- const row = await db.selectFrom(matching.limit(VISIBLE_COUNT_CAP + 1).as("matching")).select(sql`count(*)`.as("n")).executeTakeFirstOrThrow();
7025
- const n = Number(row.n);
7026
- return n > VISIBLE_COUNT_CAP ? { count: VISIBLE_COUNT_CAP, capped: true } : { count: n, capped: false };
7027
- }
7028
- function recordAccess(reader, writes) {
7029
- const none = () => {
7030
- throw new OperationError(
7031
- "internal",
7032
- "ctx.records writes are for a customer's call; staff use the record operations"
7033
- );
7034
- };
7035
- return {
7036
- list: (object, input = {}) => listVisible(reader, object, { ...input, limit: input.limit ?? 50 }),
7037
- get: (object, id) => getVisible(reader, object, id),
7038
- count: (object, filter) => countVisible(reader, object, filter),
7039
- capacity: (object, id) => readCapacity(reader, object, id),
7040
- create: writes?.create ?? none,
7041
- update: writes?.update ?? none
7042
- };
7043
- }
7044
-
7045
- // ../core/src/allowance/check.ts
7046
- function allowanceHostIssues(m) {
7047
- const issues = [];
7048
- for (const [name, object] of Object.entries(m.objects)) {
7049
- const allowance = object.allowance;
7050
- if (!allowance) continue;
7051
- const ap = `objects.${name}.allowance`;
7052
- if ("holds" in allowance) {
7053
- spendsOnList(allowance.holds).forEach((target, i) => {
7054
- if (!target.object.includes(".") || target.object.startsWith(`${m.id}.`)) return;
7055
- const p = Array.isArray(allowance.holds.spendsOn) ? `${ap}.holds.spendsOn.${i}` : `${ap}.holds.spendsOn`;
7056
- const spender = getObject(target.object);
7057
- if (!spender) return;
7058
- const def = spender.allowance;
7059
- if (def?.kind !== "spender") {
7060
- issues.push({ path: `${p}.object`, message: `${target.object} does not spend uses` });
7061
- return;
7062
- }
7063
- const ext = target.object.split(".")[0];
7064
- if (!spenderAllows({ paidBy: def.paidBy }, ext, `${m.id}.${name}`)) {
7065
- issues.push({
7066
- path: `${p}.object`,
7067
- message: `${target.object} does not let ${m.id}.${name} pay for it: its paidBy must list ${m.id} or ${m.id}.${name}`
7068
- });
7069
- }
7070
- const filled = new Set(hostFilledFields({ copy: def.copy, local: def.local }));
7071
- (target.when ?? []).forEach((clause, j) => {
7072
- if (!filled.has(clause.field)) {
7073
- issues.push({
7074
- path: `${p}.when.${j}.field`,
7075
- message: `"${clause.field}" must be a field ${target.object}'s host fills (its copy or local), so no caller sets what pays for it`
7076
- });
7077
- }
7078
- });
7079
- });
7080
- continue;
7081
- }
7082
- const s = allowance.spends;
7083
- const hops = [
7084
- ...s.at?.includes(".") ? [[`${ap}.spends.at`, s.at, "datetime"]] : [],
7085
- ...s.local?.zone?.includes(".") ? [[`${ap}.spends.local.zone`, s.local.zone, "timezone"]] : [],
7086
- ...Object.entries(s.copy ?? {}).map(
7087
- ([local, source]) => [`${ap}.spends.copy.${local}`, source, null]
7088
- )
7089
- ];
7090
- for (const [p, path, type] of hops) {
7091
- const [rel, target] = path.split(".");
7092
- const to = object.fields[rel]?.type === "relation" ? object.fields[rel]?.to : void 0;
7093
- if (!to || to.startsWith(`${m.id}.`)) continue;
7094
- const other = getObject(to);
7095
- if (!other) {
7096
- issues.push({ path: p, message: `${to} is not installed, so "${path}" cannot be read` });
7097
- continue;
7098
- }
7099
- const field = other.fields.find((f) => f.name === target);
7100
- if (!field) {
7101
- issues.push({ path: p, message: `"${target}" is not a field of ${to}` });
7102
- continue;
7103
- }
7104
- const actual = field.fieldType ?? field.type;
7105
- if (type && actual !== type) {
7106
- issues.push({ path: p, message: `"${path}" must be a ${type} field (it is ${actual})` });
7107
- }
7108
- }
7109
- }
7110
- return issues;
7111
- }
7112
-
7113
- // ../core/src/dashboards/spec.ts
7114
- var WIDGET_TYPES = [
7115
- "kpi",
7116
- "bar",
7117
- "line",
7118
- "donut",
7119
- "funnel",
7120
- "table",
7121
- "leaderboard",
7122
- "markdown"
7123
- ];
7124
- var DATA_WIDGET_TYPES = WIDGET_TYPES.filter(
7125
- (t) => t !== "markdown"
7126
- );
7127
- var DATE_PRESETS = [
7128
- "all_time",
7129
- "today",
7130
- "last_7_days",
7131
- "last_30_days",
7132
- "last_90_days",
7133
- "last_365_days",
7134
- "this_month",
7135
- "last_month",
7136
- "this_quarter",
7137
- "this_year"
7138
- ];
7139
- var paramName = external_exports.string().regex(/^[a-z][a-z0-9_]{0,30}$/, "lowercase letters, digits and _; starts with a letter");
7140
- var filterBase = {
7141
- id: paramName.describe(
7142
- "The filter's id, which names its SQL parameter(s): a dateRange `date` binds :date_from and :date_to; any other filter `owner` binds :owner"
7143
- ),
7144
- label: external_exports.string().min(1).max(100)
7145
- };
7146
- var dashboardFilterSchema = external_exports.discriminatedUnion("type", [
7147
- external_exports.object({
7148
- type: external_exports.literal("dateRange"),
7149
- ...filterBase,
7150
- default: external_exports.enum(DATE_PRESETS).default("last_90_days")
7151
- }),
7152
- external_exports.object({
7153
- type: external_exports.literal("user"),
7154
- ...filterBase,
7155
- default: external_exports.enum(["me", "anyone"]).default("anyone")
7156
- }),
7157
- external_exports.object({
7158
- type: external_exports.literal("select"),
7159
- ...filterBase,
7160
- options: external_exports.array(external_exports.object({ value: external_exports.string().max(200), label: external_exports.string().max(200) })).min(1).max(100),
7161
- default: external_exports.string().max(200).nullish()
7162
- }),
7163
- external_exports.object({
7164
- type: external_exports.literal("field"),
7165
- ...filterBase,
7166
- object: external_exports.string().min(1).max(80).describe("Object whose field supplies the choices"),
7167
- field: external_exports.string().min(1).max(80).describe("A select field (choices) or any text field"),
7168
- default: external_exports.string().max(200).nullish()
7169
- }),
7170
- external_exports.object({
7171
- type: external_exports.literal("text"),
7172
- ...filterBase,
7173
- default: external_exports.string().max(200).nullish()
7174
- })
7175
- ]);
7176
- var filterValueSchema = external_exports.union([
7177
- external_exports.enum(DATE_PRESETS),
7178
- external_exports.object({
7179
- from: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/),
7180
- to: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/)
7181
- }),
7182
- external_exports.string().max(200),
7183
- external_exports.null()
7184
- ]);
7185
- var filterValuesSchema = external_exports.record(external_exports.string().max(31), filterValueSchema).default({}).describe(
7186
- "Dashboard filter values by filter id: a date preset or { from, to } (YYYY-MM-DD, inclusive) for dateRange filters, a user id / 'me' / null for user filters, a value or null otherwise"
7187
- );
7188
- var widgetMappingSchema = external_exports.object({
7189
- x: external_exports.string().max(80).optional().describe("Category or time column (bar, line, funnel)"),
7190
- y: external_exports.union([external_exports.string().max(80), external_exports.array(external_exports.string().max(80)).min(1).max(8)]).optional().describe("Value column(s) (bar, line)"),
7191
- series: external_exports.string().max(80).optional().describe("A column whose values split rows into series (long format, bar/line)"),
7192
- label: external_exports.string().max(80).optional().describe("Segment or row label column (donut, leaderboard)"),
7193
- value: external_exports.string().max(80).optional().describe("Value column (kpi, donut, funnel, leaderboard)"),
7194
- columns: external_exports.array(external_exports.string().max(80)).max(20).optional().describe("Columns shown (table)")
7195
- }).default({});
7196
- var widgetOptionsSchema = external_exports.object({
7197
- orientation: external_exports.enum(["vertical", "horizontal"]).optional().describe("bar: columns or bars"),
7198
- stacked: external_exports.boolean().optional(),
7199
- area: external_exports.boolean().optional().describe("line: fill as an area chart"),
7200
- pie: external_exports.boolean().optional().describe("donut: a full pie instead of a ring"),
7201
- format: external_exports.enum(["number", "currency", "percent"]).optional(),
7202
- currency: external_exports.string().regex(/^[A-Z]{3}$/).optional(),
7203
- compare: external_exports.boolean().optional().describe("kpi: compare with the previous period of the date filter (default true)"),
7204
- limit: external_exports.number().int().min(1).max(100).optional().describe("table/leaderboard: top N rows")
7205
- }).default({});
7206
- var clickThroughSchema = external_exports.object({
7207
- object: external_exports.string().min(1).max(80).describe("The object whose list opens"),
7208
- objectColumn: external_exports.string().max(80).nullish().describe("A result column naming the object per row, when rows mix objects"),
7209
- filter: filterSchema.nullish()
7210
- });
7211
- var widgetLayoutSchema = external_exports.object({
7212
- w: external_exports.number().int().min(1).max(12).default(6).describe("Width in grid columns (of 12)"),
7213
- h: external_exports.number().int().min(1).max(8).default(2).describe("Height in grid rows (about 9rem each)")
7214
- }).default({ w: 6, h: 2 });
7215
- var widgetSpecSchema = external_exports.object({
7216
- id: external_exports.string().regex(/^[a-z0-9][a-z0-9_-]{0,40}$/).describe("Stable id within the dashboard, e.g. people-added"),
7217
- type: external_exports.enum(WIDGET_TYPES),
7218
- title: external_exports.string().min(1).max(200),
7219
- description: external_exports.string().max(1e3).nullish(),
7220
- sql: external_exports.string().max(2e4).nullish().describe(
7221
- "Data widgets: one read-only SELECT over rec_* views. Use named params for filters (:date_from, :date_to, :owner, \u2026) and the system params :now, :today and :me"
7222
- ),
7223
- markdown: external_exports.string().max(2e4).nullish().describe("Markdown widgets: the text"),
7224
- mapping: widgetMappingSchema,
7225
- options: widgetOptionsSchema,
7226
- clickThrough: clickThroughSchema.nullish(),
7227
- layout: widgetLayoutSchema
7228
- }).superRefine((widget, ctx) => {
7229
- if (widget.type === "markdown") {
7230
- if (!widget.markdown?.trim()) {
7231
- ctx.addIssue({ code: "custom", path: ["markdown"], message: "markdown widgets need text" });
7232
- }
7233
- } else if (!widget.sql?.trim()) {
7234
- ctx.addIssue({ code: "custom", path: ["sql"], message: `${widget.type} widgets need sql` });
7235
- }
7236
- });
7237
- var dashboardSpecSchema = external_exports.object({
7238
- filters: external_exports.array(dashboardFilterSchema).max(8).default([]),
7239
- widgets: external_exports.array(widgetSpecSchema).max(30).default([])
7240
- });
7241
- var SYSTEM_PARAMS = {
7242
- now: "The current time (ISO-8601 UTC, to the minute)",
7243
- today: "Today's date (YYYY-MM-DD, UTC)",
7244
- me: "The id of the user viewing the dashboard",
7245
- record_id: "On a record tab or panel: the record's id (null elsewhere)"
7246
- };
7247
- function filterParamNames(filters) {
7248
- return filters.flatMap((f) => f.type === "dateRange" ? [`${f.id}_from`, `${f.id}_to`] : [f.id]);
7249
- }
7250
- function allowedParamNames(filters) {
7251
- return [...Object.keys(SYSTEM_PARAMS), ...filterParamNames(filters)];
7252
- }
7253
-
7254
- // ../core/src/subscriptions/trial.ts
7255
- var TRIAL_HOLD_AFTER_EXPIRY_MS = 15 * 6e4;
7256
- var NO_TRIAL_REASONS = [
7257
- "sign_in",
7258
- "used",
7259
- "permission",
7260
- "held",
7261
- "unconfirmed",
7262
- "continuation"
7263
- ];
7264
- async function trialUsed(ctx, holderPersonId, planObject) {
7265
- const held = await ctx.db.selectFrom("core_subscription_trial").select("checkout_id").where("holder_person_id", "=", holderPersonId).where("plan_object", "=", planObject).where("used_at", "is not", null).executeTakeFirst();
7266
- if (held) return true;
7267
- const had = await ctx.db.selectFrom("core_subscription as s").innerJoin("core_subscription_checkout as c", "c.id", "s.id").select("s.id").where("s.holder_person_id", "=", holderPersonId).where("s.plan_object", "=", planObject).where("s.trial_end", "is not", null).where("c.trial_days", "is not", null).executeTakeFirst();
7268
- return Boolean(had);
7269
- }
7270
- async function hasContinuation(ctx, holderPersonId, planObject) {
7271
- const open = await ctx.db.selectFrom("core_subscription_offer").select("id").where("person_id", "=", holderPersonId).where("plan_object", "=", planObject).where("subscription_id", "is", null).where("withdrawn_at", "is", null).where("free_until", ">", ctx.now).executeTakeFirst();
7272
- if (open) return true;
7273
- const running = await ctx.db.selectFrom("core_subscription as s").innerJoin("core_subscription_checkout as c", "c.id", "s.id").select("s.id").where("s.holder_person_id", "=", holderPersonId).where("s.plan_object", "=", planObject).where("c.offer_id", "is not", null).where("s.state", "not in", ["ended", "expired"]).executeTakeFirst();
7274
- return Boolean(running);
7275
- }
7276
- async function pageStatus(ctx, target, ref) {
7277
- try {
7278
- const result = await callSubscriptionGatekeeper(
7279
- ctx.integrations,
7280
- target,
7281
- "getSubscriptionCheckout",
7282
- ref
7283
- );
7284
- const status = result.value?.status;
7285
- return status === "open" || status === "complete" || status === "expired" ? status : null;
7286
- } catch {
7287
- return null;
7288
- }
7289
- }
7290
- async function decideTrial(ctx, start, trialDays) {
7291
- if (!trialDays || trialDays <= 0) return { give: false, reason: null };
7292
- if (start.allowed === "guest") return { give: false, reason: "sign_in" };
7293
- if (start.allowed === "no_permission") return { give: false, reason: "permission" };
7294
- if (await trialUsed(ctx, start.holderPersonId, start.planObject)) {
7295
- return { give: false, reason: "used" };
7296
- }
7297
- if (await hasContinuation(ctx, start.holderPersonId, start.planObject)) {
7298
- return { give: false, reason: "continuation" };
7299
- }
7300
- const pending = await ctx.db.selectFrom("core_subscription_trial").selectAll().where("holder_person_id", "=", start.holderPersonId).where("plan_object", "=", start.planObject).where("used_at", "is", null).where("released_at", "is", null).orderBy("created_at", "desc").execute();
7301
- let held = null;
7302
- let blocked = null;
7303
- for (const row of pending) {
7304
- const status = await pageStatus(ctx, start.target, row.checkout_ref);
7305
- if (status === "complete") {
7306
- ctx.write(
7307
- ctx.db.updateTable("core_subscription_trial").set({ used_at: ctx.now }).where("checkout_id", "=", row.checkout_id).where("used_at", "is", null)
7308
- );
7309
- return { give: false, reason: "used" };
7310
- }
7311
- if (status === "expired") {
7312
- ctx.write(
7313
- ctx.db.updateTable("core_subscription_trial").set({ released_at: ctx.now }).where("checkout_id", "=", row.checkout_id).where("used_at", "is", null).where("released_at", "is", null)
7314
- );
7315
- continue;
7316
- }
7317
- if (status === null) {
7318
- blocked = "unconfirmed";
7319
- continue;
7320
- }
7321
- const expiresAt = new Date(
7322
- Date.parse(row.held_until) - TRIAL_HOLD_AFTER_EXPIRY_MS
7323
- ).toISOString();
7324
- if (!held && row.opened_by === start.caller && row.plan_id === start.planId) {
7325
- held = {
7326
- checkoutId: row.checkout_id,
7327
- url: row.url,
7328
- expiresAt,
7329
- amount: row.amount,
7330
- trialDays: row.trial_days
7331
- };
7332
- } else if (!blocked) {
7333
- blocked = "held";
7334
- }
7335
- }
7336
- if (held) return { give: false, reason: null, open: held };
7337
- if (blocked) return { give: false, reason: blocked };
7338
- return { give: true };
7339
- }
7340
- function readableInstant(value) {
7341
- if (typeof value !== "string") return null;
7342
- const at = Date.parse(value);
7343
- return Number.isNaN(at) ? null : new Date(at).toISOString();
7344
- }
7345
- function holdTrialStatement(ctx, hold) {
7346
- const expires = readableInstant(hold.expiresAt) ?? new Date(Date.parse(ctx.now) + 24 * 36e5).toISOString();
7347
- return ctx.db.insertInto("core_subscription_trial").values({
7348
- checkout_id: hold.checkoutId,
7349
- holder_person_id: hold.holderPersonId,
7350
- plan_object: hold.planObject,
7351
- plan_id: hold.planId,
7352
- url: hold.url,
7353
- checkout_ref: hold.checkoutRef,
7354
- opened_by: hold.openedBy,
7355
- amount: hold.amount,
7356
- trial_days: hold.trialDays,
7357
- held_until: new Date(Date.parse(expires) + TRIAL_HOLD_AFTER_EXPIRY_MS).toISOString(),
7358
- created_at: ctx.now
7359
- });
7360
- }
7361
- async function useTrial(ctx, row) {
7362
- if (!row.trial_end || !row.holder_person_id) return { second: false };
7363
- const checkout = await ctx.db.selectFrom("core_subscription_checkout").select("trial_days").where("id", "=", row.id).executeTakeFirst();
7364
- if (!checkout?.trial_days) return { second: false };
7365
- const mine = await ctx.db.selectFrom("core_subscription_trial").select(["used_at"]).where("checkout_id", "=", row.id).executeTakeFirst();
7366
- if (mine?.used_at) return { second: false };
7367
- const before = await ctx.db.selectFrom("core_subscription_trial").select("checkout_id").where("holder_person_id", "=", row.holder_person_id).where("plan_object", "=", row.plan_object).where("used_at", "is not", null).where("checkout_id", "!=", row.id).executeTakeFirst();
7368
- const otherSubscription = await ctx.db.selectFrom("core_subscription as s").innerJoin("core_subscription_checkout as c", "c.id", "s.id").select("s.id").where("s.holder_person_id", "=", row.holder_person_id).where("s.plan_object", "=", row.plan_object).where("s.trial_end", "is not", null).where("c.trial_days", "is not", null).where("s.id", "!=", row.id).executeTakeFirst();
7369
- if (mine) {
7370
- ctx.write(
7371
- ctx.db.updateTable("core_subscription_trial").set({ used_at: ctx.now }).where("checkout_id", "=", row.id).where("used_at", "is", null)
7372
- );
7373
- }
7374
- return { second: Boolean(before || otherSubscription) };
7375
- }
7376
-
7377
- // ../core/src/subscriptions/offers.ts
7378
- var OFFER_MIN_FREE_MS = 48 * 36e5 + 15 * 6e4;
7379
- var OFFER_IMPORT_MAX = 50;
7380
- var OFFER_STATUSES = ["open", "taken", "expired", "withdrawn"];
7381
- var OFFER_IMPORT_OUTCOMES = [
7382
- "created",
7383
- "updated",
7384
- "unchanged",
7385
- "unmatched",
7386
- "several_people",
7387
- "invalid",
7388
- "conflict"
7389
- ];
7390
- function offerStatus(row, now) {
7391
- if (row.subscription_id) return "taken";
7392
- if (row.withdrawn_at) return "withdrawn";
7393
- return row.free_until <= now ? "expired" : "open";
7394
- }
7395
- function requireManage(ctx) {
7396
- if (!holdsPermission(ctx.user, ctx.permissionGrants, "subscriptions:manage")) {
7397
- throw new ForbiddenError("The continuation offers report needs subscriptions:manage", {
7398
- permission: "subscriptions:manage"
7399
- });
7400
- }
7401
- }
7402
- async function heldPages(ctx, rows) {
7403
- const out = /* @__PURE__ */ new Map();
7404
- const held = rows.filter((r) => r.checkout_ref && !r.subscription_id);
7405
- if (!held.length) return out;
7406
- let target = null;
7407
- try {
7408
- target = await paymentsTarget(ctx.db);
7409
- } catch {
7410
- target = null;
7411
- }
7412
- for (const r of held) {
7413
- out.set(r.id, target ? await pageStatus(ctx, target, r.checkout_ref) : null);
7414
- }
7415
- return out;
7416
- }
7417
- function releaseStatement(ctx, row, version) {
7418
- return ctx.db.updateTable("core_subscription_offer").set({
7419
- checkout_id: null,
7420
- checkout_ref: null,
7421
- checkout_url: null,
7422
- held_until: null,
7423
- version
7424
- }).where("id", "=", row.id).where("checkout_id", "=", row.checkout_id);
7425
- }
7426
- async function offerPlan(records, planObject, planId) {
7427
- try {
7428
- await records.get(planObject, planId);
7429
- return { planId };
7430
- } catch (error) {
7431
- if (error.code !== "not_found") throw error;
7432
- }
7433
- const live = await records.list(planObject, { limit: 2 });
7434
- return live.items.length === 1 ? { planId: live.items[0].id } : { askUs: true };
7435
- }
7436
- var MOMENT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?(Z|([+-])(\d{2}):(\d{2}))$/;
7437
- function paidUpMoment(text, timeZone) {
7438
- const value = text.trim();
7439
- const date = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
7440
- if (date) {
7441
- const [y2, m2, d2] = [Number(date[1]), Number(date[2]), Number(date[3])];
7442
- if (!realWallClock(y2, m2, d2)) return null;
7443
- const wall = Date.UTC(y2, m2 - 1, d2);
7444
- let at2 = wall - zoneOffset(wall, timeZone);
7445
- at2 = wall - zoneOffset(at2, timeZone);
7446
- return new Date(at2).toISOString();
7447
- }
7448
- const moment = MOMENT.exec(value);
7449
- if (!moment) return null;
7450
- const [y, m, d, h, mi] = [1, 2, 3, 4, 5].map((i) => Number(moment[i]));
7451
- const s = moment[6] ? Number(moment[6]) : 0;
7452
- if (!realWallClock(y, m, d, h, mi, s)) return null;
7453
- let offset = 0;
7454
- if (moment[8] !== "Z") {
7455
- const [oh, om] = [Number(moment[10]), Number(moment[11])];
7456
- if (oh > 14 || om > 59) return null;
7457
- offset = (moment[9] === "-" ? -1 : 1) * (oh * 60 + om) * 6e4;
7458
- }
7459
- const fraction = moment[7] ? Math.floor(Number(moment[7]) * 1e3) : 0;
7460
- const at = Date.UTC(y, m - 1, d, h, mi, s) + fraction - offset;
7461
- return new Date(at).toISOString();
7462
- }
7463
- var MAX_YEARS_AHEAD = 2;
7464
- async function importOffers(ctx, input) {
7465
- const object = getObject(input.plan.object);
7466
- if (!object?.sellable?.recurring) {
7467
- throw new ValidationError(`${input.plan.object} is not a plan (an object sold every period)`, {
7468
- field: "plan",
7469
- rule: "not_a_plan"
7470
- });
7471
- }
7472
- await ctx.records.get(input.plan.object, input.plan.id);
7473
- if (input.invite && !holdsPermission(ctx.user, ctx.permissionGrants, "users:manage")) {
7474
- throw new ForbiddenError(
7475
- "Inviting the addresses to sign in needs the users:manage permission (customer.invite's)",
7476
- { field: "invite" }
7477
- );
7478
- }
7479
- const { timezone } = await loadGeneralSettings(ctx.db);
7480
- const { normaliseCustomerEmail, inviteCustomerStatement } = await import("./accounts-X4CKM3HL.js");
7481
- const addresses = input.rows.map((r) => normaliseCustomerEmail(r.email));
7482
- const valid = [...new Set(addresses.filter((a) => a !== null))];
7483
- const owners = /* @__PURE__ */ new Map();
7484
- const existing = /* @__PURE__ */ new Map();
7485
- const withdrawn = /* @__PURE__ */ new Map();
7486
- const accounts = /* @__PURE__ */ new Set();
7487
- const invites = /* @__PURE__ */ new Set();
7488
- if (valid.length) {
7489
- const people = await ctx.db.selectFrom("core_person_emails as e").innerJoin("core_person as p", "p.id", "e.person_id").select(["e.email", "e.person_id"]).where("e.email", "in", valid).where("e.live", "=", 1).where("p.deleted_at", "is", null).execute();
7490
- for (const p of people) {
7491
- owners.set(p.email, (owners.get(p.email) ?? /* @__PURE__ */ new Set()).add(p.person_id));
7492
- }
7493
- for (const row of await ctx.db.selectFrom("core_subscription_offer").selectAll().where("plan_object", "=", input.plan.object).where("email", "in", valid).orderBy("created_at").execute()) {
7494
- if (row.withdrawn_at) withdrawn.set(row.email, row);
7495
- else existing.set(row.email, row);
7496
- }
7497
- for (const a of await ctx.db.selectFrom("core_customer").select("email").where("email", "in", valid).execute()) {
7498
- accounts.add(a.email);
7499
- }
7500
- for (const i of await ctx.db.selectFrom("core_customer_invite").select("email").where("email", "in", valid).execute()) {
7501
- invites.add(i.email);
7502
- }
7503
- }
7504
- const pages = await heldPages(ctx, [...existing.values()]);
7505
- const latest = new Date(Date.parse(ctx.now) + MAX_YEARS_AHEAD * 365 * 864e5).toISOString();
7506
- const seen = /* @__PURE__ */ new Set();
7507
- const results = [];
7508
- for (const [index, row] of input.rows.entries()) {
7509
- const email = addresses[index] ?? null;
7510
- const result = (outcome2, extra = {}) => ({
7511
- email: email ?? row.email,
7512
- outcome: outcome2,
7513
- offerId: null,
7514
- personId: null,
7515
- freeUntil: null,
7516
- note: null,
7517
- signIn: null,
7518
- ...extra
7519
- });
7520
- if (!email) {
7521
- results.push(result("invalid", { note: "not an email address" }));
7522
- continue;
7523
- }
7524
- if (seen.has(email)) {
7525
- results.push(result("invalid", { note: "twice" }));
7526
- continue;
7527
- }
7528
- seen.add(email);
7529
- const freeUntil = paidUpMoment(row.freeUntil, timezone);
7530
- if (!freeUntil) {
7531
- results.push(
7532
- result("invalid", {
7533
- note: "the paid-up date is not a real date (YYYY-MM-DD) or moment with its offset"
7534
- })
7535
- );
7536
- continue;
7537
- }
7538
- if (freeUntil > latest) {
7539
- results.push(
7540
- result("invalid", {
7541
- note: `the paid-up date is more than ${MAX_YEARS_AHEAD} years away`,
7542
- freeUntil
7543
- })
7544
- );
7545
- continue;
7546
- }
7547
- const reference = row.reference?.trim() ? row.reference.trim().slice(0, 200) : null;
7548
- const people = [...owners.get(email) ?? []];
7549
- if (people.length === 0) {
7550
- results.push(result("unmatched", { freeUntil, note: "no person has this address" }));
7551
- continue;
7552
- }
7553
- if (people.length > 1) {
7554
- results.push(result("several_people", { freeUntil, note: "merge them first" }));
7555
- continue;
7556
- }
7557
- const personId = people[0];
7558
- const timing = freeUntil <= ctx.now ? "past" : Date.parse(freeUntil) - Date.parse(ctx.now) < OFFER_MIN_FREE_MS ? "under_48_hours" : null;
7559
- const before = existing.get(email);
7560
- const prior = withdrawn.get(email);
7561
- let outcome;
7562
- let offerId;
7563
- let note = timing;
7564
- if (!before && prior && !input.reissue) {
7565
- outcome = "conflict";
7566
- offerId = prior.id;
7567
- note = "withdrawn";
7568
- } else if (!before) {
7569
- outcome = "created";
7570
- offerId = newId("subscriptionOffer");
7571
- if (prior) note = timing ?? "reissued";
7572
- if (!input.dryRun) {
7573
- ctx.write(
7574
- ctx.db.insertInto("core_subscription_offer").values({
7575
- id: offerId,
7576
- plan_object: input.plan.object,
7577
- plan_id: input.plan.id,
7578
- email,
7579
- person_id: personId,
7580
- free_until: freeUntil,
7581
- reference,
7582
- imported_by: ctx.user.id,
7583
- created_at: ctx.now,
7584
- updated_at: ctx.now
7585
- })
7586
- );
7587
- if (prior) {
7588
- ctx.write(
7589
- ctx.db.updateTable("core_subscription_offer").set({ reissued_as: offerId, version: prior.version + 1 }).where("id", "=", prior.id)
7590
- );
7591
- }
7592
- ctx.recordChange({
7593
- object: "subscription_offer",
7594
- id: offerId,
7595
- action: "create",
7596
- after: {
7597
- email,
7598
- personId,
7599
- plan: input.plan,
7600
- freeUntil,
7601
- reference,
7602
- ...prior ? { reissuedFrom: prior.id } : {}
7603
- }
7604
- });
7605
- }
7606
- } else {
7607
- offerId = before.id;
7608
- let version = before.version;
7609
- const page = before.checkout_id ? pages.get(before.id) : void 0;
7610
- if (page === "expired") {
7611
- if (!input.dryRun) {
7612
- version += 1;
7613
- ctx.write(releaseStatement(ctx, before, version));
7614
- }
7615
- }
7616
- const same = before.free_until === freeUntil && (before.reference ?? null) === reference && before.plan_id === input.plan.id && before.person_id === personId;
7617
- const status = offerStatus(before, ctx.now);
7618
- const kept = status === "taken" ? "taken" : page === "complete" ? "completing" : page === "open" ? "held" : page === null ? "held_unconfirmed" : before.person_id !== personId ? "another_person" : null;
7619
- if (same) {
7620
- outcome = "unchanged";
7621
- note = kept === "taken" || kept === "completing" ? kept : timing;
7622
- } else if (kept) {
7623
- outcome = "conflict";
7624
- note = kept;
7625
- } else {
7626
- outcome = "updated";
7627
- if (!input.dryRun) {
7628
- ctx.write(
7629
- ctx.db.updateTable("core_subscription_offer").set({
7630
- plan_id: input.plan.id,
7631
- free_until: freeUntil,
7632
- reference,
7633
- updated_at: ctx.now,
7634
- version: version + 1
7635
- }).where("id", "=", before.id)
7636
- );
7637
- ctx.recordChange({
7638
- object: "subscription_offer",
7639
- id: before.id,
7640
- action: "update",
7641
- before: {
7642
- planId: before.plan_id,
7643
- freeUntil: before.free_until,
7644
- reference: before.reference
7645
- },
7646
- after: { planId: input.plan.id, freeUntil, reference }
7647
- });
7648
- }
7649
- }
7650
- }
7651
- let signIn = accounts.has(email) ? "has_account" : invites.has(email) ? "invited_before" : null;
7652
- const usable = outcome !== "conflict" && note !== "taken" && note !== "completing";
7653
- if (input.invite && signIn === null && usable && timing !== "past") {
7654
- try {
7655
- const invite = await inviteCustomerStatement(ctx.db, email, ctx.user.id, ctx.now);
7656
- if (!input.dryRun) {
7657
- ctx.write(invite.statement);
7658
- ctx.recordChange({
7659
- object: "customer_invite",
7660
- id: invite.email,
7661
- action: "create",
7662
- after: { email: invite.email, invitedBy: ctx.user.id }
7663
- });
7664
- }
7665
- signIn = "invited";
7666
- } catch {
7667
- signIn = "invite_refused";
7668
- }
7669
- }
7670
- results.push(result(outcome, { offerId, personId, freeUntil, note, signIn, email }));
7671
- }
7672
- return results;
7673
- }
7674
- async function prepareOfferTake(ctx, take) {
7675
- const offer = await ctx.db.selectFrom("core_subscription_offer").selectAll().where("id", "=", take.offerId).executeTakeFirst();
7676
- if (!offer || offer.email !== take.email || offer.person_id !== take.personId) {
7677
- throw new NotFoundError("subscription_offer", take.offerId);
7678
- }
7679
- if (offer.plan_object !== take.plan.object) {
7680
- throw new ValidationError("This offer is for another plan", {
7681
- field: "plan",
7682
- rule: "offer_plan"
7683
- });
7684
- }
7685
- if (offer.plan_id !== take.plan.id) {
7686
- const plan = await offerPlan(ctx.records, offer.plan_object, offer.plan_id);
7687
- if (!("planId" in plan) || plan.planId !== take.plan.id) {
7688
- throw new ValidationError("This offer is for another plan", {
7689
- field: "plan",
7690
- rule: "offer_plan"
7691
- });
7692
- }
7693
- }
7694
- if (offer.subscription_id) {
7695
- throw new ConflictError("You have taken this offer: your subscription is running", {
7696
- rule: "offer_taken"
7697
- });
7698
- }
7699
- if (offer.withdrawn_at) {
7700
- throw new ConflictError("This offer was withdrawn", { rule: "offer_withdrawn" });
7701
- }
7702
- let release = null;
7703
- if (offer.checkout_id && offer.checkout_ref) {
7704
- const status = await pageStatus(ctx, take.target, offer.checkout_ref);
7705
- if (status === "complete") {
7706
- throw new ConflictError(
7707
- "You have taken this offer: the payment provider is confirming your subscription",
7708
- { rule: "offer_taken" }
7709
- );
7710
- }
7711
- if (status === null) {
7712
- throw new ConflictError(
7713
- "We could not check your earlier checkout with the payment provider just now. Try again in a few minutes.",
7714
- { rule: "offer_unconfirmed" }
7715
- );
7716
- }
7717
- if (status === "open" && offer.checkout_url) {
7718
- const checkout = await ctx.db.selectFrom("core_subscription_checkout").select(["amount", "trial_end"]).where("id", "=", offer.checkout_id).executeTakeFirst();
7719
- if (checkout) {
7720
- return {
7721
- open: {
7722
- checkoutId: offer.checkout_id,
7723
- url: offer.checkout_url,
7724
- amount: checkout.amount,
7725
- freeUntil: checkout.trial_end ?? null,
7726
- expiresAt: offer.held_until ? new Date(Date.parse(offer.held_until) - TRIAL_HOLD_AFTER_EXPIRY_MS).toISOString() : null
7727
- }
7728
- };
7729
- }
7730
- }
7731
- release = offer.checkout_id;
7732
- }
7733
- if (offer.free_until <= ctx.now) {
7734
- throw new ConflictError(
7735
- `Your free time ended on ${offer.free_until.slice(0, 10)}: subscribe without the offer, charged from today`,
7736
- { rule: "offer_expired" }
7737
- );
7738
- }
7739
- const left2 = Date.parse(offer.free_until) - Date.parse(ctx.now);
7740
- return {
7741
- offerId: offer.id,
7742
- trialEnd: left2 >= OFFER_MIN_FREE_MS ? offer.free_until : null,
7743
- releaseCheckoutId: release,
7744
- version: offer.version
7745
- };
7746
- }
7747
- function holdOfferStatements(ctx, hold) {
7748
- const expires = hold.expiresAt ?? new Date(Date.parse(ctx.now) + 24 * 36e5).toISOString();
7749
- let version = hold.version;
7750
- const release = hold.releaseCheckoutId ? [releaseStatement(ctx, { id: hold.offerId, checkout_id: hold.releaseCheckoutId }, ++version)] : [];
7751
- return [
7752
- ...release,
7753
- ctx.db.updateTable("core_subscription_offer").set({
7754
- checkout_id: hold.checkoutId,
7755
- checkout_ref: hold.checkoutRef,
7756
- checkout_url: hold.url,
7757
- held_until: new Date(Date.parse(expires) + TRIAL_HOLD_AFTER_EXPIRY_MS).toISOString(),
7758
- updated_at: ctx.now,
7759
- version: version + 1
7760
- }).where("id", "=", hold.offerId)
7761
- ];
7762
- }
7763
- async function myOffers(ctx) {
7764
- const caller = ctx.principal;
7765
- if (caller.kind !== "customer") {
7766
- throw new ValidationError("A continuation offer is read by its own person, signed in", {
7767
- rule: "customer"
7768
- });
7769
- }
7770
- const account = await ctx.db.selectFrom("core_customer").select("email").where("id", "=", caller.customerId).executeTakeFirst();
7771
- if (!account) return [];
7772
- const rows = await ctx.db.selectFrom("core_subscription_offer").selectAll().where("person_id", "=", caller.personId).where("email", "=", account.email).where("subscription_id", "is", null).where("withdrawn_at", "is", null).where("free_until", ">", ctx.now).orderBy("free_until").execute();
7773
- const out = [];
7774
- for (const r of rows) {
7775
- const plan = await offerPlan(ctx.records, r.plan_object, r.plan_id);
7776
- out.push({
7777
- id: r.id,
7778
- planObject: r.plan_object,
7779
- planId: "planId" in plan ? plan.planId : r.plan_id,
7780
- freeUntil: r.free_until,
7781
- chargedNow: Date.parse(r.free_until) - Date.parse(ctx.now) < OFFER_MIN_FREE_MS,
7782
- askUs: !("planId" in plan)
7783
- });
7784
- }
7785
- return out;
7786
- }
7787
- var RUNNING_STATES = ["trialing", "active", "past_due"];
7788
- function readCursor(cursor) {
7789
- let parsed;
7790
- try {
7791
- parsed = JSON.parse(atob(cursor));
7792
- } catch {
7793
- parsed = null;
7794
- }
7795
- const c = parsed;
7796
- if (!c || typeof c !== "object" || typeof c.e !== "string" || typeof c.i !== "string" || Object.keys(c).length !== 2) {
7797
- throw new ValidationError("Not a cursor this list gave", { field: "cursor" });
7798
- }
7799
- return { e: c.e, i: c.i };
7800
- }
7801
- async function offerCounts(ctx, planObject) {
7802
- let q = ctx.db.selectFrom("core_subscription_offer").select([
7803
- sql`coalesce(sum(subscription_id IS NOT NULL), 0)`.as("taken"),
7804
- sql`coalesce(sum(subscription_id IS NULL AND withdrawn_at IS NOT NULL), 0)`.as(
7805
- "withdrawn"
7806
- ),
7807
- sql`coalesce(sum(subscription_id IS NULL AND withdrawn_at IS NULL AND free_until <= ${ctx.now}), 0)`.as(
7808
- "expired"
7809
- ),
7810
- sql`coalesce(sum(subscription_id IS NULL AND withdrawn_at IS NULL AND free_until > ${ctx.now}), 0)`.as(
7811
- "open"
7812
- )
7813
- ]);
7814
- if (planObject) q = q.where("plan_object", "=", planObject);
7815
- const row = await q.executeTakeFirst();
7816
- return {
7817
- open: Number(row?.open ?? 0),
7818
- taken: Number(row?.taken ?? 0),
7819
- expired: Number(row?.expired ?? 0),
7820
- withdrawn: Number(row?.withdrawn ?? 0)
7821
- };
7822
- }
7823
- async function listOffers(ctx, input) {
7824
- const after = input.cursor ? readCursor(input.cursor) : null;
7825
- let q = ctx.db.selectFrom("core_subscription_offer as o").leftJoin("core_subscription as s", "s.id", "o.subscription_id").leftJoin("core_person as p", "p.id", "o.person_id").selectAll("o").select([
7826
- "s.state as s_state",
7827
- "s.trial_end as s_trial_end",
7828
- "s.created_at as s_created_at",
7829
- "p.display_name as person_name"
7830
- ]);
7831
- if (input.planObject) q = q.where("o.plan_object", "=", input.planObject);
7832
- switch (input.status) {
7833
- case "taken":
7834
- q = q.where("o.subscription_id", "is not", null);
7835
- break;
7836
- case "withdrawn":
7837
- q = q.where("o.subscription_id", "is", null).where("o.withdrawn_at", "is not", null);
7838
- break;
7839
- case "expired":
7840
- q = q.where("o.subscription_id", "is", null).where("o.withdrawn_at", "is", null).where("o.free_until", "<=", ctx.now);
7841
- break;
7842
- case "open":
7843
- q = q.where("o.subscription_id", "is", null).where("o.withdrawn_at", "is", null).where("o.free_until", ">", ctx.now);
7844
- break;
7845
- default:
7846
- break;
7847
- }
7848
- if (after) {
7849
- const { e, i } = after;
7850
- q = q.where(
7851
- (eb) => eb.or([eb("o.email", ">", e), eb.and([eb("o.email", "=", e), eb("o.id", ">", i)])])
7852
- );
7853
- }
7854
- const rows = await q.orderBy("o.email").orderBy("o.id").limit(input.limit + 1).execute();
7855
- const page = rows.slice(0, input.limit);
7856
- const untaken = page.filter((r) => !r.subscription_id && r.person_id);
7857
- const others = /* @__PURE__ */ new Map();
7858
- if (untaken.length) {
7859
- const subs = await ctx.db.selectFrom("core_subscription").select(["id", "state", "created_at", "holder_person_id", "plan_object"]).where(
7860
- "holder_person_id",
7861
- "in",
7862
- untaken.map((r) => r.person_id)
7863
- ).where("state", "in", [...RUNNING_STATES]).orderBy("created_at", "desc").execute();
7864
- for (const s of subs) {
7865
- const key = `${s.holder_person_id}|${s.plan_object}`;
7866
- if (!others.has(key)) others.set(key, { id: s.id, state: s.state, createdAt: s.created_at });
7867
- }
7868
- }
7869
- const asked = input.pages === false ? /* @__PURE__ */ new Map() : await heldPages(
7870
- ctx,
7871
- page.filter((r) => offerStatus(r, ctx.now) === "open")
7872
- );
7873
- const items = page.map((r) => {
7874
- const status = offerStatus(r, ctx.now);
7875
- const chargedFromStart = r.charged_from_start === 1;
7876
- const said = r.checkout_id && status === "open" ? asked.get(r.id) : void 0;
7877
- return {
7878
- id: r.id,
7879
- email: r.email,
7880
- personId: r.person_id,
7881
- personName: r.person_name ?? null,
7882
- planObject: r.plan_object,
7883
- planId: r.plan_id,
7884
- reference: r.reference,
7885
- freeUntil: r.free_until,
7886
- status,
7887
- page: said === "open" ? "open" : said === "complete" ? "completing" : said === null ? "unconfirmed" : null,
7888
- takenAt: r.taken_at,
7889
- subscriptionId: r.subscription_id,
7890
- subscriptionState: r.s_state ?? null,
7891
- chargesFrom: r.subscription_id ? chargedFromStart ? r.s_created_at ?? r.taken_at : r.s_trial_end ?? r.free_until : null,
7892
- chargedFromStart,
7893
- subscribedWithout: !r.subscription_id && r.person_id ? others.get(`${r.person_id}|${r.plan_object}`) ?? null : null,
7894
- withdrawnAt: r.withdrawn_at,
7895
- withdrawReason: r.withdraw_reason,
7896
- reissuedAs: r.reissued_as,
7897
- createdAt: r.created_at
7898
- };
7899
- });
7900
- const last = page.at(-1);
7901
- return {
7902
- items,
7903
- nextCursor: rows.length > input.limit && last ? btoa(JSON.stringify({ e: last.email, i: last.id })) : null,
7904
- counts: input.counts === false ? { open: 0, taken: 0, expired: 0, withdrawn: 0 } : await offerCounts(ctx, input.planObject)
7905
- };
7906
- }
7907
- var CSV_COLUMNS = [
7908
- "email",
7909
- "name",
7910
- "reference",
7911
- "paid_up_to",
7912
- "status",
7913
- "taken_at",
7914
- "charges_from",
7915
- "charged_from_start",
7916
- "subscription",
7917
- "subscription_state",
7918
- "subscribed_without_offer",
7919
- "withdrawn_at",
7920
- "withdraw_reason",
7921
- "reissued_as"
7922
- ];
7923
- function csvCell(value) {
7924
- if (value === null || value === void 0) return "";
7925
- let text = String(value);
7926
- if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`;
7927
- return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
7928
- }
7929
- async function exportOffers(ctx, input) {
7930
- const lines = [CSV_COLUMNS.join(",")];
7931
- let cursor;
7932
- let rowCount = 0;
7933
- do {
7934
- const page = await listOffers(ctx, {
7935
- ...input,
7936
- limit: 200,
7937
- counts: false,
7938
- pages: false,
7939
- ...cursor ? { cursor } : {}
7940
- });
7941
- for (const o of page.items) {
7942
- rowCount += 1;
7943
- lines.push(
7944
- [
7945
- o.email,
7946
- o.personName,
7947
- o.reference,
7948
- o.freeUntil,
7949
- o.status,
7950
- o.takenAt,
7951
- o.chargesFrom,
7952
- o.subscriptionId ? o.chargedFromStart ? "yes" : "no" : "",
7953
- o.subscriptionId,
7954
- o.subscriptionState,
7955
- o.subscribedWithout ? `${o.subscribedWithout.id} (${o.subscribedWithout.state})` : "",
7956
- o.withdrawnAt,
7957
- o.withdrawReason,
7958
- o.reissuedAs
7959
- ].map(csvCell).join(",")
7960
- );
7961
- }
7962
- cursor = page.nextCursor ?? void 0;
7963
- } while (cursor);
7964
- return {
7965
- filename: `continuation-offers-${input.status ?? "all"}-${ctx.now.slice(0, 10)}.csv`,
7966
- csv: `${lines.join("\n")}
7967
- `,
7968
- rowCount
7969
- };
7970
- }
7971
- async function withdrawOffer(ctx, id, reason) {
7972
- const offer = await ctx.db.selectFrom("core_subscription_offer").selectAll().where("id", "=", id).executeTakeFirst();
7973
- if (!offer) throw new NotFoundError("subscription_offer", id);
7974
- if (offer.subscription_id) {
7975
- throw new ConflictError(
7976
- "This offer was taken: its subscription is running. End the subscription instead.",
7977
- { rule: "offer_taken", subscription: offer.subscription_id }
7978
- );
7979
- }
7980
- if (offer.withdrawn_at) {
7981
- throw new ConflictError("This offer is already withdrawn", { rule: "offer_withdrawn" });
7982
- }
7983
- const page = offer.checkout_id ? (await heldPages(ctx, [offer])).get(offer.id) : void 0;
7984
- let version = offer.version;
7985
- if (page === "expired") {
7986
- version += 1;
7987
- ctx.write(releaseStatement(ctx, offer, version));
7988
- }
7989
- ctx.write(
7990
- ctx.db.updateTable("core_subscription_offer").set({
7991
- withdrawn_at: ctx.now,
7992
- withdrawn_by: ctx.user.id,
7993
- withdraw_reason: reason,
7994
- updated_at: ctx.now,
7995
- version: version + 1
7996
- }).where("id", "=", id)
7997
- );
7998
- ctx.recordChange({
7999
- object: "subscription_offer",
8000
- id,
8001
- action: "update",
8002
- before: { withdrawnAt: null },
8003
- after: { withdrawnAt: ctx.now, reason }
8004
- });
8005
- return { id, pageOpen: page !== void 0 && page !== "expired" };
8006
- }
8007
-
8008
- // ../core/src/subscriptions/sweep.ts
8009
- var PAST_DUE_GRACE_DAYS = 30;
8010
-
8011
- // ../core/src/subscriptions/access.ts
8012
- var SUBSCRIPTION_ACCESS_KIND = "subscription";
8013
- var GIVING_STATES = ["trialing", "active", "past_due"];
8014
- var optionsOf = (source) => "options" in source ? source.options ?? {} : {};
8015
- function problems(object, source) {
8016
- const options = optionsOf(source);
8017
- const out = [];
8018
- for (const key of Object.keys(options)) {
8019
- if (key !== "plans" && key !== "covers")
8020
- out.push(`a subscription source has no option "${key}"`);
8021
- }
8022
- if (options.covers !== "all") out.push('covers must be "all" (every live record)');
8023
- const plans = options.plans;
8024
- if (typeof plans !== "string" || !plans) {
8025
- out.push("plans must name the plan object");
8026
- return out;
8027
- }
8028
- const plan = getObject(plans);
8029
- if (!plan || !object.extension || plan.extension !== object.extension || plan.name === object.name) {
8030
- out.push(`plans "${plans}" must be another object of the same extension`);
8031
- } else if (!plan.sellable?.recurring) {
8032
- out.push(`plans "${plans}" must be a plan: an object whose sellable declares recurring`);
8033
- }
8034
- return out;
8035
- }
8036
- function givingSubscriptionSql(personId, planObject, now) {
8037
- return sql`SELECT id FROM core_subscription
8038
- WHERE holder_person_id = ${personId}
8039
- AND plan_object = ${planObject}
8040
- AND state IN (${sql.join(GIVING_STATES.map((s) => sql`${s}`))})
8041
- AND NOT (cancel_at_period_end = 1 AND current_period_end IS NOT NULL AND current_period_end <= ${now})
8042
- AND NOT (cancel_at IS NOT NULL AND cancel_at <= ${now})
8043
- AND NOT (state = 'past_due' AND failing_since IS NOT NULL AND failing_since <= ${pastDueLapsesBefore(now)})
8044
- LIMIT 1`;
8045
- }
8046
- function pastDueLapsesBefore(now) {
8047
- return new Date(Date.parse(now) - PAST_DUE_GRACE_DAYS * 864e5).toISOString();
8048
- }
8049
- async function holders(query, source) {
8050
- if (problems(query.object, source).length) return /* @__PURE__ */ new Set();
8051
- const plans = String(optionsOf(source).plans);
8052
- const rows = await givingSubscriptionSql(query.personId, plans, query.now).execute(query.db);
8053
- if (!rows.rows.length) return /* @__PURE__ */ new Set();
8054
- const object = query.object;
8055
- const view = object.publishable && object.public && object.extension ? liveViewOf(object.name) : object.source;
8056
- const live = await sql`SELECT id FROM ${sql.table(view)} WHERE id IN (${sql.join(
8057
- query.ids.map((id) => sql`${id}`)
8058
- )})`.execute(query.db);
8059
- return new Set(live.rows.map((r) => String(r.id)));
8060
- }
8061
- registerAccessSource(SUBSCRIPTION_ACCESS_KIND, { holders, problems });
8062
-
8063
- // ../core/src/extensions/seed.ts
8064
- var ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
8065
- function fnv(text, seed) {
8066
- let hash = (2166136261 ^ seed) >>> 0;
8067
- for (let i = 0; i < text.length; i++) {
8068
- hash ^= text.charCodeAt(i);
8069
- hash = Math.imul(hash, 16777619) >>> 0;
8070
- }
8071
- return hash;
8072
- }
8073
- function seedRecordId(extension, object, key) {
8074
- const text = `${extension}.${object}.${key}`;
8075
- let out = "";
8076
- for (const seed of [1, 2, 3, 4]) {
8077
- let hash = fnv(text, seed);
8078
- for (let i = 0; i < 4; i++) {
8079
- out += ALPHABET[hash % 32];
8080
- hash = Math.floor(hash / 32);
8081
- }
8082
- }
8083
- return `rec_0000000000${out}`;
8084
- }
8085
- function seedStatements(manifest, local, now) {
8086
- const object = manifest.objects[local];
8087
- const statements = [];
8088
- const issues = [];
8089
- if (!object?.seed) return { statements, issues };
8090
- const table = objectTable(manifest.id, local);
8091
- const principal = `extension:${manifest.id}`;
8092
- for (const [key, values] of Object.entries(object.seed)) {
8093
- const path = `objects.${local}.seed.${key}`;
8094
- const id = seedRecordId(manifest.id, local, key);
8095
- const columns = [];
8096
- const params = [];
8097
- for (const [name, raw2] of Object.entries(values)) {
8098
- const field = object.fields[name];
8099
- if (!field || field.type === "formula") continue;
8100
- let value = raw2;
8101
- if (field.type === "relation" && raw2 && typeof raw2 === "object" && !Array.isArray(raw2)) {
8102
- const target = field.to?.split(".")[1] ?? "";
8103
- value = seedRecordId(manifest.id, target, String(raw2.seed));
8104
- }
8105
- const spec = FIELD_TYPE_REGISTRY[field.type];
8106
- const parsed = spec.schema(field).safeParse(value);
8107
- if (!parsed.success) {
8108
- issues.push({
8109
- path: `${path}.${name}`,
8110
- message: `Invalid seed value for ${name}: ${parsed.error.issues[0]?.message ?? "invalid"}`
8111
- });
8112
- continue;
8113
- }
8114
- columns.push(columnName(name));
8115
- params.push(spec.toStorage(parsed.data));
8116
- }
8117
- const all = ["id", "created_at", "updated_at", "created_by", ...columns];
8118
- statements.push(
8119
- CompiledQuery.raw(
8120
- `INSERT OR IGNORE INTO ${table} (${all.join(", ")}) VALUES (${all.map(() => "?").join(", ")})`,
8121
- [id, now, now, principal, ...params]
8122
- )
8123
- );
8124
- const title = values[object.titleField];
8125
- statements.push(
8126
- CompiledQuery.raw(
8127
- "INSERT OR IGNORE INTO core_search_docs (object_type, record_id, title, body) VALUES (?, ?, ?, '')",
8128
- [`${manifest.id}.${local}`, id, typeof title === "string" ? title : ""]
8129
- )
8130
- );
8131
- }
8132
- return { statements, issues };
8133
- }
8134
-
8135
- // ../core/src/extensions/reconciler.ts
8136
- var HIDDEN_RETENTION_DAYS = 30;
8137
- function clone(state) {
8138
- return structuredClone(state);
8139
- }
8140
- function columnDdl(name, type) {
8141
- const storage = FIELD_TYPE_REGISTRY[type].storage;
8142
- if (!storage) throw new Error(`${type} fields have no column`);
8143
- return `${ident(name)} ${storage}`;
8144
- }
8145
- function stateDefault(object, field) {
8146
- const states = object?.states;
8147
- return states?.field === field ? ` DEFAULT '${states.initial.replace(/'/g, "''")}'` : "";
8148
- }
8149
- function storedDefinition(field) {
8150
- const { renamedFrom: _renamed, ...rest } = field;
8151
- return rest;
8152
- }
8153
- function sameDefinition(a, b) {
8154
- const { resultType: _a2, ...left2 } = a;
8155
- const { resultType: _b, ...right } = b;
8156
- return JSON.stringify(left2) === JSON.stringify(right);
8157
- }
8158
- function sameStorage(a, b) {
8159
- return FIELD_TYPE_REGISTRY[a].storage === FIELD_TYPE_REGISTRY[b].storage;
8160
- }
8161
- var raw = (text) => CompiledQuery.raw(text);
8162
- async function planReconcile(db, manifest, options) {
8163
- const { timezone } = await loadGeneralSettings(db);
8164
- const current = await loadSchemaState(db);
8165
- const plan = planFromState(db, current, manifest, options.now, timezone);
8166
- plan.issues.push(...await dataIssues(db, current, plan.next, manifest.id));
8167
- return plan;
8168
- }
8169
- function uniqueIndexes(state, object, ext) {
8170
- const out = [];
8171
- (object.definition.unique ?? []).forEach((rule, i) => {
8172
- const columnOf = (local) => state.fields.find(
8173
- (f) => f.object === object.name && f.extensionId === ext && f.localName === local && f.status === "active" && f.tableName === object.tableName
8174
- )?.columnName ?? null;
8175
- const columns = rule.fields.map(columnOf);
8176
- const stateColumn = rule.states && object.definition.states ? columnOf(object.definition.states.field) : null;
8177
- if (columns.some((c) => c === null) || rule.states && !stateColumn) return;
8178
- const named = columns.map((c) => ident(c));
8179
- const filled = named.map((c) => `${c} IS NOT NULL`);
8180
- const states = rule.states ? [`${ident(stateColumn)} IN (${rule.states.map(sqlString).join(", ")})`] : [];
8181
- const where = ["deleted_at IS NULL", ...filled, ...states].join(" AND ");
8182
- const name = ident(`${object.tableName}__${named.join("__")}__u${shortHash(where)}`);
8183
- out.push({ rule: i, name, columns: named, where });
8184
- });
8185
- return out;
8186
- }
8187
- async function dataIssues(db, current, next, ext) {
8188
- const issues = [];
8189
- const reader = orgReader(db);
8190
- const anyDb = db;
8191
- for (const object of next.objects) {
8192
- if (object.extensionId !== ext || object.status !== "active") continue;
8193
- const before = current.objects.find(
8194
- (o) => o.name === object.name && o.tableName === object.tableName && o.status === "active"
8195
- );
8196
- const installed = getObject(object.name);
8197
- if (!before || !installed) continue;
8198
- const columnOf = (name) => name ? installed.fields.find((f) => f.name === name)?.column : void 0;
8199
- for (const index of uniqueIndexes(next, object, ext)) {
8200
- if ((current.indexes ?? []).some((i) => i.name === index.name)) continue;
8201
- const rule = object.definition.unique?.[index.rule];
8202
- const columns = (rule?.fields ?? []).map(columnOf);
8203
- if (!rule || columns.some((c) => !c)) continue;
8204
- const stateColumn = rule.states ? columnOf(object.definition.states?.field) : void 0;
8205
- if (rule.states && !stateColumn) continue;
8206
- let query = anyDb.selectFrom(visibleSource(reader, installed)).select(sql`group_concat(id, ', ')`.as("ids"));
8207
- for (const column2 of columns) query = query.where(column2, "is not", null);
8208
- if (rule.states && stateColumn) query = query.where(stateColumn, "in", [...rule.states]);
8209
- const clash = await query.groupBy(columns).having(sql`count(*)`, ">", 1).limit(5).execute();
8210
- if (clash.length) {
8211
- issues.push({
8212
- code: "unique_conflict",
8213
- path: `objects.${object.localName}.unique.${index.rule}`,
8214
- message: `${object.name}: live records already share these values: ${clash.map((r) => r.ids).join("; ")}. Change or delete them first.`
8215
- });
8216
- }
8217
- }
8218
- const grantsWas = before.definition.sellable?.recurring?.grants;
8219
- const grantsNow = object.definition.sellable?.recurring?.grants;
8220
- const grantKey = (g) => g ? JSON.stringify({
8221
- object: g.object.includes(".") ? g.object : `${ext}.${g.object}`,
8222
- states: g.states,
8223
- from: g.from ?? null,
8224
- until: g.until ?? null
8225
- }) : null;
8226
- if (grantsWas && grantKey(grantsWas) !== grantKey(grantsNow)) {
8227
- const running = await db.selectFrom("core_subscription_grant as g").innerJoin("core_subscription as s", "s.id", "g.subscription_id").select(["s.id", "g.record_id"]).where("s.plan_object", "=", object.name).where("s.state", "not in", ["ended", "expired"]).limit(10).execute();
8228
- if (running.length) {
8229
- issues.push({
8230
- code: "grants_conflict",
8231
- path: `objects.${object.localName}.sellable.recurring.grants`,
8232
- message: `${object.name}: what its subscriptions grant cannot be dropped or changed while subscriptions still running hold one (${running.map((r) => `${r.id} \u2192 ${r.record_id}`).join(", ")}). End them first, or keep the declaration.`
8233
- });
8234
- }
8235
- }
8236
- const was = before.definition.claims;
8237
- const now = object.definition.claims;
8238
- if (JSON.stringify(was ?? null) === JSON.stringify(now ?? null)) continue;
8239
- const column = columnOf(object.definition.states?.field ?? before.definition.states?.field);
8240
- const states = [
8241
- .../* @__PURE__ */ new Set([
8242
- ...was?.held ?? [],
8243
- ...was?.confirmed ?? [],
8244
- ...now?.held ?? [],
8245
- ...now?.confirmed ?? []
8246
- ])
8247
- ];
8248
- if (!column || !states.length) continue;
8249
- const live = await anyDb.selectFrom(visibleSource(reader, installed)).select("id").where(column, "in", states).limit(10).execute();
8250
- if (live.length) {
8251
- issues.push({
8252
- code: "claims_conflict",
8253
- path: `objects.${object.localName}.claims`,
8254
- message: `${object.name}: claims cannot change while records are in a state it names (${states.join(", ")}): ${live.map((r) => r.id).join(", ")}. Move them out of those states first.`
8255
- });
8256
- }
8257
- }
8258
- return issues;
8259
- }
8260
- function planFromState(db, current, manifest, now, orgZone = "UTC") {
8261
- const ext = manifest.id;
8262
- const next = clone(current);
8263
- const tableDdl = [];
8264
- const dataStatements = [];
8265
- const changes = [];
8266
- const issues = [];
8267
- const seedWrites = [];
8268
- const knownTables = /* @__PURE__ */ new Set([
8269
- ...current.objects.map((o) => o.tableName),
8270
- ...current.fields.map((f) => f.tableName)
8271
- ]);
8272
- const declaredObjects = /* @__PURE__ */ new Set();
8273
- for (const [local, object] of Object.entries(manifest.objects)) {
8274
- const name = `${ext}.${local}`;
8275
- declaredObjects.add(name);
8276
- const definition = {
8277
- label: object.label,
8278
- plural: object.plural,
8279
- ...object.icon ? { icon: object.icon } : {},
8280
- titleField: object.titleField,
8281
- ...object.description ? { description: object.description } : {},
8282
- fieldOrder: Object.keys(object.fields),
8283
- ...object.navigation ? { navigation: object.navigation } : {},
8284
- ...object.indexes?.length ? { indexes: object.indexes } : {},
8285
- ...object.timelineLinks?.length ? { timelineLinks: object.timelineLinks } : {},
8286
- ...object.stages ? { stages: object.stages } : {},
8287
- ...object.capacity ? { capacity: object.capacity } : {},
8288
- ...object.sellable ? { sellable: object.sellable } : {},
8289
- ...object.allowance ? { allowance: object.allowance } : {},
8290
- ...object.states ? { states: object.states } : {},
8291
- ...object.claims ? { claims: object.claims } : {},
8292
- ...object.unique?.length ? { unique: object.unique } : {},
8293
- ...object.recurring ? { recurring: object.recurring } : {},
8294
- ...object.owner ? { owner: object.owner } : {},
8295
- ...object.customer ? { customer: object.customer } : {},
8296
- ...object.public ? { public: object.public } : {},
8297
- ...object.signedIn ? { signedIn: object.signedIn } : {},
8298
- ...object.customerVia ? { customerVia: object.customerVia } : {},
8299
- ...object.access ? { access: object.access } : {},
8300
- ...object.publishable ? { publishable: object.publishable } : {},
8301
- ...object.navigationOrder !== void 0 ? { navigationOrder: object.navigationOrder } : {},
8302
- ...object.requireOneOf?.length ? { requireOneOf: object.requireOneOf } : {},
8303
- ...object.titleDefault ? { titleDefault: object.titleDefault } : {}
8304
- };
8305
- let existing = next.objects.find((o) => o.name === name);
8306
- if (!existing && object.renamedFrom) {
8307
- const oldName = `${ext}.${object.renamedFrom}`;
8308
- const old = next.objects.find((o) => o.name === oldName);
8309
- if (old) {
8310
- const table2 = objectTable(ext, local);
8311
- if (knownTables.has(table2)) {
8312
- issues.push({
8313
- code: "rename_conflict",
8314
- path: `objects.${local}.renamedFrom`,
8315
- message: `Cannot rename ${oldName} to ${name}: table ${table2} already exists`
8316
- });
8317
- continue;
8318
- }
8319
- tableDdl.push(`ALTER TABLE ${ident(old.tableName)} RENAME TO ${table2}`);
8320
- for (const table3 of [
8321
- "core_activity_links",
8322
- "core_task_links",
8323
- "core_record_tags",
8324
- "core_search_docs"
8325
- ]) {
8326
- dataStatements.push(
8327
- CompiledQuery.raw(`UPDATE ${table3} SET object_type = ? WHERE object_type = ?`, [
8328
- name,
8329
- oldName
8330
- ])
8331
- );
8332
- }
8333
- for (const field of next.fields) {
8334
- if (field.object === oldName) {
8335
- field.object = name;
8336
- if (field.tableName === old.tableName) field.tableName = table2;
8337
- field.updatedAt = now;
8338
- }
8339
- }
8340
- old.name = name;
8341
- old.localName = local;
8342
- old.tableName = table2;
8343
- old.updatedAt = now;
8344
- knownTables.add(table2);
8345
- changes.push({ kind: "rename_object", object: name, from: oldName });
8346
- existing = old;
8347
- }
8348
- }
8349
- if (existing) {
8350
- if (existing.status === "hidden") {
8351
- existing.status = "active";
8352
- existing.hiddenAt = null;
8353
- changes.push({ kind: "restore_object", object: name });
8354
- }
8355
- if (JSON.stringify(existing.definition) !== JSON.stringify(definition)) {
8356
- changes.push({ kind: "update_object", object: name });
8357
- }
8358
- existing.definition = definition;
8359
- existing.updatedAt = now;
8360
- continue;
8361
- }
8362
- const table = objectTable(ext, local);
8363
- const columns = Object.entries(object.fields).filter(([, field]) => field.type !== "formula").map(
8364
- ([field, spec]) => columnDdl(columnName(field), spec.type) + stateDefault(object, field)
8365
- );
8366
- tableDdl.push(
8367
- `CREATE TABLE ${table} (id TEXT PRIMARY KEY NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, created_by TEXT, updated_by TEXT, deleted_at TEXT, deleted_by TEXT${columns.length ? `, ${columns.join(", ")}` : ""})`
8368
- );
8369
- knownTables.add(table);
8370
- next.objects.push({
8371
- name,
8372
- extensionId: ext,
8373
- localName: local,
8374
- tableName: table,
8375
- status: "active",
8376
- hiddenAt: null,
8377
- definition,
8378
- createdAt: now,
8379
- updatedAt: now
8380
- });
8381
- changes.push({ kind: "create_object", object: name });
8382
- if (object.seed && Object.keys(object.seed).length) {
8383
- const seeded = seedStatements(manifest, local, now);
8384
- for (const issue of seeded.issues) issues.push({ code: "seed", ...issue });
8385
- seedWrites.push(...seeded.statements);
8386
- changes.push({
8387
- kind: "seed_records",
8388
- object: name,
8389
- detail: `${Object.keys(object.seed).length} record(s)`
8390
- });
8391
- }
8392
- for (const [field, spec] of Object.entries(object.fields)) {
8393
- next.fields.push({
8394
- extensionId: ext,
8395
- object: name,
8396
- localName: field,
8397
- name: field,
8398
- tableName: table,
8399
- columnName: spec.type === "formula" ? null : columnName(field),
8400
- type: spec.type,
8401
- definition: storedDefinition(spec),
8402
- status: "active",
8403
- hiddenAt: null,
8404
- createdAt: now,
8405
- updatedAt: now
8406
- });
8407
- changes.push({ kind: "add_field", object: name, field });
8408
- }
8409
- }
8410
- for (const object of next.objects) {
8411
- if (object.extensionId !== ext || object.status !== "active") continue;
8412
- if (!declaredObjects.has(object.name)) {
8413
- object.status = "hidden";
8414
- object.hiddenAt = now;
8415
- object.updatedAt = now;
8416
- changes.push({
8417
- kind: "hide_object",
8418
- object: object.name,
8419
- detail: `Hidden; its records are kept and can be dropped after ${HIDDEN_RETENTION_DAYS} days`
8420
- });
8421
- }
8422
- }
8423
- const targets = [
8424
- ...Object.entries(manifest.objects).map(
8425
- ([local, o]) => [`${ext}.${local}`, o.fields, `objects.${local}.fields`]
8426
- ),
8427
- ...Object.entries(manifest.fields).map(
8428
- ([target, fields]) => [target, fields, `fields.${target}`]
8429
- )
8430
- ];
8431
- const declaredFields = /* @__PURE__ */ new Set();
8432
- for (const [target, fields, basePath] of targets) {
8433
- const own = target.startsWith(`${ext}.`);
8434
- if (!own) {
8435
- if (!isCoreTarget(target)) {
8436
- const parts = splitObjectName(target);
8437
- const exists = next.objects.some((o) => o.name === target && o.status === "active");
8438
- if (!parts || !exists) {
8439
- issues.push({
8440
- code: "unknown_target",
8441
- path: basePath,
8442
- message: `Cannot add fields to ${target}: no such object is installed`
8443
- });
8444
- continue;
8445
- }
8446
- }
8447
- }
8448
- const table = own ? next.objects.find((o) => o.name === target).tableName : sideTable(ext, target);
8449
- for (const [local, spec] of Object.entries(fields)) {
8450
- const name = registryFieldName(ext, target, local);
8451
- const path = `${basePath}.${local}`;
8452
- declaredFields.add(`${target}|${name}`);
8453
- const mine = (f) => f.extensionId === ext && f.object === target;
8454
- let existing = next.fields.find((f) => mine(f) && f.localName === local);
8455
- if (existing && existing.createdAt === now && existing.updatedAt === now && own) {
8456
- if (changes.some((c) => c.kind === "create_object" && c.object === target)) continue;
8457
- }
8458
- if (!existing && spec.renamedFrom) {
8459
- const old = next.fields.find(
8460
- (f) => mine(f) && f.localName === spec.renamedFrom && f.status === "active"
8461
- );
8462
- if (old) {
8463
- if (old.columnName) {
8464
- const column2 = columnName(local);
8465
- tableDdl.push(
8466
- `ALTER TABLE ${ident(old.tableName)} RENAME COLUMN ${ident(old.columnName)} TO ${column2}`
8467
- );
8468
- old.columnName = column2;
8469
- }
8470
- changes.push({ kind: "rename_field", object: target, field: name, from: old.name });
8471
- old.localName = local;
8472
- old.name = name;
8473
- old.updatedAt = now;
8474
- existing = old;
8475
- }
8476
- }
8477
- if (existing) {
8478
- if (existing.status === "hidden") {
8479
- if (!sameStorage(existing.type, spec.type) || existing.type === "formula" !== (spec.type === "formula")) {
8480
- issues.push({
8481
- code: "hidden_conflict",
8482
- path,
8483
- message: `A removed ${existing.type} field named ${local} still holds data on ${target}`,
8484
- suggestion: `Choose another name, or drop the hidden field first (extension.dropHidden)`
8485
- });
8486
- continue;
8487
- }
8488
- existing.status = "active";
8489
- existing.hiddenAt = null;
8490
- changes.push({ kind: "restore_field", object: target, field: name });
8491
- }
8492
- if (existing.type !== spec.type) {
8493
- const formulaSwap = existing.type === "formula" !== (spec.type === "formula");
8494
- const manyChange = (existing.definition.many ?? false) !== (spec.many ?? false);
8495
- if (formulaSwap || manyChange || !isLosslessChange(existing.type, spec.type)) {
8496
- issues.push({
8497
- code: "lossy_type_change",
8498
- path: `${path}.type`,
8499
- message: `Changing ${target}.${name} from ${existing.type} to ${spec.type} could lose data`,
8500
- suggestion: `Add a new ${spec.type} field (e.g. ${local}${spec.type[0]?.toUpperCase()}${spec.type.slice(1)}), copy the values with a tool, then remove ${local}`
8501
- });
8502
- continue;
8503
- }
8504
- changes.push({
8505
- kind: "change_type",
8506
- object: target,
8507
- field: name,
8508
- detail: `${existing.type} \u2192 ${spec.type}`
8509
- });
8510
- existing.type = spec.type;
8511
- } else if ((existing.definition.many ?? false) !== (spec.many ?? false)) {
8512
- issues.push({
8513
- code: "lossy_type_change",
8514
- path: `${path}.many`,
8515
- message: `Changing ${target}.${name} between one and many could lose data`,
8516
- suggestion: "Add a new relation field instead"
8517
- });
8518
- continue;
8519
- } else if (!sameDefinition(existing.definition, storedDefinition(spec))) {
8520
- changes.push({ kind: "update_field", object: target, field: name });
8521
- }
8522
- existing.definition = storedDefinition(spec);
8523
- existing.updatedAt = now;
8524
- continue;
8525
- }
8526
- const column = spec.type === "formula" ? null : columnName(local);
8527
- if (column) {
8528
- if (!own && !knownTables.has(table)) {
8529
- tableDdl.push(`CREATE TABLE ${table} (id TEXT PRIMARY KEY NOT NULL)`);
8530
- knownTables.add(table);
8531
- }
8532
- if (next.fields.some((f) => f.tableName === table && f.columnName === column)) {
8533
- issues.push({
8534
- code: "rename_conflict",
8535
- path,
8536
- message: `Column ${column} already exists on ${table}`,
8537
- suggestion: "Choose another field name"
8538
- });
8539
- continue;
8540
- }
8541
- const declaring = own ? manifest.objects[target.slice(ext.length + 1)] : void 0;
8542
- tableDdl.push(
8543
- `ALTER TABLE ${table} ADD COLUMN ${columnDdl(column, spec.type)}${stateDefault(declaring, local)}`
8544
- );
8545
- if (spec.type === "timezone" && !spec.default) {
8546
- dataStatements.push(
8547
- CompiledQuery.raw(
8548
- `UPDATE ${table} SET ${ident(column)} = COALESCE((SELECT json_extract(value, '$') FROM core_settings WHERE key = ?), 'UTC') WHERE ${ident(column)} IS NULL`,
8549
- [ORG_TIMEZONE_SETTING]
8550
- )
8551
- );
8552
- }
8553
- }
8554
- next.fields.push({
8555
- extensionId: ext,
8556
- object: target,
8557
- localName: local,
8558
- name,
8559
- tableName: table,
8560
- columnName: column,
8561
- type: spec.type,
8562
- definition: storedDefinition(spec),
8563
- status: "active",
8564
- hiddenAt: null,
8565
- createdAt: now,
8566
- updatedAt: now
8567
- });
8568
- changes.push({ kind: "add_field", object: target, field: name });
8569
- }
8570
- }
8571
- for (const field of next.fields) {
8572
- if (field.extensionId !== ext || field.status !== "active") continue;
8573
- if (!declaredFields.has(`${field.object}|${field.name}`)) {
8574
- const objectHidden = next.objects.some(
8575
- (o) => o.name === field.object && o.status === "hidden"
8576
- );
8577
- if (objectHidden) continue;
8578
- field.status = "hidden";
8579
- field.hiddenAt = now;
8580
- field.updatedAt = now;
8581
- changes.push({
8582
- kind: "hide_field",
8583
- object: field.object,
8584
- field: field.name,
8585
- detail: `Hidden; its data is kept and can be dropped after ${HIDDEN_RETENTION_DAYS} days`
8586
- });
8587
- }
8588
- }
8589
- for (const object of next.objects) {
8590
- if (object.extensionId !== ext || object.status !== "active") continue;
8591
- const wanted = /* @__PURE__ */ new Map();
8592
- for (const fields of object.definition.indexes ?? []) {
8593
- const columns = fields.map((field) => {
8594
- if (field === "createdAt") return "created_at";
8595
- if (field === "updatedAt") return "updated_at";
8596
- const state = next.fields.find(
8597
- (f) => f.object === object.name && f.extensionId === ext && f.localName === field
8598
- );
8599
- return state?.columnName ?? null;
8600
- });
8601
- if (columns.some((c) => c === null)) continue;
8602
- const name = ident(`${object.tableName}__${columns.join("__")}`);
8603
- wanted.set(
8604
- name,
8605
- `CREATE INDEX IF NOT EXISTS ${name} ON ${ident(object.tableName)} (${columns.join(", ")}) WHERE deleted_at IS NULL`
8606
- );
8607
- }
8608
- for (const field of next.fields) {
8609
- if (field.object !== object.name || field.extensionId !== ext || field.status !== "active" || field.type !== "slug" || !field.columnName || field.tableName !== object.tableName) {
8610
- continue;
8611
- }
8612
- const column = ident(field.columnName);
8613
- const name = ident(`${object.tableName}__${column}__unique`);
8614
- wanted.set(
8615
- name,
8616
- `CREATE UNIQUE INDEX IF NOT EXISTS ${name} ON ${ident(object.tableName)} (${column}) WHERE deleted_at IS NULL AND ${column} IS NOT NULL`
8617
- );
8618
- }
8619
- for (const index of uniqueIndexes(next, object, ext)) {
8620
- wanted.set(
8621
- index.name,
8622
- `CREATE UNIQUE INDEX IF NOT EXISTS ${index.name} ON ${ident(object.tableName)} (${index.columns.join(", ")}) WHERE ${index.where}`
8623
- );
8624
- }
8625
- const existing = (current.indexes ?? []).filter(
8626
- (index) => index.table === object.tableName && index.name.startsWith(`${object.tableName}__`)
8627
- );
8628
- for (const index of existing) {
8629
- if (wanted.has(index.name)) continue;
8630
- tableDdl.push(`DROP INDEX IF EXISTS ${ident(index.name)}`);
8631
- changes.push({ kind: "drop_index", object: object.name, detail: index.name });
8632
- }
8633
- for (const [name, ddl] of wanted) {
8634
- if (existing.some((index) => index.name === name)) continue;
8635
- tableDdl.push(ddl);
8636
- changes.push({ kind: "add_index", object: object.name, detail: name });
8637
- }
8638
- }
8639
- return finishPlan(
8640
- db,
8641
- ext,
8642
- current,
8643
- next,
8644
- tableDdl,
8645
- [
8646
- ...dataStatements,
8647
- ...seedWrites,
8648
- ...capacityBackfill(next, ext, now),
8649
- ...allowanceBackfill(next, ext, orgZone, now)
8650
- ],
8651
- changes,
8652
- issues
8653
- );
8654
- }
8655
- function finishPlan(db, ext, current, next, tableDdl, dataStatements, changes, issues) {
8656
- const views = buildViews(next);
8657
- for (const { object, field, error } of views.errors) {
8658
- const f = next.fields.find((x) => x.object === object && x.name === field);
8659
- if (f?.extensionId !== ext) continue;
8660
- issues.push({
8661
- code: "formula",
8662
- path: `${object}.${field}`,
8663
- message: `${object}.${field}: ${error.message}`
8664
- });
8665
- }
8666
- for (const field of next.fields) {
8667
- const type = views.formulaTypes.get(`${field.object}|${field.name}`);
8668
- if (type) field.definition = { ...field.definition, resultType: type };
8669
- }
8670
- const staleViews = current.objects.filter(
8671
- (o) => !next.objects.some((n) => n.tableName === o.tableName && n.localName === o.localName)
8672
- ).map((o) => `DROP VIEW IF EXISTS ${objectView(o.extensionId, o.localName)}`);
8673
- const ddl = [.../* @__PURE__ */ new Set([...staleViews, ...views.drops]), ...tableDdl, ...views.creates];
8674
- const touched = /* @__PURE__ */ new Set([
8675
- ext,
8676
- ...next.fields.filter((f) => changes.some((c) => c.object === f.object)).map((f) => f.extensionId)
8677
- ]);
8678
- const stateWrites = [];
8679
- for (const extension of touched) {
8680
- stateWrites.push(
8681
- db.deleteFrom("core_extension_fields").where("extension_id", "=", extension).compile(),
8682
- db.deleteFrom("core_extension_objects").where("extension_id", "=", extension).compile()
8683
- );
8684
- for (const object of next.objects.filter((o) => o.extensionId === extension)) {
8685
- stateWrites.push(
8686
- db.insertInto("core_extension_objects").values({
8687
- name: object.name,
8688
- extension_id: object.extensionId,
8689
- local_name: object.localName,
8690
- table_name: object.tableName,
8691
- status: object.status,
8692
- hidden_at: object.hiddenAt,
8693
- definition: JSON.stringify(object.definition),
8694
- created_at: object.createdAt,
8695
- updated_at: object.updatedAt
8696
- }).compile()
8697
- );
8698
- }
8699
- const rows = next.fields.filter((f) => f.extensionId === extension);
8700
- for (const field of rows) {
8701
- stateWrites.push(
8702
- db.insertInto("core_extension_fields").values({
8703
- extension_id: field.extensionId,
8704
- object: field.object,
8705
- local_name: field.localName,
8706
- name: field.name,
8707
- table_name: field.tableName,
8708
- column_name: field.columnName,
8709
- type: field.type,
8710
- definition: JSON.stringify(field.definition),
8711
- status: field.status,
8712
- hidden_at: field.hiddenAt,
8713
- created_at: field.createdAt,
8714
- updated_at: field.updatedAt
8715
- }).compile()
8716
- );
8717
- }
8718
- }
8719
- return {
8720
- extension: ext,
8721
- ddl,
8722
- statements: [...ddl.map(raw), ...dataStatements, ...stateWrites],
8723
- changes,
8724
- issues,
8725
- next
8726
- };
8727
- }
8728
- async function planDropHidden(db, ext, options) {
8729
- const current = await loadSchemaState(db);
8730
- const next = clone(current);
8731
- const cutoff = new Date(
8732
- Date.parse(options.now) - (options.minAgeDays ?? HIDDEN_RETENTION_DAYS) * 864e5
8733
- ).toISOString();
8734
- const due = (hiddenAt) => hiddenAt !== null && hiddenAt <= cutoff;
8735
- const wanted = (name) => !options.only || options.only.includes(name);
8736
- const tableDdl = [];
8737
- const changes = [];
8738
- const droppedObjects = next.objects.filter(
8739
- (o) => o.extensionId === ext && o.status === "hidden" && due(o.hiddenAt) && wanted(o.name)
8740
- );
8741
- for (const object of droppedObjects) {
8742
- tableDdl.push(`DROP TABLE IF EXISTS ${ident(object.tableName)}`);
8743
- changes.push({ kind: "drop_object", object: object.name });
8744
- }
8745
- next.objects = next.objects.filter((o) => !droppedObjects.includes(o));
8746
- const droppedTables = new Set(droppedObjects.map((o) => o.tableName));
8747
- const droppedFields = next.fields.filter(
8748
- (f) => f.extensionId === ext && (droppedTables.has(f.tableName) || f.status === "hidden" && due(f.hiddenAt) && wanted(`${f.object}.${f.name}`))
8749
- );
8750
- for (const field of droppedFields) {
8751
- if (droppedTables.has(field.tableName)) continue;
8752
- if (field.columnName) {
8753
- tableDdl.push(`ALTER TABLE ${ident(field.tableName)} DROP COLUMN ${ident(field.columnName)}`);
8754
- }
8755
- changes.push({ kind: "drop_field", object: field.object, field: field.name });
8756
- }
8757
- next.fields = next.fields.filter((f) => !droppedFields.includes(f));
8758
- for (const table of new Set(droppedFields.map((f) => f.tableName))) {
8759
- if (droppedTables.has(table)) continue;
8760
- const isObjectTable = next.objects.some((o) => o.tableName === table);
8761
- if (!isObjectTable && !next.fields.some((f) => f.tableName === table)) {
8762
- tableDdl.push(`DROP TABLE IF EXISTS ${ident(table)}`);
8763
- }
8764
- }
8765
- const capacityDrops = droppedObjects.filter((o) => o.definition.capacity).flatMap((o) => dropCapacityStatements(o.name));
8766
- const claimantDrops = droppedObjects.filter((o) => o.definition.claims).flatMap((o) => releaseAllClaimsStatements(o.name, options.now));
8767
- const recurringDrops = droppedObjects.flatMap((o) => dropRecurringStatements(o.name));
8768
- const allowanceDrops = droppedObjects.flatMap((o) => {
8769
- const declared = o.definition.allowance;
8770
- if (!declared) return [];
8771
- return dropAllowanceStatements(o.name, "holds" in declared ? "holder" : "spender", options.now);
8772
- });
8773
- const granted = new Set(
8774
- current.objects.flatMap((o) => {
8775
- const to = o.definition.sellable?.grants?.object;
8776
- return to ? [to.includes(".") ? to : `${o.extensionId}.${to}`] : [];
8777
- })
8778
- );
8779
- const subscriptionGranted = new Set(
8780
- current.objects.flatMap((o) => {
8781
- const to = o.definition.sellable?.recurring?.grants?.object;
8782
- return to ? [to.includes(".") ? to : `${o.extensionId}.${to}`] : [];
8783
- })
8784
- );
8785
- const grantDrops = droppedObjects.flatMap((o) => [
8786
- ...granted.has(o.name) ? [CompiledQuery.raw("DELETE FROM core_order_grant WHERE object_type = ?", [o.name])] : [],
8787
- // What subscriptions granted of it (ADR 0510): the subscriptions stay.
8788
- ...subscriptionGranted.has(o.name) ? [CompiledQuery.raw("DELETE FROM core_subscription_grant WHERE object_type = ?", [o.name])] : []
8789
- ]);
8790
- return finishPlan(
8791
- db,
8792
- ext,
8793
- current,
8794
- next,
8795
- tableDdl,
8796
- [...capacityDrops, ...claimantDrops, ...recurringDrops, ...allowanceDrops, ...grantDrops],
8797
- changes,
8798
- []
8799
- );
8800
- }
8801
- function capacityBackfill(state, ext, now) {
8802
- const objects = state.objects.filter(
8803
- (o) => o.extensionId === ext && o.status === "active" && o.definition.capacity
8804
- );
8805
- const ordered = [
8806
- ...objects.filter((o) => !o.definition.capacity?.pool),
8807
- ...objects.filter((o) => o.definition.capacity?.pool)
8808
- ];
8809
- const statements = [];
8810
- for (const object of ordered) {
8811
- const capacity = object.definition.capacity;
8812
- if (!capacity) continue;
8813
- const column = (local) => state.fields.find(
8814
- (f) => f.object === object.name && f.extensionId === ext && f.localName === local && f.tableName === object.tableName
8815
- );
8816
- const places = column(capacity.places);
8817
- if (!places?.columnName) continue;
8818
- const pool = capacity.pool ? column(capacity.pool) : void 0;
8819
- statements.push(
8820
- backfillCounters({
8821
- object: object.name,
8822
- table: ident(object.tableName),
8823
- placesColumn: ident(places.columnName),
8824
- pool: pool?.columnName && pool.definition.to ? { column: ident(pool.columnName), object: pool.definition.to } : void 0,
8825
- now
8826
- })
8827
- );
8828
- }
8829
- return statements;
8830
- }
8831
- function allowanceBackfill(state, ext, orgZone, now) {
8832
- const statements = [];
8833
- for (const object of state.objects) {
8834
- const declared = object.definition.allowance;
8835
- if (object.extensionId !== ext || object.status !== "active") continue;
8836
- if (!declared || !("holds" in declared)) continue;
8837
- const h = declared.holds;
8838
- const field = (local) => local === void 0 ? void 0 : state.fields.find(
8839
- (f) => f.object === object.name && f.extensionId === ext && f.localName === local && f.tableName === object.tableName && f.status === "active"
8840
- );
8841
- const column = (local) => {
8842
- const found = field(local);
8843
- return found?.columnName ? ident(found.columnName) : void 0;
8844
- };
8845
- const person = column(h.person);
8846
- const uses = column(h.uses);
8847
- const per = typeof h.per === "string" ? { fixed: h.per } : { column: column(h.per.field) };
8848
- const stateColumn = object.definition.states ? column(object.definition.states.field) : void 0;
8849
- if (!person || !uses || !per.fixed && !per.column) continue;
8850
- const bound = (local) => {
8851
- const found = field(local);
8852
- return found?.columnName ? { column: ident(found.columnName), date: found.type === "date" } : void 0;
8853
- };
8854
- statements.push(
8855
- ...termsSyncStatements(
8856
- {
8857
- object: object.name,
8858
- table: ident(object.tableName),
8859
- person,
8860
- uses,
8861
- per: per.fixed ? { fixed: per.fixed } : { column: per.column },
8862
- from: bound(h.from),
8863
- until: bound(h.until),
8864
- zone: h.zone ? column(h.zone) : void 0,
8865
- live: h.live && stateColumn ? { column: stateColumn, states: h.live } : void 0,
8866
- emptyIsUnlimited: h.emptyIsUnlimited === true
8867
- },
8868
- "all",
8869
- orgZone,
8870
- now
8871
- )
8872
- );
8873
- }
8874
- return statements;
8875
- }
8876
- function sqlString(value) {
8877
- return `'${value.replaceAll("'", "''")}'`;
8878
- }
8879
- function shortHash(text) {
8880
- let hash = 2166136261;
8881
- for (let i = 0; i < text.length; i += 1) {
8882
- hash ^= text.charCodeAt(i);
8883
- hash = Math.imul(hash, 16777619) >>> 0;
8884
- }
8885
- return hash.toString(16).padStart(8, "0");
8886
- }
8887
-
8888
- // ../core/src/extensions/install.ts
8889
- function requireHost(ctx) {
8890
- if (!ctx.extensionHost) {
8891
- throw new ConfigError("The extension runtime is not available to this caller");
8892
- }
8893
- return ctx.extensionHost;
8894
- }
8895
- function fromSource(issue) {
8896
- return { stage: "typecheck", code: issue.code, path: issue.path, message: issue.message };
8897
- }
8898
- function fromManifest(issue) {
8899
- return {
8900
- stage: issue.code === "contract" ? "contract" : "formula",
8901
- code: issue.code,
8902
- path: issue.path,
8903
- message: issue.message,
8904
- ...issue.span ? { span: issue.span } : {}
8905
- };
8906
- }
8907
- function fromReconcile(issue) {
8908
- return {
8909
- stage: issue.code === "formula" ? "formula" : "reconcile",
8910
- code: issue.code,
8911
- path: issue.path,
8912
- message: issue.message,
8913
- ...issue.suggestion ? { suggestion: issue.suggestion } : {}
8914
- };
8915
- }
8916
- async function checkManifest(db, id, rawManifest, now, options = {}) {
8917
- const knownObjects = listObjects().map((o) => o.name).filter((name) => name.includes(".") && !name.startsWith(`${id}.`));
8918
- const { manifest, issues } = validateManifest(rawManifest, {
8919
- knownObjects,
8920
- baseFields: (object) => isCoreTarget(object) ? coreFormulaFields(object) : {}
8921
- });
8922
- const all = issues.map(fromManifest);
8923
- for (const [name, dashboard] of Object.entries(manifest?.dashboards ?? {})) {
8924
- const parsed = dashboardSpecSchema.safeParse(dashboard);
8925
- if (!parsed.success) {
8926
- for (const issue of parsed.error.issues.slice(0, 10)) {
8927
- all.push({
8928
- stage: "contract",
8929
- code: "contract",
8930
- path: `dashboards.${name}.${issue.path.join(".")}`,
8931
- message: issue.message
8932
- });
8933
- }
8934
- }
8935
- }
8936
- if (manifest && options.source === "runtime") all.push(...outsideDeclarations(manifest));
8937
- const raw2 = rawManifest?.requires;
8938
- const required = Array.isArray(raw2) ? raw2.filter((r) => typeof r === "string").slice(0, 10) : [];
8939
- if (required.length) {
8940
- const present = new Set(
8941
- (await db.selectFrom("core_extensions").select("id").where("id", "in", required).where("status", "=", "active").execute()).map((r) => r.id)
8942
- );
8943
- for (const id2 of options.installed ?? []) present.add(id2);
8944
- required.forEach((id2, i) => {
8945
- if (!present.has(id2)) {
8946
- all.unshift({
8947
- stage: "contract",
8948
- code: "contract",
8949
- path: `requires.${i}`,
8950
- message: `This extension requires the ${id2} extension, which is not installed and on here`
8951
- });
8952
- }
8953
- });
8954
- }
8955
- if (manifest) {
8956
- for (const issue of allowanceHostIssues(manifest)) {
8957
- all.push({ stage: "contract", code: "contract", path: issue.path, message: issue.message });
8958
- }
8959
- }
8960
- for (const [name, object] of Object.entries(manifest?.objects ?? {})) {
8961
- (object.access?.sources ?? []).forEach((source, i) => {
8962
- if ("kind" in source && source.kind !== void 0 && !hasAccessSourceKind(source.kind)) {
8963
- all.push({
8964
- stage: "contract",
8965
- code: "contract",
8966
- path: `objects.${name}.access.sources.${i}.kind`,
8967
- message: `The host provides no source of access of kind "${source.kind}"`
8968
- });
8969
- }
8970
- });
8971
- }
8972
- if (manifest && manifest.id !== id) {
8973
- all.push({
8974
- stage: "contract",
8975
- code: "contract",
8976
- path: "id",
8977
- message: `The extension declares id "${manifest.id}" but is installed as "${id}"`
8978
- });
8979
- }
8980
- if (!manifest || all.length) return { issues: all, manifest, plan: null };
8981
- const plan = await planReconcile(db, manifest, { now });
8982
- return { issues: plan.issues.map(fromReconcile), manifest, plan };
8983
- }
8984
- function outsideDeclarations(manifest) {
8985
- const issues = [];
8986
- const why = "Only a shipped extension, or one in the org's own repository, can do that: it is a reviewed change. Remove it, or move the extension out of the workspace.";
8987
- manifest.permissions.operations.forEach((operation, i) => {
8988
- if (operation.startsWith("x.")) {
8989
- issues.push({
8990
- stage: "contract",
8991
- code: "outside_audience",
8992
- path: `permissions.operations.${i}`,
8993
- message: `A runtime extension cannot call another extension's tool (${operation}). ${why}`
8994
- });
8995
- }
8996
- });
8997
- for (const [name, tool] of Object.entries(manifest.tools)) {
8998
- const open = (tool.audiences ?? []).filter((audience) => audience !== "staff");
8999
- if (open.length || tool.customerFields) {
9000
- issues.push({
9001
- stage: "contract",
9002
- code: "outside_audience",
9003
- path: `tools.${name}.audiences`,
9004
- message: `A runtime extension cannot open a tool to ${open.join(" or ") || "customer"} callers. ${why}`
9005
- });
9006
- }
9007
- }
9008
- for (const [name, tool] of Object.entries(manifest.tools)) {
9009
- if (tool.permission) {
9010
- issues.push({
9011
- stage: "contract",
9012
- code: "outside_audience",
9013
- path: `tools.${name}.permission`,
9014
- message: `A runtime extension cannot declare a permission for a staff role. ${why}`
9015
- });
9016
- }
9017
- }
9018
- if (manifest.grantable?.length) {
9019
- issues.push({
9020
- stage: "contract",
9021
- code: "outside_audience",
9022
- path: "grantable",
9023
- message: `A runtime extension cannot declare a permission an admin grants. ${why}`
9024
- });
9025
- }
9026
- for (const name of Object.keys(manifest.roles ?? {})) {
9027
- issues.push({
9028
- stage: "contract",
9029
- code: "outside_audience",
9030
- path: `roles.${name}`,
9031
- message: `A runtime extension cannot declare a staff role. ${why}`
9032
- });
9033
- }
9034
- for (const [name, object] of Object.entries(manifest.objects)) {
9035
- if (object.customer) {
9036
- issues.push({
9037
- stage: "contract",
9038
- code: "outside_audience",
9039
- path: `objects.${name}.customer`,
9040
- message: `A runtime extension cannot make ${name} visible to customers. ${why}`
9041
- });
9042
- }
9043
- if (object.public) {
9044
- issues.push({
9045
- stage: "contract",
9046
- code: "outside_audience",
9047
- path: `objects.${name}.public`,
9048
- message: `A runtime extension cannot make ${name} readable by the public. ${why}`
9049
- });
9050
- }
9051
- if (object.customerVia) {
9052
- issues.push({
9053
- stage: "contract",
9054
- code: "outside_audience",
9055
- path: `objects.${name}.customerVia`,
9056
- message: `A runtime extension cannot make ${name} readable by customers through their own records. ${why}`
9057
- });
9058
- }
9059
- if (object.access) {
9060
- issues.push({
9061
- stage: "contract",
9062
- code: "outside_audience",
9063
- path: `objects.${name}.access`,
9064
- message: `A runtime extension cannot declare who holds access to ${name}. ${why}`
9065
- });
9066
- }
9067
- if (object.signedIn) {
9068
- issues.push({
9069
- stage: "contract",
9070
- code: "outside_audience",
9071
- path: `objects.${name}.signedIn`,
9072
- message: `A runtime extension cannot make ${name} readable by signed-in customers. ${why}`
9073
- });
9074
- }
9075
- if (object.sellable) {
9076
- issues.push({
9077
- stage: "contract",
9078
- code: "outside_audience",
9079
- path: `objects.${name}.sellable`,
9080
- message: `A runtime extension cannot make ${name} something customers and the public can buy. ${why}`
9081
- });
9082
- }
9083
- }
9084
- return issues;
9085
- }
9086
- async function checkEvaluated(db, id, evaluated, now, options = {}) {
9087
- if (!evaluated.ok) {
9088
- return { ok: false, issues: evaluated.issues.map(fromSource), manifest: null, plan: null };
9089
- }
9090
- const { issues, manifest, plan } = await checkManifest(db, id, evaluated.manifest, now, options);
9091
- return {
9092
- ok: issues.length === 0,
9093
- issues,
9094
- manifest,
9095
- plan: plan ? { ddl: plan.ddl, changes: plan.changes } : null
9096
- };
9097
- }
9098
- async function checkExtension(ctx, input) {
9099
- const host = requireHost(ctx);
9100
- return checkEvaluated(ctx.db, input.id, await host.evaluate(input), ctx.now, {
9101
- source: "runtime"
9102
- });
9103
- }
9104
- function firstIssue(issues) {
9105
- const first = issues[0];
9106
- if (!first) return "";
9107
- const more = issues.length > 1 ? ` (and ${issues.length - 1} more)` : "";
9108
- return `: ${first.path}: ${first.message}${more}`;
9109
- }
9110
- function extensionPrincipalId(id) {
9111
- return `extension:${id}`;
9112
- }
9113
- async function installExtension(ctx, input) {
9114
- const host = requireHost(ctx);
9115
- const existing = await ctx.db.selectFrom("core_extensions").selectAll().where("id", "=", input.id).executeTakeFirst();
9116
- const ejecting = input.eject && existing?.source === "shipped" && input.source === "runtime";
9117
- if (existing && existing.source !== input.source && !ejecting) {
9118
- throw new ValidationError(
9119
- `${input.id} is already installed as a ${existing.source} extension`,
9120
- { id: input.id }
9121
- );
9122
- }
9123
- const evaluated = await host.evaluate({ id: input.id, commit: input.commit });
9124
- if (!evaluated.ok) {
9125
- const issues2 = evaluated.issues.map(fromSource);
9126
- throw new ValidationError(`${input.id} failed its check${firstIssue(issues2)}`, { issues: issues2 });
9127
- }
9128
- const { issues, manifest, plan } = await checkManifest(
9129
- ctx.db,
9130
- input.id,
9131
- evaluated.manifest,
9132
- ctx.now,
9133
- { source: input.source }
9134
- );
9135
- if (issues.length || !manifest || !plan) {
9136
- throw new ValidationError(`${input.id} failed its check${firstIssue(issues)}`, { issues });
9137
- }
9138
- const unchanged = existing?.commit_oid === input.commit && existing.status === "active" && plan.changes.length === 0;
9139
- if (unchanged) {
9140
- return {
9141
- id: input.id,
9142
- version: manifest.version,
9143
- commit: input.commit,
9144
- source: input.source,
9145
- changes: [],
9146
- changed: false
9147
- };
9148
- }
9149
- const principal = extensionPrincipalId(input.id);
9150
- const user = await ctx.db.selectFrom("core_user").select("id").where("id", "=", principal).executeTakeFirst();
9151
- if (!user) {
9152
- ctx.write(
9153
- ctx.db.insertInto("core_user").values({
9154
- id: principal,
9155
- name: manifest.label ?? input.id,
9156
- email: `${input.id}@extensions.crm.invalid`,
9157
- email_verified: 0,
9158
- image: null,
9159
- created_at: ctx.now,
9160
- updated_at: ctx.now,
9161
- role: "member",
9162
- kind: "extension"
9163
- })
9164
- );
9165
- }
9166
- ctx.write(...plan.statements);
9167
- const installedBy = ctx.user.id === "system" ? null : ctx.user.id;
9168
- const manifestJson = JSON.stringify(manifest);
9169
- ctx.write(
9170
- ctx.db.insertInto("core_extensions").values({
9171
- id: input.id,
9172
- source: input.source,
9173
- status: "active",
9174
- status_reason: null,
9175
- version: manifest.version,
9176
- commit_oid: input.commit,
9177
- last_good_commit: existing?.last_good_commit ?? null,
9178
- manifest: manifestJson,
9179
- failure_count: 0,
9180
- user_id: principal,
9181
- installed_at: ctx.now,
9182
- installed_by: installedBy,
9183
- updated_at: ctx.now
9184
- }).onConflict(
9185
- (oc) => oc.column("id").doUpdateSet({
9186
- source: input.source,
9187
- status: "active",
9188
- status_reason: null,
9189
- version: manifest.version,
9190
- commit_oid: input.commit,
9191
- manifest: manifestJson,
9192
- failure_count: 0,
9193
- updated_at: ctx.now
9194
- })
9195
- ),
9196
- ctx.db.insertInto("core_extension_versions").values({
9197
- extension_id: input.id,
9198
- commit_oid: input.commit,
9199
- version: manifest.version,
9200
- manifest: manifestJson,
9201
- installed_at: ctx.now,
9202
- installed_by: installedBy
9203
- }).onConflict(
9204
- (oc) => oc.columns(["extension_id", "commit_oid"]).doUpdateSet({ installed_at: ctx.now })
9205
- )
9206
- );
9207
- ctx.write(
9208
- ...automationSyncStatements(ctx.db, {
9209
- extensionId: input.id,
9210
- commit: input.commit,
9211
- automations: manifest.automations ?? {},
9212
- now: ctx.now
9213
- })
9214
- );
9215
- return {
9216
- id: input.id,
9217
- version: manifest.version,
9218
- commit: input.commit,
9219
- source: input.source,
9220
- changes: plan.changes,
9221
- changed: true
9222
- };
9223
- }
9224
-
9225
6803
  // ../db/src/dialect.ts
9226
6804
  var D1Connection = class {
9227
6805
  constructor(db) {
@@ -9311,41 +6889,6 @@ function createDb(d1) {
9311
6889
  }
9312
6890
 
9313
6891
  export {
9314
- WIDGET_TYPES,
9315
- dashboardFilterSchema,
9316
- filterValuesSchema,
9317
- widgetSpecSchema,
9318
- dashboardSpecSchema,
9319
- SYSTEM_PARAMS,
9320
- allowedParamNames,
9321
- listVisible,
9322
- getVisible,
9323
- previewVisible,
9324
- recordAccess,
9325
- NO_TRIAL_REASONS,
9326
- decideTrial,
9327
- readableInstant,
9328
- holdTrialStatement,
9329
- useTrial,
9330
6892
  ReadOnlyDatabaseError,
9331
- createDb,
9332
- HIDDEN_RETENTION_DAYS,
9333
- planDropHidden,
9334
- OFFER_IMPORT_MAX,
9335
- OFFER_STATUSES,
9336
- OFFER_IMPORT_OUTCOMES,
9337
- requireManage,
9338
- importOffers,
9339
- prepareOfferTake,
9340
- holdOfferStatements,
9341
- myOffers,
9342
- listOffers,
9343
- exportOffers,
9344
- withdrawOffer,
9345
- PAST_DUE_GRACE_DAYS,
9346
- requireHost,
9347
- checkManifest,
9348
- checkEvaluated,
9349
- checkExtension,
9350
- installExtension
6893
+ createDb
9351
6894
  };