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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/rich-text.js CHANGED
@@ -36,7 +36,12 @@ const blocks = {
36
36
  list: listShape(),
37
37
  quote: object({ content: inlines, attribution: optional(prose(300)) }),
38
38
  image: object({
39
- media: { type: "ref", to: RICH_TEXT_MEDIA_OBJECT, description: "The picture, from media" },
39
+ media: {
40
+ type: "ref",
41
+ to: RICH_TEXT_MEDIA_OBJECT,
42
+ media: "image",
43
+ description: "The picture, from media",
44
+ },
40
45
  alt: prose(500, { description: "What the picture shows, for people who cannot see it" }),
41
46
  caption: optional(inlines),
42
47
  }),
@@ -101,7 +106,12 @@ export const RICH_TEXT_SCHEMA = {
101
106
  */
102
107
  export const IMAGE_SCHEMA = {
103
108
  root: object({
104
- media: { type: "ref", to: RICH_TEXT_MEDIA_OBJECT, description: "The picture, from media" },
109
+ media: {
110
+ type: "ref",
111
+ to: RICH_TEXT_MEDIA_OBJECT,
112
+ media: "image",
113
+ description: "The picture, from media",
114
+ },
105
115
  alt: prose(500, { description: "What the picture shows, for people who cannot see it" }),
106
116
  focal: optional(object({
107
117
  x: { type: "number", min: 0, max: 1 },
@@ -111,9 +121,41 @@ export const IMAGE_SCHEMA = {
111
121
  };
112
122
  /** The most an image field's value may be, in bytes of its JSON. */
113
123
  export const IMAGE_MAX_BYTES = 2048;
114
- /** The field types whose value is a document (ADR 0445): `document`, `richText` and `image`. */
124
+ /**
125
+ * A video from the media library (stage 42, ADR 0475), as a node a declared document may use: the
126
+ * video (a ready one, checked on write) and, optionally, a picture to show before it plays.
127
+ */
128
+ export const VIDEO_NODE = object({
129
+ media: {
130
+ type: "ref",
131
+ to: RICH_TEXT_MEDIA_OBJECT,
132
+ media: "video",
133
+ description: "The video, from media (a ready one)",
134
+ },
135
+ poster: optional({
136
+ type: "ref",
137
+ to: RICH_TEXT_MEDIA_OBJECT,
138
+ media: "image",
139
+ description: "A picture shown before it plays",
140
+ }),
141
+ });
142
+ /** A downloadable file from the media library (a PDF), as a node a declared document may use. */
143
+ export const FILE_NODE = {
144
+ type: "ref",
145
+ to: RICH_TEXT_MEDIA_OBJECT,
146
+ media: "file",
147
+ description: "The file, from media",
148
+ };
149
+ /** The `video` field type (stage 42, ADR 0475): `{ media, poster? }`. */
150
+ export const VIDEO_SCHEMA = { root: VIDEO_NODE };
151
+ /** The most a video field's value may be, in bytes of its JSON. */
152
+ export const VIDEO_MAX_BYTES = 1024;
153
+ /**
154
+ * The field types whose value is a document (ADR 0445): `document`, `richText`, `image` and
155
+ * `video`.
156
+ */
115
157
  export function isDocumentType(type) {
116
- return type === "document" || type === "richText" || type === "image";
158
+ return type === "document" || type === "richText" || type === "image" || type === "video";
117
159
  }
118
160
  /**
119
161
  * The schema a document-valued field is checked against: its declared one, or richText's. Not a
@@ -124,6 +166,8 @@ export function documentSchemaOf(field) {
124
166
  return RICH_TEXT_SCHEMA;
125
167
  if (field.type === "image")
126
168
  return IMAGE_SCHEMA;
169
+ if (field.type === "video")
170
+ return VIDEO_SCHEMA;
127
171
  if (field.type === "document")
128
172
  return field.schema;
129
173
  return undefined;
@@ -132,6 +176,8 @@ export function documentSchemaOf(field) {
132
176
  export function documentMaxBytesOf(field) {
133
177
  if (field.type === "image")
134
178
  return IMAGE_MAX_BYTES;
179
+ if (field.type === "video")
180
+ return VIDEO_MAX_BYTES;
135
181
  if (field.maxBytes !== undefined)
136
182
  return field.maxBytes;
137
183
  return field.type === "richText" ? RICH_TEXT_DEFAULT_BYTES : undefined;
@@ -55,6 +55,11 @@ export interface GrantSpec {
55
55
  * - `deposit`: paying by deposit (stage 25): the field holding the deposit for one, and the date
56
56
  * field saying when the balance is due. A record offers a deposit when both have a value.
57
57
  * - `grants`: what a paid line grants (see GrantSpec).
58
+ * - `tax`: tax at checkout (ADR 0479), see TaxSpec. A line is taxed only when this is declared and
59
+ * a human admin has turned tax on for the deployment.
60
+ * - `recurring`: a plan, paid for every period (stage 32a, ADR 0485), see RecurringSpec. Its records
61
+ * are subscribed to, never put on an order: `price` is the price of one period. Not with
62
+ * `deposit`, `maxPerOrder` or `grants` (32b adds what a subscription grants).
58
63
  */
59
64
  export interface SellableSpec {
60
65
  price: string;
@@ -69,7 +74,45 @@ export interface SellableSpec {
69
74
  balanceDue: string;
70
75
  };
71
76
  grants?: GrantSpec;
77
+ tax?: TaxSpec;
78
+ recurring?: RecurringSpec;
72
79
  }
80
+ /**
81
+ * How a plan recurs (ADR 0485). The payment provider charges every `interval` on its own schedule;
82
+ * the host learns of each paid period from its verified events and writes a paid order for it.
83
+ *
84
+ * - `interval`: `week`, `month` or `year`.
85
+ * - `trialDays`: a number field of the plan holding the days of a free first period (the card is
86
+ * taken at the start, the first charge is when it ends). Empty or zero: no trial.
87
+ */
88
+ export interface RecurringSpec {
89
+ interval: "week" | "month" | "year";
90
+ trialDays?: string;
91
+ }
92
+ /**
93
+ * How the payment provider taxes a line of this object (ADR 0479). Prices stay what the buyer
94
+ * pays: the provider works the tax out inside them.
95
+ *
96
+ * - `code`: the provider's product tax code (Stripe's list: `txcd_` and eight digits). A human
97
+ * admin may override it per object in Settings → Orders.
98
+ * - `place`: for admission to an in-person event, where it is held, so the provider taxes it
99
+ * there and not where the buyer lives. Text fields of this object, or of the record its
100
+ * relation `via` points at (a ticket type's event): `country` (two letters, ISO 3166-1) and,
101
+ * when given, `region`, `postcode`, `city` and `line1`.
102
+ */
103
+ export interface TaxSpec {
104
+ code: string;
105
+ place?: {
106
+ via?: string;
107
+ country: string;
108
+ region?: string;
109
+ postcode?: string;
110
+ city?: string;
111
+ line1?: string;
112
+ };
113
+ }
114
+ /** A product tax code as Stripe's list has them. */
115
+ export declare const TAX_CODE_PATTERN: RegExp;
73
116
  export declare const GRANT_SOURCES: readonly ["item", "order", "order.person", "order.email", "line", "line.title", "line.unitPrice", "code"];
74
117
  export declare const sellableManifestSchema: z.ZodObject<{
75
118
  price: z.ZodString;
@@ -97,6 +140,25 @@ export declare const sellableManifestSchema: z.ZodObject<{
97
140
  }>, z.ZodString]>>;
98
141
  void: z.ZodString;
99
142
  }, z.core.$strict>>;
143
+ tax: z.ZodOptional<z.ZodObject<{
144
+ code: z.ZodString;
145
+ place: z.ZodOptional<z.ZodObject<{
146
+ via: z.ZodOptional<z.ZodString>;
147
+ country: z.ZodString;
148
+ region: z.ZodOptional<z.ZodString>;
149
+ postcode: z.ZodOptional<z.ZodString>;
150
+ city: z.ZodOptional<z.ZodString>;
151
+ line1: z.ZodOptional<z.ZodString>;
152
+ }, z.core.$strict>>;
153
+ }, z.core.$strict>>;
154
+ recurring: z.ZodOptional<z.ZodObject<{
155
+ interval: z.ZodEnum<{
156
+ week: "week";
157
+ month: "month";
158
+ year: "year";
159
+ }>;
160
+ trialDays: z.ZodOptional<z.ZodString>;
161
+ }, z.core.$strict>>;
100
162
  }, z.core.$strict>;
101
163
  export type SellableManifest = z.infer<typeof sellableManifestSchema>;
102
164
  /** Reports problems with `objects.<name>.sellable` through `contract`. */
package/dist/sellable.js CHANGED
@@ -5,6 +5,8 @@
5
5
  // contract checks live here; the host's side is packages/core/src/orders/ (sellable.ts, grants.ts).
6
6
  import { z } from "zod";
7
7
  import { moveOrigins } from "./states.js";
8
+ /** A product tax code as Stripe's list has them. */
9
+ export const TAX_CODE_PATTERN = /^txcd_\d{8}$/;
8
10
  const fieldName = z.string().max(40);
9
11
  export const GRANT_SOURCES = [
10
12
  "item",
@@ -44,6 +46,30 @@ export const sellableManifestSchema = z
44
46
  })
45
47
  .strict()
46
48
  .optional(),
49
+ tax: z
50
+ .object({
51
+ code: z.string().regex(TAX_CODE_PATTERN, "A product tax code: txcd_ and eight digits"),
52
+ place: z
53
+ .object({
54
+ via: fieldName.optional(),
55
+ country: fieldName,
56
+ region: fieldName.optional(),
57
+ postcode: fieldName.optional(),
58
+ city: fieldName.optional(),
59
+ line1: fieldName.optional(),
60
+ })
61
+ .strict()
62
+ .optional(),
63
+ })
64
+ .strict()
65
+ .optional(),
66
+ recurring: z
67
+ .object({
68
+ interval: z.enum(["week", "month", "year"]),
69
+ trialDays: fieldName.optional(),
70
+ })
71
+ .strict()
72
+ .optional(),
47
73
  })
48
74
  .strict();
49
75
  const NUMERIC = new Set(["number", "currency"]);
@@ -83,6 +109,18 @@ export function checkObjectSellable(m, name, object, contract) {
83
109
  }
84
110
  }
85
111
  }
112
+ if (sellable.recurring) {
113
+ // A plan is subscribed to, not put on an order (ADR 0485).
114
+ for (const key of ["deposit", "maxPerOrder", "grants"]) {
115
+ if (sellable[key] !== undefined) {
116
+ contract(`${path}.${key}`, `A recurring plan has no ${key}: it is subscribed to, one at a time`);
117
+ }
118
+ }
119
+ const trial = sellable.recurring.trialDays;
120
+ if (trial !== undefined && !single(trial, new Set(["number"]))) {
121
+ contract(`${path}.recurring.trialDays`, `"${trial}" must be a number field of ${name}`);
122
+ }
123
+ }
86
124
  if (sellable.maxPerOrder !== undefined && !single(sellable.maxPerOrder, new Set(["number"]))) {
87
125
  contract(`${path}.maxPerOrder`, `"${sellable.maxPerOrder}" must be a number field of ${name}`);
88
126
  }
@@ -100,6 +138,38 @@ export function checkObjectSellable(m, name, object, contract) {
100
138
  }
101
139
  if (sellable.grants)
102
140
  checkGrants(m, name, object, sellable.grants, `${path}.grants`, contract);
141
+ const place = sellable.tax?.place;
142
+ if (place) {
143
+ let holder = object;
144
+ let holderName = name;
145
+ if (place.via !== undefined) {
146
+ const via = fieldOf(place.via);
147
+ const local = via?.to?.startsWith(`${m.id}.`) ? via.to.slice(m.id.length + 1) : undefined;
148
+ if (!via ||
149
+ via.type !== "relation" ||
150
+ via.many ||
151
+ !local ||
152
+ !Object.hasOwn(m.objects, local)) {
153
+ contract(`${path}.tax.place.via`, `"${place.via}" must be a relation of ${name} to one record of another of this extension's objects`);
154
+ holder = undefined;
155
+ }
156
+ else {
157
+ holder = m.objects[local];
158
+ holderName = local;
159
+ }
160
+ }
161
+ if (holder) {
162
+ for (const key of ["country", "region", "postcode", "city", "line1"]) {
163
+ const local = place[key];
164
+ if (local === undefined)
165
+ continue;
166
+ const field = Object.hasOwn(holder.fields, local) ? holder.fields[local] : undefined;
167
+ if (!field || field.type !== "text" || field.many) {
168
+ contract(`${path}.tax.place.${key}`, `"${local}" must be a text field of ${holderName}`);
169
+ }
170
+ }
171
+ }
172
+ }
103
173
  }
