@composable-os/cli 0.0.0-stage → 0.1.0-beta.11

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 (184) hide show
  1. package/LICENSE +109 -0
  2. package/README.md +24 -2
  3. package/dist/accounts-UHYLCLEY.js +45 -0
  4. package/dist/blocks-5IFU25J6.js +233 -0
  5. package/dist/chunk-2ABSVMGB.js +13 -0
  6. package/dist/chunk-2IVEVPMY.js +669 -0
  7. package/dist/chunk-2TWV3SVB.js +349 -0
  8. package/dist/chunk-2XC5JLBO.js +1931 -0
  9. package/dist/chunk-324WJXNP.js +320 -0
  10. package/dist/chunk-5KSXSK7Y.js +47 -0
  11. package/dist/chunk-6ELZRNUU.js +116 -0
  12. package/dist/chunk-6UWRT4VM.js +220 -0
  13. package/dist/chunk-6WGFA2IV.js +643 -0
  14. package/dist/chunk-6XTU2MTP.js +11278 -0
  15. package/dist/chunk-7CQGMVDO.js +63 -0
  16. package/dist/chunk-7D4GKZOX.js +615 -0
  17. package/dist/chunk-7OGCMQXG.js +284 -0
  18. package/dist/chunk-DHS2CV2M.js +139 -0
  19. package/dist/chunk-DU6OIFOU.js +2358 -0
  20. package/dist/chunk-E4WCYTCT.js +347 -0
  21. package/dist/chunk-E64SG24J.js +88 -0
  22. package/dist/chunk-FJIZGS5Q.js +698 -0
  23. package/dist/chunk-GYTEW66E.js +50 -0
  24. package/dist/chunk-HDIOVFAZ.js +544 -0
  25. package/dist/chunk-K34UKWEI.js +298 -0
  26. package/dist/chunk-KGHA67HG.js +765 -0
  27. package/dist/chunk-LAAL4YGR.js +365 -0
  28. package/dist/chunk-LO6WGU5Y.js +26189 -0
  29. package/dist/chunk-MBIKVRAC.js +1425 -0
  30. package/dist/chunk-P6UWZ6QQ.js +426 -0
  31. package/dist/chunk-PDD2ETVF.js +1302 -0
  32. package/dist/chunk-UB4I2QKR.js +31575 -0
  33. package/dist/chunk-WHKJGF36.js +2418 -0
  34. package/dist/chunk-XIDLW3EP.js +15471 -0
  35. package/dist/chunk-YFTLIEWU.js +504 -0
  36. package/dist/chunk-YNUZRTPH.js +182 -0
  37. package/dist/chunk-ZAWES2UD.js +9364 -0
  38. package/dist/chunk-ZZFWMVJO.js +704 -0
  39. package/dist/cli-5UNY5G5L.js +136 -0
  40. package/dist/cli-UYZMVQMR.js +24534 -0
  41. package/dist/cli.js +25 -0
  42. package/dist/client-repo-SE4EKG6W.js +55 -0
  43. package/dist/create.js +25 -0
  44. package/dist/fields-FTWWMD7N.js +50 -0
  45. package/dist/grants-LOW6TSWD.js +32 -0
  46. package/dist/invoke-6KVT6WJI.js +41 -0
  47. package/dist/moves-E2HKYCTK.js +41 -0
  48. package/dist/order-U4KZLLSJ.js +19 -0
  49. package/dist/person-UHLVBVLR.js +67 -0
  50. package/dist/plan-on-sale-TJPFCNL7.js +26 -0
  51. package/dist/platform/migrations/0001_init.sql +59 -0
  52. package/dist/platform/migrations/0002_users_settings.sql +34 -0
  53. package/dist/platform/migrations/0003_people_organisations.sql +225 -0
  54. package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
  55. package/dist/platform/migrations/0005_views_audit.sql +79 -0
  56. package/dist/platform/migrations/0006_search.sql +223 -0
  57. package/dist/platform/migrations/0007_crm_views.sql +141 -0
  58. package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
  59. package/dist/platform/migrations/0010_approval_queue.sql +90 -0
  60. package/dist/platform/migrations/0011_connected_apps.sql +36 -0
  61. package/dist/platform/migrations/0020_extensions.sql +373 -0
  62. package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
  63. package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
  64. package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
  65. package/dist/platform/migrations/0061_audit_retention.sql +95 -0
  66. package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
  67. package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
  68. package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
  69. package/dist/platform/migrations/0065_storage_stats.sql +13 -0
  70. package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
  71. package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
  72. package/dist/platform/migrations/0100_stage_history.sql +54 -0
  73. package/dist/platform/migrations/0110_integrations.sql +103 -0
  74. package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
  75. package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
  76. package/dist/platform/migrations/0130_automations.sql +113 -0
  77. package/dist/platform/migrations/0131_notifications.sql +29 -0
  78. package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
  79. package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
  80. package/dist/platform/migrations/0160_releases.sql +41 -0
  81. package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
  82. package/dist/platform/migrations/0170_automation_connections.sql +32 -0
  83. package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
  84. package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
  85. package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
  86. package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
  87. package/dist/platform/migrations/0210_daily_digest.sql +33 -0
  88. package/dist/platform/migrations/0220_entitlements.sql +13 -0
  89. package/dist/platform/migrations/0221_support_grants.sql +33 -0
  90. package/dist/platform/migrations/0250_judge.sql +11 -0
  91. package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
  92. package/dist/platform/migrations/0252_judge_usage.sql +14 -0
  93. package/dist/platform/migrations/0255_summary_checks.sql +9 -0
  94. package/dist/platform/migrations/0256_outbound_check.sql +9 -0
  95. package/dist/platform/migrations/0260_ai_usage.sql +20 -0
  96. package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
  97. package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
  98. package/dist/platform/migrations/0320_duplicates.sql +41 -0
  99. package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
  100. package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
  101. package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
  102. package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
  103. package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
  104. package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
  105. package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
  106. package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
  107. package/dist/platform/migrations/0362_voice_usage.sql +17 -0
  108. package/dist/platform/migrations/0365_routines.sql +38 -0
  109. package/dist/platform/migrations/0370_approval_execution.sql +20 -0
  110. package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
  111. package/dist/platform/migrations/0380_rec_views.sql +94 -0
  112. package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
  113. package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
  114. package/dist/platform/migrations/0402_erase_requests.sql +34 -0
  115. package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
  116. package/dist/platform/migrations/0411_device_sessions.sql +33 -0
  117. package/dist/platform/migrations/0420_transition_history.sql +100 -0
  118. package/dist/platform/migrations/0421_orders.sql +134 -0
  119. package/dist/platform/migrations/0422_order_payments.sql +109 -0
  120. package/dist/platform/migrations/0440_capacity.sql +100 -0
  121. package/dist/platform/migrations/0441_capacity_views.sql +40 -0
  122. package/dist/platform/migrations/0450_order_grants.sql +21 -0
  123. package/dist/platform/migrations/0451_pack_roles.sql +18 -0
  124. package/dist/platform/migrations/0460_content.sql +59 -0
  125. package/dist/platform/migrations/0461_media.sql +52 -0
  126. package/dist/platform/migrations/0470_publish_versions.sql +36 -0
  127. package/dist/platform/migrations/0471_permission_grants.sql +18 -0
  128. package/dist/platform/migrations/0490_staff_invites.sql +40 -0
  129. package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
  130. package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
  131. package/dist/platform/migrations/0500_published_media_field.sql +25 -0
  132. package/dist/platform/migrations/0501_import_keys.sql +23 -0
  133. package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
  134. package/dist/platform/migrations/0516_order_tax.sql +63 -0
  135. package/dist/platform/migrations/0520_publish_requests.sql +20 -0
  136. package/dist/platform/migrations/0530_subscriptions.sql +173 -0
  137. package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
  138. package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
  139. package/dist/platform/migrations/0533_allowances.sql +262 -0
  140. package/dist/platform/migrations/0560_recurring.sql +75 -0
  141. package/dist/platform/migrations/0580_subscription_grants.sql +21 -0
  142. package/dist/platform/migrations/0581_once_per_person.sql +34 -0
  143. package/dist/platform/migrations/0600_tool_actions_ran_at_queue.sql +22 -0
  144. package/dist/platform/migrations/0610_waitlists.sql +54 -0
  145. package/dist/platform/migrations/0630_subscription_changes.sql +122 -0
  146. package/dist/platform/migrations/0650_person_links.sql +90 -0
  147. package/dist/platform/migrations/0670_unmoved_guard.sql +52 -0
  148. package/dist/platform/migrations/0690_sellable_refund_due.sql +98 -0
  149. package/dist/platform/sdk/allowance.ts +522 -0
  150. package/dist/platform/sdk/automation-check.ts +534 -0
  151. package/dist/platform/sdk/automation.ts +743 -0
  152. package/dist/platform/sdk/behaviour.ts +215 -0
  153. package/dist/platform/sdk/capacity.ts +303 -0
  154. package/dist/platform/sdk/contract.ts +909 -0
  155. package/dist/platform/sdk/document.ts +935 -0
  156. package/dist/platform/sdk/field-types.ts +111 -0
  157. package/dist/platform/sdk/formula/ast.ts +72 -0
  158. package/dist/platform/sdk/formula/compile.ts +454 -0
  159. package/dist/platform/sdk/formula/index.ts +4 -0
  160. package/dist/platform/sdk/formula/parser.ts +417 -0
  161. package/dist/platform/sdk/index.ts +36 -0
  162. package/dist/platform/sdk/manifest.ts +1785 -0
  163. package/dist/platform/sdk/media.ts +108 -0
  164. package/dist/platform/sdk/permissions.ts +60 -0
  165. package/dist/platform/sdk/recurring.ts +321 -0
  166. package/dist/platform/sdk/renamed.ts +63 -0
  167. package/dist/platform/sdk/rich-text-fixture.ts +68 -0
  168. package/dist/platform/sdk/rich-text.ts +221 -0
  169. package/dist/platform/sdk/runtime.ts +410 -0
  170. package/dist/platform/sdk/sellable.ts +1138 -0
  171. package/dist/platform/sdk/slug.ts +25 -0
  172. package/dist/platform/sdk/states.ts +598 -0
  173. package/dist/platform/sdk/testing.ts +847 -0
  174. package/dist/platform/sdk/unique.ts +81 -0
  175. package/dist/products-2H5DR232.js +11 -0
  176. package/dist/run-7P4RQALH.js +648 -0
  177. package/dist/run-PO3W5BFA.js +508 -0
  178. package/dist/run-ZCGFMEZF.js +309 -0
  179. package/dist/src-CRO35DYY.js +46 -0
  180. package/dist/src-I3IJ4NKC.js +354 -0
  181. package/dist/token-MOJUA2U6.js +70 -0
  182. package/dist/token-util-TENRN4V7.js +6 -0
  183. package/dist/visibility-TVXZ67FD.js +41 -0
  184. package/package.json +33 -4
