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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/accounts-D6N77JGP.js +44 -0
  2. package/dist/{blocks-HVTAQ5W2.js → blocks-4CA4PP3P.js} +4 -4
  3. package/dist/{chunk-X6I2LWB3.js → chunk-2MLAPQU7.js} +1471 -359
  4. package/dist/{chunk-2S7375SC.js → chunk-3MIEYXRY.js} +3 -301
  5. package/dist/chunk-56A6RJIU.js +1040 -0
  6. package/dist/chunk-7CQGMVDO.js +63 -0
  7. package/dist/{chunk-STJZJIRA.js → chunk-7O4F3NU4.js} +1039 -1380
  8. package/dist/chunk-7U3OZLTK.js +1370 -0
  9. package/dist/{chunk-ZRWF6QZS.js → chunk-DU6OIFOU.js} +1 -0
  10. package/dist/chunk-E4WCYTCT.js +347 -0
  11. package/dist/{chunk-E5JLTLRM.js → chunk-GYTEW66E.js} +1 -1
  12. package/dist/chunk-LPD2VR5M.js +284 -0
  13. package/dist/chunk-NDKVIG23.js +2641 -0
  14. package/dist/chunk-NSSUOI3Z.js +333 -0
  15. package/dist/chunk-OV3OFYPI.js +746 -0
  16. package/dist/{chunk-2P4AZTFL.js → chunk-P6YZMS3F.js} +11 -5
  17. package/dist/{chunk-Y7PQ7NIL.js → chunk-RFJOPI42.js} +138 -14
  18. package/dist/{chunk-VL62IMBN.js → chunk-RXRD34QW.js} +10 -8
  19. package/dist/{chunk-BEKL3CA2.js → chunk-STBMGUTM.js} +7065 -4580
  20. package/dist/chunk-VTQNOQGA.js +150 -0
  21. package/dist/chunk-XSE37HK5.js +426 -0
  22. package/dist/{chunk-MINQ46RU.js → chunk-Z52IX5WL.js} +257 -844
  23. package/dist/chunk-ZSR5H4O7.js +552 -0
  24. package/dist/{cli-XHC6QBQW.js → cli-7A5XHYML.js} +16 -9
  25. package/dist/{cli-BRSACHSG.js → cli-T6MJM7TU.js} +20 -8
  26. package/dist/cli.js +4 -4
  27. package/dist/{client-repo-G55G4OLV.js → client-repo-PC4ISVEZ.js} +4 -4
  28. package/dist/create.js +4 -4
  29. package/dist/{fields-64BQJA62.js → fields-L24XAIOA.js} +13 -11
  30. package/dist/invoke-TLYT6CFI.js +33 -0
  31. package/dist/order-IKQBUFCV.js +19 -0
  32. package/dist/{person-AZFEPZOE.js → person-DXEOOH2A.js} +9 -5
  33. package/dist/plan-on-sale-LRCK5MJG.js +24 -0
  34. package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
  35. package/dist/platform/migrations/0516_order_tax.sql +63 -0
  36. package/dist/platform/migrations/0520_publish_requests.sql +20 -0
  37. package/dist/platform/migrations/0530_subscriptions.sql +173 -0
  38. package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
  39. package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
  40. package/dist/platform/migrations/0533_allowances.sql +262 -0
  41. package/dist/platform/migrations/0560_recurring.sql +75 -0
  42. package/dist/platform/sdk/allowance.ts +508 -0
  43. package/dist/platform/sdk/capacity.ts +89 -0
  44. package/dist/platform/sdk/contract.ts +97 -1
  45. package/dist/platform/sdk/document.ts +161 -14
  46. package/dist/platform/sdk/field-types.ts +5 -0
  47. package/dist/platform/sdk/index.ts +3 -0
  48. package/dist/platform/sdk/manifest.ts +206 -5
  49. package/dist/platform/sdk/media.ts +62 -0
  50. package/dist/platform/sdk/recurring.ts +314 -0
  51. package/dist/platform/sdk/rich-text.ts +52 -4
  52. package/dist/platform/sdk/sellable.ts +120 -0
  53. package/dist/platform/sdk/states.ts +162 -1
  54. package/dist/platform/sdk/unique.ts +81 -0
  55. package/dist/run-BMSZKTN3.js +648 -0
  56. package/dist/run-GMQBAV6H.js +309 -0
  57. package/dist/{run-4JNFLYXV.js → run-TNHMG5RI.js} +51 -390
  58. package/dist/src-7DXXGZG2.js +38 -0
  59. package/dist/{src-J27WXNLY.js → src-BDG7PERB.js} +73 -1
  60. package/dist/visibility-XSBZTO66.js +33 -0
  61. package/package.json +2 -2
  62. package/dist/chunk-MAXLUQKB.js +0 -1287
  63. package/dist/invoke-5SR5ZWW7.js +0 -26
  64. package/dist/src-SSVOBH6L.js +0 -31
