@proveanything/smartlinks 2.1.17 → 2.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/adminViews.d.ts +104 -0
  2. package/dist/adminViews.js +275 -0
  3. package/dist/api/ai.d.ts +15 -5
  4. package/dist/api/ai.js +15 -9
  5. package/dist/api/aiGuide.d.ts +108 -0
  6. package/dist/api/aiGuide.js +161 -0
  7. package/dist/api/appObjects.d.ts +21 -0
  8. package/dist/api/appObjects.js +33 -1
  9. package/dist/api/authKit.d.ts +37 -1
  10. package/dist/api/authKit.js +51 -0
  11. package/dist/api/index.d.ts +2 -0
  12. package/dist/api/index.js +2 -0
  13. package/dist/api/operations.d.ts +36 -0
  14. package/dist/api/operations.js +56 -0
  15. package/dist/api/order.d.ts +12 -1
  16. package/dist/api/order.js +15 -0
  17. package/dist/api/userGroups.d.ts +78 -0
  18. package/dist/api/userGroups.js +124 -0
  19. package/dist/docs/API_SUMMARY.md +1111 -80
  20. package/dist/docs/admin-lists-and-pickers.md +140 -0
  21. package/dist/docs/admin-views.md +147 -0
  22. package/dist/docs/app-data-storage.md +277 -276
  23. package/dist/docs/app-manifest.md +2 -0
  24. package/dist/docs/auth-kit.md +872 -741
  25. package/dist/docs/comms.md +686 -644
  26. package/dist/docs/customer-guide.md +70 -0
  27. package/dist/docs/headless-providers.md +112 -112
  28. package/dist/docs/operations.md +281 -0
  29. package/dist/docs/overview.md +3 -0
  30. package/dist/docs/server-functions.md +87 -1
  31. package/dist/docs/ui-utils.md +123 -121
  32. package/dist/docs/user-groups.md +175 -0
  33. package/dist/docs/utils.md +17 -0
  34. package/dist/headless.js +38 -2
  35. package/dist/http.js +8 -0
  36. package/dist/iframeResponder.d.ts +15 -0
  37. package/dist/iframeResponder.js +39 -1
  38. package/dist/index.d.ts +3 -1
  39. package/dist/index.js +2 -0
  40. package/dist/live.d.ts +80 -0
  41. package/dist/live.js +315 -0
  42. package/dist/openapi.yaml +1864 -48
  43. package/dist/testing/index.d.ts +35 -0
  44. package/dist/testing/index.js +86 -0
  45. package/dist/types/appManifest.d.ts +297 -1
  46. package/dist/types/appOptions.d.ts +32 -0
  47. package/dist/types/appOptions.js +3 -0
  48. package/dist/types/authKit.d.ts +193 -4
  49. package/dist/types/comms.d.ts +41 -2
  50. package/dist/types/containers.d.ts +8 -0
  51. package/dist/types/headless.d.ts +49 -1
  52. package/dist/types/iframeResponder.d.ts +16 -1
  53. package/dist/types/index.d.ts +3 -0
  54. package/dist/types/index.js +3 -0
  55. package/dist/types/operations.d.ts +598 -0
  56. package/dist/types/operations.js +8 -0
  57. package/dist/types/order.d.ts +35 -6
  58. package/dist/types/userGroups.d.ts +103 -0
  59. package/dist/types/userGroups.js +5 -0
  60. package/dist/utils/conditions.d.ts +7 -0
  61. package/dist/utils/conditions.js +16 -9
  62. package/docs/API_SUMMARY.md +1111 -80
  63. package/docs/admin-lists-and-pickers.md +140 -0
  64. package/docs/admin-views.md +147 -0
  65. package/docs/app-data-storage.md +277 -276
  66. package/docs/app-manifest.md +2 -0
  67. package/docs/auth-kit.md +872 -741
  68. package/docs/comms.md +686 -644
  69. package/docs/customer-guide.md +70 -0
  70. package/docs/headless-providers.md +112 -112
  71. package/docs/operations.md +281 -0
  72. package/docs/overview.md +3 -0
  73. package/docs/server-functions.md +87 -1
  74. package/docs/ui-utils.md +123 -121
  75. package/docs/user-groups.md +175 -0
  76. package/docs/utils.md +17 -0
  77. package/openapi.yaml +1864 -48
  78. package/package.json +1 -1
  79. package/scripts/doctor.mjs +454 -428
  80. package/scripts/lib/keyed-app-data.mjs +21 -0
