@proveanything/smartlinks 3.0.0-alpha.2 → 3.0.0-alpha.3

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 (151) hide show
  1. package/README.md +741 -741
  2. package/dist/README.md +573 -573
  3. package/dist/adminCardsView.js +55 -55
  4. package/dist/api/bookings.d.ts +49 -2
  5. package/dist/api/bookings.js +59 -2
  6. package/dist/api/index.d.ts +1 -0
  7. package/dist/api/index.js +1 -0
  8. package/dist/api/payments.d.ts +60 -0
  9. package/dist/api/payments.js +94 -0
  10. package/dist/api/realtime.d.ts +3 -0
  11. package/dist/api/realtime.js +10 -2
  12. package/dist/baseline.css +194 -194
  13. package/dist/dataChanged.d.ts +74 -0
  14. package/dist/dataChanged.js +162 -0
  15. package/dist/docs/API_SUMMARY.md +1086 -858
  16. package/dist/docs/admin-cards.md +189 -189
  17. package/dist/docs/agent-tools.md +156 -156
  18. package/dist/docs/ai-tools-and-skills.md +180 -180
  19. package/dist/docs/ai.md +1721 -1721
  20. package/dist/docs/api-versions.md +85 -85
  21. package/dist/docs/app-data-storage.md +277 -277
  22. package/dist/docs/app-docs.md +73 -73
  23. package/dist/docs/app-manifest.md +852 -852
  24. package/dist/docs/app-records-pattern.md +388 -388
  25. package/dist/docs/appConfig.md +550 -550
  26. package/dist/docs/assistant-apps.md +172 -172
  27. package/dist/docs/assistant-context.md +119 -119
  28. package/dist/docs/bookings.md +105 -8
  29. package/dist/docs/caching.md +32 -3
  30. package/dist/docs/comms.md +689 -689
  31. package/dist/docs/connectors.md +340 -340
  32. package/dist/docs/css-baseline.md +133 -133
  33. package/dist/docs/customer-guide.md +70 -70
  34. package/dist/docs/data-changed.md +91 -0
  35. package/dist/docs/deploying-apps.md +340 -340
  36. package/dist/docs/dpp.md +115 -115
  37. package/dist/docs/entitlements.md +90 -90
  38. package/dist/docs/files.md +69 -69
  39. package/dist/docs/host-dependency-contract.md +252 -252
  40. package/dist/docs/iframe-responder.md +11 -0
  41. package/dist/docs/integrations.md +322 -322
  42. package/dist/docs/interactions.md +544 -544
  43. package/dist/docs/item-context.md +181 -181
  44. package/dist/docs/knowledge.md +105 -105
  45. package/dist/docs/lists.md +157 -157
  46. package/dist/docs/lots.md +112 -112
  47. package/dist/docs/loyalty.md +348 -348
  48. package/dist/docs/members.md +183 -183
  49. package/dist/docs/memberships.md +150 -150
  50. package/dist/docs/mobile-admin-container.md +693 -693
  51. package/dist/docs/operations.md +281 -281
  52. package/dist/docs/overview.md +487 -485
  53. package/dist/docs/payments.md +94 -0
  54. package/dist/docs/proof-comms-triggers.md +142 -142
  55. package/dist/docs/proof-ownership-transfer.md +155 -155
  56. package/dist/docs/proof-product-data-scoping.md +462 -462
  57. package/dist/docs/proof-share-grants.md +305 -305
  58. package/dist/docs/realtime.md +149 -139
  59. package/dist/docs/records-admin-pattern.md +304 -304
  60. package/dist/docs/service-accounts.md +64 -64
  61. package/dist/docs/standard-query.md +196 -187
  62. package/dist/docs/tag-codes.md +97 -97
  63. package/dist/docs/tag-ranges.md +106 -106
  64. package/dist/docs/theme-tokens.md +252 -252
  65. package/dist/docs/upgrading-to-3.md +550 -532
  66. package/dist/docs/wallet-passes.md +107 -107
  67. package/dist/docs/websites.md +123 -123
  68. package/dist/http.d.ts +6 -3
  69. package/dist/http.js +48 -19
  70. package/dist/iframeResponder.d.ts +7 -0
  71. package/dist/iframeResponder.js +10 -0
  72. package/dist/index.d.ts +2 -0
  73. package/dist/index.js +2 -0
  74. package/dist/openapi.yaml +426 -3
  75. package/dist/testing/bookingsMemory.d.ts +29 -1
  76. package/dist/testing/bookingsMemory.js +89 -1
  77. package/dist/testing/index.js +4 -1
  78. package/dist/theme-boot.js +82 -82
  79. package/dist/theme.css +75 -75
  80. package/dist/types/appManifest.d.ts +26 -4
  81. package/dist/types/bookings.d.ts +99 -1
  82. package/dist/types/index.d.ts +1 -0
  83. package/dist/types/index.js +1 -0
  84. package/dist/types/payments.d.ts +101 -0
  85. package/dist/types/payments.js +5 -0
  86. package/dist/types/realtime.d.ts +5 -1
  87. package/dist/version.d.ts +1 -1
  88. package/dist/version.js +1 -1
  89. package/docs/API_SUMMARY.md +1086 -858
  90. package/docs/admin-cards.md +189 -189
  91. package/docs/agent-tools.md +156 -156
  92. package/docs/ai-tools-and-skills.md +180 -180
  93. package/docs/ai.md +1721 -1721
  94. package/docs/api-versions.md +85 -85
  95. package/docs/app-data-storage.md +277 -277
  96. package/docs/app-docs.md +73 -73
  97. package/docs/app-manifest.md +852 -852
  98. package/docs/app-records-pattern.md +388 -388
  99. package/docs/appConfig.md +550 -550
  100. package/docs/assistant-apps.md +172 -172
  101. package/docs/assistant-context.md +119 -119
  102. package/docs/bookings.md +105 -8
  103. package/docs/caching.md +32 -3
  104. package/docs/comms.md +689 -689
  105. package/docs/connectors.md +340 -340
  106. package/docs/css-baseline.md +133 -133
  107. package/docs/customer-guide.md +70 -70
  108. package/docs/data-changed.md +91 -0
  109. package/docs/deploying-apps.md +340 -340
  110. package/docs/dpp.md +115 -115
  111. package/docs/entitlements.md +90 -90
  112. package/docs/files.md +69 -69
  113. package/docs/host-dependency-contract.md +252 -252
  114. package/docs/iframe-responder.md +11 -0
  115. package/docs/integrations.md +322 -322
  116. package/docs/interactions.md +544 -544
  117. package/docs/item-context.md +181 -181
  118. package/docs/knowledge.md +105 -105
  119. package/docs/lists.md +157 -157
  120. package/docs/lots.md +112 -112
  121. package/docs/loyalty.md +348 -348
  122. package/docs/members.md +183 -183
  123. package/docs/memberships.md +150 -150
  124. package/docs/mobile-admin-container.md +693 -693
  125. package/docs/operations.md +281 -281
  126. package/docs/overview.md +487 -485
  127. package/docs/payments.md +94 -0
  128. package/docs/proof-comms-triggers.md +142 -142
  129. package/docs/proof-ownership-transfer.md +155 -155
  130. package/docs/proof-product-data-scoping.md +462 -462
  131. package/docs/proof-share-grants.md +305 -305
  132. package/docs/realtime.md +149 -139
  133. package/docs/service-accounts.md +64 -64
  134. package/docs/standard-query.md +196 -187
  135. package/docs/tag-codes.md +97 -97
  136. package/docs/tag-ranges.md +106 -106
  137. package/docs/theme-lookbook.v1.json +120 -120
  138. package/docs/theme-tokens.md +252 -252
  139. package/docs/upgrading-to-3.md +550 -532
  140. package/docs/wallet-passes.md +107 -107
  141. package/docs/websites.md +123 -123
  142. package/openapi.yaml +426 -3
  143. package/package.json +91 -91
  144. package/scripts/headless-check.mjs +87 -87
  145. package/scripts/lib/bare-imports.mjs +57 -57
  146. package/scripts/lib/keyed-app-data.mjs +21 -21
  147. package/scripts/lib/upgrade.mjs +708 -668
  148. package/scripts/publish.mjs +272 -272
  149. package/scripts/register-release.mjs +91 -91
  150. package/scripts/upgrade.mjs +79 -79
  151. package/upgrade/3.json +2 -2
@@ -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 { items: 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 { items: 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` |