104
174
  function checkGrants(m, name, item, grants, path, contract) {
105
175
  const local = grants.object.startsWith(`${m.id}.`)
package/dist/states.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
2
+ import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
3
3
  /**
4
4
  * Who may make a move. `staff`: anyone working for the organisation (people, their assistants,
5
5
  * MCP clients, automations and extensions acting for them). `customer`: a signed-in customer, on
@@ -20,6 +20,35 @@ export interface StateMove {
20
20
  requires?: readonly string[];
21
21
  /** The move ends the lifecycle: nothing moves out of `to`. */
22
22
  final?: boolean;
23
+ /**
24
+ * When a customer may make it (stage 31, ADR 0503): from `from` (inclusive) until `until`
25
+ * (exclusive), by the host's clock in the write. Staff and the host are not bound.
26
+ */
27
+ window?: MoveWindow;
28
+ /**
29
+ * A boolean field (named as a window's `at` is): while it is true, only staff and the host may
30
+ * make the move ("this class type is booked by the gym").
31
+ */
32
+ staffOnly?: string;
33
+ }
34
+ /**
35
+ * One end of a window (ADR 0503): the moment in the datetime field `at` (a field of the record,
36
+ * or `<relation>.<field>` on the record a relation of one record points to), less `daysBefore`
37
+ * whole days at the same local time in `zone` (a timezone field named the same way; the
38
+ * organisation's zone when left out) and then `minutesBefore` minutes. Each of the two is a
39
+ * number, or a number field named as `at` is. A string is short for `{ at }`. When any of them
40
+ * has no value the window cannot be worked out, and a customer's move is refused.
41
+ */
42
+ export interface WindowBound {
43
+ at: string;
44
+ daysBefore?: number | string;
45
+ minutesBefore?: number | string;
46
+ zone?: string;
47
+ }
48
+ /** A window on a move or a create (ADR 0503). */
49
+ export interface MoveWindow {
50
+ from?: string | WindowBound;
51
+ until?: string | WindowBound;
23
52
  }