@@ -0,0 +1,284 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ checkPerson,
4
+ erasedAddresses
5
+ } from "./chunk-XIDLW3EP.js";
6
+ import {
7
+ notifyStatements
8
+ } from "./chunk-ZZFWMVJO.js";
9
+ import {
10
+ newId
11
+ } from "./chunk-2XC5JLBO.js";
12
+ import {
13
+ ConfigError,
14
+ ConflictError,
15
+ NotFoundError,
16
+ ValidationError
17
+ } from "./chunk-6XTU2MTP.js";
18
+ import {
19
+ external_exports
20
+ } from "./chunk-LO6WGU5Y.js";
21
+
22
+ // ../core/src/customers/settings.ts
23
+ var CUSTOMER_SIGNUP_SETTING = "customer_signup";
24
+ var CUSTOMER_SIGNUP_MODES = ["open", "buyers", "invite_only"];
25
+ var customerSignupModeSchema = external_exports.enum(CUSTOMER_SIGNUP_MODES);
26
+ var DEFAULT_CUSTOMER_SIGNUP = "invite_only";
27
+ async function loadCustomerSignup(db) {
28
+ const row = await db.selectFrom("core_settings").select("value").where("key", "=", CUSTOMER_SIGNUP_SETTING).executeTakeFirst();
29
+ if (!row) return DEFAULT_CUSTOMER_SIGNUP;
30
+ try {
31
+ const parsed = customerSignupModeSchema.safeParse(JSON.parse(row.value));
32
+ return parsed.success ? parsed.data : DEFAULT_CUSTOMER_SIGNUP;
33
+ } catch {
34
+ return DEFAULT_CUSTOMER_SIGNUP;
35
+ }
36
+ }
37
+ var CUSTOMER_SIGNUP_SUBSCRIBERS_SETTING = "customer_signup_subscribers";
38
+ var DEFAULT_CUSTOMER_SIGNUP_SUBSCRIBERS = false;
39
+ async function loadCustomerSignupSubscribers(db) {
40
+ const row = await db.selectFrom("core_settings").select("value").where("key", "=", CUSTOMER_SIGNUP_SUBSCRIBERS_SETTING).executeTakeFirst();
41
+ if (!row) return DEFAULT_CUSTOMER_SIGNUP_SUBSCRIBERS;
42
+ try {
43
+ return JSON.parse(row.value) === true;
44
+ } catch {
45
+ return DEFAULT_CUSTOMER_SIGNUP_SUBSCRIBERS;
46
+ }
47
+ }
48
+ var CUSTOMER_ERASE_DUE_SETTING = "customer_erase_due_days";
49
+ var DEFAULT_ERASE_DUE_DAYS = 30;
50
+ var eraseDueDaysSchema = external_exports.number().int().min(1).max(365);
51
+ async function loadEraseDueDays(db) {
52
+ const row = await db.selectFrom("core_settings").select("value").where("key", "=", CUSTOMER_ERASE_DUE_SETTING).executeTakeFirst();
53
+ if (!row) return DEFAULT_ERASE_DUE_DAYS;
54
+ try {
55
+ const parsed = eraseDueDaysSchema.safeParse(JSON.parse(row.value));
56
+ return parsed.success ? parsed.data : DEFAULT_ERASE_DUE_DAYS;
57
+ } catch {
58
+ return DEFAULT_ERASE_DUE_DAYS;
59
+ }
60
+ }
61
+ var CUSTOMER_EMAIL_CONNECTION_SETTING = "customer_email_connection";
62
+ async function loadCustomerEmailConnection(db) {
63
+ const row = await db.selectFrom("core_settings").select("value").where("key", "=", CUSTOMER_EMAIL_CONNECTION_SETTING).executeTakeFirst();
64
+ if (!row) return null;
65
+ try {
66
+ const value = JSON.parse(row.value);
67
+ return typeof value === "string" && value ? value : null;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ // ../core/src/customers/accounts.ts
74
+ var emailSchema = external_exports.string().trim().toLowerCase().pipe(external_exports.email().max(320));
75
+ function normaliseCustomerEmail(email) {
76
+ const parsed = emailSchema.safeParse(email);
77
+ return parsed.success ? parsed.data : null;
78
+ }
79
+ function toAccount(row) {
80
+ return {
81
+ id: row.id,
82
+ personId: row.person_id,
83
+ email: row.email,
84
+ status: row.status,
85
+ linkState: row.link_state
86
+ };
87
+ }
88
+ var ACCOUNT_COLUMNS = ["id", "person_id", "email", "status", "link_state"];
89
+ async function loadCustomer(db, id) {
90
+ const row = await db.selectFrom("core_customer").select(ACCOUNT_COLUMNS).where("id", "=", id).executeTakeFirst();
91
+ return row ? toAccount(row) : null;
92
+ }
93
+ async function loadCustomerSignIn(db, customerId, personId) {
94
+ const row = await db.selectFrom("core_customer").select(["email", "email_verified"]).where("id", "=", customerId).where("person_id", "=", personId).where("status", "=", "active").executeTakeFirst();
95
+ return row ? { email: row.email, verified: row.email_verified === 1 } : null;
96
+ }
97
+ async function loadCustomerByEmail(db, email) {
98
+ const address = normaliseCustomerEmail(email);
99
+ if (!address) return null;
100
+ const row = await db.selectFrom("core_customer").select(ACCOUNT_COLUMNS).where("email", "=", address).executeTakeFirst();
101
+ return row ? toAccount(row) : null;
102
+ }
103
+ async function isErased(db, address) {
104
+ return (await erasedAddresses(db, [address])).size > 0;
105
+ }
106
+ async function customerCodeReason(db, email, now = (/* @__PURE__ */ new Date()).toISOString(), options = {}) {
107
+ const address = normaliseCustomerEmail(email);
108
+ if (!address) return null;
109
+ if (await isErased(db, address)) return null;
110
+ const account = await loadCustomerByEmail(db, address);
111
+ if (account) return account.status === "active" ? "account" : null;
112
+ const signup = await loadCustomerSignup(db);
113
+ if (signup === "open") return "open";
114
+ const invite = await db.selectFrom("core_customer_invite").select("email").where("email", "=", address).executeTakeFirst();
115
+ if (invite) return "invite";
116
+ if (signup === "buyers" && await hasBought(db, address)) return "buyer";
117
+ if (await loadCustomerSignupSubscribers(db)) {
118
+ const { findPlanOnSale } = await import("./plan-on-sale-TJPFCNL7.js");
119
+ const found = await findPlanOnSale(db, now, options);
120
+ if (found.state === "on_sale") return "subscription";
121
+ }
122
+ return null;
123
+ }
124
+ async function customerMayGetCode(db, email) {
125
+ return await customerCodeReason(db, email) !== null;
126
+ }
127
+ async function hasBought(db, address) {
128
+ const { orgReader, visibleSource } = await import("./visibility-TVXZ67FD.js");
129
+ const { orderObject } = await import("./order-U4KZLLSJ.js");
130
+ const owners = db.selectFrom("core_person_emails as e").innerJoin("core_person as p", "p.id", "e.person_id").select("e.person_id").where("e.email", "=", address).where("e.live", "=", 1).where("p.deleted_at", "is", null);
131
+ const row = await db.selectFrom(visibleSource(orgReader(db), orderObject)).select("id").where((eb) => eb.or([eb("email", "=", address), eb("person_id", "in", owners)])).where("paid", ">", 0).executeTakeFirst();
132
+ return Boolean(row);
133
+ }
134
+ async function inviteCustomerStatement(db, email, invitedByUserId, now) {
135
+ const address = normaliseCustomerEmail(email);
136
+ if (!address) throw new ValidationError("Not an email address", { field: "email" });
137
+ if (await isErased(db, address)) {
138
+ throw new ValidationError("This address belongs to an erased person", { field: "email" });
139
+ }
140
+ const statement = db.insertInto("core_customer_invite").values({ email: address, invited_by: invitedByUserId, invited_at: now }).onConflict(
141
+ (oc) => oc.column("email").doUpdateSet({ invited_by: invitedByUserId, invited_at: now })
142
+ );
143
+ return { email: address, statement };
144
+ }
145
+ async function inviteCustomer(db, email, invitedByUserId, now = (/* @__PURE__ */ new Date()).toISOString()) {
146
+ const { email: address, statement } = await inviteCustomerStatement(
147
+ db.query,
148
+ email,
149
+ invitedByUserId,
150
+ now
151
+ );
152
+ await db.batch([statement]);
153
+ return { email: address };
154
+ }
155
+ var CUSTOMER_LINK_AUDIT = "customer.link";
156
+ async function sameEmailPeople(db, address) {
157
+ const { conflicts } = await checkPerson(db, { emails: [address] });
158
+ return [...new Set(conflicts.map((c) => c.id))];
159
+ }
160
+ async function creatorFor(db, address) {
161
+ const active = db.selectFrom("core_user").select(["id", "email", "name", "role"]).where("kind", "=", "human").where("deactivated_at", "is", null);
162
+ const invite = await db.selectFrom("core_customer_invite").select("invited_by").where("email", "=", address).executeTakeFirst();
163
+ const row = (invite ? await active.where("id", "=", invite.invited_by).executeTakeFirst() : void 0) ?? await active.where("role", "=", "admin").orderBy("id").limit(1).executeTakeFirst();
164
+ return row ? { id: row.id, email: row.email, name: row.name, role: row.role } : null;
165
+ }
166
+ async function createPersonFor(db, address, customerId, now) {
167
+ const user = await creatorFor(db.query, address);
168
+ if (!user) throw new ConfigError("There is no admin to create the customer's Person for");
169
+ const { invoke } = await import("./invoke-6KVT6WJI.js");
170
+ const person = await invoke(
171
+ "person.create",
172
+ { emails: [{ email: address, primary: true }] },
173
+ {
174
+ actor: "automation",
175
+ user,
176
+ origin: { surface: "system", automationId: CUSTOMER_LINK_AUDIT, sessionId: customerId },
177
+ db,
178
+ clock: () => now
179
+ }
180
+ );
181
+ return person.id;
182
+ }
183
+ async function linkCustomer(db, customerId, now = /* @__PURE__ */ new Date()) {
184
+ const account = await loadCustomer(db.query, customerId);
185
+ if (!account) throw new NotFoundError("customer", customerId);
186
+ if (account.personId && account.linkState === "linked") {
187
+ return { linkState: "linked", personId: account.personId, created: false };
188
+ }
189
+ if (await isErased(db.query, account.email)) {
190
+ throw new ValidationError("This address belongs to an erased person");
191
+ }
192
+ let matches = await sameEmailPeople(db.query, account.email);
193
+ let created = false;
194
+ if (matches.length === 0) {
195
+ try {
196
+ matches = [await createPersonFor(db, account.email, account.id, now)];
197
+ created = true;
198
+ } catch (error) {
199
+ if (!(error instanceof ConflictError)) throw error;
200
+ matches = await sameEmailPeople(db.query, account.email);
201
+ if (!matches.length) throw error;
202
+ }
203
+ }
204
+ let result;
205
+ if (matches.length === 1) {
206
+ const personId = matches[0];
207
+ const holder = await db.query.selectFrom("core_customer").select("id").where("person_id", "=", personId).where("id", "!=", account.id).executeTakeFirst();
208
+ result = holder ? { linkState: "needs_merge", personId: null, created, reason: "person_has_account" } : { linkState: "linked", personId, created };
209
+ } else {
210
+ result = { linkState: "needs_merge", personId: null, created, reason: "several_people" };
211
+ }
212
+ const at = now.toISOString();
213
+ const statements = [
214
+ db.query.updateTable("core_customer").set({ person_id: result.personId, link_state: result.linkState, updated_at: at }).where("id", "=", account.id),
215
+ db.query.insertInto("core_audit").values({
216
+ id: newId("audit"),
217
+ at,
218
+ operation: CUSTOMER_LINK_AUDIT,
219
+ risk: "write",
220
+ actor: "customer",
221
+ user_id: account.id,
222
+ origin: JSON.stringify({ surface: "client" }),
223
+ input: JSON.stringify({ customerId: account.id }),
224
+ result: JSON.stringify({
225
+ linkState: result.linkState,
226
+ personId: result.personId,
227
+ created: result.created,
228
+ ...result.reason ? { reason: result.reason, people: matches } : {}
229
+ }),
230
+ gate_decision: "auto",
231
+ outcome: "ok",
232
+ error: null
233
+ })
234
+ ];
235
+ if (result.linkState === "needs_merge") {
236
+ const body = result.reason === "several_people" ? `${account.email} signed in to their customer account, and ${matches.length} people have this address. Merge them: the account links at the next sign-in.` : `${account.email} signed in to a new customer account, and the person with this address already has another one. Disable one account, then ask them to sign in again.`;
237
+ const plan = await notifyStatements(
238
+ db.query,
239
+ {
240
+ to: [{ role: "admin" }],
241
+ type: "system.message",
242
+ title: "A customer account needs a merge",
243
+ body,
244
+ link: matches[0] ? { kind: "record", object: "person", id: matches[0] } : null,
245
+ dedupeKey: `customer.needs_merge:${account.id}`,
246
+ source: { actor: "system" }
247
+ },
248
+ at
249
+ );
250
+ statements.push(...plan.statements);
251
+ }
252
+ await db.batch(statements);
253
+ return result;
254
+ }
255
+ function customerSignedInStatement(db, customerId, now) {
256
+ return db.updateTable("core_customer").set({ last_sign_in_at: now, updated_at: now }).where("id", "=", customerId);
257
+ }
258
+
259
+ export {
260
+ CUSTOMER_SIGNUP_SETTING,
261
+ customerSignupModeSchema,
262
+ loadCustomerSignup,
263
+ CUSTOMER_SIGNUP_SUBSCRIBERS_SETTING,
264
+ loadCustomerSignupSubscribers,
265
+ CUSTOMER_ERASE_DUE_SETTING,
266
+ eraseDueDaysSchema,
267
+ loadEraseDueDays,
268
+ CUSTOMER_EMAIL_CONNECTION_SETTING,
269
+ loadCustomerEmailConnection,
270
+ normaliseCustomerEmail,
271
+ loadCustomer,
272
+ loadCustomerSignIn,
273
+ loadCustomerByEmail,
274
+ customerCodeReason,
275
+ customerMayGetCode,
276
+ hasBought,
277
+ inviteCustomerStatement,
278
+ inviteCustomer,
279
+ CUSTOMER_LINK_AUDIT,
280
+ sameEmailPeople,
281
+ creatorFor,
282
+ linkCustomer,
283
+ customerSignedInStatement
284
+ };
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ priceLines,
4
+ sellableOf,
5
+ sellableProblems
6
+ } from "./chunk-6WGFA2IV.js";
7
+ import {
8
+ paymentsTarget
9
+ } from "./chunk-E64SG24J.js";
10
+ import {
11
+ loadOrderCurrency,
12
+ loadReturnOrigins
13
+ } from "./chunk-6ELZRNUU.js";
14
+ import {
15
+ ConfigError,
16
+ ValidationError,
17
+ buyableSource,
18
+ refreshSchemaRegistry,
19
+ scopeOf,
20
+ sql,
21
+ viewColumnOf
22
+ } from "./chunk-6XTU2MTP.js";
23
+ import {
24
+ listObjects
25
+ } from "./chunk-YFTLIEWU.js";
26
+
27
+ // ../core/src/orders/subscription-setup.ts
28
+ async function subscriptionSetup(db) {
29
+ let target = null;
30
+ try {
31
+ target = await paymentsTarget(db);
32
+ } catch (error) {
33
+ if (!(error instanceof ConfigError)) throw error;
34
+ }
35
+ return {
36
+ returnOrigins: [...await loadReturnOrigins(db)],
37
+ currency: await loadOrderCurrency(db),
38
+ target
39
+ };
40
+ }
41
+ function setupComplete(setup) {
42
+ return setup.returnOrigins.length > 0 && setup.currency !== null && setup.target !== null;
43
+ }
44
+
45
+ // ../core/src/customers/plan-on-sale.ts
46
+ var PUBLIC = Object.freeze({ kind: "public" });
47
+ var PLANS_LOOKED_AT = 50;
48
+ var PLAN_ON_SALE_MEMO_MS = 6e4;
49
+ var memo = null;
50
+ function forgetPlanOnSale() {
51
+ memo = null;
52
+ }
53
+ async function findPlanOnSale(db, now = (/* @__PURE__ */ new Date()).toISOString(), options = {}) {
54
+ const at = Date.now();
55
+ if (options.memo && memo && at - memo.at < PLAN_ON_SALE_MEMO_MS) return memo.value;
56
+ let value;
57
+ try {
58
+ value = await compute(db, now);
59
+ } catch (error) {
60
+ value = { state: "unknown", reason: error instanceof Error ? error.message : String(error) };
61
+ }
62
+ memo = { at, value };
63
+ return value;
64
+ }
65
+ async function hasPlanOnSale(db, now = (/* @__PURE__ */ new Date()).toISOString()) {
66
+ return (await findPlanOnSale(db, now)).state === "on_sale";
67
+ }
68
+ async function compute(db, now) {
69
+ const setup = await subscriptionSetup(db);
70
+ if (!setupComplete(setup)) return { state: "none" };
71
+ await refreshSchemaRegistry(db);
72
+ let unanswered = false;
73
+ for (const object of listObjects()) {
74
+ const sellable = sellableOf(object);
75
+ if (!sellable?.recurring || sellableProblems(sellable, object).length) continue;
76
+ const scope = scopeOf(PUBLIC, object, false);
77
+ if (scope.kind !== "public") continue;
78
+ let source;
79
+ try {
80
+ source = buyableSource({ principal: PUBLIC }, object);
81
+ } catch {
82
+ continue;
83
+ }
84
+ const readable = new Set(scope.columns);
85
+ const columnOf = (name) => {
86
+ const field = name ? object.fields.find((f) => f.name === name) : void 0;
87
+ const column = field ? viewColumnOf(field) : null;
88
+ return column && readable.has(column) ? column : null;
89
+ };
90
+ let query = db.selectFrom(source).select("id");
91
+ const price = columnOf(sellable.price);
92
+ if (price) query = query.where(sql.ref(price), ">", 0);
93
+ const day = now.slice(0, 10);
94
+ const from = columnOf(sellable.saleWindow?.from);
95
+ if (from) {
96
+ query = query.where(
97
+ (eb) => eb.or([eb(sql.ref(from), "is", null), eb(sql.ref(from), "<=", now)])
98
+ );
99
+ }
100
+ const until = columnOf(sellable.saleWindow?.until);
101
+ if (until) {
102
+ query = query.where(
103
+ (eb) => eb.or([eb(sql.ref(until), "is", null), eb(sql.ref(until), ">=", day)])
104
+ );
105
+ }
106
+ const rows = await query.orderBy("id").limit(PLANS_LOOKED_AT + 1).execute();
107
+ for (const { id } of rows.slice(0, PLANS_LOOKED_AT)) {
108
+ const found = await priced(db, object, id, setup.currency, now);
109
+ if (found) return { state: "on_sale", plan: found };
110
+ }
111
+ if (rows.length > PLANS_LOOKED_AT) unanswered = true;
112
+ }
113
+ return unanswered ? { state: "unknown", reason: `more than ${PLANS_LOOKED_AT} plans to look at` } : { state: "none" };
114
+ }
115
+ async function priced(db, object, id, currency, now) {
116
+ try {
117
+ const [line] = await priceLines(
118
+ db,
119
+ [{ object: object.name, id, quantity: 1 }],
120
+ currency,
121
+ now,
122
+ PUBLIC,
123
+ { plans: true }
124
+ );
125
+ return line?.recurring && line.unitPrice > 0 ? { object: object.name, id, title: line.title } : null;
126
+ } catch (error) {
127
+ if (error instanceof ValidationError) return null;
128
+ throw error;
129
+ }
130
+ }
131
+
132
+ export {
133
+ subscriptionSetup,
134
+ PLANS_LOOKED_AT,
135
+ PLAN_ON_SALE_MEMO_MS,
136
+ forgetPlanOnSale,
137
+ findPlanOnSale,
138
+ hasPlanOnSale
139
+ };