@@ -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;
@@ -18,6 +19,15 @@ export interface TestSlImpl {
18
19
  listTypes?(): any;
19
20
  adjust?(id: string, by: Record<string, number>, opts?: any): any;
20
21
  aggregate?(params?: any): any;
22
+ all?(recordType: string): any;
23
+ };
24
+ /** ctx.sl.userGroups.members(keys) — defaults to the `people` option. */
25
+ userGroups?: {
26
+ members?(keys?: string[]): any;
27
+ };
28
+ /** ctx.sl.appOptions.get(source, opts) — defaults to the in-memory one (records by convention, `valueLists`). */
29
+ appOptions?: {
30
+ get?(source: string, opts?: any): any;
21
31
  };
22
32
  /** ctx.sl.transaction(ops, { idempotencyKey }) — defaults to the in-memory one (all or none, replay by key). */
23
33
  transaction?(ops: any[], opts?: any): any;
@@ -69,6 +79,16 @@ export interface TestSlImpl {
69
79
  * time, idempotent creates, holds) — inspect it via `ctx.memory.bookings`.
70
80
  */
71
81
  bookings?: Record<string, any>;
82
+ /**
83
+ * Work orders, stock, bills of materials and made-from (docs/operations.md). There is no in-memory
84
+ * engine for these: give the methods your function calls, and any other call returns a stub echo.
85
+ * The harness still enforces both production gates: the capability, and collection authority.
86
+ */
87
+ workOrders?: Partial<WorkOrdersApi>;
88
+ stock?: Partial<StockApi>;
89
+ boms?: Partial<BomsApi>;
90
+ madeFrom?: Partial<MadeFromApi>;
91
+ operations?: Partial<OperationsApi>;
72
92
  }