24
53
  /**
25
54
  * A state machine (ADR 0425). The host enforces it in the record operations and the record CSV
@@ -39,6 +68,26 @@ export interface StatesSpec {
39
68
  /** The state a new record starts in. */
40
69
  initial: string;
41
70
  moves: readonly StateMove[];
71
+ /**
72
+ * Rules on every create, whatever state the record is created in (ADR 0503): `in`, the states
73
+ * a record may be created in besides `initial`, each with who may create it there (it is then
74
+ * not judged as a move from `initial`: a booking is created booked or waiting by a customer,
75
+ * pending only by the host); the `window` in which a customer
76
+ * may create one; and `staffOnly`, a boolean field while true only staff and the host create.
77
+ * Named as a move's are.
78
+ */
79
+ create?: {
80
+ in?: Readonly<Record<string, readonly Mover[]>>;
81
+ window?: MoveWindow;
82
+ staffOnly?: string;
83
+ };
84
+ /**
85
+ * Moves a caller asks for by name, resolved by the host (ADR 0503): writing the name (`cancel`)
86
+ * into the state field moves the record to the first of the listed states whose move from where
87
+ * it is the caller may make now, windows included (`["cancelled", "late_cancelled"]`). A name
88
+ * is not a state.
89
+ */
90
+ requests?: Readonly<Record<string, readonly string[]>>;
42
91
  }