@@ -1,1287 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- CompiledQuery,
4
- ConfigError,
5
- FIELD_TYPE_REGISTRY,
6
- ORG_TIMEZONE_SETTING,
7
- ValidationError,
8
- automationSyncStatements,
9
- buildViews,
10
- columnName,
11
- coreFormulaFields,
12
- filterSchema,
13
- ident,
14
- isCoreTarget,
15
- loadSchemaState,
16
- newId,
17
- objectTable,
18
- objectView,
19
- registryFieldName,
20
- sideTable,
21
- splitObjectName,
22
- sql
23
- } from "./chunk-STJZJIRA.js";
24
- import {
25
- listObjects
26
- } from "./chunk-2S7375SC.js";
27
- import {
28
- external_exports,
29
- isLosslessChange,
30
- validateManifest
31
- } from "./chunk-X6I2LWB3.js";
32
-
33
- // ../core/src/dashboards/spec.ts
34
- var WIDGET_TYPES = [
35
- "kpi",
36
- "bar",
37
- "line",
38
- "donut",
39
- "funnel",
40
- "table",
41
- "leaderboard",
42
- "markdown"
43
- ];
44
- var DATA_WIDGET_TYPES = WIDGET_TYPES.filter(
45
- (t) => t !== "markdown"
46
- );
47
- var DATE_PRESETS = [
48
- "all_time",
49
- "today",
50
- "last_7_days",
51
- "last_30_days",
52
- "last_90_days",
53
- "last_365_days",
54
- "this_month",
55
- "last_month",
56
- "this_quarter",
57
- "this_year"
58
- ];
59
- var paramName = external_exports.string().regex(/^[a-z][a-z0-9_]{0,30}$/, "lowercase letters, digits and _; starts with a letter");
60
- var filterBase = {
61
- id: paramName.describe(
62
- "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"
63
- ),
64
- label: external_exports.string().min(1).max(100)
65
- };
66
- var dashboardFilterSchema = external_exports.discriminatedUnion("type", [
67
- external_exports.object({
68
- type: external_exports.literal("dateRange"),
69
- ...filterBase,
70
- default: external_exports.enum(DATE_PRESETS).default("last_90_days")
71
- }),
72
- external_exports.object({
73
- type: external_exports.literal("user"),
74
- ...filterBase,
75
- default: external_exports.enum(["me", "anyone"]).default("anyone")
76
- }),
77
- external_exports.object({
78
- type: external_exports.literal("select"),
79
- ...filterBase,
80
- options: external_exports.array(external_exports.object({ value: external_exports.string().max(200), label: external_exports.string().max(200) })).min(1).max(100),
81
- default: external_exports.string().max(200).nullish()
82
- }),
83
- external_exports.object({
84
- type: external_exports.literal("field"),
85
- ...filterBase,
86
- object: external_exports.string().min(1).max(80).describe("Object whose field supplies the choices"),
87
- field: external_exports.string().min(1).max(80).describe("A select field (choices) or any text field"),
88
- default: external_exports.string().max(200).nullish()
89
- }),
90
- external_exports.object({
91
- type: external_exports.literal("text"),
92
- ...filterBase,
93
- default: external_exports.string().max(200).nullish()
94
- })
95
- ]);
96
- var filterValueSchema = external_exports.union([
97
- external_exports.enum(DATE_PRESETS),
98
- external_exports.object({
99
- from: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/),
100
- to: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/)
101
- }),
102
- external_exports.string().max(200),
103
- external_exports.null()
104
- ]);
105
- var filterValuesSchema = external_exports.record(external_exports.string().max(31), filterValueSchema).default({}).describe(
106
- "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"
107
- );
108
- var widgetMappingSchema = external_exports.object({
109
- x: external_exports.string().max(80).optional().describe("Category or time column (bar, line, funnel)"),
110
- 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)"),
111
- series: external_exports.string().max(80).optional().describe("A column whose values split rows into series (long format, bar/line)"),
112
- label: external_exports.string().max(80).optional().describe("Segment or row label column (donut, leaderboard)"),
113
- value: external_exports.string().max(80).optional().describe("Value column (kpi, donut, funnel, leaderboard)"),
114
- columns: external_exports.array(external_exports.string().max(80)).max(20).optional().describe("Columns shown (table)")
115
- }).default({});
116
- var widgetOptionsSchema = external_exports.object({
117
- orientation: external_exports.enum(["vertical", "horizontal"]).optional().describe("bar: columns or bars"),
118
- stacked: external_exports.boolean().optional(),
119
- area: external_exports.boolean().optional().describe("line: fill as an area chart"),
120
- pie: external_exports.boolean().optional().describe("donut: a full pie instead of a ring"),
121
- format: external_exports.enum(["number", "currency", "percent"]).optional(),
122
- currency: external_exports.string().regex(/^[A-Z]{3}$/).optional(),
123
- compare: external_exports.boolean().optional().describe("kpi: compare with the previous period of the date filter (default true)"),
124
- limit: external_exports.number().int().min(1).max(100).optional().describe("table/leaderboard: top N rows")
125
- }).default({});
126
- var clickThroughSchema = external_exports.object({
127
- object: external_exports.string().min(1).max(80).describe("The object whose list opens"),
128
- objectColumn: external_exports.string().max(80).nullish().describe("A result column naming the object per row, when rows mix objects"),
129
- filter: filterSchema.nullish()
130
- });
131
- var widgetLayoutSchema = external_exports.object({
132
- w: external_exports.number().int().min(1).max(12).default(6).describe("Width in grid columns (of 12)"),
133
- h: external_exports.number().int().min(1).max(8).default(2).describe("Height in grid rows (about 9rem each)")
134
- }).default({ w: 6, h: 2 });
135
- var widgetSpecSchema = external_exports.object({
136
- id: external_exports.string().regex(/^[a-z0-9][a-z0-9_-]{0,40}$/).describe("Stable id within the dashboard, e.g. people-added"),
137
- type: external_exports.enum(WIDGET_TYPES),
138
- title: external_exports.string().min(1).max(200),
139
- description: external_exports.string().max(1e3).nullish(),
140
- sql: external_exports.string().max(2e4).nullish().describe(
141
- "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"
142
- ),
143
- markdown: external_exports.string().max(2e4).nullish().describe("Markdown widgets: the text"),
144
- mapping: widgetMappingSchema,
145
- options: widgetOptionsSchema,
146
- clickThrough: clickThroughSchema.nullish(),
147
- layout: widgetLayoutSchema
148
- }).superRefine((widget, ctx) => {
149
- if (widget.type === "markdown") {
150
- if (!widget.markdown?.trim()) {
151
- ctx.addIssue({ code: "custom", path: ["markdown"], message: "markdown widgets need text" });
152
- }
153
- } else if (!widget.sql?.trim()) {
154
- ctx.addIssue({ code: "custom", path: ["sql"], message: `${widget.type} widgets need sql` });
155
- }
156
- });
157
- var dashboardSpecSchema = external_exports.object({
158
- filters: external_exports.array(dashboardFilterSchema).max(8).default([]),
159
- widgets: external_exports.array(widgetSpecSchema).max(30).default([])
160
- });
161
- var SYSTEM_PARAMS = {
162
- now: "The current time (ISO-8601 UTC, to the minute)",
163
- today: "Today's date (YYYY-MM-DD, UTC)",
164
- me: "The id of the user viewing the dashboard",
165
- record_id: "On a record tab or panel: the record's id (null elsewhere)"
166
- };
167
- function filterParamNames(filters) {
168
- return filters.flatMap((f) => f.type === "dateRange" ? [`${f.id}_from`, `${f.id}_to`] : [f.id]);
169
- }
170
- function allowedParamNames(filters) {
171
- return [...Object.keys(SYSTEM_PARAMS), ...filterParamNames(filters)];
172
- }
173
-
174
- // ../core/src/capacity/index.ts
175
- function claimStatements(db, request, now) {
176
- const quantity = request.quantity;
177
- if (!Number.isInteger(quantity) || quantity < 1) {
178
- throw new ValidationError("A claim is for a whole number of places, at least 1", {
179
- rule: "capacity",
180
- object: request.object,
181
- record: request.record,
182
- asked: quantity
183
- });
184
- }
185
- const id = request.id ?? newId("capacityClaim");
186
- const counter = () => db.selectFrom("core_capacity").where("object_type", "=", request.object).where("record_id", "=", request.record);
187
- const statements = [
188
- db.updateTable("core_capacity").set({ held: sql`held + ${quantity}`, updated_at: now }).where("object_type", "=", request.object).where("record_id", "=", request.record),
189
- // The pool named on the record's counter, if any: no row matches when there is none.
190
- db.updateTable("core_capacity").set({ held: sql`held + ${quantity}`, updated_at: now }).where("object_type", "=", counter().select("pool_object_type")).where("record_id", "=", counter().select("pool_record_id")),
191
- db.insertInto("core_capacity_claim").values({
192
- id,
193
- object_type: request.object,
194
- record_id: request.record,
195
- pool_object_type: counter().select("pool_object_type"),
196
- pool_record_id: counter().select("pool_record_id"),
197
- quantity,
198
- state: "held",
199
- for_type: request.for.type,
200
- for_id: request.for.id,
201
- created_at: now,
202
- updated_at: now
203
- })
204
- ];
205
- return { id, statements };
206
- }
207
-
208
- // ../core/src/capacity/records.ts
209
- async function readCounter(db, object, record) {
210
- return db.selectFrom("core_capacity as c").leftJoin(
211
- "core_capacity as p",
212
- (join) => join.onRef("p.object_type", "=", "c.pool_object_type").onRef("p.record_id", "=", "c.pool_record_id")
213
- ).select([
214
- "c.places",
215
- "c.held",
216
- "c.taken",
217
- "c.pool_object_type",
218
- "c.pool_record_id",
219
- "p.places as pool_places",
220
- "p.held as pool_held",
221
- "p.taken as pool_taken"
222
- ]).where("c.object_type", "=", object).where("c.record_id", "=", record).executeTakeFirst();
223
- }
224
- function left(places, held, taken) {
225
- return places === null ? null : Math.max(places - held - taken, 0);
226
- }
227
- var simulated = /* @__PURE__ */ new WeakMap();
228
- async function queueClaim(ctx, request) {
229
- const { id, statements } = claimStatements(ctx.db, request, ctx.now);
230
- if (ctx.simulation) {
231
- await simulateClaim(ctx, request);
232
- return id;
233
- }
234
- ctx.write(...statements);
235
- return id;
236
- }
237
- async function simulateClaim(ctx, request) {
238
- const row = await readCounter(ctx.db, request.object, request.record);
239
- if (!row) throw new ValidationError("A referenced record does not exist");
240
- const seen = simulated.get(ctx) ?? /* @__PURE__ */ new Map();
241
- simulated.set(ctx, seen);
242
- const levels = [
243
- {
244
- object: request.object,
245
- record: request.record,
246
- left: left(row.places, row.held, row.taken)
247
- },
248
- ...row.pool_object_type && row.pool_record_id ? [
249
- {
250
- object: row.pool_object_type,
251
- record: row.pool_record_id,
252
- left: left(row.pool_places, row.pool_held ?? 0, row.pool_taken ?? 0)
253
- }
254
- ] : []
255
- ];
256
- for (const level of levels) {
257
- const key = `${level.object}|${level.record}`;
258
- const already = seen.get(key) ?? 0;
259
- const available = level.left === null ? null : Math.max(level.left - already, 0);
260
- if (available !== null && request.quantity > available) {
261
- throw new ValidationError(
262
- `Not enough places: asked for ${request.quantity}, ${available} left`,
263
- {
264
- rule: "capacity",
265
- object: level.object,
266
- record: level.record,
267
- asked: request.quantity,
268
- available
269
- }
270
- );
271
- }
272
- }
273
- for (const level of levels) {
274
- const key = `${level.object}|${level.record}`;
275
- seen.set(key, (seen.get(key) ?? 0) + request.quantity);
276
- }
277
- }
278
- function placesOf(object, capacity, value) {
279
- if (value === null || value === void 0 || value === "") return null;
280
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
281
- throw new ValidationError(
282
- `${object.label}: places must be a whole number from 0, or empty for unlimited`,
283
- { field: capacity.places, rule: "capacity" }
284
- );
285
- }
286
- return value;
287
- }
288
- async function counterWrite(ctx, object, id, after, changed) {
289
- const capacity = object.capacity;
290
- if (!capacity) return null;
291
- const touches = changed === "create" || changed.includes(capacity.places) || capacity.pool !== void 0 && changed.includes(capacity.pool.field);
292
- if (!touches) return null;
293
- const places = placesOf(object, capacity, after[capacity.places]);
294
- const poolId = capacity.pool ? after[capacity.pool.field] : null;
295
- const pool = capacity.pool && typeof poolId === "string" && poolId ? { object: capacity.pool.object, record: poolId } : null;
296
- if (changed !== "create" && ctx.simulation) {
297
- const row = await readCounter(ctx.db, object.name, id);
298
- if (row && places !== null && row.held + row.taken > places) {
299
- throw new ValidationError(
300
- `Places cannot be fewer than are claimed: ${row.held} held and ${row.taken} taken`,
301
- {
302
- rule: "capacity",
303
- object: object.name,
304
- record: id,
305
- places,
306
- held: row.held,
307
- taken: row.taken
308
- }
309
- );
310
- }
311
- }
312
- return CompiledQuery.raw(
313
- "INSERT INTO core_capacity (object_type, record_id, places, pool_object_type, pool_record_id, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (object_type, record_id) DO UPDATE SET places = excluded.places, pool_object_type = excluded.pool_object_type, pool_record_id = excluded.pool_record_id, updated_at = excluded.updated_at",
314
- [object.name, id, places, pool?.object ?? null, pool?.record ?? null, ctx.now]
315
- );
316
- }
317
- async function assertNoConfirmedClaims(ctx, object, id) {
318
- if (!object.capacity) return;
319
- const row = await ctx.db.selectFrom("core_capacity").select("taken").where("object_type", "=", object.name).where("record_id", "=", id).executeTakeFirst();
320
- if (row && row.taken > 0) {
321
- throw new ValidationError(
322
- `${object.label} has ${row.taken} places taken by paid orders and cannot be deleted`,
323
- { rule: "capacity", object: object.name, record: id, taken: row.taken }
324
- );
325
- }
326
- }
327
- function dropCapacityStatements(object) {
328
- return [
329
- CompiledQuery.raw("DELETE FROM core_capacity_claim WHERE object_type = ?", [object]),
330
- CompiledQuery.raw("DELETE FROM core_capacity WHERE object_type = ?", [object])
331
- ];
332
- }
333
- function backfillCounters(input) {
334
- const places = `CASE WHEN typeof(t.${input.placesColumn}) IN ('integer', 'real') AND t.${input.placesColumn} >= 0 THEN CAST(t.${input.placesColumn} AS INTEGER) END`;
335
- const poolRecord = input.pool ? `(SELECT p.record_id FROM core_capacity p WHERE p.object_type = ? AND p.record_id = t.${input.pool.column})` : "NULL";
336
- const poolObject = input.pool ? `CASE WHEN ${poolRecord} IS NULL THEN NULL ELSE ? END` : "NULL";
337
- const params = input.pool ? [input.object, input.pool.object, input.pool.object, input.pool.object, input.now] : [input.object, input.now];
338
- return CompiledQuery.raw(
339
- `INSERT INTO core_capacity (object_type, record_id, places, pool_object_type, pool_record_id, updated_at) SELECT ?, t.id, ${places}, ${poolObject}, ${poolRecord}, ? FROM ${input.table} t WHERE true ON CONFLICT (object_type, record_id) DO NOTHING`,
340
- params
341
- );
342
- }
343
-
344
- // ../core/src/extensions/seed.ts
345
- var ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
346
- function fnv(text, seed) {
347
- let hash = (2166136261 ^ seed) >>> 0;
348
- for (let i = 0; i < text.length; i++) {
349
- hash ^= text.charCodeAt(i);
350
- hash = Math.imul(hash, 16777619) >>> 0;
351
- }
352
- return hash;
353
- }
354
- function seedRecordId(extension, object, key) {
355
- const text = `${extension}.${object}.${key}`;
356
- let out = "";
357
- for (const seed of [1, 2, 3, 4]) {
358
- let hash = fnv(text, seed);
359
- for (let i = 0; i < 4; i++) {
360
- out += ALPHABET[hash % 32];
361
- hash = Math.floor(hash / 32);
362
- }
363
- }
364
- return `rec_0000000000${out}`;
365
- }
366
- function seedStatements(manifest, local, now) {
367
- const object = manifest.objects[local];
368
- const statements = [];
369
- const issues = [];
370
- if (!object?.seed) return { statements, issues };
371
- const table = objectTable(manifest.id, local);
372
- const principal = `extension:${manifest.id}`;
373
- for (const [key, values] of Object.entries(object.seed)) {
374
- const path = `objects.${local}.seed.${key}`;
375
- const id = seedRecordId(manifest.id, local, key);
376
- const columns = [];
377
- const params = [];
378
- for (const [name, raw2] of Object.entries(values)) {
379
- const field = object.fields[name];
380
- if (!field || field.type === "formula") continue;
381
- let value = raw2;
382
- if (field.type === "relation" && raw2 && typeof raw2 === "object" && !Array.isArray(raw2)) {
383
- const target = field.to?.split(".")[1] ?? "";
384
- value = seedRecordId(manifest.id, target, String(raw2.seed));
385
- }
386
- const spec = FIELD_TYPE_REGISTRY[field.type];
387
- const parsed = spec.schema(field).safeParse(value);
388
- if (!parsed.success) {
389
- issues.push({
390
- path: `${path}.${name}`,
391
- message: `Invalid seed value for ${name}: ${parsed.error.issues[0]?.message ?? "invalid"}`
392
- });
393
- continue;
394
- }
395
- columns.push(columnName(name));
396
- params.push(spec.toStorage(parsed.data));
397
- }
398
- const all = ["id", "created_at", "updated_at", "created_by", ...columns];
399
- statements.push(
400
- CompiledQuery.raw(
401
- `INSERT OR IGNORE INTO ${table} (${all.join(", ")}) VALUES (${all.map(() => "?").join(", ")})`,
402
- [id, now, now, principal, ...params]
403
- )
404
- );
405
- const title = values[object.titleField];
406
- statements.push(
407
- CompiledQuery.raw(
408
- "INSERT OR IGNORE INTO core_search_docs (object_type, record_id, title, body) VALUES (?, ?, ?, '')",
409
- [`${manifest.id}.${local}`, id, typeof title === "string" ? title : ""]
410
- )
411
- );
412
- }
413
- return { statements, issues };
414
- }
415
-
416
- // ../core/src/extensions/reconciler.ts
417
- var HIDDEN_RETENTION_DAYS = 30;
418
- function clone(state) {
419
- return structuredClone(state);
420
- }
421
- function columnDdl(name, type) {
422
- const storage = FIELD_TYPE_REGISTRY[type].storage;
423
- if (!storage) throw new Error(`${type} fields have no column`);
424
- return `${ident(name)} ${storage}`;
425
- }
426
- function stateDefault(object, field) {
427
- const states = object?.states;
428
- return states?.field === field ? ` DEFAULT '${states.initial.replace(/'/g, "''")}'` : "";
429
- }
430
- function storedDefinition(field) {
431
- const { renamedFrom: _renamed, ...rest } = field;
432
- return rest;
433
- }
434
- function sameDefinition(a, b) {
435
- const { resultType: _a, ...left2 } = a;
436
- const { resultType: _b, ...right } = b;
437
- return JSON.stringify(left2) === JSON.stringify(right);
438
- }
439
- function sameStorage(a, b) {
440
- return FIELD_TYPE_REGISTRY[a].storage === FIELD_TYPE_REGISTRY[b].storage;
441
- }
442
- var raw = (text) => CompiledQuery.raw(text);
443
- async function planReconcile(db, manifest, options) {
444
- return planFromState(db, await loadSchemaState(db), manifest, options.now);
445
- }
446
- function planFromState(db, current, manifest, now) {
447
- const ext = manifest.id;
448
- const next = clone(current);
449
- const tableDdl = [];
450
- const dataStatements = [];
451
- const changes = [];
452
- const issues = [];
453
- const seedWrites = [];
454
- const knownTables = /* @__PURE__ */ new Set([
455
- ...current.objects.map((o) => o.tableName),
456
- ...current.fields.map((f) => f.tableName)
457
- ]);
458
- const declaredObjects = /* @__PURE__ */ new Set();
459
- for (const [local, object] of Object.entries(manifest.objects)) {
460
- const name = `${ext}.${local}`;
461
- declaredObjects.add(name);
462
- const definition = {
463
- label: object.label,
464
- plural: object.plural,
465
- ...object.icon ? { icon: object.icon } : {},
466
- titleField: object.titleField,
467
- ...object.description ? { description: object.description } : {},
468
- fieldOrder: Object.keys(object.fields),
469
- ...object.navigation ? { navigation: object.navigation } : {},
470
- ...object.indexes?.length ? { indexes: object.indexes } : {},
471
- ...object.timelineLinks?.length ? { timelineLinks: object.timelineLinks } : {},
472
- ...object.stages ? { stages: object.stages } : {},
473
- ...object.capacity ? { capacity: object.capacity } : {},
474
- ...object.sellable ? { sellable: object.sellable } : {},
475
- ...object.states ? { states: object.states } : {},
476
- ...object.owner ? { owner: object.owner } : {},
477
- ...object.customer ? { customer: object.customer } : {},
478
- ...object.public ? { public: object.public } : {},
479
- ...object.signedIn ? { signedIn: object.signedIn } : {},
480
- ...object.customerVia ? { customerVia: object.customerVia } : {},
481
- ...object.publishable ? { publishable: object.publishable } : {},
482
- ...object.navigationOrder !== void 0 ? { navigationOrder: object.navigationOrder } : {},
483
- ...object.requireOneOf?.length ? { requireOneOf: object.requireOneOf } : {},
484
- ...object.titleDefault ? { titleDefault: object.titleDefault } : {}
485
- };
486
- let existing = next.objects.find((o) => o.name === name);
487
- if (!existing && object.renamedFrom) {
488
- const oldName = `${ext}.${object.renamedFrom}`;
489
- const old = next.objects.find((o) => o.name === oldName);
490
- if (old) {
491
- const table2 = objectTable(ext, local);
492
- if (knownTables.has(table2)) {
493
- issues.push({
494
- code: "rename_conflict",
495
- path: `objects.${local}.renamedFrom`,
496
- message: `Cannot rename ${oldName} to ${name}: table ${table2} already exists`
497
- });
498
- continue;
499
- }
500
- tableDdl.push(`ALTER TABLE ${ident(old.tableName)} RENAME TO ${table2}`);
501
- for (const table3 of [
502
- "core_activity_links",
503
- "core_task_links",
504
- "core_record_tags",
505
- "core_search_docs"
506
- ]) {
507
- dataStatements.push(
508
- CompiledQuery.raw(`UPDATE ${table3} SET object_type = ? WHERE object_type = ?`, [
509
- name,
510
- oldName
511
- ])
512
- );
513
- }
514
- for (const field of next.fields) {
515
- if (field.object === oldName) {
516
- field.object = name;
517
- if (field.tableName === old.tableName) field.tableName = table2;
518
- field.updatedAt = now;
519
- }
520
- }
521
- old.name = name;
522
- old.localName = local;
523
- old.tableName = table2;
524
- old.updatedAt = now;
525
- knownTables.add(table2);
526
- changes.push({ kind: "rename_object", object: name, from: oldName });
527
- existing = old;
528
- }
529
- }
530
- if (existing) {
531
- if (existing.status === "hidden") {
532
- existing.status = "active";
533
- existing.hiddenAt = null;
534
- changes.push({ kind: "restore_object", object: name });
535
- }
536
- if (JSON.stringify(existing.definition) !== JSON.stringify(definition)) {
537
- changes.push({ kind: "update_object", object: name });
538
- }
539
- existing.definition = definition;
540
- existing.updatedAt = now;
541
- continue;
542
- }
543
- const table = objectTable(ext, local);
544
- const columns = Object.entries(object.fields).filter(([, field]) => field.type !== "formula").map(
545
- ([field, spec]) => columnDdl(columnName(field), spec.type) + stateDefault(object, field)
546
- );
547
- tableDdl.push(
548
- `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(", ")}` : ""})`
549
- );
550
- knownTables.add(table);
551
- next.objects.push({
552
- name,
553
- extensionId: ext,
554
- localName: local,
555
- tableName: table,
556
- status: "active",
557
- hiddenAt: null,
558
- definition,
559
- createdAt: now,
560
- updatedAt: now
561
- });
562
- changes.push({ kind: "create_object", object: name });
563
- if (object.seed && Object.keys(object.seed).length) {
564
- const seeded = seedStatements(manifest, local, now);
565
- for (const issue of seeded.issues) issues.push({ code: "seed", ...issue });
566
- seedWrites.push(...seeded.statements);
567
- changes.push({
568
- kind: "seed_records",
569
- object: name,
570
- detail: `${Object.keys(object.seed).length} record(s)`
571
- });
572
- }
573
- for (const [field, spec] of Object.entries(object.fields)) {
574
- next.fields.push({
575
- extensionId: ext,
576
- object: name,
577
- localName: field,
578
- name: field,
579
- tableName: table,
580
- columnName: spec.type === "formula" ? null : columnName(field),
581
- type: spec.type,
582
- definition: storedDefinition(spec),
583
- status: "active",
584
- hiddenAt: null,
585
- createdAt: now,
586
- updatedAt: now
587
- });
588
- changes.push({ kind: "add_field", object: name, field });
589
- }
590
- }
591
- for (const object of next.objects) {
592
- if (object.extensionId !== ext || object.status !== "active") continue;
593
- if (!declaredObjects.has(object.name)) {
594
- object.status = "hidden";
595
- object.hiddenAt = now;
596
- object.updatedAt = now;
597
- changes.push({
598
- kind: "hide_object",
599
- object: object.name,
600
- detail: `Hidden; its records are kept and can be dropped after ${HIDDEN_RETENTION_DAYS} days`
601
- });
602
- }
603
- }
604
- const targets = [
605
- ...Object.entries(manifest.objects).map(
606
- ([local, o]) => [`${ext}.${local}`, o.fields, `objects.${local}.fields`]
607
- ),
608
- ...Object.entries(manifest.fields).map(
609
- ([target, fields]) => [target, fields, `fields.${target}`]
610
- )
611
- ];
612
- const declaredFields = /* @__PURE__ */ new Set();
613
- for (const [target, fields, basePath] of targets) {
614
- const own = target.startsWith(`${ext}.`);
615
- if (!own) {
616
- if (!isCoreTarget(target)) {
617
- const parts = splitObjectName(target);
618
- const exists = next.objects.some((o) => o.name === target && o.status === "active");
619
- if (!parts || !exists) {
620
- issues.push({
621
- code: "unknown_target",
622
- path: basePath,
623
- message: `Cannot add fields to ${target}: no such object is installed`
624
- });
625
- continue;
626
- }
627
- }
628
- }
629
- const table = own ? next.objects.find((o) => o.name === target).tableName : sideTable(ext, target);
630
- for (const [local, spec] of Object.entries(fields)) {
631
- const name = registryFieldName(ext, target, local);
632
- const path = `${basePath}.${local}`;
633
- declaredFields.add(`${target}|${name}`);
634
- const mine = (f) => f.extensionId === ext && f.object === target;
635
- let existing = next.fields.find((f) => mine(f) && f.localName === local);
636
- if (existing && existing.createdAt === now && existing.updatedAt === now && own) {
637
- if (changes.some((c) => c.kind === "create_object" && c.object === target)) continue;
638
- }
639
- if (!existing && spec.renamedFrom) {
640
- const old = next.fields.find(
641
- (f) => mine(f) && f.localName === spec.renamedFrom && f.status === "active"
642
- );
643
- if (old) {
644
- if (old.columnName) {
645
- const column2 = columnName(local);
646
- tableDdl.push(
647
- `ALTER TABLE ${ident(old.tableName)} RENAME COLUMN ${ident(old.columnName)} TO ${column2}`
648
- );
649
- old.columnName = column2;
650
- }
651
- changes.push({ kind: "rename_field", object: target, field: name, from: old.name });
652
- old.localName = local;
653
- old.name = name;
654
- old.updatedAt = now;
655
- existing = old;
656
- }
657
- }
658
- if (existing) {
659
- if (existing.status === "hidden") {
660
- if (!sameStorage(existing.type, spec.type) || existing.type === "formula" !== (spec.type === "formula")) {
661
- issues.push({
662
- code: "hidden_conflict",
663
- path,
664
- message: `A removed ${existing.type} field named ${local} still holds data on ${target}`,
665
- suggestion: `Choose another name, or drop the hidden field first (extension.dropHidden)`
666
- });
667
- continue;
668
- }
669
- existing.status = "active";
670
- existing.hiddenAt = null;
671
- changes.push({ kind: "restore_field", object: target, field: name });
672
- }
673
- if (existing.type !== spec.type) {
674
- const formulaSwap = existing.type === "formula" !== (spec.type === "formula");
675
- const manyChange = (existing.definition.many ?? false) !== (spec.many ?? false);
676
- if (formulaSwap || manyChange || !isLosslessChange(existing.type, spec.type)) {
677
- issues.push({
678
- code: "lossy_type_change",
679
- path: `${path}.type`,
680
- message: `Changing ${target}.${name} from ${existing.type} to ${spec.type} could lose data`,
681
- 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}`
682
- });
683
- continue;
684
- }
685
- changes.push({
686
- kind: "change_type",
687
- object: target,
688
- field: name,
689
- detail: `${existing.type} \u2192 ${spec.type}`
690
- });
691
- existing.type = spec.type;
692
- } else if ((existing.definition.many ?? false) !== (spec.many ?? false)) {
693
- issues.push({
694
- code: "lossy_type_change",
695
- path: `${path}.many`,
696
- message: `Changing ${target}.${name} between one and many could lose data`,
697
- suggestion: "Add a new relation field instead"
698
- });
699
- continue;
700
- } else if (!sameDefinition(existing.definition, storedDefinition(spec))) {
701
- changes.push({ kind: "update_field", object: target, field: name });
702
- }
703
- existing.definition = storedDefinition(spec);
704
- existing.updatedAt = now;
705
- continue;
706
- }
707
- const column = spec.type === "formula" ? null : columnName(local);
708
- if (column) {
709
- if (!own && !knownTables.has(table)) {
710
- tableDdl.push(`CREATE TABLE ${table} (id TEXT PRIMARY KEY NOT NULL)`);
711
- knownTables.add(table);
712
- }
713
- if (next.fields.some((f) => f.tableName === table && f.columnName === column)) {
714
- issues.push({
715
- code: "rename_conflict",
716
- path,
717
- message: `Column ${column} already exists on ${table}`,
718
- suggestion: "Choose another field name"
719
- });
720
- continue;
721
- }
722
- const declaring = own ? manifest.objects[target.slice(ext.length + 1)] : void 0;
723
- tableDdl.push(
724
- `ALTER TABLE ${table} ADD COLUMN ${columnDdl(column, spec.type)}${stateDefault(declaring, local)}`
725
- );
726
- if (spec.type === "timezone" && !spec.default) {
727
- dataStatements.push(
728
- CompiledQuery.raw(
729
- `UPDATE ${table} SET ${ident(column)} = COALESCE((SELECT json_extract(value, '$') FROM core_settings WHERE key = ?), 'UTC') WHERE ${ident(column)} IS NULL`,
730
- [ORG_TIMEZONE_SETTING]
731
- )
732
- );
733
- }
734
- }
735
- next.fields.push({
736
- extensionId: ext,
737
- object: target,
738
- localName: local,
739
- name,
740
- tableName: table,
741
- columnName: column,
742
- type: spec.type,
743
- definition: storedDefinition(spec),
744
- status: "active",
745
- hiddenAt: null,
746
- createdAt: now,
747
- updatedAt: now
748
- });
749
- changes.push({ kind: "add_field", object: target, field: name });
750
- }
751
- }
752
- for (const field of next.fields) {
753
- if (field.extensionId !== ext || field.status !== "active") continue;
754
- if (!declaredFields.has(`${field.object}|${field.name}`)) {
755
- const objectHidden = next.objects.some(
756
- (o) => o.name === field.object && o.status === "hidden"
757
- );
758
- if (objectHidden) continue;
759
- field.status = "hidden";
760
- field.hiddenAt = now;
761
- field.updatedAt = now;
762
- changes.push({
763
- kind: "hide_field",
764
- object: field.object,
765
- field: field.name,
766
- detail: `Hidden; its data is kept and can be dropped after ${HIDDEN_RETENTION_DAYS} days`
767
- });
768
- }
769
- }
770
- for (const object of next.objects) {
771
- if (object.extensionId !== ext || object.status !== "active") continue;
772
- const wanted = /* @__PURE__ */ new Map();
773
- for (const fields of object.definition.indexes ?? []) {
774
- const columns = fields.map((field) => {
775
- if (field === "createdAt") return "created_at";
776
- if (field === "updatedAt") return "updated_at";
777
- const state = next.fields.find(
778
- (f) => f.object === object.name && f.extensionId === ext && f.localName === field
779
- );
780
- return state?.columnName ?? null;
781
- });
782
- if (columns.some((c) => c === null)) continue;
783
- const name = ident(`${object.tableName}__${columns.join("__")}`);
784
- wanted.set(
785
- name,
786
- `CREATE INDEX IF NOT EXISTS ${name} ON ${ident(object.tableName)} (${columns.join(", ")}) WHERE deleted_at IS NULL`
787
- );
788
- }
789
- for (const field of next.fields) {
790
- if (field.object !== object.name || field.extensionId !== ext || field.status !== "active" || field.type !== "slug" || !field.columnName || field.tableName !== object.tableName) {
791
- continue;
792
- }
793
- const column = ident(field.columnName);
794
- const name = ident(`${object.tableName}__${column}__unique`);
795
- wanted.set(
796
- name,
797
- `CREATE UNIQUE INDEX IF NOT EXISTS ${name} ON ${ident(object.tableName)} (${column}) WHERE deleted_at IS NULL AND ${column} IS NOT NULL`
798
- );
799
- }
800
- const existing = (current.indexes ?? []).filter(
801
- (index) => index.table === object.tableName && index.name.startsWith(`${object.tableName}__`)
802
- );
803
- for (const index of existing) {
804
- if (wanted.has(index.name)) continue;
805
- tableDdl.push(`DROP INDEX IF EXISTS ${ident(index.name)}`);
806
- changes.push({ kind: "drop_index", object: object.name, detail: index.name });
807
- }
808
- for (const [name, ddl] of wanted) {
809
- if (existing.some((index) => index.name === name)) continue;
810
- tableDdl.push(ddl);
811
- changes.push({ kind: "add_index", object: object.name, detail: name });
812
- }
813
- }
814
- return finishPlan(
815
- db,
816
- ext,
817
- current,
818
- next,
819
- tableDdl,
820
- [...dataStatements, ...seedWrites, ...capacityBackfill(next, ext, now)],
821
- changes,
822
- issues
823
- );
824
- }
825
- function finishPlan(db, ext, current, next, tableDdl, dataStatements, changes, issues) {
826
- const views = buildViews(next);
827
- for (const { object, field, error } of views.errors) {
828
- const f = next.fields.find((x) => x.object === object && x.name === field);
829
- if (f?.extensionId !== ext) continue;
830
- issues.push({
831
- code: "formula",
832
- path: `${object}.${field}`,
833
- message: `${object}.${field}: ${error.message}`
834
- });
835
- }
836
- for (const field of next.fields) {
837
- const type = views.formulaTypes.get(`${field.object}|${field.name}`);
838
- if (type) field.definition = { ...field.definition, resultType: type };
839
- }
840
- const staleViews = current.objects.filter(
841
- (o) => !next.objects.some((n) => n.tableName === o.tableName && n.localName === o.localName)
842
- ).map((o) => `DROP VIEW IF EXISTS ${objectView(o.extensionId, o.localName)}`);
843
- const ddl = [.../* @__PURE__ */ new Set([...staleViews, ...views.drops]), ...tableDdl, ...views.creates];
844
- const touched = /* @__PURE__ */ new Set([
845
- ext,
846
- ...next.fields.filter((f) => changes.some((c) => c.object === f.object)).map((f) => f.extensionId)
847
- ]);
848
- const stateWrites = [];
849
- for (const extension of touched) {
850
- stateWrites.push(
851
- db.deleteFrom("core_extension_fields").where("extension_id", "=", extension).compile(),
852
- db.deleteFrom("core_extension_objects").where("extension_id", "=", extension).compile()
853
- );
854
- for (const object of next.objects.filter((o) => o.extensionId === extension)) {
855
- stateWrites.push(
856
- db.insertInto("core_extension_objects").values({
857
- name: object.name,
858
- extension_id: object.extensionId,
859
- local_name: object.localName,
860
- table_name: object.tableName,
861
- status: object.status,
862
- hidden_at: object.hiddenAt,
863
- definition: JSON.stringify(object.definition),
864
- created_at: object.createdAt,
865
- updated_at: object.updatedAt
866
- }).compile()
867
- );
868
- }
869
- const rows = next.fields.filter((f) => f.extensionId === extension);
870
- for (const field of rows) {
871
- stateWrites.push(
872
- db.insertInto("core_extension_fields").values({
873
- extension_id: field.extensionId,
874
- object: field.object,
875
- local_name: field.localName,
876
- name: field.name,
877
- table_name: field.tableName,
878
- column_name: field.columnName,
879
- type: field.type,
880
- definition: JSON.stringify(field.definition),
881
- status: field.status,
882
- hidden_at: field.hiddenAt,
883
- created_at: field.createdAt,
884
- updated_at: field.updatedAt
885
- }).compile()
886
- );
887
- }
888
- }
889
- return {
890
- extension: ext,
891
- ddl,
892
- statements: [...ddl.map(raw), ...dataStatements, ...stateWrites],
893
- changes,
894
- issues,
895
- next
896
- };
897
- }
898
- async function planDropHidden(db, ext, options) {
899
- const current = await loadSchemaState(db);
900
- const next = clone(current);
901
- const cutoff = new Date(
902
- Date.parse(options.now) - (options.minAgeDays ?? HIDDEN_RETENTION_DAYS) * 864e5
903
- ).toISOString();
904
- const due = (hiddenAt) => hiddenAt !== null && hiddenAt <= cutoff;
905
- const wanted = (name) => !options.only || options.only.includes(name);
906
- const tableDdl = [];
907
- const changes = [];
908
- const droppedObjects = next.objects.filter(
909
- (o) => o.extensionId === ext && o.status === "hidden" && due(o.hiddenAt) && wanted(o.name)
910
- );
911
- for (const object of droppedObjects) {
912
- tableDdl.push(`DROP TABLE IF EXISTS ${ident(object.tableName)}`);
913
- changes.push({ kind: "drop_object", object: object.name });
914
- }
915
- next.objects = next.objects.filter((o) => !droppedObjects.includes(o));
916
- const droppedTables = new Set(droppedObjects.map((o) => o.tableName));
917
- const droppedFields = next.fields.filter(
918
- (f) => f.extensionId === ext && (droppedTables.has(f.tableName) || f.status === "hidden" && due(f.hiddenAt) && wanted(`${f.object}.${f.name}`))
919
- );
920
- for (const field of droppedFields) {
921
- if (droppedTables.has(field.tableName)) continue;
922
- if (field.columnName) {
923
- tableDdl.push(`ALTER TABLE ${ident(field.tableName)} DROP COLUMN ${ident(field.columnName)}`);
924
- }
925
- changes.push({ kind: "drop_field", object: field.object, field: field.name });
926
- }
927
- next.fields = next.fields.filter((f) => !droppedFields.includes(f));
928
- for (const table of new Set(droppedFields.map((f) => f.tableName))) {
929
- if (droppedTables.has(table)) continue;
930
- const isObjectTable = next.objects.some((o) => o.tableName === table);
931
- if (!isObjectTable && !next.fields.some((f) => f.tableName === table)) {
932
- tableDdl.push(`DROP TABLE IF EXISTS ${ident(table)}`);
933
- }
934
- }
935
- const capacityDrops = droppedObjects.filter((o) => o.definition.capacity).flatMap((o) => dropCapacityStatements(o.name));
936
- const granted = new Set(
937
- current.objects.flatMap((o) => {
938
- const to = o.definition.sellable?.grants?.object;
939
- return to ? [to.includes(".") ? to : `${o.extensionId}.${to}`] : [];
940
- })
941
- );
942
- const grantDrops = droppedObjects.filter((o) => granted.has(o.name)).map((o) => CompiledQuery.raw("DELETE FROM core_order_grant WHERE object_type = ?", [o.name]));
943
- return finishPlan(
944
- db,
945
- ext,
946
- current,
947
- next,
948
- tableDdl,
949
- [...capacityDrops, ...grantDrops],
950
- changes,
951
- []
952
- );
953
- }
954
- function capacityBackfill(state, ext, now) {
955
- const objects = state.objects.filter(
956
- (o) => o.extensionId === ext && o.status === "active" && o.definition.capacity
957
- );
958
- const ordered = [
959
- ...objects.filter((o) => !o.definition.capacity?.pool),
960
- ...objects.filter((o) => o.definition.capacity?.pool)
961
- ];
962
- const statements = [];
963
- for (const object of ordered) {
964
- const capacity = object.definition.capacity;
965
- if (!capacity) continue;
966
- const column = (local) => state.fields.find(
967
- (f) => f.object === object.name && f.extensionId === ext && f.localName === local && f.tableName === object.tableName
968
- );
969
- const places = column(capacity.places);
970
- if (!places?.columnName) continue;
971
- const pool = capacity.pool ? column(capacity.pool) : void 0;
972
- statements.push(
973
- backfillCounters({
974
- object: object.name,
975
- table: ident(object.tableName),
976
- placesColumn: ident(places.columnName),
977
- pool: pool?.columnName && pool.definition.to ? { column: ident(pool.columnName), object: pool.definition.to } : void 0,
978
- now
979
- })
980
- );
981
- }
982
- return statements;
983
- }
984
-
985
- // ../core/src/extensions/install.ts
986
- function requireHost(ctx) {
987
- if (!ctx.extensionHost) {
988
- throw new ConfigError("The extension runtime is not available to this caller");
989
- }
990
- return ctx.extensionHost;
991
- }
992
- function fromSource(issue) {
993
- return { stage: "typecheck", code: issue.code, path: issue.path, message: issue.message };
994
- }
995
- function fromManifest(issue) {
996
- return {
997
- stage: issue.code === "contract" ? "contract" : "formula",
998
- code: issue.code,
999
- path: issue.path,
1000
- message: issue.message,
1001
- ...issue.span ? { span: issue.span } : {}
1002
- };
1003
- }
1004
- function fromReconcile(issue) {
1005
- return {
1006
- stage: issue.code === "formula" ? "formula" : "reconcile",
1007
- code: issue.code,
1008
- path: issue.path,
1009
- message: issue.message,
1010
- ...issue.suggestion ? { suggestion: issue.suggestion } : {}
1011
- };
1012
- }
1013
- async function checkManifest(db, id, rawManifest, now, options = {}) {
1014
- const knownObjects = listObjects().map((o) => o.name).filter((name) => name.includes(".") && !name.startsWith(`${id}.`));
1015
- const { manifest, issues } = validateManifest(rawManifest, {
1016
- knownObjects,
1017
- baseFields: (object) => isCoreTarget(object) ? coreFormulaFields(object) : {}
1018
- });
1019
- const all = issues.map(fromManifest);
1020
- for (const [name, dashboard] of Object.entries(manifest?.dashboards ?? {})) {
1021
- const parsed = dashboardSpecSchema.safeParse(dashboard);
1022
- if (!parsed.success) {
1023
- for (const issue of parsed.error.issues.slice(0, 10)) {
1024
- all.push({
1025
- stage: "contract",
1026
- code: "contract",
1027
- path: `dashboards.${name}.${issue.path.join(".")}`,
1028
- message: issue.message
1029
- });
1030
- }
1031
- }
1032
- }
1033
- if (manifest && options.source === "runtime") all.push(...outsideDeclarations(manifest));
1034
- if (manifest && manifest.id !== id) {
1035
- all.push({
1036
- stage: "contract",
1037
- code: "contract",
1038
- path: "id",
1039
- message: `The extension declares id "${manifest.id}" but is installed as "${id}"`
1040
- });
1041
- }
1042
- if (!manifest || all.length) return { issues: all, manifest, plan: null };
1043
- const plan = await planReconcile(db, manifest, { now });
1044
- return { issues: plan.issues.map(fromReconcile), manifest, plan };
1045
- }
1046
- function outsideDeclarations(manifest) {
1047
- const issues = [];
1048
- 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.";
1049
- for (const [name, tool] of Object.entries(manifest.tools)) {
1050
- const open = (tool.audiences ?? []).filter((audience) => audience !== "staff");
1051
- if (open.length || tool.customerFields) {
1052
- issues.push({
1053
- stage: "contract",
1054
- code: "outside_audience",
1055
- path: `tools.${name}.audiences`,
1056
- message: `A runtime extension cannot open a tool to ${open.join(" or ") || "customer"} callers. ${why}`
1057
- });
1058
- }
1059
- }
1060
- for (const [name, tool] of Object.entries(manifest.tools)) {
1061
- if (tool.permission) {
1062
- issues.push({
1063
- stage: "contract",
1064
- code: "outside_audience",
1065
- path: `tools.${name}.permission`,
1066
- message: `A runtime extension cannot declare a permission for a staff role. ${why}`
1067
- });
1068
- }
1069
- }
1070
- if (manifest.grantable?.length) {
1071
- issues.push({
1072
- stage: "contract",
1073
- code: "outside_audience",
1074
- path: "grantable",
1075
- message: `A runtime extension cannot declare a permission an admin grants. ${why}`
1076
- });
1077
- }
1078
- for (const name of Object.keys(manifest.roles ?? {})) {
1079
- issues.push({
1080
- stage: "contract",
1081
- code: "outside_audience",
1082
- path: `roles.${name}`,
1083
- message: `A runtime extension cannot declare a staff role. ${why}`
1084
- });
1085
- }
1086
- for (const [name, object] of Object.entries(manifest.objects)) {
1087
- if (object.customer) {
1088
- issues.push({
1089
- stage: "contract",
1090
- code: "outside_audience",
1091
- path: `objects.${name}.customer`,
1092
- message: `A runtime extension cannot make ${name} visible to customers. ${why}`
1093
- });
1094
- }
1095
- if (object.public) {
1096
- issues.push({
1097
- stage: "contract",
1098
- code: "outside_audience",
1099
- path: `objects.${name}.public`,
1100
- message: `A runtime extension cannot make ${name} readable by the public. ${why}`
1101
- });
1102
- }
1103
- if (object.customerVia) {
1104
- issues.push({
1105
- stage: "contract",
1106
- code: "outside_audience",
1107
- path: `objects.${name}.customerVia`,
1108
- message: `A runtime extension cannot make ${name} readable by customers through their own records. ${why}`
1109
- });
1110
- }
1111
- if (object.signedIn) {
1112
- issues.push({
1113
- stage: "contract",
1114
- code: "outside_audience",
1115
- path: `objects.${name}.signedIn`,
1116
- message: `A runtime extension cannot make ${name} readable by signed-in customers. ${why}`
1117
- });
1118
- }
1119
- if (object.sellable) {
1120
- issues.push({
1121
- stage: "contract",
1122
- code: "outside_audience",
1123
- path: `objects.${name}.sellable`,
1124
- message: `A runtime extension cannot make ${name} something customers and the public can buy. ${why}`
1125
- });
1126
- }
1127
- }
1128
- return issues;
1129
- }
1130
- async function checkEvaluated(db, id, evaluated, now, options = {}) {
1131
- if (!evaluated.ok) {
1132
- return { ok: false, issues: evaluated.issues.map(fromSource), manifest: null, plan: null };
1133
- }
1134
- const { issues, manifest, plan } = await checkManifest(db, id, evaluated.manifest, now, options);
1135
- return {
1136
- ok: issues.length === 0,
1137
- issues,
1138
- manifest,
1139
- plan: plan ? { ddl: plan.ddl, changes: plan.changes } : null
1140
- };
1141
- }
1142
- async function checkExtension(ctx, input) {
1143
- const host = requireHost(ctx);
1144
- return checkEvaluated(ctx.db, input.id, await host.evaluate(input), ctx.now, {
1145
- source: "runtime"
1146
- });
1147
- }
1148
- function firstIssue(issues) {
1149
- const first = issues[0];
1150
- if (!first) return "";
1151
- const more = issues.length > 1 ? ` (and ${issues.length - 1} more)` : "";
1152
- return `: ${first.path}: ${first.message}${more}`;
1153
- }
1154
- function extensionPrincipalId(id) {
1155
- return `extension:${id}`;
1156
- }
1157
- async function installExtension(ctx, input) {
1158
- const host = requireHost(ctx);
1159
- const existing = await ctx.db.selectFrom("core_extensions").selectAll().where("id", "=", input.id).executeTakeFirst();
1160
- const ejecting = input.eject && existing?.source === "shipped" && input.source === "runtime";
1161
- if (existing && existing.source !== input.source && !ejecting) {
1162
- throw new ValidationError(
1163
- `${input.id} is already installed as a ${existing.source} extension`,
1164
- { id: input.id }
1165
- );
1166
- }
1167
- const evaluated = await host.evaluate({ id: input.id, commit: input.commit });
1168
- if (!evaluated.ok) {
1169
- const issues2 = evaluated.issues.map(fromSource);
1170
- throw new ValidationError(`${input.id} failed its check${firstIssue(issues2)}`, { issues: issues2 });
1171
- }
1172
- const { issues, manifest, plan } = await checkManifest(
1173
- ctx.db,
1174
- input.id,
1175
- evaluated.manifest,
1176
- ctx.now,
1177
- { source: input.source }
1178
- );
1179
- if (issues.length || !manifest || !plan) {
1180
- throw new ValidationError(`${input.id} failed its check${firstIssue(issues)}`, { issues });
1181
- }
1182
- const unchanged = existing?.commit_oid === input.commit && existing.status === "active" && plan.changes.length === 0;
1183
- if (unchanged) {
1184
- return {
1185
- id: input.id,
1186
- version: manifest.version,
1187
- commit: input.commit,
1188
- source: input.source,
1189
- changes: [],
1190
- changed: false
1191
- };
1192
- }
1193
- const principal = extensionPrincipalId(input.id);
1194
- const user = await ctx.db.selectFrom("core_user").select("id").where("id", "=", principal).executeTakeFirst();
1195
- if (!user) {
1196
- ctx.write(
1197
- ctx.db.insertInto("core_user").values({
1198
- id: principal,
1199
- name: manifest.label ?? input.id,
1200
- email: `${input.id}@extensions.crm.invalid`,
1201
- email_verified: 0,
1202
- image: null,
1203
- created_at: ctx.now,
1204
- updated_at: ctx.now,
1205
- role: "member",
1206
- kind: "extension"
1207
- })
1208
- );
1209
- }
1210
- ctx.write(...plan.statements);
1211
- const installedBy = ctx.user.id === "system" ? null : ctx.user.id;
1212
- const manifestJson = JSON.stringify(manifest);
1213
- ctx.write(
1214
- ctx.db.insertInto("core_extensions").values({
1215
- id: input.id,
1216
- source: input.source,
1217
- status: "active",
1218
- status_reason: null,
1219
- version: manifest.version,
1220
- commit_oid: input.commit,
1221
- last_good_commit: existing?.last_good_commit ?? null,
1222
- manifest: manifestJson,
1223
- failure_count: 0,
1224
- user_id: principal,
1225
- installed_at: ctx.now,
1226
- installed_by: installedBy,
1227
- updated_at: ctx.now
1228
- }).onConflict(
1229
- (oc) => oc.column("id").doUpdateSet({
1230
- source: input.source,
1231
- status: "active",
1232
- status_reason: null,
1233
- version: manifest.version,
1234
- commit_oid: input.commit,
1235
- manifest: manifestJson,
1236
- failure_count: 0,
1237
- updated_at: ctx.now
1238
- })
1239
- ),
1240
- ctx.db.insertInto("core_extension_versions").values({
1241
- extension_id: input.id,
1242
- commit_oid: input.commit,
1243
- version: manifest.version,
1244
- manifest: manifestJson,
1245
- installed_at: ctx.now,
1246
- installed_by: installedBy
1247
- }).onConflict(
1248
- (oc) => oc.columns(["extension_id", "commit_oid"]).doUpdateSet({ installed_at: ctx.now })
1249
- )
1250
- );
1251
- ctx.write(
1252
- ...automationSyncStatements(ctx.db, {
1253
- extensionId: input.id,
1254
- commit: input.commit,
1255
- automations: manifest.automations ?? {},
1256
- now: ctx.now
1257
- })
1258
- );
1259
- return {
1260
- id: input.id,
1261
- version: manifest.version,
1262
- commit: input.commit,
1263
- source: input.source,
1264
- changes: plan.changes,
1265
- changed: true
1266
- };
1267
- }
1268
-
1269
- export {
1270
- WIDGET_TYPES,
1271
- dashboardFilterSchema,
1272
- filterValuesSchema,
1273
- widgetSpecSchema,
1274
- dashboardSpecSchema,
1275
- SYSTEM_PARAMS,
1276
- allowedParamNames,
1277
- queueClaim,
1278
- counterWrite,
1279
- assertNoConfirmedClaims,
1280
- HIDDEN_RETENTION_DAYS,
1281
- planDropHidden,
1282
- requireHost,
1283
- checkManifest,
1284
- checkEvaluated,
1285
- checkExtension,
1286
- installExtension
1287
- };