@proveanything/smartlinks 2.1.41 → 2.1.43

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 (122) hide show
  1. package/README.md +754 -754
  2. package/dist/README.md +573 -573
  3. package/dist/adminCardsView.js +55 -55
  4. package/dist/adminViews.js +1 -1
  5. package/dist/api/index.d.ts +1 -0
  6. package/dist/api/index.js +1 -0
  7. package/dist/api/product.d.ts +2 -1
  8. package/dist/api/product.js +2 -1
  9. package/dist/api/subscriptions.d.ts +97 -0
  10. package/dist/api/subscriptions.js +178 -0
  11. package/dist/baseline.css +194 -194
  12. package/dist/docs/API_SUMMARY.md +1135 -832
  13. package/dist/docs/admin-cards.md +189 -189
  14. package/dist/docs/admin-views.md +9 -4
  15. package/dist/docs/agent-tools.md +156 -156
  16. package/dist/docs/ai-tools-and-skills.md +180 -180
  17. package/dist/docs/ai.md +1721 -1721
  18. package/dist/docs/analytics.md +39 -39
  19. package/dist/docs/app-data-storage.md +277 -277
  20. package/dist/docs/app-docs.md +73 -73
  21. package/dist/docs/app-manifest.md +852 -852
  22. package/dist/docs/app-records-pattern.md +388 -388
  23. package/dist/docs/appConfig.md +550 -550
  24. package/dist/docs/assistant-apps.md +172 -172
  25. package/dist/docs/assistant-context.md +119 -119
  26. package/dist/docs/bookings.md +442 -442
  27. package/dist/docs/comms.md +686 -686
  28. package/dist/docs/connectors.md +340 -340
  29. package/dist/docs/css-baseline.md +133 -133
  30. package/dist/docs/customer-guide.md +70 -70
  31. package/dist/docs/deploying-apps.md +340 -340
  32. package/dist/docs/entitlements.md +90 -90
  33. package/dist/docs/files.md +69 -69
  34. package/dist/docs/host-dependency-contract.md +210 -210
  35. package/dist/docs/i18n.md +9 -0
  36. package/dist/docs/integrations.md +322 -322
  37. package/dist/docs/interactions.md +545 -545
  38. package/dist/docs/item-context.md +181 -181
  39. package/dist/docs/knowledge.md +102 -102
  40. package/dist/docs/lots.md +111 -111
  41. package/dist/docs/loyalty.md +352 -352
  42. package/dist/docs/members.md +183 -182
  43. package/dist/docs/memberships.md +149 -0
  44. package/dist/docs/mobile-admin-container.md +693 -693
  45. package/dist/docs/operations.md +281 -281
  46. package/dist/docs/overview.md +483 -482
  47. package/dist/docs/proof-comms-triggers.md +142 -142
  48. package/dist/docs/proof-ownership-transfer.md +155 -155
  49. package/dist/docs/proof-product-data-scoping.md +462 -462
  50. package/dist/docs/proof-share-grants.md +305 -305
  51. package/dist/docs/realtime.md +138 -138
  52. package/dist/docs/records-admin-pattern.md +304 -304
  53. package/dist/docs/server-functions.md +1 -0
  54. package/dist/docs/standard-query.md +187 -187
  55. package/dist/docs/tag-codes.md +97 -97
  56. package/dist/docs/theme-tokens.md +252 -252
  57. package/dist/docs/wallet-passes.md +107 -107
  58. package/dist/docs/websites.md +123 -123
  59. package/dist/i18n.d.ts +6 -0
  60. package/dist/i18n.js +10 -0
  61. package/dist/openapi.yaml +426 -3
  62. package/dist/theme-boot.js +82 -78
  63. package/dist/theme.css +75 -75
  64. package/dist/types/appManifest.d.ts +32 -0
  65. package/dist/types/index.d.ts +1 -0
  66. package/dist/types/index.js +1 -0
  67. package/dist/types/subscriptions.d.ts +195 -0
  68. package/dist/types/subscriptions.js +9 -0
  69. package/docs/API_SUMMARY.md +1135 -832
  70. package/docs/admin-cards.md +189 -189
  71. package/docs/admin-views.md +9 -4
  72. package/docs/agent-tools.md +156 -156
  73. package/docs/ai-tools-and-skills.md +180 -180
  74. package/docs/ai.md +1721 -1721
  75. package/docs/analytics.md +39 -39
  76. package/docs/app-data-storage.md +277 -277
  77. package/docs/app-docs.md +73 -73
  78. package/docs/app-manifest.md +852 -852
  79. package/docs/app-records-pattern.md +388 -388
  80. package/docs/appConfig.md +550 -550
  81. package/docs/assistant-apps.md +172 -172
  82. package/docs/assistant-context.md +119 -119
  83. package/docs/bookings.md +442 -442
  84. package/docs/comms.md +686 -686
  85. package/docs/connectors.md +340 -340
  86. package/docs/css-baseline.md +133 -133
  87. package/docs/customer-guide.md +70 -70
  88. package/docs/deploying-apps.md +340 -340
  89. package/docs/entitlements.md +90 -90
  90. package/docs/files.md +69 -69
  91. package/docs/host-dependency-contract.md +210 -210
  92. package/docs/i18n.md +9 -0
  93. package/docs/integrations.md +322 -322
  94. package/docs/interactions.md +545 -545
  95. package/docs/item-context.md +181 -181
  96. package/docs/knowledge.md +102 -102
  97. package/docs/lots.md +111 -111
  98. package/docs/loyalty.md +352 -352
  99. package/docs/members.md +183 -182
  100. package/docs/memberships.md +149 -0
  101. package/docs/mobile-admin-container.md +693 -693
  102. package/docs/operations.md +281 -281
  103. package/docs/overview.md +483 -482
  104. package/docs/proof-comms-triggers.md +142 -142
  105. package/docs/proof-ownership-transfer.md +155 -155
  106. package/docs/proof-product-data-scoping.md +462 -462
  107. package/docs/proof-share-grants.md +305 -305
  108. package/docs/realtime.md +138 -138
  109. package/docs/server-functions.md +1 -0
  110. package/docs/standard-query.md +187 -187
  111. package/docs/tag-codes.md +97 -97
  112. package/docs/theme-lookbook.v1.json +120 -120
  113. package/docs/theme-tokens.md +252 -252
  114. package/docs/wallet-passes.md +107 -107
  115. package/docs/websites.md +123 -123
  116. package/openapi.yaml +426 -3
  117. package/package.json +87 -87
  118. package/scripts/headless-check.mjs +87 -87
  119. package/scripts/lib/bare-imports.mjs +57 -57
  120. package/scripts/lib/keyed-app-data.mjs +21 -21
  121. package/scripts/publish.mjs +272 -272
  122. package/scripts/register-release.mjs +91 -91