73
93
  export interface TestCaller {
74
94
  userId?: string | null;
@@ -77,6 +97,8 @@ export interface TestCaller {
77
97
  anonymous?: boolean;
78
98
  origin?: string | null;
79
99
  ip?: string | null;
100
+ /** Keys of the user groups the caller is in, for `ctx.caller.userGroups`. Default: none. */
101
+ userGroups?: string[];
80
102
  }
81
103
  export interface CreateFunctionTestContextOptions {
82
104
  /** The manifest declaration under test — its `capabilities` are the enforced envelope. */
@@ -98,6 +120,19 @@ export interface CreateFunctionTestContextOptions {
98
120
  knownInteractionTypes?: string[];
99
121
  /** Share one in-memory store between several contexts (e.g. concurrent callers in one test). */
100
122
  memory?: FunctionTestMemory;
123
+ /** People `ctx.sl.userGroups.members` answers from: who is in which user group (by key). */
124
+ people?: Array<{
125
+ userId: string;
126
+ name?: string | null;
127
+ email?: string | null;
128
+ userGroups: string[];
129
+ }>;
130
+ /** Value lists `ctx.sl.appOptions.get('list:<id>')` answers from, by list id (as the admin saved them). */
131
+ valueLists?: Record<string, Array<{
132
+ code: string;
133
+ label?: string;
134
+ active?: boolean;
135
+ }>>;
101
136
  }
102
137
  /** The harness's in-memory platform state (when no impl is injected). */
103
138
  export interface FunctionTestMemory {
@@ -150,6 +150,7 @@ export function createFunctionTestContext(opts) {
150
150
  return null; Object.assign(r, fields); return Object.assign({}, r); },
151
151
  delete: async (id) => { const r = mem.records.find((x) => x.id === id); if (r)
152
152
  r.deletedAt = new Date().toISOString(); return {}; },
153
+ all: async (recordType) => mem.records.filter((r) => !r.deletedAt && r.recordType === recordType).map((r) => (Object.assign({}, r))),
153
154
  // Numbers in data changed in place, with atLeast / atMost checked after the change (as the platform).
154
155
  adjust: async (id, by = {}, opts = {}) => {
155
156
  var _a, _b;
@@ -282,6 +283,36 @@ export function createFunctionTestContext(opts) {
282
283
  listTypes: gated('records', 'read', recordsFn('listTypes'), 'listTypes'),
283
284
  adjust: gated('records', 'write', recordsFn('adjust'), 'adjust'),
284
285
  aggregate: gated('records', 'read', recordsFn('aggregate'), 'aggregate'),
286
+ all: gated('records', 'read', recordsFn('all'), 'all'),
287
+ },
288
+ userGroups: {
289
+ members: gated('usergroups', 'read', impl.userGroups && impl.userGroups.members ? impl.userGroups.members.bind(impl.userGroups) : async (keys = []) => (opts.people || []).filter((p) => !keys.length || p.userGroups.some((k) => keys.includes(k)))
290
+ .map((p) => { var _a, _b; return ({ userId: p.userId, name: (_a = p.name) !== null && _a !== void 0 ? _a : null, email: (_b = p.email) !== null && _b !== void 0 ? _b : null, userGroups: keys.length ? p.userGroups.filter((k) => keys.includes(k)) : [...p.userGroups] }); }), 'members'),
291
+ },
292
+ // Pickers, in memory: a type's records by the platform's conventions (label from data.label, then
293
+ // name, then title; order from sortOrder), or a value list from `valueLists`.
294
+ appOptions: {
295
+ get: gated('records', 'read', impl.appOptions && impl.appOptions.get ? impl.appOptions.get.bind(impl.appOptions) : (impl.appRecords ? undefined : async (source) => {
296
+ const m = /^(type|list):(.+)$/.exec(String(source || ''));
297
+ if (!m)
298
+ throw Object.assign(new Error('Say what to list: type:<record type> or list:<list id>'), { code: 'BAD_SOURCE' });
299
+ let items;
300
+ if (m[1] === 'list') {
301
+ const values = (opts.valueLists || {})[m[2]];
302
+ if (!values)
303
+ throw Object.assign(new Error(`No list "${m[2]}" (pass it in valueLists)`), { code: 'NO_SUCH_LIST' });
304
+ items = values.map((v, i) => ({ id: v.code, label: v.label || v.code, active: v.active !== false, order: i }));
305
+ }
306
+ else {
307
+ items = mem.records.filter((r) => !r.deletedAt && r.recordType === m[2]).map((r) => {
308
+ var _a, _b, _c, _d, _e;
309
+ const d = r.data || {};
310
+ const order = (_a = d.sortOrder) !== null && _a !== void 0 ? _a : d.order;
311
+ return { id: r.id, label: String((_e = (_d = (_c = (_b = d.label) !== null && _b !== void 0 ? _b : d.name) !== null && _c !== void 0 ? _c : d.title) !== null && _d !== void 0 ? _d : r.ref) !== null && _e !== void 0 ? _e : r.id), active: !['inactive', 'archived'].includes(r.status || 'active'), order: typeof order === 'number' ? order : null };
312
+ }).sort((a, b) => { var _a, _b; return ((_a = a.order) !== null && _a !== void 0 ? _a : Infinity) - ((_b = b.order) !== null && _b !== void 0 ? _b : Infinity) || a.label.localeCompare(b.label); });
313
+ }
314
+ return { items, mode: 'all', version: String(items.length) };
315
+ }), 'get'),
285
316
  },
286
317
  transaction: gated('records', 'write', impl.transaction ? impl.transaction : (impl.appRecords ? undefined : async (ops, opts) => {
287
318
  if (Array.isArray(ops) && ops.some((o) => o && o.op === 'log') && !allowsSl(parsed, 'history', 'write'))
@@ -407,6 +438,60 @@ export function createFunctionTestContext(opts) {
407
438
  for (const m of ['create', 'query', 'delete']) {
408
439
  sl.bookings.blocks[m] = gated('bookings', m === 'query' ? 'read' : 'write', bkFn(bk.blocks, m), `bookings.blocks.${m}`);
409
440
  }
441
+ // Work orders, stock, bills of materials, made-from: capability + collection authority, as in production.
442
+ const OPERATIONS = {
443
+ workOrders: { resource: 'workorders', reads: ['get', 'list'], writes: ['create', 'update', 'setStatus', 'remove', 'startStage', 'progress', 'completeStage', 'skipStage', 'planStage', 'setStages'] },
444
+ stock: { resource: 'stock', reads: ['lines', 'totals', 'where', 'position', 'short'], writes: ['receive', 'produce', 'consume', 'move', 'allocate', 'release', 'hold', 'unhold', 'adjust'] },
445
+ boms: { resource: 'boms', reads: ['current', 'versions', 'whereUsed', 'explode'], writes: ['set', 'end'] },
446
+ madeFrom: { resource: 'madefrom', reads: ['of', 'usedIn', 'trace'], writes: ['record', 'end'] },
447
+ };
448
+ const triggerType = (def.trigger && def.trigger.type) || 'http';
449
+ const hasCollectionAuthority = triggerType !== 'http' || def.authority === 'collection';
450
+ const needAuthority = () => {
451
+ if (!hasCollectionAuthority)
452
+ throw Object.assign(new Error('This needs collection authority: declare the function with authority "collection"'), { code: 'NEEDS_COLLECTION_AUTHORITY', status: 403 });
453
+ };
454
+ for (const [group, g] of Object.entries(OPERATIONS)) {
455
+ sl[group] = {};
456
+ const given = impl[group] || {};
457
+ for (const m of [...g.reads, ...g.writes]) {
458
+ const op = g.reads.includes(m) ? 'read' : 'write';
459
+ sl[group][m] = async (...args) => {
460
+ if (!allowsSl(parsed, g.resource, op))
461
+ throw new CapabilityError(`sl:${g.resource}:${op}`);
462
+ needAuthority();
463
+ return typeof given[m] === 'function' ? given[m](...args) : stub(`${group}.${m}`, args);
464
+ };
465
+ }
466
+ }
467
+ sl.operations = {
468
+ // Each step must be a write this function may make; with no impl, the steps run one by one through
469
+ // the methods above (so your stand-ins are called), without the all-or-nothing the platform gives.
470
+ transaction: async (steps) => {
471
+ if (!Array.isArray(steps) || !steps.length)
472
+ throw Object.assign(new Error('A transaction needs at least one step'), { code: 'INVALID_INPUT' });
473
+ for (const st of steps) {
474
+ const [group, m] = String((st && st.op) || '').split('.');
475
+ const g = OPERATIONS[group];
476
+ if (!g || ![...g.reads, ...g.writes].includes(m))
477
+ throw Object.assign(new Error(`There is no "${st && st.op}"`), { code: 'UNKNOWN_OP' });
478
+ if (g.reads.includes(m))
479
+ throw Object.assign(new Error(`${st.op} only reads. Do reads outside the transaction`), { code: 'INVALID_INPUT' });
480
+ if (!allowsSl(parsed, g.resource, 'write'))
481
+ throw new CapabilityError(`sl:${g.resource}:write`);
482
+ }
483
+ needAuthority();
484
+ const own = impl.operations && impl.operations.transaction;
485
+ if (typeof own === 'function')
486
+ return own(steps);
487
+ const results = [];
488
+ for (const st of steps) {
489
+ const [group, m] = st.op.split('.');
490
+ results.push(await sl[group][m](...(st.args || [])));
491
+ }
492
+ return { results };
493
+ },
494
+ };
410
495
  const secretsMap = opts.secrets || {};
411
496
  const baseFetch = opts.fetch || (typeof fetch !== 'undefined' ? fetch : undefined);
412
497
  const via = (def.trigger && def.trigger.type) || 'http';
@@ -434,6 +519,7 @@ export function createFunctionTestContext(opts) {
434
519
  origin: (_f = caller.origin) !== null && _f !== void 0 ? _f : null,
435
520
  ip: (_g = caller.ip) !== null && _g !== void 0 ? _g : null,
436
521
  via,
522
+ userGroups: Object.freeze([...(caller.userGroups || [])]),
437
523
  },
438
524
  fetch: (async (input, init) => {
439
525
  let host = '';
@@ -4,6 +4,8 @@ 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 { TypedMessage, MessageAbout, EmailAttachmentSpec } from './comms.js';
8
+ import type { WorkOrdersApi, StockApi, BomsApi, MadeFromApi, OperationsApi } from './operations.js';
7
9
  import type { Booking, BookingSlot, BookingAllocation, CreateBookingInput, UpdateBookingInput, MoveBookingInput, BookingListQueryParams, CreateSlotInput, UpdateSlotInput, SlotListQueryParams, CreateBlockInput, BlockListQueryParams, FreeBusyQuery, FreeBusyResponse, MessageBookersInput, MessageBookersResult } from './bookings.js';
8
10
  /**
9
11
  * A bundle (widget or container) as returned by the collection widgets endpoint.
@@ -295,6 +297,13 @@ export interface AppFunctionDef {
295
297
  * without it, install/validation fails. Ignored for any other visibility/authority combo.
296
298
  */
297
299
  elevated?: boolean;
300
+ /**
301
+ * `http` only. Who may call it: the caller must be signed in and in at least ONE of these user
302
+ * groups (by key, e.g. `['qc-controller', 'manager']`), or be a collection admin. Checked by the
303
+ * platform before any of your code runs: anyone else gets `403 NOT_IN_USER_GROUP` (`401
304
+ * SIGN_IN_REQUIRED` when not signed in). Absent = no user group limit. See docs/user-groups.md.
305
+ */
306
+ userGroups?: string[];
298
307
  /**
299
308
  * Least-privilege capabilities this function needs, surfaced at install for
300
309
  * consent and capped at runtime — even for `collection`-authority functions.
@@ -537,7 +546,50 @@ export interface AppHistoryQuery {
537
546
  /** Default 100, at most 1000. */
538
547
  limit?: number;
539
548
  }
549
+ /** `ctx.sl.messages.send` input. Give `contactId` or `to: 'caller'`, and `templateId` or `message`. */
550
+ export interface ServerFunctionMessage {
551
+ contactId?: string;
552
+ /** The person calling this function (their contact, made if they're signed in and have none yet). */
553
+ to?: 'caller';
554
+ templateId?: string;
555
+ message?: TypedMessage;
556
+ channel?: 'preferred' | 'email' | 'sms' | 'whatsapp' | 'push' | 'wallet';
557
+ /** Extra Liquid variables. */
558
+ props?: Record<string, unknown>;
559
+ /** Records to hydrate into the template (`{ booking: 'B-123' }`, `{ productId }` …), as comm/send. */
560
+ include?: Record<string, unknown>;
561
+ about?: MessageAbout;
562
+ /** A label for the log (`'booking-cancelled'`). */
563
+ ref?: string;
564
+ attach?: EmailAttachmentSpec[];
565
+ }
566
+ export type ServerFunctionMessageResult = {
567
+ ok: true;
568
+ channel: 'email' | 'sms' | 'whatsapp' | 'push' | 'wallet';
569
+ messageId?: string;
570
+ attachmentsLeftOut?: string[];
571
+ } | {
572
+ ok: false;
573
+ reason: 'opted_out' | 'no_channel' | 'no_contact' | 'template_not_found';
574
+ };
540
575
  export interface ServerFunctionSl {
576
+ /**
577
+ * Work orders: what work is under way (`sl:workorders:read` / `:write`). Any app may read a work
578
+ * order; only the app that owns it may change it. Needs `authority: 'collection'`. See docs/operations.md.
579
+ */
580
+ workOrders: WorkOrdersApi;
581
+ /**
582
+ * Stock: how much of a product is in each container, changed only through movements, and a product's
583
+ * position (`sl:stock:read` / `:write`). Shared by every app in the collection. Needs
584
+ * `authority: 'collection'`.
585
+ */
586
+ stock: StockApi;
587
+ /** Bills of materials: what a product is made of (`sl:boms:read` / `:write`). Needs `authority: 'collection'`. */
588
+ boms: BomsApi;
589
+ /** What a batch or item was really made from (`sl:madefrom:read` / `:write`). Needs `authority: 'collection'`. */
590
+ madeFrom: MadeFromApi;
591
+ /** Several work order, stock, bill of materials and made-from writes, all or nothing. */
592
+ operations: OperationsApi;
541
593
  /** THIS app's bookings, slots and blocks (`sl:bookings:read` / `sl:bookings:write`). */
542
594
  bookings: ServerFunctionBookings;
543
595
  /**
@@ -561,8 +613,41 @@ export interface ServerFunctionSl {
561
613
  }): Promise<any>;
562
614
  /** Totals over THIS app's records: count, sum/avg/min/max of data numbers, grouped by data keys. */
563
615
  aggregate(params?: import('./appObjects.js').AggregateRequest): Promise<import('./appObjects.js').AggregateResponse & Record<string, unknown>>;
616
+ /**
617
+ * Every record of one type, with its data: a set-up list (every machine, with its rate). Up to 5,000
618
+ * (more → `TOO_MANY`: page with `query`). Read from cache for types the manifest declares `small`,
619
+ * cleared on every write. A record type or a declared type id. → mapped records, oldest first.
620
+ */
621
+ all(recordType: string): Promise<any[]>;
564
622
  [method: string]: any;
565
623
  };
624
+ /**
625
+ * Pickers: a small list for "pick a machine" or "pick a hold reason", served from cache and cleared on
626
+ * every write. `source` is `type:<record type or declared type id>` (the app's records of it: label,
627
+ * second line, on/off and order as the manifest's `data` block says) or `list:<list id>` (a value list
628
+ * the app declares in `data.lists`; the entry's `id` is the value's code). Pass the `version` you hold
629
+ * to get `{ unchanged: true }` back; a type of more than 2,000 entries answers `mode: 'search'` and
630
+ * wants `q`. Needs `sl:records:read`. docs/admin-lists-and-pickers.md
631
+ */
632
+ appOptions: {
633
+ get(source: string, opts?: {
634
+ q?: string;
635
+ version?: string;
636
+ }): Promise<import('./appOptions.js').AppOptionsResponse>;
637
+ };
638
+ /**
639
+ * Who is in the collection's user groups, by key (all keyed groups when `keys` is empty): staff lists,
640
+ * and addressing a team. Needs `sl:usergroups:read` and collection authority. At most 500 people,
641
+ * sorted by name; members whose account is gone are left out. docs/user-groups.md
642
+ */
643
+ userGroups: {
644
+ members(keys?: string[]): Promise<Array<{
645
+ userId: string;
646
+ name: string | null;
647
+ email: string | null;
648
+ userGroups: string[];
649
+ }>>;
650
+ };
566
651
  /**
567
652
  * Several record writes that land together or not at all (take 5 from bin A AND add 5 to order line B
568
653
  * AND log the move). Needs `sl:records:write`; THIS app's records in THIS collection only. A failing op
@@ -620,16 +705,39 @@ export interface ServerFunctionSl {
620
705
  eventId: string;
621
706
  }>;
622
707
  };
708
+ /**
709
+ * Messages (`sl:messages:write`): message one person through the platform — a template or a typed
710
+ * message, on their preferred channel (or one you name), logged with this app and what it's `about`, so
711
+ * it shows in Messages and on the contact's Activity and a reply finds its way back. Service messages
712
+ * only (confirmations, reminders, cancellations, updates); the person's opt-outs are respected. Someone
713
+ * who can't be reached is an answer — `{ ok: false, reason }` — not an error. docs/comms.md.
714
+ */
715
+ messages: {
716
+ send(input: ServerFunctionMessage): Promise<ServerFunctionMessageResult>;
717
+ };
623
718
  /**
624
719
  * Platform tools (`tools:<name>` or `tools:<family>.*`, e.g. `tools:pdf.create`, `tools:pdf.*`):
625
720
  * pdf.create, pdf.merge, pdf.fill, pdf.inspect, pdf.render, pdf.decodeBarcodes, pdf.inspectGraphics,
626
- * pdf.preflight, pdf.printReady, pdf.edit, image.transform. Runs as THIS collection whatever the caller
721
+ * pdf.preflight, pdf.printReady, pdf.edit, image.transform, image.ocr, pdf.extract. Runs as THIS collection whatever the caller
627
722
  * (authorised by the declaration, billed to the collection), rate-limited per collection. Returns the
628
723
  * tool's result; a failure throws an Error with `code` (e.g. bad_args, busy, too_many_pages).
629
724
  */
630
725
  tools: {
631
726
  run<T = any>(name: string, args?: Record<string, any>): Promise<T>;
632
727
  };
728
+ /**
729
+ * The collection's files (`sl:assets:read` / `sl:assets:write`, and collection authority): read any
730
+ * asset, save what the function makes as an asset of THIS app, and change or remove only this app's
731
+ * own. read/create/replace carry the file as base64 (up to 7 MB); bigger files go straight to storage
732
+ * with startUpload -> PUT to `sessionUrl` -> finishUpload, and are read by fetching the asset's `url`.
733
+ */
734
+ assets: ServerFunctionAssets;
735
+ /**
736
+ * Ask a model (`sl:ai:write`, any authority): a prompt, files (PDFs, photos, text), and optionally a
737
+ * JSON Schema for a structured answer in `data`. The collection's AI budget is ENFORCED: when it is
738
+ * used up the call throws `AI_BUDGET_EXCEEDED` / `AI_CREDITS_EXHAUSTED` (402) before anything is spent.
739
+ */
740
+ ai: ServerFunctionAi;
633
741
  /** Products, scoped by caller authority + declared capability. */
634
742
  products: any;
635
743
  /** Attestations, scoped by caller authority + declared capability. */
@@ -652,6 +760,136 @@ export interface ServerFunctionSl {
652
760
  data: Pick<AppDataHandle, 'get' | 'getData'>;
653
761
  };
654
762
  }
763
+ /** An asset as server code sees it. `url` is the current file; `assetUrl` the address that never changes. */
764
+ export interface ServerFunctionAsset {
765
+ id: string;
766
+ appId: string | null;
767
+ productId: string | null;
768
+ proofId: string | null;
769
+ name: string;
770
+ assetType: string;
771
+ mimeType: string | null;
772
+ size: number | null;
773
+ width: number | null;
774
+ height: number | null;
775
+ hash: string | null;
776
+ url: string;
777
+ assetUrl: string | null;
778
+ thumbnail: string | null;
779
+ labels: string[];
780
+ metadata: Record<string, any>;
781
+ /** How many earlier files replace() has kept. */
782
+ versions: number;
783
+ status: string;
784
+ createdAt: string;
785
+ updatedAt: string;
786
+ }
787
+ /** A file going into server code's calls: bytes as base64 (or plain text). */
788
+ export type ServerFunctionFileInput = {
789
+ base64: string;
790
+ contentType: string;
791
+ } | {
792
+ text: string;
793
+ contentType?: string;
794
+ };
795
+ /** `ctx.sl.assets` - the collection's files from server code. */
796
+ export interface ServerFunctionAssets {
797
+ get(assetId: string): Promise<ServerFunctionAsset | null>;
798
+ list(params?: {
799
+ productId?: string | null;
800
+ proofId?: string | null;
801
+ appId?: string | null;
802
+ labels?: string | string[];
803
+ assetType?: string;
804
+ limit?: number;
805
+ offset?: number;
806
+ }): Promise<ServerFunctionAsset[]>;
807
+ read(assetId: string, opts?: {
808
+ as?: 'base64';
809
+ }): Promise<{
810
+ id: string;
811
+ name: string;
812
+ contentType: string;
813
+ size: number;
814
+ base64: string;
815
+ }>;
816
+ read(assetId: string, opts: {
817
+ as: 'text';
818
+ }): Promise<{
819
+ id: string;
820
+ name: string;
821
+ contentType: string;
822
+ size: number;
823
+ text: string;
824
+ }>;
825
+ create(input: ServerFunctionFileInput & {
826
+ name: string;
827
+ productId?: string;
828
+ proofId?: string;
829
+ labels?: string[];
830
+ metadata?: Record<string, any>;
831
+ }): Promise<ServerFunctionAsset>;
832
+ /** A new file for one of this app's assets: same id and address, the old file kept as a version. */
833
+ replace(assetId: string, input: ServerFunctionFileInput & {
834
+ name?: string;
835
+ }): Promise<ServerFunctionAsset>;
836
+ update(assetId: string, patch: {
837
+ name?: string;
838
+ labels?: string[];
839
+ metadata?: Record<string, any>;
840
+ }): Promise<ServerFunctionAsset>;
841
+ remove(assetId: string): Promise<{
842
+ id: string;
843
+ deleted: true;
844
+ }>;
845
+ /** A large file: PUT its bytes to `sessionUrl` (declare `network:storage.googleapis.com`), then finishUpload. */
846
+ startUpload(input: {
847
+ name: string;
848
+ contentType: string;
849
+ productId?: string;
850
+ proofId?: string;
851
+ replaceAssetId?: string;
852
+ }): Promise<{
853
+ uploadId: string;
854
+ sessionUrl: string;
855
+ expiresAt: string;
856
+ }>;
857
+ finishUpload(uploadId: string, input?: {
858
+ name?: string;
859
+ metadata?: Record<string, any>;
860
+ }): Promise<ServerFunctionAsset>;
861
+ }
862
+ /** `ctx.sl.ai.generate` - what to ask. */
863
+ export interface ServerFunctionAiRequest {
864
+ prompt?: string;
865
+ system?: string;
866
+ /** Up to 10, 7 MB in all: an asset (needs sl:assets:read), bytes, or text. */
867
+ files?: Array<{
868
+ assetId: string;
869
+ } | {
870
+ base64: string;
871
+ contentType: string;
872
+ } | {
873
+ text: string;
874
+ name?: string;
875
+ }>;
876
+ /** A JSON Schema: the answer is parsed into `data`. */
877
+ schema?: Record<string, any>;
878
+ /** 'fast' (default) is quick and cheap; 'best' thinks harder and costs more. */
879
+ quality?: 'fast' | 'best';
880
+ }
881
+ /** `ctx.sl.ai` - model calls from server code, metered to the collection. */
882
+ export interface ServerFunctionAi {
883
+ generate<T = any>(request: ServerFunctionAiRequest): Promise<{
884
+ text: string;
885
+ data?: T;
886
+ model: string;
887
+ usage: {
888
+ inputTokens: number;
889
+ outputTokens: number;
890
+ };
891
+ }>;
892
+ }
655
893
  /** Identity of whoever invoked a server function. */
656
894
  export interface ServerFunctionCaller {
657
895
  /** Authenticated user id, or `null` for anonymous/public/system invocations. */
@@ -664,6 +902,12 @@ export interface ServerFunctionCaller {
664
902
  ip?: string | null;
665
903
  /** How the function was triggered. */
666
904
  via: AppFunctionTriggerType;
905
+ /**
906
+ * Keys of the user groups the caller is in, e.g. `['qc-controller', 'warehouse']`. Empty when nobody
907
+ * is signed in (and for `event`/`cron`). Use it for finer rules than the declaration's `userGroups`
908
+ * allows ("a manager may also override"). See docs/user-groups.md.
909
+ */
910
+ userGroups: readonly string[];
667
911
  }
668
912
  /** The signed-in caller's own contact, as a server function sees it (`ctx.sl.contacts.forCaller()`). */
669
913
  export interface CallerContact {
@@ -881,6 +1125,52 @@ export interface PublicView {
881
1125
  /** The params the caller supplies via the URL. */
882
1126
  params?: PublicViewParams;
883
1127
  }
1128
+ /**
1129
+ * One ADMIN VIEW of the app: a screen of its admin side that a host or the assistant can open by name
1130
+ * ("the campaigns list", "one campaign", "bookings for a day"). An app declares them once, in
1131
+ * `app.manifest.json#adminViews`, and the same list drives three things:
1132
+ * - the app's own side menu (`group` main and settings; see prove docs/design/core-app-layout.md),
1133
+ * - Studio's workspace menu, which can carry an app's areas itself (it then opens the app with
1134
+ * `chrome=none` and the app hides its own menu),
1135
+ * - the Studio assistant, which opens a view while it talks (`smartlinks:navigate`).
1136
+ * Admin views are NOT portal pages (`linkable`) and NOT standalone screens (`publicViews`).
1137
+ * See docs/admin-views.md and `SL.adminViews`.
1138
+ */
1139
+ export interface AdminView {
1140
+ /** Stable id, unique within the app (`campaigns`, `campaign`, `campaign.results`). Hosts keep it. */
1141
+ id: string;
1142
+ /** The label in a menu: short, the business's words ("Campaigns", "Message log"). */
1143
+ title: string;
1144
+ /**
1145
+ * Hash route within the admin page, with `{name}` placeholders for the params it needs:
1146
+ * `"/campaigns"`, `"/campaigns/{campaignId}"`, `"/day/{date}"`.
1147
+ */
1148
+ path: string;
1149
+ /**
1150
+ * Where the view sits:
1151
+ * - `main` (default): an area in the side menu, in declared order;
1152
+ * - `settings`: pinned at the bottom of the menu;
1153
+ * - `record`: inside one record (a campaign, a product). Not in the main menu: opening the record
1154
+ * swaps the menu for the record's own views, headed by "← back to" its `within` area.
1155
+ */
1156
+ group?: 'main' | 'settings' | 'record';
1157
+ /**
1158
+ * The view this one sits inside. A record's first view names its area (`campaign` within
1159
+ * `campaigns`); the record's other views name the record's first view (`campaign.results` within
1160
+ * `campaign`).
1161
+ */
1162
+ within?: string;
1163
+ /** A Lucide icon name, kebab-case (`megaphone`, `scroll-text`, `package`). */
1164
+ icon?: string;
1165
+ /** One line on what the screen shows, for the assistant ("Every message sent and what happened to it"). */
1166
+ description?: string;
1167
+ /**
1168
+ * The params the view takes, each with a few words on what it is (`{ campaignId: "a campaign's id",
1169
+ * status: "draft | scheduled | sent" }`). A `{name}` in `path` is required; any other is optional
1170
+ * and travels as a query param. Platform context (collectionId, appId, …) is never listed.
1171
+ */
1172
+ params?: Record<string, string>;
1173
+ }
884
1174
  export interface AppManifest {
885
1175
  $schema?: string;
886
1176
  meta?: {
@@ -980,6 +1270,12 @@ export interface AppManifest {
980
1270
  * See PublicView + docs/design/public-views.md.
981
1271
  */
982
1272
  publicViews?: PublicView[];
1273
+ /**
1274
+ * The app's ADMIN VIEWS: its admin screens by name, in menu order. They drive the app's own side
1275
+ * menu, Studio's workspace menu and the assistant's "open this screen". @see AdminView ·
1276
+ * docs/admin-views.md
1277
+ */
1278
+ adminViews?: AdminView[];
983
1279
  /**
984
1280
  * Executor bundle declaration. Present when the app ships a programmatic executor
985
1281
  * for AI-driven configuration, server-side SEO, and LLM content generation.
@@ -0,0 +1,32 @@
1
+ /** One entry a picker shows. */
2
+ export interface AppOption {
3
+ /** A record's id, or a value list value's code: what a record stores. */
4
+ id: string;
5
+ label: string;
6
+ /** A second line (a machine's stage), when the type declares one. */
7
+ sublabel?: string;
8
+ /** Switched off: hide it for new choices, still show its label on records that carry it. */
9
+ active: boolean;
10
+ /** Its place, when the type or list has one; entries come sorted already. */
11
+ order: number | null;
12
+ }
13
+ export type AppOptionsResponse =
14
+ /** `all`: every entry. `search`: the type is too large to send whole; these match `q`. */
15
+ {
16
+ items: AppOption[];
17
+ version: string;
18
+ mode: 'all' | 'search';
19
+ total?: number;
20
+ unchanged?: undefined;
21
+ }
22
+ /** You already hold this version. */
23
+ | {
24
+ unchanged: true;
25
+ version: string;
26
+ };
27
+ /** A value to save in a value list, in the order to show them. */
28
+ export interface AppOptionValueInput {
29
+ code: string;
30
+ label?: string;
31
+ active?: boolean;
32
+ }
@@ -0,0 +1,3 @@
1
+ // Pickers: the small, cached list behind "pick a machine" or "pick a hold reason".
2
+ // docs/admin-lists-and-pickers.md
3
+ export {};