@composable-os/sdk 0.0.0-stage → 0.1.0-beta.8
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/LICENSE +109 -0
- package/dist/automation-check.d.ts +38 -0
- package/dist/automation-check.js +454 -0
- package/dist/automation.d.ts +767 -0
- package/dist/automation.js +303 -0
- package/dist/behaviour.d.ts +3 -0
- package/dist/behaviour.js +153 -0
- package/dist/capacity.d.ts +51 -0
- package/dist/capacity.js +68 -0
- package/dist/contract.d.ts +706 -0
- package/dist/contract.js +42 -0
- package/dist/document.d.ts +165 -0
- package/dist/document.js +636 -0
- package/dist/field-types.d.ts +11 -0
- package/dist/field-types.js +93 -0
- package/dist/formula/ast.d.ts +67 -0
- package/dist/formula/ast.js +22 -0
- package/dist/formula/compile.d.ts +37 -0
- package/dist/formula/compile.js +379 -0
- package/dist/formula/index.d.ts +3 -0
- package/dist/formula/index.js +4 -0
- package/dist/formula/parser.d.ts +13 -0
- package/dist/formula/parser.js +365 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +21 -0
- package/dist/manifest.d.ts +1131 -0
- package/dist/manifest.js +1229 -0
- package/dist/media.d.ts +9 -0
- package/dist/media.js +43 -0
- package/dist/permissions.d.ts +17 -0
- package/dist/permissions.js +44 -0
- package/dist/renamed.d.ts +16 -0
- package/dist/renamed.js +59 -0
- package/dist/rich-text-fixture.d.ts +121 -0
- package/dist/rich-text-fixture.js +67 -0
- package/dist/rich-text.d.ts +34 -0
- package/dist/rich-text.js +138 -0
- package/dist/runtime.d.ts +95 -0
- package/dist/runtime.js +312 -0
- package/dist/sellable.d.ts +103 -0
- package/dist/sellable.js +258 -0
- package/dist/slug.d.ts +11 -0
- package/dist/slug.js +23 -0
- package/dist/states.d.ts +64 -0
- package/dist/states.js +101 -0
- package/dist/testing.d.ts +151 -0
- package/dist/testing.js +670 -0
- package/package.json +34 -4
- package/src/automation-check.ts +534 -0
- package/src/automation.ts +743 -0
- package/src/behaviour.ts +215 -0
- package/src/capacity.ts +112 -0
- package/src/contract.ts +766 -0
- package/src/document.ts +788 -0
- package/src/field-types.ts +106 -0
- package/src/formula/ast.ts +72 -0
- package/src/formula/compile.ts +454 -0
- package/src/formula/index.ts +4 -0
- package/src/formula/parser.ts +417 -0
- package/src/index.ts +33 -0
- package/src/manifest.ts +1484 -0
- package/src/media.ts +46 -0
- package/src/permissions.ts +60 -0
- package/src/renamed.ts +63 -0
- package/src/rich-text-fixture.ts +68 -0
- package/src/rich-text.ts +173 -0
- package/src/runtime.ts +410 -0
- package/src/sellable.ts +396 -0
- package/src/slug.ts +25 -0
- package/src/states.ts +162 -0
- package/src/testing.ts +836 -0
- package/README.md +0 -3
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// The sandbox side of the runtime. The host generates a small entry module per run that imports
|
|
2
|
+
// the extension and the host modules it declared, and calls `runExtension`. Tool handlers get a
|
|
3
|
+
// `ctx` built from those modules; a module the extension did not declare is absent, and using it
|
|
4
|
+
// throws.
|
|
5
|
+
import { durationMs, notificationInput, } from "./automation.js";
|
|
6
|
+
import { toManifest } from "./manifest.js";
|
|
7
|
+
/** Thrown by `ctx.ops.call` when the operation fails; `code` is the pipeline's error code. */
|
|
8
|
+
export class OpsCallError extends Error {
|
|
9
|
+
code;
|
|
10
|
+
details;
|
|
11
|
+
name = "OpsCallError";
|
|
12
|
+
constructor(code, message, details) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.code = code;
|
|
15
|
+
this.details = details;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function missing(name) {
|
|
19
|
+
throw new Error(`Host module "${name}" is not declared. Add "${name}" to permissions.modules in defineExtension.`);
|
|
20
|
+
}
|
|
21
|
+
function absent(name) {
|
|
22
|
+
return new Proxy({}, {
|
|
23
|
+
get(_target, prop) {
|
|
24
|
+
if (prop === "then")
|
|
25
|
+
return undefined;
|
|
26
|
+
return () => missing(name);
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
/** Builds the `ctx` tools receive from raw host modules. Exported for the testing harness. */
|
|
31
|
+
export function buildContext(extension, raw, pending = [], caller) {
|
|
32
|
+
const ops = raw.ops
|
|
33
|
+
? {
|
|
34
|
+
call: async (operation, input) => {
|
|
35
|
+
// The host answers with an envelope so error codes survive the isolate boundary.
|
|
36
|
+
const reply = (await raw.ops?.call(operation, input ?? {}));
|
|
37
|
+
if (reply.ok)
|
|
38
|
+
return reply.value;
|
|
39
|
+
throw new OpsCallError(reply.error.code, reply.error.message, reply.error.details);
|
|
40
|
+
},
|
|
41
|
+
}
|
|
42
|
+
: absent("ops");
|
|
43
|
+
const storage = raw.storage
|
|
44
|
+
? {
|
|
45
|
+
get: (key) => raw.storage?.get(key),
|
|
46
|
+
set: async (key, value) => {
|
|
47
|
+
await raw.storage?.set(key, value);
|
|
48
|
+
},
|
|
49
|
+
delete: async (key) => {
|
|
50
|
+
await raw.storage?.del(key);
|
|
51
|
+
},
|
|
52
|
+
list: (prefix) => raw.storage?.list(prefix ?? ""),
|
|
53
|
+
}
|
|
54
|
+
: absent("storage");
|
|
55
|
+
const write = (level) => (message, data) => {
|
|
56
|
+
const call = raw.log?.write(level, String(message), data ?? null);
|
|
57
|
+
if (call)
|
|
58
|
+
pending.push(call.catch(() => undefined));
|
|
59
|
+
};
|
|
60
|
+
const log = raw.log
|
|
61
|
+
? { info: write("info"), warn: write("warn"), error: write("error") }
|
|
62
|
+
: absent("log");
|
|
63
|
+
const ai = raw.ai
|
|
64
|
+
? {
|
|
65
|
+
summarise: (text, options) => raw.ai?.summarise(text, options ?? {}),
|
|
66
|
+
extract: (text, fields) => raw.ai?.extract(text, fields),
|
|
67
|
+
classify: (text, labels) => raw.ai?.classify(text, labels),
|
|
68
|
+
}
|
|
69
|
+
: absent("ai");
|
|
70
|
+
const gatekeeper = (name) => {
|
|
71
|
+
const mod = raw[name];
|
|
72
|
+
if (!mod?.call)
|
|
73
|
+
return absent(name);
|
|
74
|
+
return {
|
|
75
|
+
connections: () => mod.connections?.(),
|
|
76
|
+
call: async (connectionId, resource, method, ...args) => {
|
|
77
|
+
const reply = (await mod.call?.(connectionId, resource, method, args));
|
|
78
|
+
if (reply.ok)
|
|
79
|
+
return reply.value;
|
|
80
|
+
throw new OpsCallError(reply.error.code, reply.error.message, reply.error.details);
|
|
81
|
+
},
|
|
82
|
+
types: (connectionId, resource) => mod.types?.(connectionId, resource),
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
return {
|
|
86
|
+
extension: { id: extension.id, version: extension.version },
|
|
87
|
+
ops,
|
|
88
|
+
storage,
|
|
89
|
+
log,
|
|
90
|
+
ai,
|
|
91
|
+
gatekeeper: gatekeeper,
|
|
92
|
+
...(caller ? { caller: Object.freeze({ ...caller }) } : {}),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function toError(error) {
|
|
96
|
+
if (error && typeof error === "object") {
|
|
97
|
+
const e = error;
|
|
98
|
+
return {
|
|
99
|
+
code: typeof e.code === "string" ? e.code : "extension_error",
|
|
100
|
+
message: typeof e.message === "string" ? e.message : String(error),
|
|
101
|
+
...(e.details === undefined ? {} : { details: e.details }),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
return { code: "extension_error", message: String(error) };
|
|
105
|
+
}
|
|
106
|
+
/** Plain JSON only crosses back to the host. */
|
|
107
|
+
function plain(value) {
|
|
108
|
+
return value === undefined ? null : JSON.parse(JSON.stringify(value));
|
|
109
|
+
}
|
|
110
|
+
/** Dispatches one run request inside the sandbox. */
|
|
111
|
+
export async function runExtension(extension, request, raw) {
|
|
112
|
+
const pending = [];
|
|
113
|
+
try {
|
|
114
|
+
if (request.kind === "manifest")
|
|
115
|
+
return { ok: true, value: plain(toManifest(extension)) };
|
|
116
|
+
const tool = extension.tools?.[request.tool];
|
|
117
|
+
if (!tool) {
|
|
118
|
+
return {
|
|
119
|
+
ok: false,
|
|
120
|
+
error: { code: "unknown_tool", message: `No tool named ${request.tool}` },
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
const parsed = tool.input.safeParse(request.input);
|
|
124
|
+
if (!parsed.success) {
|
|
125
|
+
return {
|
|
126
|
+
ok: false,
|
|
127
|
+
error: {
|
|
128
|
+
code: "invalid_input",
|
|
129
|
+
message: `Invalid input for ${request.tool}`,
|
|
130
|
+
details: plain(parsed.error.issues),
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
const ctx = buildContext(extension, raw, pending, request.caller);
|
|
135
|
+
const result = await tool.handler(parsed.data, ctx);
|
|
136
|
+
const checked = tool.output.safeParse(result);
|
|
137
|
+
await Promise.all(pending);
|
|
138
|
+
if (!checked.success) {
|
|
139
|
+
return {
|
|
140
|
+
ok: false,
|
|
141
|
+
error: {
|
|
142
|
+
code: "invalid_output",
|
|
143
|
+
message: `${request.tool} returned an invalid result`,
|
|
144
|
+
details: plain(checked.error.issues),
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
return { ok: true, value: plain(checked.data) };
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
await Promise.all(pending);
|
|
152
|
+
return { ok: false, error: toError(error) };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/** Thrown to unwind `run` once the advance has done its one step. Never reaches the host. */
|
|
156
|
+
class AdvanceStop extends Error {
|
|
157
|
+
name = "AdvanceStop";
|
|
158
|
+
}
|
|
159
|
+
/** A step call that does not match the declarations (the declarations are the contract). */
|
|
160
|
+
export class AutomationStepError extends Error {
|
|
161
|
+
name = "AutomationStepError";
|
|
162
|
+
code = "undeclared_step";
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Builds the automation `ctx`: the extension context plus `notify`, which calls
|
|
166
|
+
* `notification.send` with `notificationInput`. Its dedupe key is `<step>:<n>` (the n-th notify
|
|
167
|
+
* of that step), so a step retried or replayed never notifies twice.
|
|
168
|
+
*/
|
|
169
|
+
export function buildAutomationContext(extension, raw, event, pending = [], currentStep = () => null) {
|
|
170
|
+
const base = buildContext(extension, raw, pending);
|
|
171
|
+
const counts = new Map();
|
|
172
|
+
return {
|
|
173
|
+
...base,
|
|
174
|
+
async notify(to, message) {
|
|
175
|
+
const step = currentStep() ?? "run";
|
|
176
|
+
const n = (counts.get(step) ?? 0) + 1;
|
|
177
|
+
counts.set(step, n);
|
|
178
|
+
const input = notificationInput(event, to, message, `${step}:${n}`);
|
|
179
|
+
const out = (await base.ops.call("notification.send", input));
|
|
180
|
+
return { sent: typeof out?.sent === "number" ? out.sent : 0 };
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/** Runs one advance (or a whole test run) of an automation inside the sandbox. */
|
|
185
|
+
export async function runAutomation(extension, request, raw) {
|
|
186
|
+
const spec = extension.automations?.[request.automation];
|
|
187
|
+
if (!spec) {
|
|
188
|
+
return {
|
|
189
|
+
ok: false,
|
|
190
|
+
error: { code: "unknown_automation", message: `No automation named ${request.automation}` },
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
const test = request.mode === "test";
|
|
194
|
+
const journal = request.journal ?? [];
|
|
195
|
+
const declared = new Map(spec.steps.map((s) => [s.name, s]));
|
|
196
|
+
const testSteps = [];
|
|
197
|
+
let cursor = 0;
|
|
198
|
+
let stop = null;
|
|
199
|
+
const declaredStep = (name, kind) => {
|
|
200
|
+
const step = declared.get(name);
|
|
201
|
+
if (!step) {
|
|
202
|
+
throw new AutomationStepError(`step.${kind}("${name}") is not a declared step of ${request.automation}; add it to steps`);
|
|
203
|
+
}
|
|
204
|
+
const declaredKind = step.kind ?? "do";
|
|
205
|
+
if (declaredKind !== kind) {
|
|
206
|
+
throw new AutomationStepError(`"${name}" is declared as a ${declaredKind} step but was called with step.${kind}`);
|
|
207
|
+
}
|
|
208
|
+
return step;
|
|
209
|
+
};
|
|
210
|
+
/** The journaled result of the next step, or undefined when it is new. */
|
|
211
|
+
const replayed = (name, kind) => {
|
|
212
|
+
if (stop)
|
|
213
|
+
throw new AdvanceStop();
|
|
214
|
+
const entry = journal[cursor];
|
|
215
|
+
if (!entry)
|
|
216
|
+
return undefined;
|
|
217
|
+
if (entry.name !== name || entry.kind !== kind) {
|
|
218
|
+
throw new AutomationStepError(`The run took a different path on replay: step ${cursor + 1} was "${entry.name}" ` +
|
|
219
|
+
`(${entry.kind}) and is now "${name}" (${kind}). Steps must run in the same order ` +
|
|
220
|
+
"every time; base branches on step results, not on the clock or randomness.");
|
|
221
|
+
}
|
|
222
|
+
cursor += 1;
|
|
223
|
+
return { value: entry.value };
|
|
224
|
+
};
|
|
225
|
+
const halt = (advance) => {
|
|
226
|
+
stop = advance;
|
|
227
|
+
throw new AdvanceStop();
|
|
228
|
+
};
|
|
229
|
+
const pending = [];
|
|
230
|
+
// Every ops call carries the step it ran in, so the host can file it under that step (and
|
|
231
|
+
// flag writes the step did not declare).
|
|
232
|
+
let current = null;
|
|
233
|
+
const ops = raw.ops;
|
|
234
|
+
const tagged = ops
|
|
235
|
+
? { ...raw, ops: { call: (operation, input) => ops.call(operation, input, { step: current }) } }
|
|
236
|
+
: raw;
|
|
237
|
+
const ctx = buildAutomationContext(extension, tagged, request.event, pending, () => current);
|
|
238
|
+
const step = {
|
|
239
|
+
async do(name, a, b) {
|
|
240
|
+
const fn = (typeof a === "function" ? a : b);
|
|
241
|
+
const declaredDo = declaredStep(name, "do");
|
|
242
|
+
if (a && typeof a === "object") {
|
|
243
|
+
const intent = a;
|
|
244
|
+
const allowed = new Set((declaredDo.writes ?? []).map((w) => w.object));
|
|
245
|
+
const extra = (intent.writes ?? []).find((w) => !allowed.has(w.object));
|
|
246
|
+
if (extra) {
|
|
247
|
+
throw new AutomationStepError(`step.do("${name}") writes ${extra.object}, which its declaration does not list`);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const r = replayed(name, "do");
|
|
251
|
+
if (r)
|
|
252
|
+
return r.value;
|
|
253
|
+
current = name;
|
|
254
|
+
let value;
|
|
255
|
+
try {
|
|
256
|
+
value = plain(await fn());
|
|
257
|
+
}
|
|
258
|
+
finally {
|
|
259
|
+
current = null;
|
|
260
|
+
}
|
|
261
|
+
if (test) {
|
|
262
|
+
testSteps.push({ name, kind: "do", value });
|
|
263
|
+
return value;
|
|
264
|
+
}
|
|
265
|
+
return halt({ kind: "do", name, value });
|
|
266
|
+
},
|
|
267
|
+
async sleep(name, duration) {
|
|
268
|
+
declaredStep(name, "sleep");
|
|
269
|
+
if (replayed(name, "sleep"))
|
|
270
|
+
return;
|
|
271
|
+
const ms = durationMs(duration);
|
|
272
|
+
if (test) {
|
|
273
|
+
testSteps.push({ name, kind: "sleep", skippedMs: ms });
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
halt({ kind: "sleep", name, ms });
|
|
277
|
+
},
|
|
278
|
+
async waitForEvent(name) {
|
|
279
|
+
const declaredWait = declaredStep(name, "waitForEvent");
|
|
280
|
+
const r = replayed(name, "waitForEvent");
|
|
281
|
+
if (r)
|
|
282
|
+
return r.value ?? null;
|
|
283
|
+
const timeoutMs = durationMs(declaredWait.timeout ?? "7 days");
|
|
284
|
+
if (test) {
|
|
285
|
+
testSteps.push({ name, kind: "waitForEvent", skippedMs: timeoutMs });
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
return halt({ kind: "waitForEvent", name, event: declaredWait.event, timeoutMs });
|
|
289
|
+
},
|
|
290
|
+
};
|
|
291
|
+
try {
|
|
292
|
+
const value = await spec.run(request.event, step, ctx);
|
|
293
|
+
await Promise.all(pending);
|
|
294
|
+
if (stop)
|
|
295
|
+
return { ok: true, value: plain(stop) };
|
|
296
|
+
const done = test
|
|
297
|
+
? { kind: "test", steps: testSteps, value: plain(value) }
|
|
298
|
+
: { kind: "done", value: plain(value) };
|
|
299
|
+
return { ok: true, value: plain(done) };
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
await Promise.all(pending);
|
|
303
|
+
// The stop unwinds `run` by throwing; code that catches and rethrows it changes nothing.
|
|
304
|
+
if (stop)
|
|
305
|
+
return { ok: true, value: plain(stop) };
|
|
306
|
+
// Test mode keeps the steps that ran before the failure, for the report.
|
|
307
|
+
if (test) {
|
|
308
|
+
return { ok: false, error: { ...toError(error), details: { steps: plain(testSteps) } } };
|
|
309
|
+
}
|
|
310
|
+
return { ok: false, error: toError(error) };
|
|
311
|
+
}
|
|
312
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Where a granted record's field gets its value, when the host creates it:
|
|
5
|
+
*
|
|
6
|
+
* - `item`: the record that was bought (a relation to this sellable object);
|
|
7
|
+
* - `item.<field>`: a field of the record that was bought (its event, its name);
|
|
8
|
+
* - `order`: the order's id (a text field);
|
|
9
|
+
* - `order.person`: the buyer, a relation to a person (empty when the order belongs to no one
|
|
10
|
+
* yet, so the field cannot be required);
|
|
11
|
+
* - `order.email`: the address the order was placed with;
|
|
12
|
+
* - `line`: the order line's id (a text field);
|
|
13
|
+
* - `line.title`: what the line was called when it was bought;
|
|
14
|
+
* - `line.unitPrice`: what one cost, in the currency's major unit;
|
|
15
|
+
* - `code`: a long, random, unguessable code the host makes (a ticket's). A read-only text field;
|
|
16
|
+
* at most one per grant. The host keeps it unique across every granted record.
|
|
17
|
+
*/
|
|
18
|
+
export type GrantSource = "item" | `item.${string}` | "order" | "order.person" | "order.email" | "line" | "line.title" | "line.unitPrice" | "code";
|
|
19
|
+
/**
|
|
20
|
+
* What a paid line grants: one record of `object` for each unit bought (two tickets for a line
|
|
21
|
+
* of two), created by the host, as the host, when the order is first paid (the move to `paid`,
|
|
22
|
+
* or to `part_paid` for a deposit), in the same batch. No extension code runs.
|
|
23
|
+
*
|
|
24
|
+
* - `object` is another of this extension's objects. It declares `states`; its records start in
|
|
25
|
+
* the initial state.
|
|
26
|
+
* - `set` names, for each field of the granted record the host fills, where its value comes from
|
|
27
|
+
* (see GrantSource). Every required field of the granted object must be set from a source that
|
|
28
|
+
* always has a value.
|
|
29
|
+
* - `void` is the state the host moves what was granted to when the order is refunded in full, or
|
|
30
|
+
* cancelled after a deposit. Every state but `void` and the final ones needs a `host` move into
|
|
31
|
+
* it. A record already there, or in a final state, is left alone.
|
|
32
|
+
*/
|
|
33
|
+
export interface GrantSpec {
|
|
34
|
+
object: string;
|
|
35
|
+
set: Readonly<Record<string, GrantSource>>;
|
|
36
|
+
void: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Something that can be bought (ADR 0435). An order line may point only at a record of an object
|
|
40
|
+
* that declares it; the host prices the line from the record, so a caller never sends a price.
|
|
41
|
+
* Only a shipped pack or the org's own extension may declare it: selling to the public is a
|
|
42
|
+
* reviewed change, so a runtime extension that does is refused at check and install.
|
|
43
|
+
*
|
|
44
|
+
* - `price`: this object's currency (or number) field holding the price of one, in the currency's
|
|
45
|
+
* major unit. A record with no price cannot be bought.
|
|
46
|
+
* - `currency`: what the price is in (ISO 4217). Left out, the price field's own currency, and
|
|
47
|
+
* with neither, the deployment's. A line priced in another currency than the deployment's is
|
|
48
|
+
* refused.
|
|
49
|
+
* - `saleWindow`: the date or datetime fields saying when a record is on sale, from `from` and
|
|
50
|
+
* until `until` (a date: the whole day, in UTC). Empty values leave that end open. A line
|
|
51
|
+
* outside it is refused with `{ rule: "sale_window" }`.
|
|
52
|
+
* - `maxPerOrder`: a number field holding the most of one record one order may hold. Empty means
|
|
53
|
+
* no limit beyond the host's own: 10 when the object grants, and never more than 100 grants
|
|
54
|
+
* on one order (the paid batch has a size). More is refused with `{ rule: "max_per_order" }`.
|
|
55
|
+
* - `deposit`: paying by deposit (stage 25): the field holding the deposit for one, and the date
|
|
56
|
+
* field saying when the balance is due. A record offers a deposit when both have a value.
|
|
57
|
+
* - `grants`: what a paid line grants (see GrantSpec).
|
|
58
|
+
*/
|
|
59
|
+
export interface SellableSpec {
|
|
60
|
+
price: string;
|
|
61
|
+
currency?: string;
|
|
62
|
+
saleWindow?: {
|
|
63
|
+
from?: string;
|
|
64
|
+
until?: string;
|
|
65
|
+
};
|
|
66
|
+
maxPerOrder?: string;
|
|
67
|
+
deposit?: {
|
|
68
|
+
amount: string;
|
|
69
|
+
balanceDue: string;
|
|
70
|
+
};
|
|
71
|
+
grants?: GrantSpec;
|
|
72
|
+
}
|
|
73
|
+
export declare const GRANT_SOURCES: readonly ["item", "order", "order.person", "order.email", "line", "line.title", "line.unitPrice", "code"];
|
|
74
|
+
export declare const sellableManifestSchema: z.ZodObject<{
|
|
75
|
+
price: z.ZodString;
|
|
76
|
+
currency: z.ZodOptional<z.ZodString>;
|
|
77
|
+
saleWindow: z.ZodOptional<z.ZodObject<{
|
|
78
|
+
from: z.ZodOptional<z.ZodString>;
|
|
79
|
+
until: z.ZodOptional<z.ZodString>;
|
|
80
|
+
}, z.core.$strict>>;
|
|
81
|
+
maxPerOrder: z.ZodOptional<z.ZodString>;
|
|
82
|
+
deposit: z.ZodOptional<z.ZodObject<{
|
|
83
|
+
amount: z.ZodOptional<z.ZodString>;
|
|
84
|
+
balanceDue: z.ZodOptional<z.ZodString>;
|
|
85
|
+
}, z.core.$strict>>;
|
|
86
|
+
grants: z.ZodOptional<z.ZodObject<{
|
|
87
|
+
object: z.ZodString;
|
|
88
|
+
set: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodEnum<{
|
|
89
|
+
item: "item";
|
|
90
|
+
order: "order";
|
|
91
|
+
"order.person": "order.person";
|
|
92
|
+
"order.email": "order.email";
|
|
93
|
+
line: "line";
|
|
94
|
+
"line.title": "line.title";
|
|
95
|
+
"line.unitPrice": "line.unitPrice";
|
|
96
|
+
code: "code";
|
|
97
|
+
}>, z.ZodString]>>;
|
|
98
|
+
void: z.ZodString;
|
|
99
|
+
}, z.core.$strict>>;
|
|
100
|
+
}, z.core.$strict>;
|
|
101
|
+
export type SellableManifest = z.infer<typeof sellableManifestSchema>;
|
|
102
|
+
/** Reports problems with `objects.<name>.sellable` through `contract`. */
|
|
103
|
+
export declare function checkObjectSellable(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
|
package/dist/sellable.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// The `sellable` behaviour (stage 27, ADR 0435): an object's records can be put on an order. The
|
|
2
|
+
// host reads the price from the record, refuses a line outside the sale window or over the most
|
|
3
|
+
// one order may hold, and, when the order is first paid, creates what a paid line grants (a
|
|
4
|
+
// ticket per place) in the batch that marks it paid. Its declaration, its manifest schema and its
|
|
5
|
+
// contract checks live here; the host's side is packages/core/src/orders/ (sellable.ts, grants.ts).
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { moveOrigins } from "./states.js";
|
|
8
|
+
const fieldName = z.string().max(40);
|
|
9
|
+
export const GRANT_SOURCES = [
|
|
10
|
+
"item",
|
|
11
|
+
"order",
|
|
12
|
+
"order.person",
|
|
13
|
+
"order.email",
|
|
14
|
+
"line",
|
|
15
|
+
"line.title",
|
|
16
|
+
"line.unitPrice",
|
|
17
|
+
"code",
|
|
18
|
+
];
|
|
19
|
+
const grantSource = z.union([
|
|
20
|
+
z.enum(GRANT_SOURCES),
|
|
21
|
+
z.string().regex(/^item\.[a-z][a-zA-Z0-9]{0,39}$/, "Use item, item.<field>, order, line or code"),
|
|
22
|
+
]);
|
|
23
|
+
export const sellableManifestSchema = z
|
|
24
|
+
.object({
|
|
25
|
+
price: fieldName,
|
|
26
|
+
currency: z
|
|
27
|
+
.string()
|
|
28
|
+
.regex(/^[A-Z]{3}$/)
|
|
29
|
+
.optional(),
|
|
30
|
+
saleWindow: z
|
|
31
|
+
.object({ from: fieldName.optional(), until: fieldName.optional() })
|
|
32
|
+
.strict()
|
|
33
|
+
.optional(),
|
|
34
|
+
maxPerOrder: fieldName.optional(),
|
|
35
|
+
deposit: z
|
|
36
|
+
.object({ amount: fieldName.optional(), balanceDue: fieldName.optional() })
|
|
37
|
+
.strict()
|
|
38
|
+
.optional(),
|
|
39
|
+
grants: z
|
|
40
|
+
.object({
|
|
41
|
+
object: z.string().max(40),
|
|
42
|
+
set: z.record(fieldName, grantSource),
|
|
43
|
+
void: z.string().min(1).max(100),
|
|
44
|
+
})
|
|
45
|
+
.strict()
|
|
46
|
+
.optional(),
|
|
47
|
+
})
|
|
48
|
+
.strict();
|
|
49
|
+
const NUMERIC = new Set(["number", "currency"]);
|
|
50
|
+
const DATES = new Set(["date", "datetime"]);
|
|
51
|
+
const TEXT = new Set(["text"]);
|
|
52
|
+
/** Reports problems with `objects.<name>.sellable` through `contract`. */
|
|
53
|
+
export function checkObjectSellable(m, name, object, contract) {
|
|
54
|
+
const sellable = object.sellable;
|
|
55
|
+
if (!sellable)
|
|
56
|
+
return;
|
|
57
|
+
const path = `objects.${name}.sellable`;
|
|
58
|
+
const fieldOf = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
|
|
59
|
+
const single = (local, types) => {
|
|
60
|
+
const field = fieldOf(local);
|
|
61
|
+
return field !== undefined && types.has(field.type) && !field.many;
|
|
62
|
+
};
|
|
63
|
+
if (!single(sellable.price, NUMERIC)) {
|
|
64
|
+
contract(`${path}.price`, `"${sellable.price}" must be a currency or number field of ${name}`);
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
const own = fieldOf(sellable.price)?.currency;
|
|
68
|
+
if (sellable.currency && own && own !== sellable.currency) {
|
|
69
|
+
contract(`${path}.currency`, `The price field is in ${own}; currency says ${sellable.currency}. Declare one`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (sellable.saleWindow) {
|
|
73
|
+
const { from, until } = sellable.saleWindow;
|
|
74
|
+
if (from === undefined && until === undefined) {
|
|
75
|
+
contract(`${path}.saleWindow`, "A sale window names its from field, its until field or both");
|
|
76
|
+
}
|
|
77
|
+
for (const [key, local] of [
|
|
78
|
+
["from", from],
|
|
79
|
+
["until", until],
|
|
80
|
+
]) {
|
|
81
|
+
if (local !== undefined && !single(local, DATES)) {
|
|
82
|
+
contract(`${path}.saleWindow.${key}`, `"${local}" must be a date or datetime field of ${name}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (sellable.maxPerOrder !== undefined && !single(sellable.maxPerOrder, new Set(["number"]))) {
|
|
87
|
+
contract(`${path}.maxPerOrder`, `"${sellable.maxPerOrder}" must be a number field of ${name}`);
|
|
88
|
+
}
|
|
89
|
+
if (sellable.deposit) {
|
|
90
|
+
const { amount, balanceDue } = sellable.deposit;
|
|
91
|
+
if (amount === undefined || balanceDue === undefined) {
|
|
92
|
+
contract(`${path}.deposit`, "A deposit names both fields: amount (the deposit for one) and balanceDue (when the rest is due)");
|
|
93
|
+
}
|
|
94
|
+
if (amount !== undefined && !single(amount, NUMERIC)) {
|
|
95
|
+
contract(`${path}.deposit.amount`, `"${amount}" must be a currency or number field of ${name}`);
|
|
96
|
+
}
|
|
97
|
+
if (balanceDue !== undefined && !single(balanceDue, DATES)) {
|
|
98
|
+
contract(`${path}.deposit.balanceDue`, `"${balanceDue}" must be a date or datetime field of ${name}`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (sellable.grants)
|
|
102
|
+
checkGrants(m, name, object, sellable.grants, `${path}.grants`, contract);
|
|
103
|
+
}
|
|
104
|
+
function checkGrants(m, name, item, grants, path, contract) {
|
|
105
|
+
const local = grants.object.startsWith(`${m.id}.`)
|
|
106
|
+
? grants.object.slice(m.id.length + 1)
|
|
107
|
+
: grants.object;
|
|
108
|
+
const granted = Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
|
|
109
|
+
if (!granted) {
|
|
110
|
+
contract(`${path}.object`, `"${grants.object}" must be another of this extension's objects`);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (local === name) {
|
|
114
|
+
contract(`${path}.object`, "An object cannot grant records of itself");
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (granted.sellable) {
|
|
118
|
+
contract(`${path}.object`, `${local} is itself sellable; a grant is what was bought, not more for sale`);
|
|
119
|
+
}
|
|
120
|
+
const states = granted.states;
|
|
121
|
+
if (!states) {
|
|
122
|
+
contract(`${path}.object`, `${local} must declare states, so what was granted can be voided (to "${grants.void}")`);
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
const stateField = granted.fields[states.field];
|
|
126
|
+
const values = new Set((stateField?.options ?? []).map((o) => o.value));
|
|
127
|
+
const finals = new Set(states.moves.filter((mv) => mv.final).map((mv) => mv.to));
|
|
128
|
+
if (!values.has(grants.void)) {
|
|
129
|
+
contract(`${path}.void`, `"${grants.void}" is not a state of ${local}`);
|
|
130
|
+
}
|
|
131
|
+
else if (grants.void === states.initial) {
|
|
132
|
+
contract(`${path}.void`, `"${grants.void}" is ${local}'s initial state; void is where a grant ends`);
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
for (const state of values) {
|
|
136
|
+
if (state === grants.void || finals.has(state))
|
|
137
|
+
continue;
|
|
138
|
+
const moves = states.moves.some((mv) => mv.to === grants.void && moveOrigins(mv).includes(state) && mv.by.includes("host"));
|
|
139
|
+
if (!moves) {
|
|
140
|
+
contract(`${path}.void`, `${local} needs a move from "${state}" to "${grants.void}" that the host may make (by: ["host", ...])`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (Object.hasOwn(grants.set, states.field)) {
|
|
145
|
+
contract(`${path}.set.${states.field}`, `${states.field} is ${local}'s state: a granted record starts in "${states.initial}"`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const itemField = (f) => (Object.hasOwn(item.fields, f) ? item.fields[f] : undefined);
|
|
149
|
+
let codes = 0;
|
|
150
|
+
for (const [target, source] of Object.entries(grants.set)) {
|
|
151
|
+
const fp = `${path}.set.${target}`;
|
|
152
|
+
const field = Object.hasOwn(granted.fields, target) ? granted.fields[target] : undefined;
|
|
153
|
+
if (!field || field.type === "formula") {
|
|
154
|
+
contract(fp, `"${target}" must be a field of ${local} other than a formula`);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const want = (ok, what) => {
|
|
158
|
+
if (!ok)
|
|
159
|
+
contract(fp, `${source} needs ${what}; "${target}" is a ${field.type} field`);
|
|
160
|
+
};
|
|
161
|
+
const one = !field.many;
|
|
162
|
+
if (source === "item") {
|
|
163
|
+
want(field.type === "relation" && one && field.to === `${m.id}.${name}`, `a relation (one record) to ${m.id}.${name}`);
|
|
164
|
+
}
|
|
165
|
+
else if (source.startsWith("item.")) {
|
|
166
|
+
const from = source.slice("item.".length);
|
|
167
|
+
const own = itemField(from);
|
|
168
|
+
if (!own || own.type === "formula") {
|
|
169
|
+
contract(fp, `"${from}" is not a field of ${name}`);
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
want(own.type === field.type &&
|
|
173
|
+
Boolean(own.many) === Boolean(field.many) &&
|
|
174
|
+
(own.type !== "relation" || own.to === field.to), `a ${own.type} field${own.to ? ` to ${own.to}` : ""}, like ${name}.${from}`);
|
|
175
|
+
if (field.required && !own.required) {
|
|
176
|
+
contract(fp, `"${target}" is required and ${name}.${from} may be empty`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
else if (source === "order.person") {
|
|
180
|
+
want(field.type === "relation" && one && field.to === "person", "a relation to one person");
|
|
181
|
+
if (field.required) {
|
|
182
|
+
contract(fp, `"${target}" cannot be required: an order may belong to no one yet`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
else if (source === "order.email") {
|
|
186
|
+
want(field.type === "email" || field.type === "text", "an email or text field");
|
|
187
|
+
}
|
|
188
|
+
else if (source === "order" || source === "line" || source === "line.title") {
|
|
189
|
+
want(TEXT.has(field.type), "a text field");
|
|
190
|
+
}
|
|
191
|
+
else if (source === "line.unitPrice") {
|
|
192
|
+
want(NUMERIC.has(field.type), "a currency or number field");
|
|
193
|
+
}
|
|
194
|
+
else if (source === "code") {
|
|
195
|
+
codes += 1;
|
|
196
|
+
want(TEXT.has(field.type), "a text field");
|
|
197
|
+
if (!field.readOnly) {
|
|
198
|
+
contract(fp, `"${target}" holds the host's code: make it readOnly, so nobody can change it`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (codes > 1)
|
|
203
|
+
contract(`${path}.set`, "A grant has at most one code");
|
|
204
|
+
// The granted object's own rules must not be able to refuse the host's insert, since that
|
|
205
|
+
// would refuse the payment. What a grant always fills: its set fields whose source always has
|
|
206
|
+
// a value, and fields with a default.
|
|
207
|
+
const always = (source) => source === "order.person"
|
|
208
|
+
? false
|
|
209
|
+
: source.startsWith("item.")
|
|
210
|
+
? Boolean(itemField(source.slice("item.".length))?.required)
|
|
211
|
+
: true;
|
|
212
|
+
const filled = new Set([
|
|
213
|
+
...Object.entries(grants.set)
|
|
214
|
+
.filter(([, source]) => always(source))
|
|
215
|
+
.map(([field]) => field),
|
|
216
|
+
...Object.entries(granted.fields)
|
|
217
|
+
.filter(([, field]) => field.default !== undefined)
|
|
218
|
+
.map(([name]) => name),
|
|
219
|
+
]);
|
|
220
|
+
if (granted.owner !== undefined) {
|
|
221
|
+
contract(`objects.${local}.owner`, `${local} is granted by ${name}: an owner would run assignment rules in the paid batch, which could refuse it. Remove owner`);
|
|
222
|
+
}
|
|
223
|
+
granted.requireOneOf?.forEach((group, i) => {
|
|
224
|
+
if (!group.some((field) => filled.has(field))) {
|
|
225
|
+
contract(`objects.${local}.requireOneOf.${i}`, `${local} is granted by ${name}: set one of ${group.join(", ")} in grants.set from a source that always has a value`);
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
for (const [fieldName, field] of Object.entries(granted.fields)) {
|
|
229
|
+
if (field.type !== "select")
|
|
230
|
+
continue;
|
|
231
|
+
const source = grants.set[fieldName];
|
|
232
|
+
// The choices a granted record can hold when it is created.
|
|
233
|
+
const values = source?.startsWith("item.") === true
|
|
234
|
+
? (field.options ?? []).map((o) => o.value)
|
|
235
|
+
: states && fieldName === states.field
|
|
236
|
+
? [states.initial]
|
|
237
|
+
: field.default !== undefined
|
|
238
|
+
? [String(field.default)]
|
|
239
|
+
: [];
|
|
240
|
+
for (const option of field.options ?? []) {
|
|
241
|
+
if (!values.includes(option.value))
|
|
242
|
+
continue;
|
|
243
|
+
const missing = (option.requires ?? []).filter((required) => !filled.has(required));
|
|
244
|
+
if (missing.length) {
|
|
245
|
+
contract(`objects.${local}.fields.${fieldName}.options`, `${local} is granted by ${name}: "${option.value}" needs ${missing.join(", ")}, which grants.set does not always fill`);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
for (const [fieldName, field] of Object.entries(granted.fields)) {
|
|
250
|
+
if (!field.required || field.type === "formula" || field.default !== undefined)
|
|
251
|
+
continue;
|
|
252
|
+
if (states && fieldName === states.field)
|
|
253
|
+
continue;
|
|
254
|
+
if (!Object.hasOwn(grants.set, fieldName)) {
|
|
255
|
+
contract(`${path}.set`, `${local}.${fieldName} is required: set it from the item, the order or the line`);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
package/dist/slug.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** What a slug may be. */
|
|
2
|
+
export declare const SLUG_RE: RegExp;
|
|
3
|
+
/** The longest a slug may be. */
|
|
4
|
+
export declare const SLUG_MAX = 120;
|
|
5
|
+
/** The longest slug made from a title, leaving room for a `-<n>` that tells two apart. */
|
|
6
|
+
export declare const SLUG_FROM_TITLE_MAX = 80;
|
|
7
|
+
/**
|
|
8
|
+
* A slug made from a title: accents dropped, every run of anything that is not a letter or digit
|
|
9
|
+
* a hyphen, at most SLUG_FROM_TITLE_MAX characters. Empty when nothing is left.
|
|
10
|
+
*/
|
|
11
|
+
export declare function slugify(title: string): string;
|