@@ -1,322 +1,322 @@
1
- # Integrations
2
-
3
- An **integration flow** is one input/output pipeline between SmartLinks and an external
4
- system. There are two directions:
5
-
6
- - **outbound** — read a SmartLinks **product** that changed, or **one event** (an interaction, a
7
- contact change, a tag scan — any spine event) as the [envelope](#event-sourced-flows-and-the-envelope),
8
- transform it with field mappings, and send it to an external endpoint (signed, if you want).
9
- - **inbound** — fetch from an external system and write a SmartLinks **product** or **contact**
10
- (a provider's view of a person: member id, tier, points — see [Contact as a target](#contact-as-a-target)).
11
-
12
- Flows are triggered three ways, all converging on the same executor:
13
-
14
- - **manual** — `integrations.runFlow(...)`, inline (returns a run summary) or enqueued.
15
- - **event** — an outbound flow subscribed to an event type (e.g. `product.updated`,
16
- `interaction.submitted`, `contact.*`, `tag.scanned`, `*`) fires automatically when it happens. See
17
- [Event names and patterns](#event-names-and-patterns).
18
- - **schedule** — a flow carrying a cron/interval `schedule` is run by the scan job. *(next)*
19
-
20
- Provider-specific logic (a provider's payload format, its API, its connect form) lives in a
21
- **connector app**, not in the engine: see **[Connectors](connectors.md)**. A flow uses one with
22
- `config.connector = { appId }`.
23
-
24
- **Reliability.** A record that fails is retried on its own with exponential backoff (honouring the
25
- destination's `Retry-After`); a permanent failure (most 4xx) or one out of attempts is **dead** and
26
- waits in `integrations.listFailed` for `integrations.retryFailed`. A destination that keeps failing
27
- **pauses the flow automatically** (`flow.circuitOpenedAt`): edits are held, small probes check for
28
- recovery, and it resumes on its own (or with `integrations.resumeFlow`).
29
-
30
- **Observability.** `integrations.getHealth` shows every flow at a glance (paused?, running?, last 24h,
31
- backlog); `getFlowHealth` one flow; `getProductLineage` where a product's data came from and where it
32
- went. Every run and every record is kept in BigQuery (`analytics.integration_runs`,
33
- `analytics.integration_run_items`); the API's run history is a 7-day window. Outbound sends carry
34
- `X-SmartLinks-Run` (the run) and an `Idempotency-Key` (same record, same content → same key).
35
-
36
- **Change capture.** Every product and record write is captured where it's saved, whatever made it (the
37
- admin, an import, a server function). A product change *wakes* each subscribed outbound flow, which then
38
- sweeps every product changed since its last sweep (deletions included). A burst of edits, such as a big
39
- import, is one sweep, not one send per product. A reconciliation sweep every 15 minutes catches anything
40
- a wake missed. Events that need one call each (app functions, flows on record events) are recorded
41
- durably and retried until they're delivered.
42
-
43
- Credentials are **never** stored on the flow. The connection holds an opaque
44
- `credentialRef` into the **sealed-secret store** (`secrets` namespace); the value is sealed
45
- at rest and resolved server-side only, at execution.
46
-
47
- ---
48
-
49
- ## The flow model
50
-
51
- ```ts
52
- interface IntegrationFlow {
53
- id: string
54
- direction: 'inbound' | 'outbound'
55
- name: string
56
- status: 'draft' | 'active' | 'paused' | 'error' // only 'active' flows fire on events/schedule
57
- eventTypes: string[] // e.g. ['product.updated'], ['interaction.*'], ['*']
58
- schedule: string | null // cron/interval for scheduled flows
59
- sourceEntity: 'product' | 'interaction' | 'contact' | 'event' | null // outbound: what it reads
60
- targetEntity: 'product' | 'contact' | null // inbound: what it writes
61
- config: {
62
- connection?: {
63
- baseUrl?: string
64
- sendEndpoint?: string // outbound: appended to baseUrl
65
- defaultHeaders?: Record<string, string>
66
- auth?: { method: 'api_key' | 'bearer' | 'basic' | ..., headerName?: string, credentialRef?: string }
67
- timeoutMs?: number
68
- }
69
- signing?: { credentialRef: string, previousCredentialRef?: string } // X-SmartLinks-Signature (below)
70
- identity?: { policy?: 'externalIds' | 'hashed' | 'raw', hashKeyCredentialRef?: string } // event-sourced flows
71
- eventMapping?: EventMapping // event-sourced flows: many events → the provider's few
72
- fieldMappings?: FieldMapping[]
73
- }
74
- // ...run watermark/telemetry: lastRunAt, lastRunStatus, lastRunCount, totalSynced
75
- }
76
- ```
77
-
78
- ### Field mappings (transform)
79
-
80
- Each mapping produces one field on the target payload:
81
-
82
- | transformType | uses | meaning |
83
- |---|---|---|
84
- | `direct` | `sourcePath` | copy the value at that dot-path |
85
- | `static` | `transformExpression` | a constant |
86
- | `template` | `transformExpression` | a Liquid template rendered against the source record |
87
- | `jsonata` / `ai` | — | recognised but not yet executed; reported as a per-field error |
88
-
89
- A single field's failure is collected and the rest continue (partial success) — it never
90
- aborts the whole record.
91
-
92
- ---
93
-
94
- ## Event names and patterns
95
-
96
- A flow's `eventTypes` (and a server function's `trigger.eventTypes`) name events exactly or by prefix:
97
-
98
- | Subscription | Matches |
99
- |---|---|
100
- | `product.updated` | exactly that |
101
- | `interaction.submitted:<typeId>` | one interaction type's submissions |
102
- | `interaction.*` | every interaction event |
103
- | `record.updated:*` | record updates of any type |
104
- | `*` | everything in the collection — a raw event stream |
105
-
106
- Events on the spine today: `product.created / updated / deleted`, `record.<verb>[:<recordType>]`,
107
- `interaction.submitted[:<typeId>]`, `contact.created / updated / deleted / erased`,
108
- `tag.scanned[:<eventType>]` (a scan resolves in the redirect, before any page could run a tag),
109
- `proof.created / transferred`, `attestation.created[:type]`, `booking.*`, `slot.*`.
110
-
111
- ---
112
-
113
- ## Event-sourced flows and the envelope
114
-
115
- A flow with `sourceEntity: 'interaction' | 'contact' | 'event'` sends **one event per run** — not a
116
- product. Every such event is wrapped in the same **envelope**, whatever the destination, and only then
117
- mapped with the flow's field mappings (or handed to a connector's `serialize`):
118
-
119
- ```jsonc
120
- {
121
- "specVersion": 1, // bumped only when a consumer could break
122
- "id": "0b2b…", // the event's id — stable across retries; use it as the destination's idempotency / transaction id
123
- "type": "interaction.submitted:quiz-1",
124
- "entityType": "interaction", "entityId": "0b2b…",
125
- "occurredAt": "2026-11-08T10:00:00.000Z",
126
- "collectionId": "…", "orgId": "…", "appId": "quiz",
127
- "identity": {
128
- "contactId": "…", "userId": "…",
129
- "externalIds": { "acme-loyalty": "M-9", "crm": "C-1" }, // ids other systems know this person by
130
- "anonymousId": "v-77", "sessionId": "s-1", // the visitor / device and session, before anyone signed in (every policy)
131
- "emailHash": "…", "phoneHash": "…", "hashAlgorithm": "hmac-sha256" // policy 'hashed' (default)
132
- // "email", "phone": only under policy 'raw'
133
- },
134
- "identityPolicy": "hashed",
135
- "product": { "id": "P1", "name": "Widget", "sku": "W-1", "gtin": "0500…", "variantId": null, "batchId": null },
136
- "proof": { "id": "…" },
137
- "consent": { "channels": { "email": "opted_in", "sms": "suppressed", "push": "unknown", "whatsapp": "unknown" }, "topics": { "offers": true }, "updatedAt": "…" }, // null when about nobody we hold
138
- "subject": { "interactionId": "quiz-1", "outcome": "completed", "metadata": { "score": 9 }, "source": "hub" },
139
- "event": { "name": "engagement_completed", "attributes": { "kind": "quiz", "score": 9 }, "rule": "quiz" }, // from eventMapping
140
- "attributes": {}
141
- }
142
- ```
143
-
144
- Field mappings read envelope paths (`identity.externalIds.acme-loyalty`, `subject.outcome`,
145
- `event.name`, `product.sku`). With no mappings the envelope itself is sent. A failed event delivery
146
- keeps its envelope and is retried from it; a product is re-read instead.
147
-
148
- **CloudEvents.** `config.envelopeFormat: 'cloudevents'` wraps each delivered body (mapped or not) as a
149
- CloudEvents 1.0 structured event — `{ specversion: '1.0', id, type, source: 'urn:smartlinks:collection:<id>',
150
- subject, time, datacontenttype, dataschema: 'urn:smartlinks:envelope:v1', data }` — the shape every event
151
- bus, lake and serverless tool already consumes.
152
-
153
- ```ts
154
- const flow = await integrations.createFlow(collectionId, {
155
- appId: 'core-integrations', direction: 'outbound', name: 'Engagement → loyalty', status: 'active',
156
- eventTypes: ['interaction.*', 'tag.scanned:*'],
157
- sourceEntity: 'event',
158
- config: {
159
- connection: { baseUrl: 'https://api.acme.example', sendEndpoint: '/events', auth: { method: 'bearer', credentialRef: ref } },
160
- signing: { credentialRef: signingRef },
161
- identity: { policy: 'hashed' },
162
- eventMapping: {
163
- rules: [
164
- { id: 'quiz', match: { interactionIds: ['quiz-1'], outcomes: ['completed'] }, event: 'engagement_completed',
165
- attributes: { kind: 'quiz', score: '{{ subject.metadata.score }}', sku: { path: 'product.sku' } } },
166
- { id: 'scan', match: { types: ['tag.scanned:*'] }, event: 'pack_scanned', attributes: { sku: { path: 'product.sku' } } },
167
- ],
168
- unmatched: 'skip',
169
- },
170
- fieldMappings: [
171
- { targetPath: 'event_name', sourcePath: 'event.name', transformType: 'direct' },
172
- { targetPath: 'external_id', sourcePath: 'identity.externalIds.acme-loyalty', transformType: 'direct' },
173
- { targetPath: 'transaction_id', sourcePath: 'id', transformType: 'direct' },
174
- ],
175
- },
176
- })
177
- ```
178
-
179
- ### Identity policy
180
-
181
- `config.identity.policy` decides what about the person leaves the platform:
182
-
183
- | Policy | The envelope's `identity` carries |
184
- |---|---|
185
- | `externalIds` | `contactId`, `userId`, `externalIds` — nothing else |
186
- | `hashed` (default) | the above plus `emailHash` / `phoneHash`: HMAC-SHA256 with a **per-collection** key, or the brand's own key when `identity.hashKeyCredentialRef` names one (so hashes match a mirror the brand built) |
187
- | `raw` | the above plus `email` and `phone` |
188
-
189
- No hash key configured on the server → no hashes, never an unkeyed hash.
190
-
191
- ### Event mapping
192
-
193
- Loyalty and engagement platforms accept a small, pre-registered set of event names. `config.eventMapping`
194
- folds our many interaction types into those names: rules in order, first match wins; `match` may name
195
- `types` (exact or patterns), `interactionIds`, `outcomes`, `appIds`; attributes are literals, Liquid
196
- templates over the envelope, or `{ path, default }`. Unmatched events are skipped (and shown as skipped
197
- in the run) unless `unmatched: 'passthrough'`. When the flow has a connector with a `describeEvents`
198
- step, the mapping is **validated when saved** against the provider's registered events and its
199
- `limits` (`maxEvents`, `maxAttributes`): `createFlow` / `updateFlow` answer `400 EVENT_MAPPING_INVALID`
200
- with `problems[]`.
201
-
202
- ### Signed deliveries
203
-
204
- With `config.signing.credentialRef`, every HTTP delivery carries:
205
-
206
- ```
207
- X-SmartLinks-Signature: t=1730900000,v1=<hex HMAC-SHA256(secret, `${t}.${rawBody}`)>
208
- X-SmartLinks-Delivery: <uuid, new per attempt>
209
- X-SmartLinks-Event: interaction.submitted:quiz-1
210
- X-SmartLinks-Run: <run id>
211
- Idempotency-Key: <flowId>:<eventId>:<hash of the body>
212
- ```
213
-
214
- The signature covers the exact bytes of the body. A receiver recomputes it, compares in constant time,
215
- and rejects `t` older than about five minutes. During a rotation `previousCredentialRef` adds a second
216
- `v1=` so a receiver that knows either secret verifies.
217
-
218
- Destinations must be **public hosts**: loopback, private ranges and cloud metadata addresses are
219
- refused as a permanent failure. (Local development: `INTEGRATION_ALLOW_PRIVATE_DESTINATIONS=1` on the
220
- server.)
221
-
222
- ### Contact as a target
223
-
224
- An inbound flow with `targetEntity: 'contact'` writes a provider's view of a person. After the
225
- connector's `shape` (or your field mappings) each record is a **member document**:
226
-
227
- ```jsonc
228
- {
229
- "identity": { "externalId": "M-9", "email": "ada@example.com" }, // contactId | externalId | email | phone — at least one
230
- "contact": { "firstName": "Ada", "lastName": "Lovelace" }, // fills EMPTY profile fields only
231
- "externalIds": { "acme-crm": "C-1" }, // merged
232
- "customFields": { "region": "UK" }, // merged (never `comms`)
233
- "tags": { "add": ["gold"], "remove": ["silver"] },
234
- "loyalty": { "memberId": "M-9", "tier": "gold", "points": 1500, "status": "active", "asOf": "…", "attributes": { "since": 2024 } }
235
- }
236
- ```
237
-
238
- Matching: `contactId` → `externalIds[<provider>]` → email → phone; a new contact is created once however
239
- many workers see the same member. Loyalty lands as `customFields.loyalty` plus flat
240
- `customFields.loyaltyTier / loyaltyPoints / loyaltyMemberId / loyaltyProvider` for segments and comms
241
- targeting. The same document is what a server function applies with `ctx.sl.members.apply(...)` (a
242
- provider's webhook, see [connectors.md](connectors.md#loyalty-and-crm-connectors)).
243
-
244
- ---
245
-
246
- ## Secrets (write-only)
247
-
248
- The secret store is **write-only from the client**: you can set, rotate, list (refs +
249
- masked hints + metadata) and delete — but a value never comes back over the API.
250
-
251
- ```ts
252
- import { secrets, integrations } from '@proveanything/smartlinks'
253
-
254
- // 1. Store the destination credential — keep the returned ref.
255
- const { ref } = await secrets.set(collectionId, {
256
- name: 'Acme API key',
257
- purpose: 'integration',
258
- value: 'sk_live_…', // sent once; never retrievable
259
- })
260
-
261
- // list shows refs + masked hints only (safe to render)
262
- const { secrets: list } = await secrets.list(collectionId)
263
- // → [{ ref, name: 'Acme API key', hint: '…live_1a2b', purpose, createdAt, ... }]
264
- ```
265
-
266
- ---
267
-
268
- ## Creating and running a flow
269
-
270
- ```ts
271
- // 2. Create an outbound flow that pushes products to Acme, authed by the secret above.
272
- const flow = await integrations.createFlow(collectionId, {
273
- appId: 'my-integration-app',
274
- direction: 'outbound',
275
- name: 'Push products to Acme',
276
- status: 'active',
277
- eventTypes: ['product.updated'], // fire whenever a product changes
278
- sourceEntity: 'product',
279
- config: {
280
- connection: {
281
- baseUrl: 'https://api.acme.example',
282
- sendEndpoint: '/v1/products',
283
- auth: { method: 'api_key', headerName: 'X-API-Key', credentialRef: ref },
284
- },
285
- fieldMappings: [
286
- { targetPath: 'sku', sourcePath: 'sku', transformType: 'direct' },
287
- { targetPath: 'name', sourcePath: 'name', transformType: 'direct' },
288
- { targetPath: 'label', transformType: 'template', transformExpression: '{{name}} ({{sku}})' },
289
- ],
290
- },
291
- })
292
-
293
- // 3a. Test it now against one product — inline, returns a summary.
294
- const result = await integrations.runFlow(collectionId, flow.id, { entityId: 'P1045716' })
295
- if (integrations.isRunSummary(result)) {
296
- console.log(result) // { records: 1, sent: 1, failed: 0, status: 'success' }
297
- }
298
-
299
- // 3b. Or enqueue on the worker (returns immediately).
300
- await integrations.runFlow(collectionId, flow.id, { entityId: 'P1045716', async: true })
301
- ```
302
-
303
- Once `status: 'active'` with `eventTypes: ['product.updated']`, editing that product in the
304
- admin API fires the flow automatically — no manual run needed.
305
-
306
- ---
307
-
308
- ## Reference
309
-
310
- | Function | HTTP |
311
- |---|---|
312
- | `integrations.listFlows(collectionId, query?)` | `GET /integrations/flows` |
313
- | `integrations.createFlow(collectionId, input)` | `POST /integrations/flows` |
314
- | `integrations.getFlow(collectionId, id)` | `GET /integrations/flows/:id` |
315
- | `integrations.updateFlow(collectionId, id, input)` | `PUT /integrations/flows/:id` |
316
- | `integrations.deleteFlow(collectionId, id)` | `DELETE /integrations/flows/:id` |
317
- | `integrations.runFlow(collectionId, id, opts?)` | `POST /integrations/flows/:id/run` |
318
- | `secrets.list(collectionId, query?)` | `GET /secrets` |
319
- | `secrets.set(collectionId, input)` | `POST /secrets` (generated ref — for flows; an app's server functions use `secrets.put`, see server-functions.md) |
320
- | `secrets.get(collectionId, ref)` | `GET /secrets/:ref` |
321
- | `secrets.rotate(collectionId, ref, input)` | `PUT /secrets/:ref` |
322
- | `secrets.remove(collectionId, ref)` | `DELETE /secrets/:ref` |
1
+ # Integrations
2
+
3
+ An **integration flow** is one input/output pipeline between SmartLinks and an external
4
+ system. There are two directions:
5
+
6
+ - **outbound** — read a SmartLinks **product** that changed, or **one event** (an interaction, a
7
+ contact change, a tag scan — any spine event) as the [envelope](#event-sourced-flows-and-the-envelope),
8
+ transform it with field mappings, and send it to an external endpoint (signed, if you want).
9
+ - **inbound** — fetch from an external system and write a SmartLinks **product** or **contact**
10
+ (a provider's view of a person: member id, tier, points — see [Contact as a target](#contact-as-a-target)).
11
+
12
+ Flows are triggered three ways, all converging on the same executor:
13
+
14
+ - **manual** — `integrations.runFlow(...)`, inline (returns a run summary) or enqueued.
15
+ - **event** — an outbound flow subscribed to an event type (e.g. `product.updated`,
16
+ `interaction.submitted`, `contact.*`, `tag.scanned`, `*`) fires automatically when it happens. See
17
+ [Event names and patterns](#event-names-and-patterns).
18
+ - **schedule** — a flow carrying a cron/interval `schedule` is run by the scan job. *(next)*
19
+
20
+ Provider-specific logic (a provider's payload format, its API, its connect form) lives in a
21
+ **connector app**, not in the engine: see **[Connectors](connectors.md)**. A flow uses one with
22
+ `config.connector = { appId }`.
23
+
24
+ **Reliability.** A record that fails is retried on its own with exponential backoff (honouring the
25
+ destination's `Retry-After`); a permanent failure (most 4xx) or one out of attempts is **dead** and
26
+ waits in `integrations.listFailed` for `integrations.retryFailed`. A destination that keeps failing
27
+ **pauses the flow automatically** (`flow.circuitOpenedAt`): edits are held, small probes check for
28
+ recovery, and it resumes on its own (or with `integrations.resumeFlow`).
29
+
30
+ **Observability.** `integrations.getHealth` shows every flow at a glance (paused?, running?, last 24h,
31
+ backlog); `getFlowHealth` one flow; `getProductLineage` where a product's data came from and where it
32
+ went. Every run and every record is kept in BigQuery (`analytics.integration_runs`,
33
+ `analytics.integration_run_items`); the API's run history is a 7-day window. Outbound sends carry
34
+ `X-SmartLinks-Run` (the run) and an `Idempotency-Key` (same record, same content → same key).
35
+
36
+ **Change capture.** Every product and record write is captured where it's saved, whatever made it (the
37
+ admin, an import, a server function). A product change *wakes* each subscribed outbound flow, which then
38
+ sweeps every product changed since its last sweep (deletions included). A burst of edits, such as a big
39
+ import, is one sweep, not one send per product. A reconciliation sweep every 15 minutes catches anything
40
+ a wake missed. Events that need one call each (app functions, flows on record events) are recorded
41
+ durably and retried until they're delivered.
42
+
43
+ Credentials are **never** stored on the flow. The connection holds an opaque
44
+ `credentialRef` into the **sealed-secret store** (`secrets` namespace); the value is sealed
45
+ at rest and resolved server-side only, at execution.
46
+
47
+ ---
48
+
49
+ ## The flow model
50
+
51
+ ```ts
52
+ interface IntegrationFlow {
53
+ id: string
54
+ direction: 'inbound' | 'outbound'
55
+ name: string
56
+ status: 'draft' | 'active' | 'paused' | 'error' // only 'active' flows fire on events/schedule
57
+ eventTypes: string[] // e.g. ['product.updated'], ['interaction.*'], ['*']
58
+ schedule: string | null // cron/interval for scheduled flows
59
+ sourceEntity: 'product' | 'interaction' | 'contact' | 'event' | null // outbound: what it reads
60
+ targetEntity: 'product' | 'contact' | null // inbound: what it writes
61
+ config: {
62
+ connection?: {
63
+ baseUrl?: string
64
+ sendEndpoint?: string // outbound: appended to baseUrl
65
+ defaultHeaders?: Record<string, string>
66
+ auth?: { method: 'api_key' | 'bearer' | 'basic' | ..., headerName?: string, credentialRef?: string }
67
+ timeoutMs?: number
68
+ }
69
+ signing?: { credentialRef: string, previousCredentialRef?: string } // X-SmartLinks-Signature (below)
70
+ identity?: { policy?: 'externalIds' | 'hashed' | 'raw', hashKeyCredentialRef?: string } // event-sourced flows
71
+ eventMapping?: EventMapping // event-sourced flows: many events → the provider's few
72
+ fieldMappings?: FieldMapping[]
73
+ }
74
+ // ...run watermark/telemetry: lastRunAt, lastRunStatus, lastRunCount, totalSynced
75
+ }
76
+ ```
77
+
78
+ ### Field mappings (transform)
79
+
80
+ Each mapping produces one field on the target payload:
81
+
82
+ | transformType | uses | meaning |
83
+ |---|---|---|
84
+ | `direct` | `sourcePath` | copy the value at that dot-path |
85
+ | `static` | `transformExpression` | a constant |
86
+ | `template` | `transformExpression` | a Liquid template rendered against the source record |
87
+ | `jsonata` / `ai` | — | recognised but not yet executed; reported as a per-field error |
88
+
89
+ A single field's failure is collected and the rest continue (partial success) — it never
90
+ aborts the whole record.
91
+
92
+ ---
93
+
94
+ ## Event names and patterns
95
+
96
+ A flow's `eventTypes` (and a server function's `trigger.eventTypes`) name events exactly or by prefix:
97
+
98
+ | Subscription | Matches |
99
+ |---|---|
100
+ | `product.updated` | exactly that |
101
+ | `interaction.submitted:<typeId>` | one interaction type's submissions |
102
+ | `interaction.*` | every interaction event |
103
+ | `record.updated:*` | record updates of any type |
104
+ | `*` | everything in the collection — a raw event stream |
105
+
106
+ Events on the spine today: `product.created / updated / deleted`, `record.<verb>[:<recordType>]`,
107
+ `interaction.submitted[:<typeId>]`, `contact.created / updated / deleted / erased`,
108
+ `tag.scanned[:<eventType>]` (a scan resolves in the redirect, before any page could run a tag),
109
+ `proof.created / transferred`, `attestation.created[:type]`, `booking.*`, `slot.*`.
110
+
111
+ ---
112
+
113
+ ## Event-sourced flows and the envelope
114
+
115
+ A flow with `sourceEntity: 'interaction' | 'contact' | 'event'` sends **one event per run** — not a
116
+ product. Every such event is wrapped in the same **envelope**, whatever the destination, and only then
117
+ mapped with the flow's field mappings (or handed to a connector's `serialize`):
118
+
119
+ ```jsonc
120
+ {
121
+ "specVersion": 1, // bumped only when a consumer could break
122
+ "id": "0b2b…", // the event's id — stable across retries; use it as the destination's idempotency / transaction id
123
+ "type": "interaction.submitted:quiz-1",
124
+ "entityType": "interaction", "entityId": "0b2b…",
125
+ "occurredAt": "2026-11-08T10:00:00.000Z",
126
+ "collectionId": "…", "orgId": "…", "appId": "quiz",
127
+ "identity": {
128
+ "contactId": "…", "userId": "…",
129
+ "externalIds": { "acme-loyalty": "M-9", "crm": "C-1" }, // ids other systems know this person by
130
+ "anonymousId": "v-77", "sessionId": "s-1", // the visitor / device and session, before anyone signed in (every policy)
131
+ "emailHash": "…", "phoneHash": "…", "hashAlgorithm": "hmac-sha256" // policy 'hashed' (default)
132
+ // "email", "phone": only under policy 'raw'
133
+ },
134
+ "identityPolicy": "hashed",
135
+ "product": { "id": "P1", "name": "Widget", "sku": "W-1", "gtin": "0500…", "variantId": null, "batchId": null },
136
+ "proof": { "id": "…" },
137
+ "consent": { "channels": { "email": "opted_in", "sms": "suppressed", "push": "unknown", "whatsapp": "unknown" }, "topics": { "offers": true }, "updatedAt": "…" }, // null when about nobody we hold
138
+ "subject": { "interactionId": "quiz-1", "outcome": "completed", "metadata": { "score": 9 }, "source": "hub" },
139
+ "event": { "name": "engagement_completed", "attributes": { "kind": "quiz", "score": 9 }, "rule": "quiz" }, // from eventMapping
140
+ "attributes": {}
141
+ }
142
+ ```
143
+
144
+ Field mappings read envelope paths (`identity.externalIds.acme-loyalty`, `subject.outcome`,
145
+ `event.name`, `product.sku`). With no mappings the envelope itself is sent. A failed event delivery
146
+ keeps its envelope and is retried from it; a product is re-read instead.
147
+
148
+ **CloudEvents.** `config.envelopeFormat: 'cloudevents'` wraps each delivered body (mapped or not) as a
149
+ CloudEvents 1.0 structured event — `{ specversion: '1.0', id, type, source: 'urn:smartlinks:collection:<id>',
150
+ subject, time, datacontenttype, dataschema: 'urn:smartlinks:envelope:v1', data }` — the shape every event
151
+ bus, lake and serverless tool already consumes.
152
+
153
+ ```ts
154
+ const flow = await integrations.createFlow(collectionId, {
155
+ appId: 'core-integrations', direction: 'outbound', name: 'Engagement → loyalty', status: 'active',
156
+ eventTypes: ['interaction.*', 'tag.scanned:*'],
157
+ sourceEntity: 'event',
158
+ config: {
159
+ connection: { baseUrl: 'https://api.acme.example', sendEndpoint: '/events', auth: { method: 'bearer', credentialRef: ref } },
160
+ signing: { credentialRef: signingRef },
161
+ identity: { policy: 'hashed' },
162
+ eventMapping: {
163
+ rules: [
164
+ { id: 'quiz', match: { interactionIds: ['quiz-1'], outcomes: ['completed'] }, event: 'engagement_completed',
165
+ attributes: { kind: 'quiz', score: '{{ subject.metadata.score }}', sku: { path: 'product.sku' } } },
166
+ { id: 'scan', match: { types: ['tag.scanned:*'] }, event: 'pack_scanned', attributes: { sku: { path: 'product.sku' } } },
167
+ ],
168
+ unmatched: 'skip',
169
+ },
170
+ fieldMappings: [
171
+ { targetPath: 'event_name', sourcePath: 'event.name', transformType: 'direct' },
172
+ { targetPath: 'external_id', sourcePath: 'identity.externalIds.acme-loyalty', transformType: 'direct' },
173
+ { targetPath: 'transaction_id', sourcePath: 'id', transformType: 'direct' },
174
+ ],
175
+ },
176
+ })
177
+ ```
178
+
179
+ ### Identity policy
180
+
181
+ `config.identity.policy` decides what about the person leaves the platform:
182
+
183
+ | Policy | The envelope's `identity` carries |
184
+ |---|---|
185
+ | `externalIds` | `contactId`, `userId`, `externalIds` — nothing else |
186
+ | `hashed` (default) | the above plus `emailHash` / `phoneHash`: HMAC-SHA256 with a **per-collection** key, or the brand's own key when `identity.hashKeyCredentialRef` names one (so hashes match a mirror the brand built) |
187
+ | `raw` | the above plus `email` and `phone` |
188
+
189
+ No hash key configured on the server → no hashes, never an unkeyed hash.
190
+
191
+ ### Event mapping
192
+
193
+ Loyalty and engagement platforms accept a small, pre-registered set of event names. `config.eventMapping`
194
+ folds our many interaction types into those names: rules in order, first match wins; `match` may name
195
+ `types` (exact or patterns), `interactionIds`, `outcomes`, `appIds`; attributes are literals, Liquid
196
+ templates over the envelope, or `{ path, default }`. Unmatched events are skipped (and shown as skipped
197
+ in the run) unless `unmatched: 'passthrough'`. When the flow has a connector with a `describeEvents`
198
+ step, the mapping is **validated when saved** against the provider's registered events and its
199
+ `limits` (`maxEvents`, `maxAttributes`): `createFlow` / `updateFlow` answer `400 EVENT_MAPPING_INVALID`
200
+ with `problems[]`.
201
+
202
+ ### Signed deliveries
203
+
204
+ With `config.signing.credentialRef`, every HTTP delivery carries:
205
+
206
+ ```
207
+ X-SmartLinks-Signature: t=1730900000,v1=<hex HMAC-SHA256(secret, `${t}.${rawBody}`)>
208
+ X-SmartLinks-Delivery: <uuid, new per attempt>
209
+ X-SmartLinks-Event: interaction.submitted:quiz-1
210
+ X-SmartLinks-Run: <run id>
211
+ Idempotency-Key: <flowId>:<eventId>:<hash of the body>
212
+ ```
213
+
214
+ The signature covers the exact bytes of the body. A receiver recomputes it, compares in constant time,
215
+ and rejects `t` older than about five minutes. During a rotation `previousCredentialRef` adds a second
216
+ `v1=` so a receiver that knows either secret verifies.
217
+
218
+ Destinations must be **public hosts**: loopback, private ranges and cloud metadata addresses are
219
+ refused as a permanent failure. (Local development: `INTEGRATION_ALLOW_PRIVATE_DESTINATIONS=1` on the
220
+ server.)
221
+
222
+ ### Contact as a target
223
+
224
+ An inbound flow with `targetEntity: 'contact'` writes a provider's view of a person. After the
225
+ connector's `shape` (or your field mappings) each record is a **member document**:
226
+
227
+ ```jsonc
228
+ {
229
+ "identity": { "externalId": "M-9", "email": "ada@example.com" }, // contactId | externalId | email | phone — at least one
230
+ "contact": { "firstName": "Ada", "lastName": "Lovelace" }, // fills EMPTY profile fields only
231
+ "externalIds": { "acme-crm": "C-1" }, // merged
232
+ "customFields": { "region": "UK" }, // merged (never `comms`)
233
+ "tags": { "add": ["gold"], "remove": ["silver"] },
234
+ "loyalty": { "memberId": "M-9", "tier": "gold", "points": 1500, "status": "active", "asOf": "…", "attributes": { "since": 2024 } }
235
+ }
236
+ ```
237
+
238
+ Matching: `contactId` → `externalIds[<provider>]` → email → phone; a new contact is created once however
239
+ many workers see the same member. Loyalty lands as `customFields.loyalty` plus flat
240
+ `customFields.loyaltyTier / loyaltyPoints / loyaltyMemberId / loyaltyProvider` for segments and comms
241
+ targeting. The same document is what a server function applies with `ctx.sl.members.apply(...)` (a
242
+ provider's webhook, see [connectors.md](connectors.md#loyalty-and-crm-connectors)).
243
+
244
+ ---
245
+
246
+ ## Secrets (write-only)
247
+
248
+ The secret store is **write-only from the client**: you can set, rotate, list (refs +
249
+ masked hints + metadata) and delete — but a value never comes back over the API.
250
+
251
+ ```ts
252
+ import { secrets, integrations } from '@proveanything/smartlinks'
253
+
254
+ // 1. Store the destination credential — keep the returned ref.
255
+ const { ref } = await secrets.set(collectionId, {
256
+ name: 'Acme API key',
257
+ purpose: 'integration',
258
+ value: 'sk_live_…', // sent once; never retrievable
259
+ })
260
+
261
+ // list shows refs + masked hints only (safe to render)
262
+ const { secrets: list } = await secrets.list(collectionId)
263
+ // → [{ ref, name: 'Acme API key', hint: '…live_1a2b', purpose, createdAt, ... }]
264
+ ```
265
+
266
+ ---
267
+
268
+ ## Creating and running a flow
269
+
270
+ ```ts
271
+ // 2. Create an outbound flow that pushes products to Acme, authed by the secret above.
272
+ const flow = await integrations.createFlow(collectionId, {
273
+ appId: 'my-integration-app',
274
+ direction: 'outbound',
275
+ name: 'Push products to Acme',
276
+ status: 'active',
277
+ eventTypes: ['product.updated'], // fire whenever a product changes
278
+ sourceEntity: 'product',
279
+ config: {
280
+ connection: {
281
+ baseUrl: 'https://api.acme.example',
282
+ sendEndpoint: '/v1/products',
283
+ auth: { method: 'api_key', headerName: 'X-API-Key', credentialRef: ref },
284
+ },
285
+ fieldMappings: [
286
+ { targetPath: 'sku', sourcePath: 'sku', transformType: 'direct' },
287
+ { targetPath: 'name', sourcePath: 'name', transformType: 'direct' },
288
+ { targetPath: 'label', transformType: 'template', transformExpression: '{{name}} ({{sku}})' },
289
+ ],
290
+ },
291
+ })
292
+
293
+ // 3a. Test it now against one product — inline, returns a summary.
294
+ const result = await integrations.runFlow(collectionId, flow.id, { entityId: 'P1045716' })
295
+ if (integrations.isRunSummary(result)) {
296
+ console.log(result) // { records: 1, sent: 1, failed: 0, status: 'success' }
297
+ }
298
+
299
+ // 3b. Or enqueue on the worker (returns immediately).
300
+ await integrations.runFlow(collectionId, flow.id, { entityId: 'P1045716', async: true })
301
+ ```
302
+
303
+ Once `status: 'active'` with `eventTypes: ['product.updated']`, editing that product in the
304
+ admin API fires the flow automatically — no manual run needed.
305
+
306
+ ---
307
+
308
+ ## Reference
309
+
310
+ | Function | HTTP |
311
+ |---|---|
312
+ | `integrations.listFlows(collectionId, query?)` | `GET /integrations/flows` |
313
+ | `integrations.createFlow(collectionId, input)` | `POST /integrations/flows` |
314
+ | `integrations.getFlow(collectionId, id)` | `GET /integrations/flows/:id` |
315
+ | `integrations.updateFlow(collectionId, id, input)` | `PUT /integrations/flows/:id` |
316
+ | `integrations.deleteFlow(collectionId, id)` | `DELETE /integrations/flows/:id` |
317
+ | `integrations.runFlow(collectionId, id, opts?)` | `POST /integrations/flows/:id/run` |
318
+ | `secrets.list(collectionId, query?)` | `GET /secrets` |
319
+ | `secrets.set(collectionId, input)` | `POST /secrets` (generated ref — for flows; an app's server functions use `secrets.put`, see server-functions.md) |
320
+ | `secrets.get(collectionId, ref)` | `GET /secrets/:ref` |
321
+ | `secrets.rotate(collectionId, ref, input)` | `PUT /secrets/:ref` |
322
+ | `secrets.remove(collectionId, ref)` | `DELETE /secrets/:ref` |