43
92
  export declare const statesManifestSchema: z.ZodObject<{
44
93
  field: z.ZodString;
@@ -53,7 +102,45 @@ export declare const statesManifestSchema: z.ZodObject<{
53
102
  }>>;
54
103
  requires: z.ZodOptional<z.ZodArray<z.ZodString>>;
55
104
  final: z.ZodOptional<z.ZodBoolean>;
105
+ window: z.ZodOptional<z.ZodObject<{
106
+ from: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
107
+ at: z.ZodString;
108
+ daysBefore: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
109
+ minutesBefore: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
110
+ zone: z.ZodOptional<z.ZodString>;
111
+ }, z.core.$strict>]>>;
112
+ until: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
113
+ at: z.ZodString;
114
+ daysBefore: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
115
+ minutesBefore: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
116
+ zone: z.ZodOptional<z.ZodString>;
117
+ }, z.core.$strict>]>>;
118
+ }, z.core.$strict>>;
119
+ staffOnly: z.ZodOptional<z.ZodString>;
56
120
  }, z.core.$strip>>;
121
+ create: z.ZodOptional<z.ZodObject<{
122
+ in: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodEnum<{
123
+ staff: "staff";
124
+ customer: "customer";
125
+ host: "host";
126
+ }>>>>;
127
+ window: z.ZodOptional<z.ZodObject<{
128
+ from: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
129
+ at: z.ZodString;
130
+ daysBefore: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
131
+ minutesBefore: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
132
+ zone: z.ZodOptional<z.ZodString>;
133
+ }, z.core.$strict>]>>;
134
+ until: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
135
+ at: z.ZodString;
136
+ daysBefore: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
137
+ minutesBefore: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
138
+ zone: z.ZodOptional<z.ZodString>;
139
+ }, z.core.$strict>]>>;
140
+ }, z.core.$strict>>;
141
+ staffOnly: z.ZodOptional<z.ZodString>;
142
+ }, z.core.$strict>>;
143
+ requests: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodString>>>;
57
144
  }, z.core.$strip>;
