@proveanything/smartlinks 2.1.16 → 2.1.18
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/adminViews.d.ts +85 -0
- package/dist/adminViews.js +259 -0
- package/dist/api/errors.d.ts +10 -0
- package/dist/api/errors.js +17 -0
- package/dist/api/index.d.ts +3 -0
- package/dist/api/index.js +3 -0
- package/dist/api/operations.d.ts +36 -0
- package/dist/api/operations.js +56 -0
- package/dist/api/order.d.ts +12 -1
- package/dist/api/order.js +15 -0
- package/dist/api/partner.d.ts +7 -1
- package/dist/api/partner.js +9 -0
- package/dist/api/userGroups.d.ts +78 -0
- package/dist/api/userGroups.js +124 -0
- package/dist/docs/API_SUMMARY.md +699 -46
- package/dist/docs/admin-views.md +125 -0
- package/dist/docs/app-manifest.md +2 -0
- package/dist/docs/app-objects.md +23 -0
- package/dist/docs/operations.md +281 -0
- package/dist/docs/overview.md +3 -0
- package/dist/docs/server-functions.md +106 -0
- package/dist/docs/tag-ranges.md +8 -0
- package/dist/docs/user-groups.md +168 -0
- package/dist/docs/utils.md +17 -0
- package/dist/http.js +4 -0
- package/dist/iframeResponder.d.ts +15 -0
- package/dist/iframeResponder.js +39 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/openapi.yaml +1426 -276
- package/dist/testing/index.d.ts +29 -0
- package/dist/testing/index.js +178 -1
- package/dist/types/appManifest.d.ts +170 -0
- package/dist/types/appObjects.d.ts +22 -1
- package/dist/types/claimSet.d.ts +2 -0
- package/dist/types/clientLog.d.ts +46 -0
- package/dist/types/clientLog.js +1 -0
- package/dist/types/containers.d.ts +8 -0
- package/dist/types/iframeResponder.d.ts +16 -1
- package/dist/types/index.d.ts +3 -0
- package/dist/types/index.js +3 -0
- package/dist/types/operations.d.ts +598 -0
- package/dist/types/operations.js +8 -0
- package/dist/types/order.d.ts +35 -6
- package/dist/types/userGroups.d.ts +103 -0
- package/dist/types/userGroups.js +5 -0
- package/dist/utils/conditions.d.ts +7 -0
- package/dist/utils/conditions.js +16 -9
- package/docs/API_SUMMARY.md +699 -46
- package/docs/admin-views.md +125 -0
- package/docs/app-manifest.md +2 -0
- package/docs/app-objects.md +23 -0
- package/docs/operations.md +281 -0
- package/docs/overview.md +3 -0
- package/docs/server-functions.md +106 -0
- package/docs/tag-ranges.md +8 -0
- package/docs/user-groups.md +168 -0
- package/docs/utils.md +17 -0
- package/openapi.yaml +1426 -276
- package/package.json +1 -1
package/dist/testing/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AppFunctionDef, ServerFunctionContext, ServerFunctionInputs } from '../types/appManifest.js';
|
|
2
|
+
import type { WorkOrdersApi, StockApi, BomsApi, MadeFromApi, OperationsApi } from '../types/operations.js';
|
|
2
3
|
import { type BookingsMemory } from './bookingsMemory.js';
|
|
3
4
|
export declare class CapabilityError extends Error {
|
|
4
5
|
capability: string;
|
|
@@ -16,7 +17,11 @@ export interface TestSlImpl {
|
|
|
16
17
|
get?(id: string): any;
|
|
17
18
|
query?(params: any): any;
|
|
18
19
|
listTypes?(): any;
|
|
20
|
+
adjust?(id: string, by: Record<string, number>, opts?: any): any;
|
|
21
|
+
aggregate?(params?: any): any;
|
|
19
22
|
};
|
|
23
|
+
/** ctx.sl.transaction(ops, { idempotencyKey }) — defaults to the in-memory one (all or none, replay by key). */
|
|
24
|
+
transaction?(ops: any[], opts?: any): any;
|
|
20
25
|
counters?: {
|
|
21
26
|
next?(name: string, opts?: any): any;
|
|
22
27
|
get?(name: string): any;
|
|
@@ -65,6 +70,16 @@ export interface TestSlImpl {
|
|
|
65
70
|
* time, idempotent creates, holds) — inspect it via `ctx.memory.bookings`.
|
|
66
71
|
*/
|
|
67
72
|
bookings?: Record<string, any>;
|
|
73
|
+
/**
|
|
74
|
+
* Work orders, stock, bills of materials and made-from (docs/operations.md). There is no in-memory
|
|
75
|
+
* engine for these: give the methods your function calls, and any other call returns a stub echo.
|
|
76
|
+
* The harness still enforces both production gates: the capability, and collection authority.
|
|
77
|
+
*/
|
|
78
|
+
workOrders?: Partial<WorkOrdersApi>;
|
|
79
|
+
stock?: Partial<StockApi>;
|
|
80
|
+
boms?: Partial<BomsApi>;
|
|
81
|
+
madeFrom?: Partial<MadeFromApi>;
|
|
82
|
+
operations?: Partial<OperationsApi>;
|
|
68
83
|
}
|
|
69
84
|
export interface TestCaller {
|
|
70
85
|
userId?: string | null;
|
|
@@ -73,6 +88,8 @@ export interface TestCaller {
|
|
|
73
88
|
anonymous?: boolean;
|
|
74
89
|
origin?: string | null;
|
|
75
90
|
ip?: string | null;
|
|
91
|
+
/** Keys of the user groups the caller is in, for `ctx.caller.userGroups`. Default: none. */
|
|
92
|
+
userGroups?: string[];
|
|
76
93
|
}
|
|
77
94
|
export interface CreateFunctionTestContextOptions {
|
|
78
95
|
/** The manifest declaration under test — its `capabilities` are the enforced envelope. */
|
|
@@ -108,6 +125,18 @@ export interface FunctionTestMemory {
|
|
|
108
125
|
interactions: any[];
|
|
109
126
|
/** Slots, bookings and allocations of the in-memory bookings engine. */
|
|
110
127
|
bookings: BookingsMemory;
|
|
128
|
+
/** ctx.sl.transaction results by idempotency key (a repeat replays them). */
|
|
129
|
+
transactions: Record<string, any[]>;
|
|
130
|
+
/** ctx.sl.history events (log ops and history.log), oldest first. */
|
|
131
|
+
history: Array<{
|
|
132
|
+
id: string;
|
|
133
|
+
at: string;
|
|
134
|
+
type: string;
|
|
135
|
+
entityId: string | null;
|
|
136
|
+
data: Record<string, any>;
|
|
137
|
+
actorType: null;
|
|
138
|
+
actorId: null;
|
|
139
|
+
}>;
|
|
111
140
|
}
|
|
112
141
|
/** A fresh in-memory store — pass the same one to several test contexts to simulate concurrent callers. */
|
|
113
142
|
export declare function createFunctionTestMemory(): FunctionTestMemory;
|
package/dist/testing/index.js
CHANGED
|
@@ -77,7 +77,7 @@ function allowsSl(p, resource, op) {
|
|
|
77
77
|
}
|
|
78
78
|
/** A fresh in-memory store — pass the same one to several test contexts to simulate concurrent callers. */
|
|
79
79
|
export function createFunctionTestMemory() {
|
|
80
|
-
return { records: [], counters: {}, contacts: [], interactions: [], bookings: createBookingsMemory() };
|
|
80
|
+
return { records: [], counters: {}, contacts: [], interactions: [], bookings: createBookingsMemory(), transactions: {}, history: [] };
|
|
81
81
|
}
|
|
82
82
|
const stub = (method, args) => ({ __stub: true, method, args });
|
|
83
83
|
/**
|
|
@@ -101,6 +101,9 @@ export function createFunctionTestContext(opts) {
|
|
|
101
101
|
return fn ? fn(...args) : stub(`${resource}.${name}`, args);
|
|
102
102
|
};
|
|
103
103
|
const mem = opts.memory || createFunctionTestMemory();
|
|
104
|
+
// A memory built before history / transactions existed still works.
|
|
105
|
+
mem.history = mem.history || [];
|
|
106
|
+
mem.transactions = mem.transactions || {};
|
|
104
107
|
const ar = impl.appRecords || {};
|
|
105
108
|
const pr = impl.products || {};
|
|
106
109
|
const at = impl.attestations || {};
|
|
@@ -147,6 +150,60 @@ export function createFunctionTestContext(opts) {
|
|
|
147
150
|
return null; Object.assign(r, fields); return Object.assign({}, r); },
|
|
148
151
|
delete: async (id) => { const r = mem.records.find((x) => x.id === id); if (r)
|
|
149
152
|
r.deletedAt = new Date().toISOString(); return {}; },
|
|
153
|
+
// Numbers in data changed in place, with atLeast / atMost checked after the change (as the platform).
|
|
154
|
+
adjust: async (id, by = {}, opts = {}) => {
|
|
155
|
+
var _a, _b;
|
|
156
|
+
const r = mem.records.find((x) => x.id === id && !x.deletedAt);
|
|
157
|
+
if (!r)
|
|
158
|
+
throw Object.assign(new Error('Record not found'), { code: 'NOT_FOUND', statusCode: 404 });
|
|
159
|
+
const data = r.data || {};
|
|
160
|
+
const keys = [...new Set([...Object.keys(by), ...Object.keys(opts.atLeast || {}), ...Object.keys(opts.atMost || {})])];
|
|
161
|
+
const bad = keys.find((k) => data[k] != null && typeof data[k] !== 'number');
|
|
162
|
+
if (bad)
|
|
163
|
+
throw Object.assign(new Error(`data.${bad} isn't a number, so it can't be adjusted`), { code: 'NOT_A_NUMBER', statusCode: 400, key: bad });
|
|
164
|
+
const next = {};
|
|
165
|
+
for (const k of keys)
|
|
166
|
+
next[k] = ((_a = data[k]) !== null && _a !== void 0 ? _a : 0) + ((_b = by[k]) !== null && _b !== void 0 ? _b : 0);
|
|
167
|
+
const broken = Object.entries(opts.atLeast || {}).some(([k, n]) => next[k] < n) || Object.entries(opts.atMost || {}).some(([k, n]) => next[k] > n);
|
|
168
|
+
if (broken)
|
|
169
|
+
throw Object.assign(new Error('The change would break its condition (atLeast / atMost)'), { code: 'CONDITION_FAILED', statusCode: 409, current: Object.fromEntries(keys.map((k) => { var _a; return [k, (_a = data[k]) !== null && _a !== void 0 ? _a : 0]; })) });
|
|
170
|
+
r.data = Object.assign(Object.assign({}, data), Object.fromEntries(Object.keys(by).map((k) => [k, next[k]])));
|
|
171
|
+
return Object.assign({}, r);
|
|
172
|
+
},
|
|
173
|
+
// count / sum: / avg: / min: / max: over data numbers, grouped by top-level fields or data keys
|
|
174
|
+
// ('data.location'); filters.data (exact) as the platform. A simple stand-in for tests.
|
|
175
|
+
aggregate: async (params = {}) => {
|
|
176
|
+
const { groupBy = [], metrics = ['count'], filters = {} } = params || {};
|
|
177
|
+
const rows = mem.records.filter((r) => !r.deletedAt &&
|
|
178
|
+
(!filters.record_type || r.recordType === filters.record_type) &&
|
|
179
|
+
(!filters.status || r.status === filters.status) &&
|
|
180
|
+
Object.entries(filters.data || {}).every(([k, v]) => (Array.isArray(v) ? v.map(String) : [String(v)]).includes(String((r.data || {})[k]))));
|
|
181
|
+
const field = (r, f) => (f.startsWith('data.') ? (r.data || {})[f.slice(5)] : r[f === 'record_type' ? 'recordType' : f]);
|
|
182
|
+
const measure = (set) => {
|
|
183
|
+
const out = {};
|
|
184
|
+
for (const m of metrics) {
|
|
185
|
+
if (m === 'count') {
|
|
186
|
+
out.count = set.length;
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const [fn, key] = String(m).split(':');
|
|
190
|
+
const nums = set.map((r) => (r.data || {})[key]).filter((v) => typeof v === 'number');
|
|
191
|
+
const sum = nums.reduce((a, b) => a + b, 0);
|
|
192
|
+
out[`${fn}_${key}`] = !nums.length ? null : fn === 'sum' ? sum : fn === 'avg' ? sum / nums.length : fn === 'min' ? Math.min(...nums) : Math.max(...nums);
|
|
193
|
+
}
|
|
194
|
+
return out;
|
|
195
|
+
};
|
|
196
|
+
if (!groupBy.length)
|
|
197
|
+
return measure(rows);
|
|
198
|
+
const buckets = new Map();
|
|
199
|
+
for (const r of rows) {
|
|
200
|
+
const key = JSON.stringify(groupBy.map((f) => { var _a; return (_a = field(r, f)) !== null && _a !== void 0 ? _a : null; }));
|
|
201
|
+
if (!buckets.has(key))
|
|
202
|
+
buckets.set(key, []);
|
|
203
|
+
buckets.get(key).push(r);
|
|
204
|
+
}
|
|
205
|
+
return { groups: [...buckets].map(([key, set]) => (Object.assign(Object.assign({}, Object.fromEntries(groupBy.map((f, i) => [f, JSON.parse(key)[i]]))), measure(set)))) };
|
|
206
|
+
},
|
|
150
207
|
// Simple equality filter on top-level fields (recordType, proofId, customId, status, …).
|
|
151
208
|
query: async (params = {}) => {
|
|
152
209
|
const _a = params || {}, { limit, offset, sort } = _a, where = __rest(_a, ["limit", "offset", "sort"]);
|
|
@@ -158,6 +215,60 @@ export function createFunctionTestContext(opts) {
|
|
|
158
215
|
return { data, pagination: { total: all.length, limit: size, offset: from, hasMore: from + data.length < all.length } };
|
|
159
216
|
},
|
|
160
217
|
};
|
|
218
|
+
// The app's history, in memory (newest first when read, like the platform).
|
|
219
|
+
let nextEventId = 1;
|
|
220
|
+
const memLog = (type, data = {}, opts = {}) => {
|
|
221
|
+
var _a;
|
|
222
|
+
if (typeof type !== 'string' || !/^[a-z][a-z0-9._-]{0,63}$/.test(type))
|
|
223
|
+
throw Object.assign(new Error('history type: lowercase letters, digits and . _ - (e.g. "stock.moved")'), { code: 'INVALID_INPUT', statusCode: 400 });
|
|
224
|
+
const ev = { id: `ev-${nextEventId++}`, at: new Date().toISOString(), type, entityId: (_a = opts.entityId) !== null && _a !== void 0 ? _a : null, data: data || {}, actorType: null, actorId: null };
|
|
225
|
+
mem.history.push(ev);
|
|
226
|
+
return { id: ev.id };
|
|
227
|
+
};
|
|
228
|
+
const memHistoryQuery = async (params = {}) => {
|
|
229
|
+
const types = params.types == null ? null : (Array.isArray(params.types) ? params.types : [params.types]);
|
|
230
|
+
return mem.history
|
|
231
|
+
.filter((e) => (!types || types.includes(e.type)) && (params.entityId == null || e.entityId === params.entityId) &&
|
|
232
|
+
Object.entries(params.data || {}).every(([k, v]) => (Array.isArray(v) ? v.map(String) : [String(v)]).includes(String(e.data[k]))))
|
|
233
|
+
.slice().reverse().slice(0, params.limit || 100).map((e) => (Object.assign({}, e)));
|
|
234
|
+
};
|
|
235
|
+
// All ops or none, like the platform: records are restored when an op fails; a repeat of an
|
|
236
|
+
// idempotencyKey replays the first results.
|
|
237
|
+
const memTransaction = async (ops, opts = {}) => {
|
|
238
|
+
const key = opts.idempotencyKey;
|
|
239
|
+
if (key && mem.transactions[key])
|
|
240
|
+
return { results: mem.transactions[key], replayed: true };
|
|
241
|
+
const before = JSON.parse(JSON.stringify(mem.records));
|
|
242
|
+
const historyBefore = mem.history.length;
|
|
243
|
+
const results = [];
|
|
244
|
+
for (let i = 0; i < ops.length; i++) {
|
|
245
|
+
const o = ops[i] || {};
|
|
246
|
+
try {
|
|
247
|
+
if (o.op === 'create')
|
|
248
|
+
results.push(await memRecords.create(o.record || {}));
|
|
249
|
+
else if (o.op === 'update')
|
|
250
|
+
results.push(await memRecords.update(o.recordId, o.fields || {}));
|
|
251
|
+
else if (o.op === 'adjust')
|
|
252
|
+
results.push(await memRecords.adjust(o.recordId, o.by, { atLeast: o.atLeast, atMost: o.atMost }));
|
|
253
|
+
else if (o.op === 'delete') {
|
|
254
|
+
await memRecords.delete(o.recordId);
|
|
255
|
+
results.push({ deleted: o.recordId });
|
|
256
|
+
}
|
|
257
|
+
else if (o.op === 'log')
|
|
258
|
+
results.push({ logged: memLog(o.type, o.data, { entityId: o.entityId }).id });
|
|
259
|
+
else
|
|
260
|
+
throw Object.assign(new Error(`ops[${i}].op must be create, update, adjust, delete or log`), { code: 'INVALID_INPUT', statusCode: 400 });
|
|
261
|
+
}
|
|
262
|
+
catch (err) {
|
|
263
|
+
mem.records.splice(0, mem.records.length, ...before);
|
|
264
|
+
mem.history.splice(historyBefore);
|
|
265
|
+
throw Object.assign(err, { opIndex: i });
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
if (key)
|
|
269
|
+
mem.transactions[key] = results;
|
|
270
|
+
return { results, replayed: false };
|
|
271
|
+
};
|
|
161
272
|
const recordsFn = (name) => ar[name] ? ar[name].bind(ar) : (impl.appRecords ? undefined : memRecords[name]);
|
|
162
273
|
const sl = {
|
|
163
274
|
appRecords: {
|
|
@@ -169,6 +280,17 @@ export function createFunctionTestContext(opts) {
|
|
|
169
280
|
get: gated('records', 'read', recordsFn('get'), 'get'),
|
|
170
281
|
query: gated('records', 'read', recordsFn('query'), 'query'),
|
|
171
282
|
listTypes: gated('records', 'read', recordsFn('listTypes'), 'listTypes'),
|
|
283
|
+
adjust: gated('records', 'write', recordsFn('adjust'), 'adjust'),
|
|
284
|
+
aggregate: gated('records', 'read', recordsFn('aggregate'), 'aggregate'),
|
|
285
|
+
},
|
|
286
|
+
transaction: gated('records', 'write', impl.transaction ? impl.transaction : (impl.appRecords ? undefined : async (ops, opts) => {
|
|
287
|
+
if (Array.isArray(ops) && ops.some((o) => o && o.op === 'log') && !allowsSl(parsed, 'history', 'write'))
|
|
288
|
+
throw new CapabilityError('sl:history:write');
|
|
289
|
+
return memTransaction(ops, opts);
|
|
290
|
+
}), 'transaction'),
|
|
291
|
+
history: {
|
|
292
|
+
log: gated('history', 'write', async (type, data, opts) => memLog(type, data, opts), 'log'),
|
|
293
|
+
query: gated('history', 'read', memHistoryQuery, 'query'),
|
|
172
294
|
},
|
|
173
295
|
products: {
|
|
174
296
|
get: gated('products', 'read', pr.get && pr.get.bind(pr), 'get'),
|
|
@@ -285,6 +407,60 @@ export function createFunctionTestContext(opts) {
|
|
|
285
407
|
for (const m of ['create', 'query', 'delete']) {
|
|
286
408
|
sl.bookings.blocks[m] = gated('bookings', m === 'query' ? 'read' : 'write', bkFn(bk.blocks, m), `bookings.blocks.${m}`);
|
|
287
409
|
}
|
|
410
|
+
// Work orders, stock, bills of materials, made-from: capability + collection authority, as in production.
|
|
411
|
+
const OPERATIONS = {
|
|
412
|
+
workOrders: { resource: 'workorders', reads: ['get', 'list'], writes: ['create', 'update', 'setStatus', 'remove', 'startStage', 'progress', 'completeStage', 'skipStage', 'planStage', 'setStages'] },
|
|
413
|
+
stock: { resource: 'stock', reads: ['lines', 'totals', 'where', 'position', 'short'], writes: ['receive', 'produce', 'consume', 'move', 'allocate', 'release', 'hold', 'unhold', 'adjust'] },
|
|
414
|
+
boms: { resource: 'boms', reads: ['current', 'versions', 'whereUsed', 'explode'], writes: ['set', 'end'] },
|
|
415
|
+
madeFrom: { resource: 'madefrom', reads: ['of', 'usedIn', 'trace'], writes: ['record', 'end'] },
|
|
416
|
+
};
|
|
417
|
+
const triggerType = (def.trigger && def.trigger.type) || 'http';
|
|
418
|
+
const hasCollectionAuthority = triggerType !== 'http' || def.authority === 'collection';
|
|
419
|
+
const needAuthority = () => {
|
|
420
|
+
if (!hasCollectionAuthority)
|
|
421
|
+
throw Object.assign(new Error('This needs collection authority: declare the function with authority "collection"'), { code: 'NEEDS_COLLECTION_AUTHORITY', status: 403 });
|
|
422
|
+
};
|
|
423
|
+
for (const [group, g] of Object.entries(OPERATIONS)) {
|
|
424
|
+
sl[group] = {};
|
|
425
|
+
const given = impl[group] || {};
|
|
426
|
+
for (const m of [...g.reads, ...g.writes]) {
|
|
427
|
+
const op = g.reads.includes(m) ? 'read' : 'write';
|
|
428
|
+
sl[group][m] = async (...args) => {
|
|
429
|
+
if (!allowsSl(parsed, g.resource, op))
|
|
430
|
+
throw new CapabilityError(`sl:${g.resource}:${op}`);
|
|
431
|
+
needAuthority();
|
|
432
|
+
return typeof given[m] === 'function' ? given[m](...args) : stub(`${group}.${m}`, args);
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
sl.operations = {
|
|
437
|
+
// Each step must be a write this function may make; with no impl, the steps run one by one through
|
|
438
|
+
// the methods above (so your stand-ins are called), without the all-or-nothing the platform gives.
|
|
439
|
+
transaction: async (steps) => {
|
|
440
|
+
if (!Array.isArray(steps) || !steps.length)
|
|
441
|
+
throw Object.assign(new Error('A transaction needs at least one step'), { code: 'INVALID_INPUT' });
|
|
442
|
+
for (const st of steps) {
|
|
443
|
+
const [group, m] = String((st && st.op) || '').split('.');
|
|
444
|
+
const g = OPERATIONS[group];
|
|
445
|
+
if (!g || ![...g.reads, ...g.writes].includes(m))
|
|
446
|
+
throw Object.assign(new Error(`There is no "${st && st.op}"`), { code: 'UNKNOWN_OP' });
|
|
447
|
+
if (g.reads.includes(m))
|
|
448
|
+
throw Object.assign(new Error(`${st.op} only reads. Do reads outside the transaction`), { code: 'INVALID_INPUT' });
|
|
449
|
+
if (!allowsSl(parsed, g.resource, 'write'))
|
|
450
|
+
throw new CapabilityError(`sl:${g.resource}:write`);
|
|
451
|
+
}
|
|
452
|
+
needAuthority();
|
|
453
|
+
const own = impl.operations && impl.operations.transaction;
|
|
454
|
+
if (typeof own === 'function')
|
|
455
|
+
return own(steps);
|
|
456
|
+
const results = [];
|
|
457
|
+
for (const st of steps) {
|
|
458
|
+
const [group, m] = st.op.split('.');
|
|
459
|
+
results.push(await sl[group][m](...(st.args || [])));
|
|
460
|
+
}
|
|
461
|
+
return { results };
|
|
462
|
+
},
|
|
463
|
+
};
|
|
288
464
|
const secretsMap = opts.secrets || {};
|
|
289
465
|
const baseFetch = opts.fetch || (typeof fetch !== 'undefined' ? fetch : undefined);
|
|
290
466
|
const via = (def.trigger && def.trigger.type) || 'http';
|
|
@@ -312,6 +488,7 @@ export function createFunctionTestContext(opts) {
|
|
|
312
488
|
origin: (_f = caller.origin) !== null && _f !== void 0 ? _f : null,
|
|
313
489
|
ip: (_g = caller.ip) !== null && _g !== void 0 ? _g : null,
|
|
314
490
|
via,
|
|
491
|
+
userGroups: Object.freeze([...(caller.userGroups || [])]),
|
|
315
492
|
},
|
|
316
493
|
fetch: (async (input, init) => {
|
|
317
494
|
let host = '';
|
|
@@ -4,6 +4,7 @@ import type { AppDataDeclaration, AppHeadlessDeclaration } from './headless.js';
|
|
|
4
4
|
import type { RealtimeChannelDeclaration } from './realtime.js';
|
|
5
5
|
import type { AppManifestAdminCards } from './adminCards.js';
|
|
6
6
|
import type { PaginatedResponse } from './appObjects.js';
|
|
7
|
+
import type { WorkOrdersApi, StockApi, BomsApi, MadeFromApi, OperationsApi } from './operations.js';
|
|
7
8
|
import type { Booking, BookingSlot, BookingAllocation, CreateBookingInput, UpdateBookingInput, MoveBookingInput, BookingListQueryParams, CreateSlotInput, UpdateSlotInput, SlotListQueryParams, CreateBlockInput, BlockListQueryParams, FreeBusyQuery, FreeBusyResponse, MessageBookersInput, MessageBookersResult } from './bookings.js';
|
|
8
9
|
/**
|
|
9
10
|
* A bundle (widget or container) as returned by the collection widgets endpoint.
|
|
@@ -295,6 +296,13 @@ export interface AppFunctionDef {
|
|
|
295
296
|
* without it, install/validation fails. Ignored for any other visibility/authority combo.
|
|
296
297
|
*/
|
|
297
298
|
elevated?: boolean;
|
|
299
|
+
/**
|
|
300
|
+
* `http` only. Who may call it: the caller must be signed in and in at least ONE of these user
|
|
301
|
+
* groups (by key, e.g. `['qc-controller', 'manager']`), or be a collection admin. Checked by the
|
|
302
|
+
* platform before any of your code runs: anyone else gets `403 NOT_IN_USER_GROUP` (`401
|
|
303
|
+
* SIGN_IN_REQUIRED` when not signed in). Absent = no user group limit. See docs/user-groups.md.
|
|
304
|
+
*/
|
|
305
|
+
userGroups?: string[];
|
|
298
306
|
/**
|
|
299
307
|
* Least-privilege capabilities this function needs, surfaced at install for
|
|
300
308
|
* consent and capped at runtime — even for `collection`-authority functions.
|
|
@@ -490,7 +498,71 @@ export interface ServerFunctionBookings {
|
|
|
490
498
|
}>;
|
|
491
499
|
};
|
|
492
500
|
}
|
|
501
|
+
/** One write in ctx.sl.transaction. */
|
|
502
|
+
export type RecordTransactionOp = {
|
|
503
|
+
op: 'create';
|
|
504
|
+
record: Record<string, any>;
|
|
505
|
+
} | {
|
|
506
|
+
op: 'update';
|
|
507
|
+
recordId: string;
|
|
508
|
+
fields: Record<string, any>;
|
|
509
|
+
} | {
|
|
510
|
+
op: 'adjust';
|
|
511
|
+
recordId: string;
|
|
512
|
+
by: Record<string, number>;
|
|
513
|
+
atLeast?: Record<string, number>;
|
|
514
|
+
atMost?: Record<string, number>;
|
|
515
|
+
} | {
|
|
516
|
+
op: 'delete';
|
|
517
|
+
recordId: string;
|
|
518
|
+
}
|
|
519
|
+
/** An event in the app's history (BigQuery): commits with the other ops, delivered after. Needs sl:history:write. */
|
|
520
|
+
| {
|
|
521
|
+
op: 'log';
|
|
522
|
+
type: string;
|
|
523
|
+
data?: Record<string, any>;
|
|
524
|
+
entityId?: string;
|
|
525
|
+
};
|
|
526
|
+
/** One event from an app's history. */
|
|
527
|
+
export interface AppHistoryEvent {
|
|
528
|
+
id: string;
|
|
529
|
+
at: string;
|
|
530
|
+
type: string;
|
|
531
|
+
entityId: string | null;
|
|
532
|
+
data: Record<string, any>;
|
|
533
|
+
actorType: 'user' | 'contact' | null;
|
|
534
|
+
actorId: string | null;
|
|
535
|
+
}
|
|
536
|
+
/** Reading an app's history: its own events in this collection, newest first. */
|
|
537
|
+
export interface AppHistoryQuery {
|
|
538
|
+
types?: string | string[];
|
|
539
|
+
entityId?: string;
|
|
540
|
+
/** Exact match on top-level data keys (one value or several). */
|
|
541
|
+
data?: Record<string, string | number | boolean | Array<string | number | boolean>>;
|
|
542
|
+
/** ISO dates. Default: the last 30 days; at most 400 days. */
|
|
543
|
+
from?: string;
|
|
544
|
+
to?: string;
|
|
545
|
+
/** Default 100, at most 1000. */
|
|
546
|
+
limit?: number;
|
|
547
|
+
}
|
|
493
548
|
export interface ServerFunctionSl {
|
|
549
|
+
/**
|
|
550
|
+
* Work orders: what work is under way (`sl:workorders:read` / `:write`). Any app may read a work
|
|
551
|
+
* order; only the app that owns it may change it. Needs `authority: 'collection'`. See docs/operations.md.
|
|
552
|
+
*/
|
|
553
|
+
workOrders: WorkOrdersApi;
|
|
554
|
+
/**
|
|
555
|
+
* Stock: how much of a product is in each container, changed only through movements, and a product's
|
|
556
|
+
* position (`sl:stock:read` / `:write`). Shared by every app in the collection. Needs
|
|
557
|
+
* `authority: 'collection'`.
|
|
558
|
+
*/
|
|
559
|
+
stock: StockApi;
|
|
560
|
+
/** Bills of materials: what a product is made of (`sl:boms:read` / `:write`). Needs `authority: 'collection'`. */
|
|
561
|
+
boms: BomsApi;
|
|
562
|
+
/** What a batch or item was really made from (`sl:madefrom:read` / `:write`). Needs `authority: 'collection'`. */
|
|
563
|
+
madeFrom: MadeFromApi;
|
|
564
|
+
/** Several work order, stock, bill of materials and made-from writes, all or nothing. */
|
|
565
|
+
operations: OperationsApi;
|
|
494
566
|
/** THIS app's bookings, slots and blocks (`sl:bookings:read` / `sl:bookings:write`). */
|
|
495
567
|
bookings: ServerFunctionBookings;
|
|
496
568
|
/**
|
|
@@ -502,8 +574,48 @@ export interface ServerFunctionSl {
|
|
|
502
574
|
*/
|
|
503
575
|
appRecords: {
|
|
504
576
|
claim(fields: Record<string, any>): Promise<AppRecordClaimResult>;
|
|
577
|
+
/**
|
|
578
|
+
* Numbers in a record's `data`, changed in place in one statement: two scanners on one bin never lose
|
|
579
|
+
* a count. `by` `{ qty: -5 }` (missing counts as 0). `atLeast` / `atMost` are checked on the values
|
|
580
|
+
* AFTER the change: `{ atLeast: { qty: 0 } }` never takes a bin below zero. Refusals carry `code`:
|
|
581
|
+
* `NOT_FOUND`, `NOT_A_NUMBER`, `CONDITION_FAILED` (with `current` values). → the updated record.
|
|
582
|
+
*/
|
|
583
|
+
adjust(recordId: string, by: Record<string, number>, opts?: {
|
|
584
|
+
atLeast?: Record<string, number>;
|
|
585
|
+
atMost?: Record<string, number>;
|
|
586
|
+
}): Promise<any>;
|
|
587
|
+
/** Totals over THIS app's records: count, sum/avg/min/max of data numbers, grouped by data keys. */
|
|
588
|
+
aggregate(params?: import('./appObjects.js').AggregateRequest): Promise<import('./appObjects.js').AggregateResponse & Record<string, unknown>>;
|
|
505
589
|
[method: string]: any;
|
|
506
590
|
};
|
|
591
|
+
/**
|
|
592
|
+
* Several record writes that land together or not at all (take 5 from bin A AND add 5 to order line B
|
|
593
|
+
* AND log the move). Needs `sl:records:write`; THIS app's records in THIS collection only. A failing op
|
|
594
|
+
* rolls everything back; its error says which (`opIndex`) and why (`code`). With `idempotencyKey`, a
|
|
595
|
+
* repeat of the key (a scanner retrying after a dropped signal) returns the first results
|
|
596
|
+
* (`replayed: true`) instead of writing twice; keys are remembered for 30 days.
|
|
597
|
+
*/
|
|
598
|
+
transaction(ops: RecordTransactionOp[], opts?: {
|
|
599
|
+
idempotencyKey?: string;
|
|
600
|
+
}): Promise<{
|
|
601
|
+
results: any[];
|
|
602
|
+
replayed: boolean;
|
|
603
|
+
}>;
|
|
604
|
+
/**
|
|
605
|
+
* The app's HISTORY: append-only events kept in BigQuery (stock moved, a count taken, an order shipped),
|
|
606
|
+
* so the app's records hold current state and never grow with activity. `log` (`sl:history:write`)
|
|
607
|
+
* stores one event (it arrives within seconds; a failed delivery is retried, never lost); inside a
|
|
608
|
+
* transaction use a `log` op instead, so it commits with the change. `query` (`sl:history:read`) reads
|
|
609
|
+
* this app's events in this collection, newest first.
|
|
610
|
+
*/
|
|
611
|
+
history: {
|
|
612
|
+
log(type: string, data?: Record<string, any>, opts?: {
|
|
613
|
+
entityId?: string;
|
|
614
|
+
}): Promise<{
|
|
615
|
+
id: string;
|
|
616
|
+
}>;
|
|
617
|
+
query(params?: AppHistoryQuery): Promise<AppHistoryEvent[]>;
|
|
618
|
+
};
|
|
507
619
|
/** Atomic named counters for this app in this collection (`sl:data:write` / `sl:data:read`). */
|
|
508
620
|
counters: ServerFunctionCounters;
|
|
509
621
|
/** Tags (`sl:tags:read`): `resolve(id)` → the real tag in THIS collection, or `null` for a made-up id. */
|
|
@@ -577,6 +689,12 @@ export interface ServerFunctionCaller {
|
|
|
577
689
|
ip?: string | null;
|
|
578
690
|
/** How the function was triggered. */
|
|
579
691
|
via: AppFunctionTriggerType;
|
|
692
|
+
/**
|
|
693
|
+
* Keys of the user groups the caller is in, e.g. `['qc-controller', 'warehouse']`. Empty when nobody
|
|
694
|
+
* is signed in (and for `event`/`cron`). Use it for finer rules than the declaration's `userGroups`
|
|
695
|
+
* allows ("a manager may also override"). See docs/user-groups.md.
|
|
696
|
+
*/
|
|
697
|
+
userGroups: readonly string[];
|
|
580
698
|
}
|
|
581
699
|
/** The signed-in caller's own contact, as a server function sees it (`ctx.sl.contacts.forCaller()`). */
|
|
582
700
|
export interface CallerContact {
|
|
@@ -794,6 +912,52 @@ export interface PublicView {
|
|
|
794
912
|
/** The params the caller supplies via the URL. */
|
|
795
913
|
params?: PublicViewParams;
|
|
796
914
|
}
|
|
915
|
+
/**
|
|
916
|
+
* One ADMIN VIEW of the app: a screen of its admin side that a host or the assistant can open by name
|
|
917
|
+
* ("the campaigns list", "one campaign", "bookings for a day"). An app declares them once, in
|
|
918
|
+
* `app.manifest.json#adminViews`, and the same list drives three things:
|
|
919
|
+
* - the app's own side menu (`group` main and settings; see prove docs/design/core-app-layout.md),
|
|
920
|
+
* - Studio's workspace menu, which can carry an app's areas itself (it then opens the app with
|
|
921
|
+
* `chrome=none` and the app hides its own menu),
|
|
922
|
+
* - the Studio assistant, which opens a view while it talks (`smartlinks:navigate`).
|
|
923
|
+
* Admin views are NOT portal pages (`linkable`) and NOT standalone screens (`publicViews`).
|
|
924
|
+
* See docs/admin-views.md and `SL.adminViews`.
|
|
925
|
+
*/
|
|
926
|
+
export interface AdminView {
|
|
927
|
+
/** Stable id, unique within the app (`campaigns`, `campaign`, `campaign.results`). Hosts keep it. */
|
|
928
|
+
id: string;
|
|
929
|
+
/** The label in a menu: short, the business's words ("Campaigns", "Message log"). */
|
|
930
|
+
title: string;
|
|
931
|
+
/**
|
|
932
|
+
* Hash route within the admin page, with `{name}` placeholders for the params it needs:
|
|
933
|
+
* `"/campaigns"`, `"/campaigns/{campaignId}"`, `"/day/{date}"`.
|
|
934
|
+
*/
|
|
935
|
+
path: string;
|
|
936
|
+
/**
|
|
937
|
+
* Where the view sits:
|
|
938
|
+
* - `main` (default): an area in the side menu, in declared order;
|
|
939
|
+
* - `settings`: pinned at the bottom of the menu;
|
|
940
|
+
* - `record`: inside one record (a campaign, a product). Not in the main menu: opening the record
|
|
941
|
+
* swaps the menu for the record's own views, headed by "← back to" its `within` area.
|
|
942
|
+
*/
|
|
943
|
+
group?: 'main' | 'settings' | 'record';
|
|
944
|
+
/**
|
|
945
|
+
* The view this one sits inside. A record's first view names its area (`campaign` within
|
|
946
|
+
* `campaigns`); the record's other views name the record's first view (`campaign.results` within
|
|
947
|
+
* `campaign`).
|
|
948
|
+
*/
|
|
949
|
+
within?: string;
|
|
950
|
+
/** A Lucide icon name, kebab-case (`megaphone`, `scroll-text`, `package`). */
|
|
951
|
+
icon?: string;
|
|
952
|
+
/** One line on what the screen shows, for the assistant ("Every message sent and what happened to it"). */
|
|
953
|
+
description?: string;
|
|
954
|
+
/**
|
|
955
|
+
* The params the view takes, each with a few words on what it is (`{ campaignId: "a campaign's id",
|
|
956
|
+
* status: "draft | scheduled | sent" }`). A `{name}` in `path` is required; any other is optional
|
|
957
|
+
* and travels as a query param. Platform context (collectionId, appId, …) is never listed.
|
|
958
|
+
*/
|
|
959
|
+
params?: Record<string, string>;
|
|
960
|
+
}
|
|
797
961
|
export interface AppManifest {
|
|
798
962
|
$schema?: string;
|
|
799
963
|
meta?: {
|
|
@@ -893,6 +1057,12 @@ export interface AppManifest {
|
|
|
893
1057
|
* See PublicView + docs/design/public-views.md.
|
|
894
1058
|
*/
|
|
895
1059
|
publicViews?: PublicView[];
|
|
1060
|
+
/**
|
|
1061
|
+
* The app's ADMIN VIEWS: its admin screens by name, in menu order. They drive the app's own side
|
|
1062
|
+
* menu, Studio's workspace menu and the assistant's "open this screen". @see AdminView ·
|
|
1063
|
+
* docs/admin-views.md
|
|
1064
|
+
*/
|
|
1065
|
+
adminViews?: AdminView[];
|
|
896
1066
|
/**
|
|
897
1067
|
* Executor bundle declaration. Present when the app ships a programmatic executor
|
|
898
1068
|
* for AI-driven configuration, server-side SEO, and LLM content generation.
|
|
@@ -55,8 +55,29 @@ export interface AggregateRequest {
|
|
|
55
55
|
expires_at?: {
|
|
56
56
|
lte?: string;
|
|
57
57
|
};
|
|
58
|
+
updated_at?: {
|
|
59
|
+
gte?: string;
|
|
60
|
+
lte?: string;
|
|
61
|
+
};
|
|
62
|
+
/** Records only: exact match on top-level data keys, one value or any of several. */
|
|
63
|
+
data?: Record<string, string | number | boolean | Array<string | number | boolean>>;
|
|
64
|
+
/** Records only: numeric comparisons on top-level data keys (numbers only; others never match). */
|
|
65
|
+
dataRange?: Record<string, {
|
|
66
|
+
gte?: number;
|
|
67
|
+
gt?: number;
|
|
68
|
+
lte?: number;
|
|
69
|
+
lt?: number;
|
|
70
|
+
}>;
|
|
58
71
|
};
|
|
72
|
+
/**
|
|
73
|
+
* Columns per resource; records also take top-level data keys as `'data.<key>'` (e.g. `'data.location'`),
|
|
74
|
+
* up to 5. Each group comes back with its key under the same name.
|
|
75
|
+
*/
|
|
59
76
|
groupBy?: string[];
|
|
77
|
+
/**
|
|
78
|
+
* `'count'`; records also take `'sum:<key>'`, `'avg:<key>'`, `'min:<key>'`, `'max:<key>'` over numbers in a
|
|
79
|
+
* top-level data key (non-numbers ignored) → `sum_<key>`, `avg_<key>`… in the result.
|
|
80
|
+
*/
|
|
60
81
|
metrics?: string[];
|
|
61
82
|
timeSeriesField?: string;
|
|
62
83
|
timeSeriesInterval?: 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';
|
|
@@ -66,7 +87,7 @@ export interface AggregateRequest {
|
|
|
66
87
|
*/
|
|
67
88
|
export interface AggregateResponse {
|
|
68
89
|
groups?: ({
|
|
69
|
-
count
|
|
90
|
+
count?: number;
|
|
70
91
|
} & Record<string, unknown>)[];
|
|
71
92
|
timeSeries?: ({
|
|
72
93
|
bucket: string;
|
package/dist/types/claimSet.d.ts
CHANGED
|
@@ -361,6 +361,8 @@ export interface PartnerTagHit {
|
|
|
361
361
|
url: string | null;
|
|
362
362
|
};
|
|
363
363
|
range: ClaimSetRange | null;
|
|
364
|
+
/** The group the tag was added to, if any */
|
|
365
|
+
group: ClaimSetRange | null;
|
|
364
366
|
}
|
|
365
367
|
export interface CreatePartnerClaimSetRequest {
|
|
366
368
|
name: string;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An app reporting an error it saw (errors.report): kept in the platform's one error log (CloudEvents + ECS
|
|
3
|
+
* rows in BigQuery), the same place server-side errors go. Say what it was about with entityType/entityId
|
|
4
|
+
* (a tag's chip UID, a product id, an order id), put routing facts in labels and the detail in context.
|
|
5
|
+
* Never include keys, passwords or tokens: the server drops any field whose name looks like one.
|
|
6
|
+
*/
|
|
7
|
+
export interface ClientErrorReport {
|
|
8
|
+
/** Which app: 'sidekick', 'studio', a site's app id. Default 'client'. */
|
|
9
|
+
app?: string;
|
|
10
|
+
appVersion?: string;
|
|
11
|
+
/** The collection it concerns, when there is one (owners see their collection's errors) */
|
|
12
|
+
collectionId?: string;
|
|
13
|
+
/** What was being done: 'tag.program', 'order.submit', … */
|
|
14
|
+
operation?: string;
|
|
15
|
+
severity?: 'debug' | 'info' | 'warning' | 'error' | 'critical';
|
|
16
|
+
/** A short stable code: 'TAG_LOST', 'TIMEOUT', … (this or message is required) */
|
|
17
|
+
errorCode?: string;
|
|
18
|
+
errorType?: string;
|
|
19
|
+
message?: string;
|
|
20
|
+
stack?: string;
|
|
21
|
+
/** What it was about: 'tag', 'product', 'order', … */
|
|
22
|
+
entityType?: string;
|
|
23
|
+
/** …and which one: a chip UID (normalised for 'tag'), a product id, … */
|
|
24
|
+
entityId?: string;
|
|
25
|
+
labels?: Record<string, unknown>;
|
|
26
|
+
context?: Record<string, unknown>;
|
|
27
|
+
/** An operation id to group by (a batch, a job) */
|
|
28
|
+
refId?: string;
|
|
29
|
+
correlationId?: string;
|
|
30
|
+
}
|
|
31
|
+
/** One kept error event, as the lookups return it (newest first). */
|
|
32
|
+
export interface ClientErrorEvent {
|
|
33
|
+
id: string;
|
|
34
|
+
time: string;
|
|
35
|
+
event_category: string;
|
|
36
|
+
event_action: string | null;
|
|
37
|
+
log_level: string;
|
|
38
|
+
error_code: string | null;
|
|
39
|
+
error_message: string | null;
|
|
40
|
+
service_name: string | null;
|
|
41
|
+
service_version: string | null;
|
|
42
|
+
collection_id: string | null;
|
|
43
|
+
user_id: string | null;
|
|
44
|
+
labels: Record<string, unknown> | null;
|
|
45
|
+
context: Record<string, unknown> | null;
|
|
46
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -41,6 +41,11 @@ export interface Container {
|
|
|
41
41
|
metadata?: Record<string, any>;
|
|
42
42
|
/** UUID of the parent container; `undefined` / `null` for top-level containers */
|
|
43
43
|
parentContainerId?: string;
|
|
44
|
+
/**
|
|
45
|
+
* A place that doesn't move (a site, a rack, a bin) rather than something carried (a pallet, a drum).
|
|
46
|
+
* "Where is this pallet?" is the first fixed container above it. Default `false`.
|
|
47
|
+
*/
|
|
48
|
+
fixed?: boolean;
|
|
44
49
|
/** Recursively nested children — populated only when `?tree=true` */
|
|
45
50
|
children?: Container[];
|
|
46
51
|
/** Current (or historical) items — populated only when `?includeContents=true` */
|
|
@@ -91,6 +96,8 @@ export interface CreateContainerInput {
|
|
|
91
96
|
metadata?: Record<string, any>;
|
|
92
97
|
/** UUID of the parent container; omit to create a top-level container */
|
|
93
98
|
parentContainerId?: string;
|
|
99
|
+
/** A place that doesn't move (a bin), rather than something carried (a pallet). Default `false`. */
|
|
100
|
+
fixed?: boolean;
|
|
94
101
|
}
|
|
95
102
|
/**
|
|
96
103
|
* Request body for `PATCH /containers/:id`.
|
|
@@ -105,6 +112,7 @@ export interface UpdateContainerInput {
|
|
|
105
112
|
metadata?: Record<string, any>;
|
|
106
113
|
/** Pass `null` to promote the container to top-level. */
|
|
107
114
|
parentContainerId?: string | null;
|
|
115
|
+
fixed?: boolean;
|
|
108
116
|
}
|
|
109
117
|
/** Request body for `POST /containers/:id/items` — adds items to a container. */
|
|
110
118
|
export interface AddContainerItemsInput {
|