58
145
  export type StatesManifest = z.infer<typeof statesManifestSchema>;
59
146
  /** The states a move leaves, as a list. */
@@ -61,4 +148,9 @@ export declare function moveOrigins(move: {
61
148
  from: string | readonly string[];
62
149
  }): readonly string[];
63
150
  /** Reports problems with `objects.<name>.states` through `contract`. */
64
- export declare function checkObjectStates(_m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
151
+ export declare function checkObjectStates(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
152
+ /**
153
+ * The field a path names (ADR 0503): `field` on the object, or `relation.field` on the object a
154
+ * relation of one record points to, within the same extension.
155
+ */
156
+ export declare function resolveFieldPath(m: ExtensionManifest, object: ObjectManifest, path: string): FieldManifest | undefined;
package/dist/states.js CHANGED
@@ -12,6 +12,22 @@ import { z } from "zod";
12
12
  export const MOVERS = ["staff", "customer", "host"];
13
13
  const fieldName = z.string().max(40);
14
14
  const stateValue = z.string().min(1).max(100);
15
+ const fieldPath = z.string().min(1).max(81);
16
+ const windowBound = z.union([
17
+ fieldPath,
18
+ z
19
+ .object({
20
+ at: fieldPath,
21
+ daysBefore: z.union([z.number().int().min(-366).max(366), fieldPath]).optional(),
22
+ minutesBefore: z.union([z.number().int().min(-527_040).max(527_040), fieldPath]).optional(),
23
+ zone: fieldPath.optional(),
24
+ })
25
+ .strict(),
26
+ ]);
27
+ const moveWindow = z
28
+ .object({ from: windowBound.optional(), until: windowBound.optional() })
29
+ .strict()
30
+ .refine((w) => w.from !== undefined || w.until !== undefined, "A window needs from or until");
15
31
  export const statesManifestSchema = z.object({
16
32
  field: fieldName,
17
33
  initial: stateValue,
@@ -22,15 +38,32 @@ export const statesManifestSchema = z.object({
22
38
  by: z.array(z.enum(MOVERS)).min(1).max(MOVERS.length),
23
39
  requires: z.array(fieldName).max(50).optional(),
24
40
  final: z.boolean().optional(),
41
+ window: moveWindow.optional(),
42
+ staffOnly: fieldPath.optional(),
25
43
  }))
26
44
  .max(200),
45
+ create: z
46
+ .object({
47
+ in: z
48
+ .record(stateValue, z.array(z.enum(MOVERS)).min(1).max(MOVERS.length))
49
+ .refine((r) => Object.keys(r).length <= 20, "At most 20 states")
50
+ .optional(),
51
+ window: moveWindow.optional(),
52
+ staffOnly: fieldPath.optional(),
53
+ })
54
+ .strict()
55
+ .optional(),
56
+ requests: z
57
+ .record(z.string().regex(/^[a-z][a-z0-9_]{0,39}$/), z.array(stateValue).min(1).max(10))
58
+ .refine((r) => Object.keys(r).length <= 10, "At most 10 requests")
59
+ .optional(),
27
60
  });
28
61
  /** The states a move leaves, as a list. */
29
62
  export function moveOrigins(move) {
30
63
  return typeof move.from === "string" ? [move.from] : move.from;
31
64
  }
32
65
  /** Reports problems with `objects.<name>.states` through `contract`. */
33
- export function checkObjectStates(_m, name, object, contract) {
66
+ export function checkObjectStates(m, name, object, contract) {
34
67
  const states = object.states;
35
68
  if (!states)
36
69
  return;
@@ -98,4 +131,79 @@ export function checkObjectStates(_m, name, object, contract) {
98
131
  }
99
132
  }
100
133
  });
134
+ // Windows, staff-only rules and requests (ADR 0503).
135
+ const checkPath = (at, path, type) => {
136
+ const field = resolveFieldPath(m, object, at);
137
+ if (field?.type !== type || field.many) {
138
+ contract(path, `"${at}" must be a ${type} field of ${name}, or <relation>.<field> through a relation (one record) to another of this extension's objects`);
139
+ }
140
+ };
141
+ const checkWindow = (window, path) => {
142
+ for (const end of ["from", "until"]) {
143
+ const bound = window?.[end];
144
+ if (bound === undefined)
145
+ continue;
146
+ const b = typeof bound === "string" ? { at: bound } : bound;
147
+ checkPath(b.at, `${path}.${end}.at`, "datetime");
148
+ for (const key of ["daysBefore", "minutesBefore"]) {
149
+ const value = b[key];
150
+ if (typeof value === "string")
151
+ checkPath(value, `${path}.${end}.${key}`, "number");
152
+ }
153
+ if (b.zone !== undefined)
154
+ checkPath(b.zone, `${path}.${end}.zone`, "timezone");
155
+ }
156
+ };
157
+ states.moves.forEach((move, i) => {
158
+ const mp = `${sp}.moves.${i}`;
159
+ if ((move.window || move.staffOnly) && !move.by.includes("customer")) {
160
+ contract(mp, "A window or staffOnly binds customers: the move must list customer in by");
161
+ }
162
+ checkWindow(move.window, `${mp}.window`);
163
+ if (move.staffOnly)
164
+ checkPath(move.staffOnly, `${mp}.staffOnly`, "boolean");
165
+ });
166
+ if (states.create) {
167
+ for (const state of Object.keys(states.create.in ?? {})) {
168
+ if (!isState(state))
169
+ contract(`${sp}.create.in`, `"${state}" is not an option of ${states.field}`);
170
+ if (finals.has(state))
171
+ contract(`${sp}.create.in`, `"${state}" is final: nothing is created in it`);
172
+ }
173
+ checkWindow(states.create.window, `${sp}.create.window`);
174
+ if (states.create.staffOnly)
175
+ checkPath(states.create.staffOnly, `${sp}.create.staffOnly`, "boolean");
176
+ }
177
+ for (const [request, targets] of Object.entries(states.requests ?? {})) {
178
+ const rp = `${sp}.requests.${request}`;
179
+ if (isState(request))
180
+ contract(rp, `"${request}" is a state; a request needs its own name`);
181
+ if (new Set(targets).size !== targets.length)
182
+ contract(rp, "List each state once");
183
+ for (const to of targets) {
184
+ if (!isState(to))
185
+ contract(rp, `"${to}" is not an option of ${states.field}`);
186
+ else if (!states.moves.some((move) => move.to === to)) {
187
+ contract(rp, `No move goes to "${to}"`);
188
+ }
189
+ }
190
+ }
191
+ }
192
+ /**
193
+ * The field a path names (ADR 0503): `field` on the object, or `relation.field` on the object a
194
+ * relation of one record points to, within the same extension.
195
+ */
196
+ export function resolveFieldPath(m, object, path) {
197
+ const own = (o, local) => Object.hasOwn(o.fields, local) ? o.fields[local] : undefined;
198
+ const parts = path.split(".");
199
+ if (parts.length === 1)
200
+ return own(object, path);
201
+ if (parts.length !== 2)
202
+ return undefined;
203
+ const [relation, local] = parts;
204
+ const via = own(object, relation);
205
+ const to = via?.type === "relation" && !via.many ? via.to : undefined;
206
+ const target = to?.startsWith(`${m.id}.`) ? to.slice(m.id.length + 1) : undefined;
207
+ const targetObject = target !== undefined && Object.hasOwn(m.objects, target) ? m.objects[target] : undefined;
208
+ return targetObject ? own(targetObject, local) : undefined;
101
209
  }
@@ -0,0 +1,20 @@
1
+ import { z } from "zod";
2
+ import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
3
+ /**
4
+ * One uniqueness rule: no two live records with the same values of `fields` (one to four
5
+ * single-valued fields of this object; a record with any of them empty is not counted) while
6
+ * their state (the object's `states` field) is one of `states`. Left without `states`, every
7
+ * live record counts. The database refuses a second record, or a move back into a counted state,
8
+ * as a conflict (`rule: "unique"`).
9
+ */
10
+ export interface UniqueSpec {
11
+ fields: readonly string[];
12
+ states?: readonly string[];
13
+ }
14
+ export declare const uniqueManifestSchema: z.ZodArray<z.ZodObject<{
15
+ fields: z.ZodArray<z.ZodString>;
16
+ states: z.ZodOptional<z.ZodArray<z.ZodString>>;
17
+ }, z.core.$strict>>;
18
+ export type UniqueManifest = z.infer<typeof uniqueManifestSchema>;
19
+ /** Reports problems with `objects.<name>.unique` through `contract`. */
20
+ export declare function checkObjectUnique(_m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
package/dist/unique.js ADDED
@@ -0,0 +1,58 @@
1
+ // Declared uniqueness (stage 31, ADR 0502): an object says that among its live records in some
2
+ // states, no two share the values of some fields (one active booking per Person per class). The
3
+ // host refuses the second in the database, for every actor, however many write at once.
4
+ import { z } from "zod";
5
+ export const uniqueManifestSchema = z
6
+ .array(z
7
+ .object({
8
+ fields: z.array(z.string().max(40)).min(1).max(4),
9
+ states: z.array(z.string().min(1).max(100)).min(1).max(20).optional(),
10
+ })
11
+ .strict())
12
+ .min(1)
13
+ .max(4);
14
+ const UNIQUE_TYPES = new Set([
15
+ "text",
16
+ "number",
17
+ "date",
18
+ "datetime",
19
+ "boolean",
20
+ "select",
21
+ "relation",
22
+ "user",
23
+ "email",
24
+ "phone",
25
+ "url",
26
+ "slug",
27
+ "timezone",
28
+ ]);
29
+ /** Reports problems with `objects.<name>.unique` through `contract`. */
30
+ export function checkObjectUnique(_m, name, object, contract) {
31
+ (object.unique ?? []).forEach((rule, i) => {
32
+ const path = `objects.${name}.unique.${i}`;
33
+ if (new Set(rule.fields).size !== rule.fields.length) {
34
+ contract(`${path}.fields`, "List each field once");
35
+ }
36
+ for (const local of rule.fields) {
37
+ const field = Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
38
+ if (!field || field.many || !UNIQUE_TYPES.has(field.type)) {
39
+ contract(`${path}.fields`, `"${local}" must be a single-valued, stored field of ${name}`);
40
+ }
41
+ }
42
+ if (rule.states) {
43
+ const states = object.states;
44
+ if (!states) {
45
+ contract(`${path}.states`, `${name} has no states`);
46
+ return;
47
+ }
48
+ const field = Object.hasOwn(object.fields, states.field)
49
+ ? object.fields[states.field]
50
+ : undefined;
51
+ const values = new Set((field?.options ?? []).map((o) => o.value));
52
+ for (const state of rule.states) {
53
+ if (!values.has(state))
54
+ contract(`${path}.states`, `"${state}" is not a state of ${name}`);
55
+ }
56
+ }
57
+ });
58
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@composable-os/sdk",
3
- "version": "0.1.0-beta.8",
3
+ "version": "0.1.0-beta.9",
4
4
  "license": "FSL-1.1-ALv2",
5
5
  "type": "module",
6
6
  "repository": {