@proveanything/smartlinks 3.0.0-alpha.1 → 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 (272) 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/analytics.d.ts +5 -4
  5. package/dist/api/analytics.js +5 -4
  6. package/dist/api/appConfiguration.d.ts +23 -18
  7. package/dist/api/appConfiguration.js +24 -18
  8. package/dist/api/appObjects.d.ts +54 -10
  9. package/dist/api/appObjects.js +75 -40
  10. package/dist/api/asset.d.ts +28 -22
  11. package/dist/api/asset.js +45 -56
  12. package/dist/api/attestation.d.ts +11 -3
  13. package/dist/api/attestation.js +12 -3
  14. package/dist/api/attestations.d.ts +12 -8
  15. package/dist/api/attestations.js +18 -21
  16. package/dist/api/authKit.d.ts +15 -10
  17. package/dist/api/authKit.js +17 -11
  18. package/dist/api/batch.d.ts +36 -25
  19. package/dist/api/batch.js +46 -39
  20. package/dist/api/bookings.d.ts +67 -11
  21. package/dist/api/bookings.js +82 -15
  22. package/dist/api/broadcasts.js +3 -17
  23. package/dist/api/claimSet.d.ts +26 -12
  24. package/dist/api/claimSet.js +32 -24
  25. package/dist/api/collection.d.ts +15 -10
  26. package/dist/api/collection.js +17 -11
  27. package/dist/api/comms.d.ts +12 -6
  28. package/dist/api/comms.js +12 -6
  29. package/dist/api/conditions.d.ts +7 -6
  30. package/dist/api/conditions.js +8 -6
  31. package/dist/api/contact.d.ts +6 -2
  32. package/dist/api/contact.js +25 -60
  33. package/dist/api/containers.d.ts +14 -10
  34. package/dist/api/containers.js +19 -14
  35. package/dist/api/crate.js +7 -9
  36. package/dist/api/dpp.d.ts +20 -13
  37. package/dist/api/dpp.js +23 -15
  38. package/dist/api/facets.d.ts +38 -13
  39. package/dist/api/facets.js +40 -15
  40. package/dist/api/files.d.ts +5 -2
  41. package/dist/api/files.js +7 -4
  42. package/dist/api/form.d.ts +8 -5
  43. package/dist/api/form.js +9 -5
  44. package/dist/api/index.d.ts +1 -1
  45. package/dist/api/index.js +1 -1
  46. package/dist/api/integrations.d.ts +29 -17
  47. package/dist/api/integrations.js +32 -25
  48. package/dist/api/interactions.d.ts +11 -6
  49. package/dist/api/interactions.js +14 -23
  50. package/dist/api/jobs.d.ts +16 -6
  51. package/dist/api/jobs.js +30 -20
  52. package/dist/api/journeys.js +2 -14
  53. package/dist/api/journeysAnalytics.d.ts +8 -5
  54. package/dist/api/journeysAnalytics.js +8 -5
  55. package/dist/api/knowledge.d.ts +20 -14
  56. package/dist/api/knowledge.js +22 -15
  57. package/dist/api/location.d.ts +6 -3
  58. package/dist/api/location.js +8 -22
  59. package/dist/api/lots.d.ts +9 -5
  60. package/dist/api/lots.js +22 -26
  61. package/dist/api/loyalty.d.ts +25 -16
  62. package/dist/api/loyalty.js +33 -32
  63. package/dist/api/nfc.d.ts +3 -1
  64. package/dist/api/nfc.js +3 -1
  65. package/dist/api/order.d.ts +45 -39
  66. package/dist/api/order.js +48 -65
  67. package/dist/api/partner.d.ts +17 -14
  68. package/dist/api/partner.js +21 -22
  69. package/dist/api/payments.d.ts +60 -0
  70. package/dist/api/payments.js +94 -0
  71. package/dist/api/products.d.ts +35 -12
  72. package/dist/api/products.js +36 -13
  73. package/dist/api/proof.d.ts +41 -19
  74. package/dist/api/proof.js +44 -23
  75. package/dist/api/realtime.d.ts +3 -0
  76. package/dist/api/realtime.js +10 -2
  77. package/dist/api/segments.js +3 -15
  78. package/dist/api/serviceAccounts.d.ts +8 -5
  79. package/dist/api/serviceAccounts.js +9 -6
  80. package/dist/api/shop.d.ts +7 -5
  81. package/dist/api/shop.js +13 -19
  82. package/dist/api/subscriptions.d.ts +12 -10
  83. package/dist/api/subscriptions.js +17 -25
  84. package/dist/api/tags.d.ts +23 -20
  85. package/dist/api/tags.js +40 -52
  86. package/dist/api/template.d.ts +16 -11
  87. package/dist/api/template.js +19 -13
  88. package/dist/api/translations.js +2 -12
  89. package/dist/api/userGroups.d.ts +26 -16
  90. package/dist/api/userGroups.js +43 -30
  91. package/dist/api/variant.d.ts +10 -7
  92. package/dist/api/variant.js +11 -7
  93. package/dist/api/wallet.d.ts +14 -11
  94. package/dist/api/wallet.js +15 -12
  95. package/dist/baseline.css +194 -194
  96. package/dist/dataChanged.d.ts +74 -0
  97. package/dist/dataChanged.js +162 -0
  98. package/dist/docs/API_SUMMARY.md +1443 -1409
  99. package/dist/docs/admin-cards.md +189 -189
  100. package/dist/docs/agent-tools.md +156 -156
  101. package/dist/docs/ai-tools-and-skills.md +180 -180
  102. package/dist/docs/ai.md +1721 -1721
  103. package/dist/docs/analytics.md +1 -1
  104. package/dist/docs/api-versions.md +85 -85
  105. package/dist/docs/app-data-storage.md +277 -277
  106. package/dist/docs/app-docs.md +73 -73
  107. package/dist/docs/app-manifest.md +852 -852
  108. package/dist/docs/app-objects.md +4 -4
  109. package/dist/docs/app-records-pattern.md +388 -388
  110. package/dist/docs/appConfig.md +550 -550
  111. package/dist/docs/assistant-apps.md +172 -172
  112. package/dist/docs/assistant-context.md +119 -119
  113. package/dist/docs/attestations.md +8 -8
  114. package/dist/docs/bookings.md +105 -8
  115. package/dist/docs/caching.md +32 -3
  116. package/dist/docs/comms.md +689 -689
  117. package/dist/docs/connectors.md +340 -340
  118. package/dist/docs/contact-search.md +2 -3
  119. package/dist/docs/css-baseline.md +133 -133
  120. package/dist/docs/customer-guide.md +70 -70
  121. package/dist/docs/data-changed.md +91 -0
  122. package/dist/docs/deploying-apps.md +340 -340
  123. package/dist/docs/dpp.md +115 -115
  124. package/dist/docs/entitlements.md +90 -90
  125. package/dist/docs/files.md +69 -69
  126. package/dist/docs/host-dependency-contract.md +252 -252
  127. package/dist/docs/iframe-responder.md +11 -0
  128. package/dist/docs/integrations.md +322 -322
  129. package/dist/docs/interactions.md +544 -544
  130. package/dist/docs/item-context.md +181 -181
  131. package/dist/docs/knowledge.md +105 -105
  132. package/dist/docs/lists.md +157 -114
  133. package/dist/docs/lots.md +112 -112
  134. package/dist/docs/loyalty.md +348 -348
  135. package/dist/docs/members.md +183 -183
  136. package/dist/docs/memberships.md +150 -150
  137. package/dist/docs/mobile-admin-container.md +693 -693
  138. package/dist/docs/operations.md +281 -281
  139. package/dist/docs/overview.md +487 -485
  140. package/dist/docs/payments.md +94 -0
  141. package/dist/docs/proof-comms-triggers.md +142 -142
  142. package/dist/docs/proof-ownership-transfer.md +155 -155
  143. package/dist/docs/proof-product-data-scoping.md +462 -462
  144. package/dist/docs/proof-share-grants.md +305 -305
  145. package/dist/docs/realtime.md +149 -139
  146. package/dist/docs/records-admin-pattern.md +304 -304
  147. package/dist/docs/service-accounts.md +64 -64
  148. package/dist/docs/standard-query.md +196 -187
  149. package/dist/docs/tag-codes.md +97 -97
  150. package/dist/docs/tag-ranges.md +106 -106
  151. package/dist/docs/theme-tokens.md +252 -252
  152. package/dist/docs/upgrading-to-3.md +550 -430
  153. package/dist/docs/wallet-passes.md +107 -107
  154. package/dist/docs/websites.md +123 -123
  155. package/dist/http.d.ts +6 -3
  156. package/dist/http.js +48 -19
  157. package/dist/iframeResponder.d.ts +7 -0
  158. package/dist/iframeResponder.js +10 -0
  159. package/dist/index.d.ts +2 -0
  160. package/dist/index.js +2 -0
  161. package/dist/list.d.ts +12 -0
  162. package/dist/list.js +59 -0
  163. package/dist/openapi.yaml +722 -660
  164. package/dist/testing/bookingsMemory.d.ts +29 -1
  165. package/dist/testing/bookingsMemory.js +89 -1
  166. package/dist/testing/index.js +4 -1
  167. package/dist/theme-boot.js +82 -82
  168. package/dist/theme.css +75 -75
  169. package/dist/types/analytics.d.ts +7 -3
  170. package/dist/types/appManifest.d.ts +26 -4
  171. package/dist/types/appObjects.d.ts +27 -12
  172. package/dist/types/appOptions.d.ts +2 -2
  173. package/dist/types/asset.d.ts +5 -6
  174. package/dist/types/attestations.d.ts +7 -9
  175. package/dist/types/batch.d.ts +5 -5
  176. package/dist/types/bookings.d.ts +109 -6
  177. package/dist/types/comms.d.ts +9 -5
  178. package/dist/types/contact.d.ts +7 -4
  179. package/dist/types/containers.d.ts +2 -1
  180. package/dist/types/facets.d.ts +14 -2
  181. package/dist/types/files.d.ts +3 -2
  182. package/dist/types/index.d.ts +1 -0
  183. package/dist/types/index.js +1 -0
  184. package/dist/types/integrations.d.ts +2 -1
  185. package/dist/types/interaction.d.ts +15 -7
  186. package/dist/types/jobs.d.ts +1 -1
  187. package/dist/types/journeysAnalytics.d.ts +3 -2
  188. package/dist/types/knowledge.d.ts +6 -3
  189. package/dist/types/knowledge.js +0 -1
  190. package/dist/types/list.d.ts +30 -2
  191. package/dist/types/location.d.ts +7 -2
  192. package/dist/types/location.js +0 -1
  193. package/dist/types/lots.d.ts +5 -2
  194. package/dist/types/lots.js +0 -6
  195. package/dist/types/order.d.ts +22 -20
  196. package/dist/types/payments.d.ts +101 -0
  197. package/dist/types/payments.js +5 -0
  198. package/dist/types/product.d.ts +28 -11
  199. package/dist/types/proof.d.ts +7 -8
  200. package/dist/types/realtime.d.ts +5 -1
  201. package/dist/types/tags.d.ts +5 -3
  202. package/dist/types/userGroups.d.ts +3 -3
  203. package/dist/types/userGroups.js +0 -4
  204. package/dist/version.d.ts +1 -1
  205. package/dist/version.js +1 -1
  206. package/docs/API_SUMMARY.md +1443 -1409
  207. package/docs/admin-cards.md +189 -189
  208. package/docs/agent-tools.md +156 -156
  209. package/docs/ai-tools-and-skills.md +180 -180
  210. package/docs/ai.md +1721 -1721
  211. package/docs/analytics.md +1 -1
  212. package/docs/api-versions.md +85 -85
  213. package/docs/app-data-storage.md +277 -277
  214. package/docs/app-docs.md +73 -73
  215. package/docs/app-manifest.md +852 -852
  216. package/docs/app-objects.md +4 -4
  217. package/docs/app-records-pattern.md +388 -388
  218. package/docs/appConfig.md +550 -550
  219. package/docs/assistant-apps.md +172 -172
  220. package/docs/assistant-context.md +119 -119
  221. package/docs/attestations.md +8 -8
  222. package/docs/bookings.md +105 -8
  223. package/docs/caching.md +32 -3
  224. package/docs/comms.md +689 -689
  225. package/docs/connectors.md +340 -340
  226. package/docs/contact-search.md +2 -3
  227. package/docs/css-baseline.md +133 -133
  228. package/docs/customer-guide.md +70 -70
  229. package/docs/data-changed.md +91 -0
  230. package/docs/deploying-apps.md +340 -340
  231. package/docs/dpp.md +115 -115
  232. package/docs/entitlements.md +90 -90
  233. package/docs/files.md +69 -69
  234. package/docs/host-dependency-contract.md +252 -252
  235. package/docs/iframe-responder.md +11 -0
  236. package/docs/integrations.md +322 -322
  237. package/docs/interactions.md +544 -544
  238. package/docs/item-context.md +181 -181
  239. package/docs/knowledge.md +105 -105
  240. package/docs/lists.md +157 -114
  241. package/docs/lots.md +112 -112
  242. package/docs/loyalty.md +348 -348
  243. package/docs/members.md +183 -183
  244. package/docs/memberships.md +150 -150
  245. package/docs/mobile-admin-container.md +693 -693
  246. package/docs/operations.md +281 -281
  247. package/docs/overview.md +487 -485
  248. package/docs/payments.md +94 -0
  249. package/docs/proof-comms-triggers.md +142 -142
  250. package/docs/proof-ownership-transfer.md +155 -155
  251. package/docs/proof-product-data-scoping.md +462 -462
  252. package/docs/proof-share-grants.md +305 -305
  253. package/docs/realtime.md +149 -139
  254. package/docs/service-accounts.md +64 -64
  255. package/docs/standard-query.md +196 -187
  256. package/docs/tag-codes.md +97 -97
  257. package/docs/tag-ranges.md +106 -106
  258. package/docs/theme-lookbook.v1.json +120 -120
  259. package/docs/theme-tokens.md +252 -252
  260. package/docs/upgrading-to-3.md +550 -430
  261. package/docs/wallet-passes.md +107 -107
  262. package/docs/websites.md +123 -123
  263. package/openapi.yaml +722 -660
  264. package/package.json +91 -91
  265. package/scripts/headless-check.mjs +87 -87
  266. package/scripts/lib/bare-imports.mjs +57 -57
  267. package/scripts/lib/keyed-app-data.mjs +21 -21
  268. package/scripts/lib/upgrade.mjs +708 -512
  269. package/scripts/publish.mjs +272 -272
  270. package/scripts/register-release.mjs +91 -91
  271. package/scripts/upgrade.mjs +79 -56
  272. package/upgrade/3.json +2731 -2213
package/docs/comms.md CHANGED
@@ -1,689 +1,689 @@
1
- # Communications (Comms & Broadcasts)
2
-
3
- This guide covers the full communications surface of the SDK: transactional sends, multi-channel broadcasts, consent management, push registration, and analytics.
4
-
5
- ---
6
-
7
- ## What You Can Do
8
-
9
- - **Transactional Send** — Fire a single targeted message to one contact without creating a broadcast record.
10
- - **Broadcasts** — Define and enqueue multi-channel campaigns (email, push, SMS, wallet); preview and test before sending.
11
- - **Comms Settings** — Configure topics and unsubscribe behaviour per collection.
12
- - **Consent & Preferences** — Record opt-ins/outs and per-subject preferences.
13
- - **Method Registration** — Register email, SMS, and Web Push contact methods.
14
- - **Analytics** — Query delivery events, recipient lists, and log custom events.
15
-
16
- ---
17
-
18
- ## Transactional Send
19
-
20
- Sends a single message to one contact using a template. No broadcast record is created. The send is logged to the contact's communication history with `sourceType: 'transactional'`.
21
-
22
- **Endpoint:** `POST /admin/collection/:collectionId/comm/send`
23
-
24
- ```typescript
25
- import { comms } from '@proveanything/smartlinks'
26
- import type { TransactionalSendRequest } from '@proveanything/smartlinks'
27
-
28
- const result = await comms.sendTransactional('collectionId', {
29
- contactId: 'e4f2a1b0-...',
30
- templateId: 'warranty-update',
31
- channel: 'preferred', // 'email' | 'sms' | 'whatsapp' | 'push' | 'wallet' | 'preferred' (default)
32
- props: { claimRef: 'CLM-0042', decision: 'approved' },
33
- include: {
34
- productId: 'prod-abc123', // hydrate product context into template
35
- appCase: 'c9d1e2f3-...', // hydrate an app case record
36
- },
37
- ref: 'warranty-decision-notification', // arbitrary string for your own tracking
38
- appId: 'warrantyApp',
39
- })
40
-
41
- if (result.ok) {
42
- console.log(`Sent via ${result.channel}`, result.messageId)
43
- } else {
44
- console.error('Send failed:', result.error)
45
- }
46
- ```
47
-
48
- ### Request Body
49
-
50
- | Field | Type | Description |
51
- |-------|------|-------------|
52
- | `contactId` | `string` | **Required.** Contact to send to. |
53
- | `templateId` | `string` | **Required.** Template to render. |
54
- | `channel` | `'email' \| 'sms' \| 'whatsapp' \| 'push' \| 'wallet' \| 'preferred'` | Channel to send on. `'preferred'` (default) picks the contact's best available channel. |
55
- | `props` | `Record<string, unknown>` | Extra variables merged into template rendering. |
56
- | `include` | object | Hydration flags — see table below. |
57
- | `ref` | `string` | Arbitrary reference string stored with the event. |
58
- | `appId` | `string` | App identifier, used for context/logging. |
59
- | `attach` | `EmailAttachmentSpec[]` | Files on the email — see [Attachments](#attachments). |
60
-
61
- **`include` fields:**
62
-
63
- | Field | Type | Description |
64
- |-------|------|-------------|
65
- | `collection` | `boolean` | Include collection data in template context. |
66
- | `productId` | `string` | Hydrate a specific product. |
67
- | `proofId` | `string` | Hydrate a specific proof. |
68
- | `user` | `boolean` | Include the requesting user's data. |
69
- | `appCase` | `string` | Hydrate an app case record by ID. |
70
- | `appThread` | `string` | Hydrate an app thread record by ID. |
71
- | `appRecord` | `string` | Hydrate an app record by ID. |
72
-
73
- ### Response
74
-
75
- ```typescript
76
- // Success
77
- { ok: true; channel: 'email' | 'sms' | 'whatsapp' | 'push' | 'wallet'; messageId?: string; attachmentsLeftOut?: string[] }
78
-
79
- // Failure
80
- { ok: false; error: string }
81
- ```
82
-
83
- ### Attachments
84
-
85
- `attach` puts files on the email (email only — ignored when the send goes by text or push). At most 5
86
- files and 10 MB in all; PDF, Word / Excel / PowerPoint, images, text, CSV and calendar files.
87
-
88
- ```typescript
89
- await comms.sendTransactional(collectionId, {
90
- contactId, templateId: 'booking-confirmed', appId: 'appointment-booking',
91
- include: { booking: bookingId },
92
- attach: [
93
- 'calendar', // the booking's .ics invite (needs include.booking + appId)
94
- { asset: 'a1b2c3' }, // a file uploaded to the collection's assets
95
- { function: 'receiptPdf' }, // the app's own server function makes it
96
- { filename: 'Quote.pdf', contentType: 'application/pdf', content: base64 }, // a file you made
97
- { filename: 'Report.pdf', file: signedUrl }, // a private file you made (pdf.create return: 'signedUrl')
98
- ],
99
- })
100
- ```
101
-
102
- A malformed list is refused (`transactional.attach_invalid`). A file that can't be made at send time
103
- (a missing asset, a function that fails) is left out and listed in `attachmentsLeftOut` — the email
104
- still goes. The request body is capped at 10 MB, so for big files make a private file and pass `file`.
105
- `bookings.message` takes the same `attach` (`'calendar'` is each person's own booking).
106
-
107
- ---
108
-
109
- ## Messaging one person from an app
110
-
111
- Every app sends through the platform: a booking reminder, a cancellation, an event update, "we got your
112
- entry". You never set up email or SMS yourself. Each message:
113
- - goes out on the person's preferred channel, or one you name;
114
- - respects their opt-outs;
115
- - is logged with your app;
116
- - shows in the Messages app and on the contact's Activity in the CRM.
117
-
118
- **From server code** (`sl:messages:write`):
119
-
120
- ```js
121
- const out = await ctx.sl.messages.send({
122
- to: 'caller', // or contactId
123
- templateId: 'tpl_booking_cancelled', // or message: { subject, body, sms? }
124
- include: { booking: bookingId }, // hydrates {{ booking }}, as comm/send
125
- about: { type: 'booking', id: bookingId, view: 'booking', params: { bookingId }, label: 'Sat 3pm' },
126
- })
127
- if (!out.ok) ctx.log('not sent', { reason: out.reason }) // 'opted_out' | 'no_channel' | 'no_contact' | 'template_not_found'
128
- ```
129
-
130
- **From an admin screen:** `SL.comms.sendTransactional(collectionId, { contactId, message | templateId, about, category: 'service', appId })`.
131
-
132
- - **Service messages only.** A confirmation, a reminder, a cancellation or an update. Marketing goes out
133
- as a campaign, with its opt-in and unsubscribe.
134
- - **Someone who can't be reached is an answer, not an error.** `ctx.sl.messages.send` returns
135
- `{ ok: false, reason }`; only a real failure throws.
136
- - **A typed message** is plain text with Liquid (`{{ contact.firstName }}`), sent exactly like a template:
137
- `{ subject, body, sms? }`.
138
-
139
- ### What a message is about
140
-
141
- `about: { appId?, type, id, view?, params?, label? }` names the record the message was sent for, and the
142
- admin screen that shows it. `view` and `params` are one of your manifest `adminViews`
143
- ([admin-views.md](admin-views.md)).
144
- - **Where it shows:** the Message log shows "Bookings · Sat 3pm", and it is a link to your screen. A reply
145
- opens a conversation that links to the same record.
146
- - **Defaults:** `appId` defaults to your app.
147
- - **Ids only:** never put content in it.
148
- - **Reading it back:** the log can be filtered by it: `GET /admin/collection/:id/comm/query/events?aboutType=booking&aboutId=B-123`,
149
- or `app=<appId>` for everything your app sent.
150
-
151
- ## Broadcasts
152
-
153
- Broadcasts are multi-channel campaigns defined and managed under a collection. Create a broadcast record in the platform first, then use the SDK to preview, test, and enqueue.
154
-
155
- **Import:**
156
- ```typescript
157
- import { broadcasts } from '@proveanything/smartlinks'
158
- import type { BroadcastSendRequest } from '@proveanything/smartlinks'
159
- ```
160
-
161
- ### Preview
162
-
163
- Render a broadcast template for a given channel without sending.
164
-
165
- ```typescript
166
- const preview = await broadcasts.preview('collectionId', 'broadcastId', {
167
- email: 'user@example.com', // optional: override recipient email for preview
168
- channelOverride: 'push', // force a specific channel
169
- props: { productId: 'prod_123' },
170
- hydrate: true,
171
- include: { product: true, proof: true }
172
- })
173
- // preview.channel — which channel was rendered
174
- // preview.payload / preview.subject / preview.body — channel-specific render output
175
- ```
176
-
177
- ### Test Send
178
-
179
- Send a single test message to a contact.
180
-
181
- ```typescript
182
- await broadcasts.sendTest('collectionId', 'broadcastId', {
183
- contactId: 'contact_123',
184
- props: { promo: 'JAN' }
185
- })
186
- ```
187
-
188
- ### Enqueue Production Send
189
-
190
- Enqueue a background send to all recipients. When `channel` is omitted the broadcast's own mode setting drives channel selection:
191
- - `preferred` — picks the best single channel per recipient.
192
- - `channels` / `all` — sends on every enabled channel.
193
-
194
- ```typescript
195
- const body: BroadcastSendRequest = {
196
- pageSize: 200,
197
- hydrate: true,
198
- include: { product: true, proof: true, user: true }
199
- }
200
- await broadcasts.send('collectionId', 'broadcastId', body)
201
- ```
202
-
203
- ### Manual Send
204
-
205
- ```typescript
206
- await broadcasts.sendManual('collectionId', 'broadcastId', { /* overrides */ })
207
- ```
208
-
209
- ### Topic Targeting and Consent
210
-
211
- A broadcast must declare a `topic` under `broadcast.data.topic` (e.g. `newsletter`, `critical`). The topic key must match one defined in your collection's comms settings, and consent enforcement uses it at send time.
212
-
213
- Consent resolution order (per recipient, per channel):
214
- 1. `preferences._default.topicsByChannel[channel][topic]`
215
- 2. `preferences._default.channels[channel]`
216
- 3. `preferences._default.topics[topic]`
217
- 4. Subject-specific preferences (when hydrating a subject context)
218
-
219
- Minimal broadcast data shape (`attach` is optional — uploaded assets only, the same files on every email):
220
- ```json
221
- {
222
- "data": {
223
- "topic": "newsletter",
224
- "attach": [{ "asset": "a1b2c3" }],
225
- "channelSettings": {
226
- "mode": "preferred",
227
- "channels": [
228
- { "channel": "email", "enabled": true, "priority": 1, "templateId": "tmpl_newsletter_email" },
229
- { "channel": "push", "enabled": true, "priority": 2 }
230
- ]
231
- }
232
- }
233
- }
234
- ```
235
-
236
- ### Append Recipients and Events
237
-
238
- ```typescript
239
- // Append a single delivery event
240
- await broadcasts.append('collectionId', {
241
- broadcastId: 'broadcastId',
242
- contactId: 'contact_123',
243
- channel: 'email',
244
- eventType: 'delivered',
245
- outcome: 'success'
246
- })
247
-
248
- // Append bulk events
249
- await broadcasts.appendBulk('collectionId', {
250
- params: { broadcastId: 'broadcastId', channel: 'push' },
251
- ids: ['contact_1', 'contact_2'],
252
- idField: 'contactId'
253
- })
254
-
255
- // List recipients
256
- const recips = await broadcasts.recipients('collectionId', 'broadcastId', { limit: 50 })
257
- recips.items // the contacts on this page
258
- recips.count // how many in all
259
- recips.nextCursor // pass back as `cursor` for the next page; null on the last
260
- ```
261
-
262
- ---
263
-
264
- ## Admin Comms Settings
265
-
266
- Configure unsubscribe behaviour and topics per collection.
267
-
268
- **Base path:** `admin/collection/:collectionId/comm.settings`
269
-
270
- ### Get Settings
271
-
272
- ```typescript
273
- import { comms } from '@proveanything/smartlinks'
274
- const { settings } = await comms.getSettings('collectionId', { includeSecret: true })
275
- // settings.unsub — { requireToken, hasSecret }
276
- // settings.topics — map of topic key → config
277
- ```
278
-
279
- ### Patch Settings
280
-
281
- ```typescript
282
- await comms.patchSettings('collectionId', {
283
- unsub: { requireToken: true, secret: '<your-secret>' },
284
- topics: { /* ... */ }
285
- })
286
- ```
287
-
288
- To clear the unsubscribe secret, send `secret: ''`.
289
-
290
- ### Topics Config
291
-
292
- Each topic key maps to a config object:
293
-
294
- ```json
295
- {
296
- "newsletter": {
297
- "label": "Newsletter",
298
- "description": "Occasional updates and stories",
299
- "classification": "marketing",
300
- "defaults": {
301
- "policy": "opt-in",
302
- "byChannel": { "email": "opt-in", "push": "opt-in" },
303
- "channels": { "email": true, "push": true, "sms": false }
304
- },
305
- "rules": {
306
- "allowChannels": ["email", "sms", "push"],
307
- "allowUnsubscribe": true
308
- },
309
- "required": false
310
- },
311
- "critical": {
312
- "label": "Critical Notices",
313
- "classification": "transactional",
314
- "defaults": {
315
- "policy": "opt-out",
316
- "channels": { "email": true, "push": true }
317
- },
318
- "rules": { "allowChannels": ["email", "push"], "allowUnsubscribe": false },
319
- "required": true
320
- }
321
- }
322
- ```
323
-
324
- - `classification`: `'transactional'` or `'marketing'` — used by the UI when no explicit policy is set.
325
- - `defaults.policy`: `'opt-in'` or `'opt-out'` — fallback policy for channels not overridden by `byChannel`.
326
- - `required: true` and `rules.allowUnsubscribe: false` — use for critical/mandatory messages.
327
-
328
- ### Unsubscribe Tokens
329
-
330
- If `unsub.requireToken` is true, public unsubscribe calls must include a `token` query param.
331
-
332
- Token generation (topic opt-out):
333
- ```
334
- basis = "${contactId}:${topic}"
335
- token = sha256(basis + ":" + unsub.secret) // hex
336
- ```
337
-
338
- Token generation (channel opt-out):
339
- ```
340
- basis = "${contactId}:channel:${channel}"
341
- token = sha256(basis + ":" + unsub.secret)
342
- ```
343
-
344
- Browser helper:
345
- ```typescript
346
- async function sha256Hex(input: string): Promise<string> {
347
- const data = new TextEncoder().encode(input)
348
- const hash = await crypto.subtle.digest('SHA-256', data)
349
- return Array.from(new Uint8Array(hash))
350
- .map(b => b.toString(16).padStart(2, '0'))
351
- .join('')
352
- }
353
-
354
- const token = await sha256Hex(`${contactId}:${topic}:${secret}`)
355
- ```
356
-
357
- ---
358
-
359
- ## Public Comms API
360
-
361
- All public endpoints live under `public/collection/:collectionId/comm/*` and do not require an API key.
362
-
363
- ### Get Topics
364
-
365
- ```typescript
366
- const { topics } = await comms.getPublicTopics('collectionId')
367
- ```
368
-
369
- Each topic carries UI metadata:
370
- - `classification`: `'transactional'` | `'marketing'`
371
- - `defaults.policy`: `'opt-in'` | `'opt-out'`
372
- - `defaults.byChannel[channel]`: per-channel override
373
-
374
- Helper to resolve effective policy for a toggle UI:
375
- ```typescript
376
- type Policy = 'opt-in' | 'opt-out'
377
-
378
- function effectivePolicy(topic: any, channel: 'email' | 'sms' | 'push' | 'wallet'): Policy {
379
- return (
380
- topic?.defaults?.byChannel?.[channel] ??
381
- topic?.defaults?.policy ??
382
- (topic?.classification === 'marketing' ? 'opt-in' : 'opt-out')
383
- ) as Policy
384
- }
385
- ```
386
-
387
- ### Sign-up with double opt-in (newsletters)
388
-
389
- For a sign-up form — works signed out. SmartLinks emails the address a "confirm your subscription"
390
- link; nothing is consented until it's clicked. The answer is always the same, so the form can't be
391
- used to find out who's registered.
392
-
393
- ```typescript
394
- await comms.signup('collectionId', {
395
- email: 'sam@example.com',
396
- topics: ['newsletter'],
397
- templateId: config.confirmationTemplateId, // YOUR confirmation email (required)
398
- fields: { firstName: 'Sam', customFields: { favouriteStore: 'Leeds' } }, // optional
399
- appId: 'my-newsletter',
400
- })
401
- // → { ok: true, pending: true } — tell the visitor to check their inbox
402
- ```
403
-
404
- - **The confirmation email is the app's own** (emails belong to the app that runs the flow — there is
405
- no platform default): a template in the collection, created and edited in the app's admin, e.g.
406
- `SL.template.create(collectionId, { name: 'Confirm your subscription', type: 'email', engine: 'liquid',
407
- subject: 'Please confirm your subscription', body: '…<a href="{{ action_url }}">Yes, subscribe me</a>…' })`.
408
- It gets `{{ action_url }}` (the confirm link), `{{ topics }}` (labels) and `{{ contact.firstName }}`.
409
- - **Form answers** (`fields`) are applied only once the address is confirmed, and only to the
410
- contact's empty fields — a sign-up can never overwrite someone else's details.
411
-
412
- - Topics must exist in the collection's comm settings. Give a newsletter topic
413
- `defaults.policy: 'opt-in'`: broadcasts on an opt-in topic only reach people who said yes
414
- (confirmed sign-ups), never the whole contact list.
415
- - Confirming turns on the email channel and the topics, and marks the address verified.
416
- - Don't use `contact.publicUpsert` + `comms.upsertConsent` for a signed-out form: consent calls act only
417
- for the signed-in contact. `comms.signup` is the signed-out path.
418
- - Set comm settings `signup.confirmedUrl` (https) to send people to your own "thanks" page after
419
- they confirm (`?confirmed=1`, or `0` for an expired link); otherwise SmartLinks shows a short page.
420
-
421
- ### Consent (Default)
422
-
423
- Record a contact's default channel and topic opt-ins. These calls (consent, preferences, subscribe,
424
- methods, push/email/SMS registration) act for the **signed-in** contact — `contactId` may be omitted
425
- to mean "me"; only collection admins may name another contact. An email registered here is verified
426
- only if it's the one the user signed in with; any other address is sent a confirmation link.
427
-
428
- ```typescript
429
- await comms.upsertConsent('collectionId', {
430
- contactId: 'contact_123',
431
- channels: { email: true, push: true },
432
- topics: { newsletter: true, critical: true },
433
- topicsByChannel: { email: { newsletter: true }, push: { critical: true } }
434
- })
435
- ```
436
-
437
- ### Preferences (Subject-Specific)
438
-
439
- Record consent specific to a product, proof, or other subject. Omit `subject` to update defaults.
440
-
441
- ```typescript
442
- await comms.upsertPreferences('collectionId', {
443
- contactId: 'contact_123',
444
- subject: { type: 'product', id: 'prod_1' },
445
- channels: { email: true },
446
- topics: { updates: true }
447
- })
448
- ```
449
-
450
- ### Subscribe / Unsubscribe (Subject)
451
-
452
- Manage subscriptions to a specific subject (e.g. product updates, proof alerts).
453
-
454
- ```typescript
455
- // Subscribe
456
- const { subscriptionId } = await comms.subscribe('collectionId', {
457
- contactId: 'contact_123',
458
- subject: { type: 'proof', id: 'prf_1', productId: 'prod_1' },
459
- subscribe: true,
460
- source: 'api'
461
- })
462
-
463
- // Unsubscribe (same call, subscribe: false)
464
- await comms.subscribe('collectionId', {
465
- contactId: 'contact_123',
466
- subject: { type: 'proof', id: 'prf_1', productId: 'prod_1' },
467
- subscribe: false,
468
- source: 'api'
469
- })
470
- ```
471
-
472
- ### Check Subscription
473
-
474
- ```typescript
475
- const r = await comms.checkSubscription('collectionId', {
476
- contactId: 'contact_123',
477
- subjectType: 'proof',
478
- subjectId: 'prf_1',
479
- productId: 'prod_1'
480
- })
481
- // r.subscribed === true | false
482
- ```
483
-
484
- ### Resolve Subscriptions
485
-
486
- Find contacts that are subscribed to a subject using identity hints.
487
-
488
- ```typescript
489
- const res = await comms.resolveSubscriptions('collectionId', {
490
- subject: { type: 'product', id: 'prod_1' },
491
- hints: { userId: 'user_1', email: 'user@example.com' }
492
- })
493
- ```
494
-
495
- ### List and Register Methods
496
-
497
- ```typescript
498
- // List registered methods for a contact
499
- const { items: methods } = await comms.listMethods('collectionId', {
500
- contactId: 'contact_123',
501
- type: 'email' // optional filter: 'email' | 'sms' | 'push'
502
- })
503
-
504
- // Register email
505
- await comms.registerEmail('collectionId', {
506
- contactId: 'contact_123',
507
- email: 'user@example.com'
508
- })
509
-
510
- // Register SMS
511
- await comms.registerSms('collectionId', {
512
- contactId: 'contact_123',
513
- phone: '+12065550100'
514
- })
515
- ```
516
-
517
- ### Unsubscribe (Public Link / One-Click)
518
-
519
- ```typescript
520
- await comms.unsubscribe('collectionId', {
521
- contactId: 'contact_123',
522
- topic: 'newsletter',
523
- token: '<sha256-hex-when-requireToken-is-true>'
524
- })
525
- ```
526
-
527
- Omit `topic` to unsubscribe from all. Omit `channel` to apply across all channels.
528
-
529
- ---
530
-
531
- ## Push Registration
532
-
533
- Web Push requires a service worker and the browser's Push API.
534
-
535
- ### 1. Fetch the VAPID Public Key
536
-
537
- ```typescript
538
- import { comms } from '@proveanything/smartlinks'
539
- const { publicKey } = await comms.getPushVapidPublicKey('collectionId')
540
- ```
541
-
542
- ### 2. Subscribe in the Service Worker
543
-
544
- ```typescript
545
- const registration = await navigator.serviceWorker.ready
546
- const subscription = await registration.pushManager.subscribe({
547
- userVisibleOnly: true,
548
- applicationServerKey: urlBase64ToUint8Array(publicKey),
549
- })
550
- const subJson = subscription.toJSON() as any
551
- ```
552
-
553
- ### 3. Register the Method
554
-
555
- ```typescript
556
- await comms.registerPush('collectionId', {
557
- contactId: 'contact_123',
558
- endpoint: subscription.endpoint,
559
- keys: subJson?.keys,
560
- meta: { userId: 'user_1' }
561
- })
562
- ```
563
-
564
- ### VAPID Key Utility
565
-
566
- ```typescript
567
- function urlBase64ToUint8Array(base64String: string): Uint8Array {
568
- const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
569
- const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')
570
- const rawData = atob(base64)
571
- const output = new Uint8Array(rawData.length)
572
- for (let i = 0; i < rawData.length; i++) output[i] = rawData.charCodeAt(i)
573
- return output
574
- }
575
- ```
576
-
577
- ---
578
-
579
- ## Analytics
580
-
581
- ### Query Events by User / Contact
582
-
583
- ```typescript
584
- const { items: events } = await comms.queryByUser('collectionId', {
585
- userId: 'user_123',
586
- limit: 100
587
- })
588
- ```
589
-
590
- ### Recipient IDs for a Source
591
-
592
- ```typescript
593
- const { items: ids } = await comms.queryRecipientIds('collectionId', {
594
- broadcastId: 'br_456'
595
- })
596
- ```
597
-
598
- ### Recipients Without an Interaction
599
-
600
- ```typescript
601
- const { items: didNot } = await comms.queryRecipientsWithoutInteraction('collectionId', {
602
- broadcastId: 'br_456',
603
- interactionId: 'survey-done'
604
- })
605
- ```
606
-
607
- ### Recipients With an Interaction
608
-
609
- ```typescript
610
- const { items: did } = await comms.queryRecipientsWithInteraction('collectionId', {
611
- broadcastId: 'br_456',
612
- interactionId: 'survey-done',
613
- includeOutcome: true // each item is { id, outcome } instead of an id
614
- })
615
- ```
616
-
617
- ### Log Events
618
-
619
- ```typescript
620
- // Single event
621
- await comms.logCommunicationEvent('collectionId', {
622
- eventType: 'opened',
623
- channel: 'email',
624
- contactId: 'contact_123'
625
- })
626
-
627
- // Bulk events (same params applied to all IDs)
628
- await comms.logBulkCommunicationEvents('collectionId', {
629
- params: { broadcastId: 'br_456', channel: 'email', eventType: 'delivered' },
630
- ids: ['contact_1', 'contact_2', 'contact_3'],
631
- idField: 'contactId'
632
- })
633
- ```
634
-
635
- ---
636
-
637
- ## End-to-End Admin Workflow
638
-
639
- A typical sequence from setup to delivery:
640
-
641
- ```typescript
642
- import { comms, broadcasts } from '@proveanything/smartlinks'
643
-
644
- // 1. Configure topics and unsubscribe rules
645
- await comms.patchSettings('collectionId', {
646
- unsub: { requireToken: true, secret: process.env.UNSUB_SECRET },
647
- topics: {
648
- newsletter: {
649
- label: 'Newsletter', classification: 'marketing',
650
- defaults: { policy: 'opt-in', channels: { email: true, push: true } },
651
- rules: { allowChannels: ['email', 'push', 'sms'], allowUnsubscribe: true }
652
- }
653
- }
654
- })
655
-
656
- // 2. Register contact methods (done at contact creation / profile update)
657
- await comms.registerEmail('collectionId', { contactId: 'c_123', email: 'user@example.com' })
658
-
659
- // 3. Record consent (done when user confirms opt-in)
660
- await comms.upsertConsent('collectionId', {
661
- contactId: 'c_123',
662
- channels: { email: true }, topics: { newsletter: true }
663
- })
664
-
665
- // 4a. Transactional: send a one-off triggered message
666
- const result = await comms.sendTransactional('collectionId', {
667
- contactId: 'c_123', templateId: 'order-confirmed',
668
- channel: 'email', props: { orderId: 'ORD-001' }
669
- })
670
-
671
- // 4b. Broadcast: preview → test → enqueue
672
- const preview = await broadcasts.preview('collectionId', 'br_spring', {
673
- channelOverride: 'email', hydrate: true, include: { product: true }
674
- })
675
- await broadcasts.sendTest('collectionId', 'br_spring', { contactId: 'c_123' })
676
- await broadcasts.send('collectionId', 'br_spring', { pageSize: 200, hydrate: true })
677
- ```
678
-
679
- ---
680
-
681
- ## Prerequisites
682
-
683
- | Feature | Requirement |
684
- |---------|-------------|
685
- | Email | SendGrid credentials (env or collection comms settings) |
686
- | Push | `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` env vars |
687
- | SMS | Twilio credentials (env or collection comms settings) |
688
- | Wallet | Google Wallet issuer + service account |
689
- | Hydration | Set `hydrate: true` and populate `include` on broadcast/transactional sends |
1
+ # Communications (Comms & Broadcasts)
2
+
3
+ This guide covers the full communications surface of the SDK: transactional sends, multi-channel broadcasts, consent management, push registration, and analytics.
4
+
5
+ ---
6
+
7
+ ## What You Can Do
8
+
9
+ - **Transactional Send** — Fire a single targeted message to one contact without creating a broadcast record.
10
+ - **Broadcasts** — Define and enqueue multi-channel campaigns (email, push, SMS, wallet); preview and test before sending.
11
+ - **Comms Settings** — Configure topics and unsubscribe behaviour per collection.
12
+ - **Consent & Preferences** — Record opt-ins/outs and per-subject preferences.
13
+ - **Method Registration** — Register email, SMS, and Web Push contact methods.
14
+ - **Analytics** — Query delivery events, recipient lists, and log custom events.
15
+
16
+ ---
17
+
18
+ ## Transactional Send
19
+
20
+ Sends a single message to one contact using a template. No broadcast record is created. The send is logged to the contact's communication history with `sourceType: 'transactional'`.
21
+
22
+ **Endpoint:** `POST /admin/collection/:collectionId/comm/send`
23
+
24
+ ```typescript
25
+ import { comms } from '@proveanything/smartlinks'
26
+ import type { TransactionalSendRequest } from '@proveanything/smartlinks'
27
+
28
+ const result = await comms.sendTransactional('collectionId', {
29
+ contactId: 'e4f2a1b0-...',
30
+ templateId: 'warranty-update',
31
+ channel: 'preferred', // 'email' | 'sms' | 'whatsapp' | 'push' | 'wallet' | 'preferred' (default)
32
+ props: { claimRef: 'CLM-0042', decision: 'approved' },
33
+ include: {
34
+ productId: 'prod-abc123', // hydrate product context into template
35
+ appCase: 'c9d1e2f3-...', // hydrate an app case record
36
+ },
37
+ ref: 'warranty-decision-notification', // arbitrary string for your own tracking
38
+ appId: 'warrantyApp',
39
+ })
40
+
41
+ if (result.ok) {
42
+ console.log(`Sent via ${result.channel}`, result.messageId)
43
+ } else {
44
+ console.error('Send failed:', result.error)
45
+ }
46
+ ```
47
+
48
+ ### Request Body
49
+
50
+ | Field | Type | Description |
51
+ |-------|------|-------------|
52
+ | `contactId` | `string` | **Required.** Contact to send to. |
53
+ | `templateId` | `string` | **Required.** Template to render. |
54
+ | `channel` | `'email' \| 'sms' \| 'whatsapp' \| 'push' \| 'wallet' \| 'preferred'` | Channel to send on. `'preferred'` (default) picks the contact's best available channel. |
55
+ | `props` | `Record<string, unknown>` | Extra variables merged into template rendering. |
56
+ | `include` | object | Hydration flags — see table below. |
57
+ | `ref` | `string` | Arbitrary reference string stored with the event. |
58
+ | `appId` | `string` | App identifier, used for context/logging. |
59
+ | `attach` | `EmailAttachmentSpec[]` | Files on the email — see [Attachments](#attachments). |
60
+
61
+ **`include` fields:**
62
+
63
+ | Field | Type | Description |
64
+ |-------|------|-------------|
65
+ | `collection` | `boolean` | Include collection data in template context. |
66
+ | `productId` | `string` | Hydrate a specific product. |
67
+ | `proofId` | `string` | Hydrate a specific proof. |
68
+ | `user` | `boolean` | Include the requesting user's data. |
69
+ | `appCase` | `string` | Hydrate an app case record by ID. |
70
+ | `appThread` | `string` | Hydrate an app thread record by ID. |
71
+ | `appRecord` | `string` | Hydrate an app record by ID. |
72
+
73
+ ### Response
74
+
75
+ ```typescript
76
+ // Success
77
+ { ok: true; channel: 'email' | 'sms' | 'whatsapp' | 'push' | 'wallet'; messageId?: string; attachmentsLeftOut?: string[] }
78
+
79
+ // Failure
80
+ { ok: false; error: string }
81
+ ```
82
+
83
+ ### Attachments
84
+
85
+ `attach` puts files on the email (email only — ignored when the send goes by text or push). At most 5
86
+ files and 10 MB in all; PDF, Word / Excel / PowerPoint, images, text, CSV and calendar files.
87
+
88
+ ```typescript
89
+ await comms.sendTransactional(collectionId, {
90
+ contactId, templateId: 'booking-confirmed', appId: 'appointment-booking',
91
+ include: { booking: bookingId },
92
+ attach: [
93
+ 'calendar', // the booking's .ics invite (needs include.booking + appId)
94
+ { asset: 'a1b2c3' }, // a file uploaded to the collection's assets
95
+ { function: 'receiptPdf' }, // the app's own server function makes it
96
+ { filename: 'Quote.pdf', contentType: 'application/pdf', content: base64 }, // a file you made
97
+ { filename: 'Report.pdf', file: signedUrl }, // a private file you made (pdf.create return: 'signedUrl')
98
+ ],
99
+ })
100
+ ```
101
+
102
+ A malformed list is refused (`transactional.attach_invalid`). A file that can't be made at send time
103
+ (a missing asset, a function that fails) is left out and listed in `attachmentsLeftOut` — the email
104
+ still goes. The request body is capped at 10 MB, so for big files make a private file and pass `file`.
105
+ `bookings.message` takes the same `attach` (`'calendar'` is each person's own booking).
106
+
107
+ ---
108
+
109
+ ## Messaging one person from an app
110
+
111
+ Every app sends through the platform: a booking reminder, a cancellation, an event update, "we got your
112
+ entry". You never set up email or SMS yourself. Each message:
113
+ - goes out on the person's preferred channel, or one you name;
114
+ - respects their opt-outs;
115
+ - is logged with your app;
116
+ - shows in the Messages app and on the contact's Activity in the CRM.
117
+
118
+ **From server code** (`sl:messages:write`):
119
+
120
+ ```js
121
+ const out = await ctx.sl.messages.send({
122
+ to: 'caller', // or contactId
123
+ templateId: 'tpl_booking_cancelled', // or message: { subject, body, sms? }
124
+ include: { booking: bookingId }, // hydrates {{ booking }}, as comm/send
125
+ about: { type: 'booking', id: bookingId, view: 'booking', params: { bookingId }, label: 'Sat 3pm' },
126
+ })
127
+ if (!out.ok) ctx.log('not sent', { reason: out.reason }) // 'opted_out' | 'no_channel' | 'no_contact' | 'template_not_found'
128
+ ```
129
+
130
+ **From an admin screen:** `SL.comms.sendTransactional(collectionId, { contactId, message | templateId, about, category: 'service', appId })`.
131
+
132
+ - **Service messages only.** A confirmation, a reminder, a cancellation or an update. Marketing goes out
133
+ as a campaign, with its opt-in and unsubscribe.
134
+ - **Someone who can't be reached is an answer, not an error.** `ctx.sl.messages.send` returns
135
+ `{ ok: false, reason }`; only a real failure throws.
136
+ - **A typed message** is plain text with Liquid (`{{ contact.firstName }}`), sent exactly like a template:
137
+ `{ subject, body, sms? }`.
138
+
139
+ ### What a message is about
140
+
141
+ `about: { appId?, type, id, view?, params?, label? }` names the record the message was sent for, and the
142
+ admin screen that shows it. `view` and `params` are one of your manifest `adminViews`
143
+ ([admin-views.md](admin-views.md)).
144
+ - **Where it shows:** the Message log shows "Bookings · Sat 3pm", and it is a link to your screen. A reply
145
+ opens a conversation that links to the same record.
146
+ - **Defaults:** `appId` defaults to your app.
147
+ - **Ids only:** never put content in it.
148
+ - **Reading it back:** the log can be filtered by it: `GET /admin/collection/:id/comm/query/events?aboutType=booking&aboutId=B-123`,
149
+ or `app=<appId>` for everything your app sent.
150
+
151
+ ## Broadcasts
152
+
153
+ Broadcasts are multi-channel campaigns defined and managed under a collection. Create a broadcast record in the platform first, then use the SDK to preview, test, and enqueue.
154
+
155
+ **Import:**
156
+ ```typescript
157
+ import { broadcasts } from '@proveanything/smartlinks'
158
+ import type { BroadcastSendRequest } from '@proveanything/smartlinks'
159
+ ```
160
+
161
+ ### Preview
162
+
163
+ Render a broadcast template for a given channel without sending.
164
+
165
+ ```typescript
166
+ const preview = await broadcasts.preview('collectionId', 'broadcastId', {
167
+ email: 'user@example.com', // optional: override recipient email for preview
168
+ channelOverride: 'push', // force a specific channel
169
+ props: { productId: 'prod_123' },
170
+ hydrate: true,
171
+ include: { product: true, proof: true }
172
+ })
173
+ // preview.channel — which channel was rendered
174
+ // preview.payload / preview.subject / preview.body — channel-specific render output
175
+ ```
176
+
177
+ ### Test Send
178
+
179
+ Send a single test message to a contact.
180
+
181
+ ```typescript
182
+ await broadcasts.sendTest('collectionId', 'broadcastId', {
183
+ contactId: 'contact_123',
184
+ props: { promo: 'JAN' }
185
+ })
186
+ ```
187
+
188
+ ### Enqueue Production Send
189
+
190
+ Enqueue a background send to all recipients. When `channel` is omitted the broadcast's own mode setting drives channel selection:
191
+ - `preferred` — picks the best single channel per recipient.
192
+ - `channels` / `all` — sends on every enabled channel.
193
+
194
+ ```typescript
195
+ const body: BroadcastSendRequest = {
196
+ pageSize: 200,
197
+ hydrate: true,
198
+ include: { product: true, proof: true, user: true }
199
+ }
200
+ await broadcasts.send('collectionId', 'broadcastId', body)
201
+ ```
202
+
203
+ ### Manual Send
204
+
205
+ ```typescript
206
+ await broadcasts.sendManual('collectionId', 'broadcastId', { /* overrides */ })
207
+ ```
208
+
209
+ ### Topic Targeting and Consent
210
+
211
+ A broadcast must declare a `topic` under `broadcast.data.topic` (e.g. `newsletter`, `critical`). The topic key must match one defined in your collection's comms settings, and consent enforcement uses it at send time.
212
+
213
+ Consent resolution order (per recipient, per channel):
214
+ 1. `preferences._default.topicsByChannel[channel][topic]`
215
+ 2. `preferences._default.channels[channel]`
216
+ 3. `preferences._default.topics[topic]`
217
+ 4. Subject-specific preferences (when hydrating a subject context)
218
+
219
+ Minimal broadcast data shape (`attach` is optional — uploaded assets only, the same files on every email):
220
+ ```json
221
+ {
222
+ "data": {
223
+ "topic": "newsletter",
224
+ "attach": [{ "asset": "a1b2c3" }],
225
+ "channelSettings": {
226
+ "mode": "preferred",
227
+ "channels": [
228
+ { "channel": "email", "enabled": true, "priority": 1, "templateId": "tmpl_newsletter_email" },
229
+ { "channel": "push", "enabled": true, "priority": 2 }
230
+ ]
231
+ }
232
+ }
233
+ }
234
+ ```
235
+
236
+ ### Append Recipients and Events
237
+
238
+ ```typescript
239
+ // Append a single delivery event
240
+ await broadcasts.append('collectionId', {
241
+ broadcastId: 'broadcastId',
242
+ contactId: 'contact_123',
243
+ channel: 'email',
244
+ eventType: 'delivered',
245
+ outcome: 'success'
246
+ })
247
+
248
+ // Append bulk events
249
+ await broadcasts.appendBulk('collectionId', {
250
+ params: { broadcastId: 'broadcastId', channel: 'push' },
251
+ ids: ['contact_1', 'contact_2'],
252
+ idField: 'contactId'
253
+ })
254
+
255
+ // List recipients
256
+ const recips = await broadcasts.recipients('collectionId', 'broadcastId', { limit: 50 })
257
+ recips.items // the contacts on this page
258
+ recips.count // how many in all
259
+ recips.nextCursor // pass back as `cursor` for the next page; null on the last
260
+ ```
261
+
262
+ ---
263
+
264
+ ## Admin Comms Settings
265
+
266
+ Configure unsubscribe behaviour and topics per collection.
267
+
268
+ **Base path:** `admin/collection/:collectionId/comm.settings`
269
+
270
+ ### Get Settings
271
+
272
+ ```typescript
273
+ import { comms } from '@proveanything/smartlinks'
274
+ const { settings } = await comms.getSettings('collectionId', { includeSecret: true })
275
+ // settings.unsub — { requireToken, hasSecret }
276
+ // settings.topics — map of topic key → config
277
+ ```
278
+
279
+ ### Patch Settings
280
+
281
+ ```typescript
282
+ await comms.patchSettings('collectionId', {
283
+ unsub: { requireToken: true, secret: '<your-secret>' },
284
+ topics: { /* ... */ }
285
+ })
286
+ ```
287
+
288
+ To clear the unsubscribe secret, send `secret: ''`.
289
+
290
+ ### Topics Config
291
+
292
+ Each topic key maps to a config object:
293
+
294
+ ```json
295
+ {
296
+ "newsletter": {
297
+ "label": "Newsletter",
298
+ "description": "Occasional updates and stories",
299
+ "classification": "marketing",
300
+ "defaults": {
301
+ "policy": "opt-in",
302
+ "byChannel": { "email": "opt-in", "push": "opt-in" },
303
+ "channels": { "email": true, "push": true, "sms": false }
304
+ },
305
+ "rules": {
306
+ "allowChannels": ["email", "sms", "push"],
307
+ "allowUnsubscribe": true
308
+ },
309
+ "required": false
310
+ },
311
+ "critical": {
312
+ "label": "Critical Notices",
313
+ "classification": "transactional",
314
+ "defaults": {
315
+ "policy": "opt-out",
316
+ "channels": { "email": true, "push": true }
317
+ },
318
+ "rules": { "allowChannels": ["email", "push"], "allowUnsubscribe": false },
319
+ "required": true
320
+ }
321
+ }
322
+ ```
323
+
324
+ - `classification`: `'transactional'` or `'marketing'` — used by the UI when no explicit policy is set.
325
+ - `defaults.policy`: `'opt-in'` or `'opt-out'` — fallback policy for channels not overridden by `byChannel`.
326
+ - `required: true` and `rules.allowUnsubscribe: false` — use for critical/mandatory messages.
327
+
328
+ ### Unsubscribe Tokens
329
+
330
+ If `unsub.requireToken` is true, public unsubscribe calls must include a `token` query param.
331
+
332
+ Token generation (topic opt-out):
333
+ ```
334
+ basis = "${contactId}:${topic}"
335
+ token = sha256(basis + ":" + unsub.secret) // hex
336
+ ```
337
+
338
+ Token generation (channel opt-out):
339
+ ```
340
+ basis = "${contactId}:channel:${channel}"
341
+ token = sha256(basis + ":" + unsub.secret)
342
+ ```
343
+
344
+ Browser helper:
345
+ ```typescript
346
+ async function sha256Hex(input: string): Promise<string> {
347
+ const data = new TextEncoder().encode(input)
348
+ const hash = await crypto.subtle.digest('SHA-256', data)
349
+ return Array.from(new Uint8Array(hash))
350
+ .map(b => b.toString(16).padStart(2, '0'))
351
+ .join('')
352
+ }
353
+
354
+ const token = await sha256Hex(`${contactId}:${topic}:${secret}`)
355
+ ```
356
+
357
+ ---
358
+
359
+ ## Public Comms API
360
+
361
+ All public endpoints live under `public/collection/:collectionId/comm/*` and do not require an API key.
362
+
363
+ ### Get Topics
364
+
365
+ ```typescript
366
+ const { topics } = await comms.getPublicTopics('collectionId')
367
+ ```
368
+
369
+ Each topic carries UI metadata:
370
+ - `classification`: `'transactional'` | `'marketing'`
371
+ - `defaults.policy`: `'opt-in'` | `'opt-out'`
372
+ - `defaults.byChannel[channel]`: per-channel override
373
+
374
+ Helper to resolve effective policy for a toggle UI:
375
+ ```typescript
376
+ type Policy = 'opt-in' | 'opt-out'
377
+
378
+ function effectivePolicy(topic: any, channel: 'email' | 'sms' | 'push' | 'wallet'): Policy {
379
+ return (
380
+ topic?.defaults?.byChannel?.[channel] ??
381
+ topic?.defaults?.policy ??
382
+ (topic?.classification === 'marketing' ? 'opt-in' : 'opt-out')
383
+ ) as Policy
384
+ }
385
+ ```
386
+
387
+ ### Sign-up with double opt-in (newsletters)
388
+
389
+ For a sign-up form — works signed out. SmartLinks emails the address a "confirm your subscription"
390
+ link; nothing is consented until it's clicked. The answer is always the same, so the form can't be
391
+ used to find out who's registered.
392
+
393
+ ```typescript
394
+ await comms.signup('collectionId', {
395
+ email: 'sam@example.com',
396
+ topics: ['newsletter'],
397
+ templateId: config.confirmationTemplateId, // YOUR confirmation email (required)
398
+ fields: { firstName: 'Sam', customFields: { favouriteStore: 'Leeds' } }, // optional
399
+ appId: 'my-newsletter',
400
+ })
401
+ // → { ok: true, pending: true } — tell the visitor to check their inbox
402
+ ```
403
+
404
+ - **The confirmation email is the app's own** (emails belong to the app that runs the flow — there is
405
+ no platform default): a template in the collection, created and edited in the app's admin, e.g.
406
+ `SL.template.create(collectionId, { name: 'Confirm your subscription', type: 'email', engine: 'liquid',
407
+ subject: 'Please confirm your subscription', body: '…<a href="{{ action_url }}">Yes, subscribe me</a>…' })`.
408
+ It gets `{{ action_url }}` (the confirm link), `{{ topics }}` (labels) and `{{ contact.firstName }}`.
409
+ - **Form answers** (`fields`) are applied only once the address is confirmed, and only to the
410
+ contact's empty fields — a sign-up can never overwrite someone else's details.
411
+
412
+ - Topics must exist in the collection's comm settings. Give a newsletter topic
413
+ `defaults.policy: 'opt-in'`: broadcasts on an opt-in topic only reach people who said yes
414
+ (confirmed sign-ups), never the whole contact list.
415
+ - Confirming turns on the email channel and the topics, and marks the address verified.
416
+ - Don't use `contact.publicUpsert` + `comms.upsertConsent` for a signed-out form: consent calls act only
417
+ for the signed-in contact. `comms.signup` is the signed-out path.
418
+ - Set comm settings `signup.confirmedUrl` (https) to send people to your own "thanks" page after
419
+ they confirm (`?confirmed=1`, or `0` for an expired link); otherwise SmartLinks shows a short page.
420
+
421
+ ### Consent (Default)
422
+
423
+ Record a contact's default channel and topic opt-ins. These calls (consent, preferences, subscribe,
424
+ methods, push/email/SMS registration) act for the **signed-in** contact — `contactId` may be omitted
425
+ to mean "me"; only collection admins may name another contact. An email registered here is verified
426
+ only if it's the one the user signed in with; any other address is sent a confirmation link.
427
+
428
+ ```typescript
429
+ await comms.upsertConsent('collectionId', {
430
+ contactId: 'contact_123',
431
+ channels: { email: true, push: true },
432
+ topics: { newsletter: true, critical: true },
433
+ topicsByChannel: { email: { newsletter: true }, push: { critical: true } }
434
+ })
435
+ ```
436
+
437
+ ### Preferences (Subject-Specific)
438
+
439
+ Record consent specific to a product, proof, or other subject. Omit `subject` to update defaults.
440
+
441
+ ```typescript
442
+ await comms.upsertPreferences('collectionId', {
443
+ contactId: 'contact_123',
444
+ subject: { type: 'product', id: 'prod_1' },
445
+ channels: { email: true },
446
+ topics: { updates: true }
447
+ })
448
+ ```
449
+
450
+ ### Subscribe / Unsubscribe (Subject)
451
+
452
+ Manage subscriptions to a specific subject (e.g. product updates, proof alerts).
453
+
454
+ ```typescript
455
+ // Subscribe
456
+ const { subscriptionId } = await comms.subscribe('collectionId', {
457
+ contactId: 'contact_123',
458
+ subject: { type: 'proof', id: 'prf_1', productId: 'prod_1' },
459
+ subscribe: true,
460
+ source: 'api'
461
+ })
462
+
463
+ // Unsubscribe (same call, subscribe: false)
464
+ await comms.subscribe('collectionId', {
465
+ contactId: 'contact_123',
466
+ subject: { type: 'proof', id: 'prf_1', productId: 'prod_1' },
467
+ subscribe: false,
468
+ source: 'api'
469
+ })
470
+ ```
471
+
472
+ ### Check Subscription
473
+
474
+ ```typescript
475
+ const r = await comms.checkSubscription('collectionId', {
476
+ contactId: 'contact_123',
477
+ subjectType: 'proof',
478
+ subjectId: 'prf_1',
479
+ productId: 'prod_1'
480
+ })
481
+ // r.subscribed === true | false
482
+ ```
483
+
484
+ ### Resolve Subscriptions
485
+
486
+ Find contacts that are subscribed to a subject using identity hints.
487
+
488
+ ```typescript
489
+ const res = await comms.resolveSubscriptions('collectionId', {
490
+ subject: { type: 'product', id: 'prod_1' },
491
+ hints: { userId: 'user_1', email: 'user@example.com' }
492
+ })
493
+ ```
494
+
495
+ ### List and Register Methods
496
+
497
+ ```typescript
498
+ // List registered methods for a contact
499
+ const { items: methods } = await comms.listMethods('collectionId', {
500
+ contactId: 'contact_123',
501
+ type: 'email' // optional filter: 'email' | 'sms' | 'push'
502
+ })
503
+
504
+ // Register email
505
+ await comms.registerEmail('collectionId', {
506
+ contactId: 'contact_123',
507
+ email: 'user@example.com'
508
+ })
509
+
510
+ // Register SMS
511
+ await comms.registerSms('collectionId', {
512
+ contactId: 'contact_123',
513
+ phone: '+12065550100'
514
+ })
515
+ ```
516
+
517
+ ### Unsubscribe (Public Link / One-Click)
518
+
519
+ ```typescript
520
+ await comms.unsubscribe('collectionId', {
521
+ contactId: 'contact_123',
522
+ topic: 'newsletter',
523
+ token: '<sha256-hex-when-requireToken-is-true>'
524
+ })
525
+ ```
526
+
527
+ Omit `topic` to unsubscribe from all. Omit `channel` to apply across all channels.
528
+
529
+ ---
530
+
531
+ ## Push Registration
532
+
533
+ Web Push requires a service worker and the browser's Push API.
534
+
535
+ ### 1. Fetch the VAPID Public Key
536
+
537
+ ```typescript
538
+ import { comms } from '@proveanything/smartlinks'
539
+ const { publicKey } = await comms.getPushVapidPublicKey('collectionId')
540
+ ```
541
+
542
+ ### 2. Subscribe in the Service Worker
543
+
544
+ ```typescript
545
+ const registration = await navigator.serviceWorker.ready
546
+ const subscription = await registration.pushManager.subscribe({
547
+ userVisibleOnly: true,
548
+ applicationServerKey: urlBase64ToUint8Array(publicKey),
549
+ })
550
+ const subJson = subscription.toJSON() as any
551
+ ```
552
+
553
+ ### 3. Register the Method
554
+
555
+ ```typescript
556
+ await comms.registerPush('collectionId', {
557
+ contactId: 'contact_123',
558
+ endpoint: subscription.endpoint,
559
+ keys: subJson?.keys,
560
+ meta: { userId: 'user_1' }
561
+ })
562
+ ```
563
+
564
+ ### VAPID Key Utility
565
+
566
+ ```typescript
567
+ function urlBase64ToUint8Array(base64String: string): Uint8Array {
568
+ const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
569
+ const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')
570
+ const rawData = atob(base64)
571
+ const output = new Uint8Array(rawData.length)
572
+ for (let i = 0; i < rawData.length; i++) output[i] = rawData.charCodeAt(i)
573
+ return output
574
+ }
575
+ ```
576
+
577
+ ---
578
+
579
+ ## Analytics
580
+
581
+ ### Query Events by User / Contact
582
+
583
+ ```typescript
584
+ const { items: events } = await comms.queryByUser('collectionId', {
585
+ userId: 'user_123',
586
+ limit: 100
587
+ })
588
+ ```
589
+
590
+ ### Recipient IDs for a Source
591
+
592
+ ```typescript
593
+ const { items: ids } = await comms.queryRecipientIds('collectionId', {
594
+ broadcastId: 'br_456'
595
+ })
596
+ ```
597
+
598
+ ### Recipients Without an Interaction
599
+
600
+ ```typescript
601
+ const { items: didNot } = await comms.queryRecipientsWithoutInteraction('collectionId', {
602
+ broadcastId: 'br_456',
603
+ interactionId: 'survey-done'
604
+ })
605
+ ```
606
+
607
+ ### Recipients With an Interaction
608
+
609
+ ```typescript
610
+ const { items: did } = await comms.queryRecipientsWithInteraction('collectionId', {
611
+ broadcastId: 'br_456',
612
+ interactionId: 'survey-done',
613
+ includeOutcome: true // each item is { id, outcome } instead of an id
614
+ })
615
+ ```
616
+
617
+ ### Log Events
618
+
619
+ ```typescript
620
+ // Single event
621
+ await comms.logCommunicationEvent('collectionId', {
622
+ eventType: 'opened',
623
+ channel: 'email',
624
+ contactId: 'contact_123'
625
+ })
626
+
627
+ // Bulk events (same params applied to all IDs)
628
+ await comms.logBulkCommunicationEvents('collectionId', {
629
+ params: { broadcastId: 'br_456', channel: 'email', eventType: 'delivered' },
630
+ ids: ['contact_1', 'contact_2', 'contact_3'],
631
+ idField: 'contactId'
632
+ })
633
+ ```
634
+
635
+ ---
636
+
637
+ ## End-to-End Admin Workflow
638
+
639
+ A typical sequence from setup to delivery:
640
+
641
+ ```typescript
642
+ import { comms, broadcasts } from '@proveanything/smartlinks'
643
+
644
+ // 1. Configure topics and unsubscribe rules
645
+ await comms.patchSettings('collectionId', {
646
+ unsub: { requireToken: true, secret: process.env.UNSUB_SECRET },
647
+ topics: {
648
+ newsletter: {
649
+ label: 'Newsletter', classification: 'marketing',
650
+ defaults: { policy: 'opt-in', channels: { email: true, push: true } },
651
+ rules: { allowChannels: ['email', 'push', 'sms'], allowUnsubscribe: true }
652
+ }
653
+ }
654
+ })
655
+
656
+ // 2. Register contact methods (done at contact creation / profile update)
657
+ await comms.registerEmail('collectionId', { contactId: 'c_123', email: 'user@example.com' })
658
+
659
+ // 3. Record consent (done when user confirms opt-in)
660
+ await comms.upsertConsent('collectionId', {
661
+ contactId: 'c_123',
662
+ channels: { email: true }, topics: { newsletter: true }
663
+ })
664
+
665
+ // 4a. Transactional: send a one-off triggered message
666
+ const result = await comms.sendTransactional('collectionId', {
667
+ contactId: 'c_123', templateId: 'order-confirmed',
668
+ channel: 'email', props: { orderId: 'ORD-001' }
669
+ })
670
+
671
+ // 4b. Broadcast: preview → test → enqueue
672
+ const preview = await broadcasts.preview('collectionId', 'br_spring', {
673
+ channelOverride: 'email', hydrate: true, include: { product: true }
674
+ })
675
+ await broadcasts.sendTest('collectionId', 'br_spring', { contactId: 'c_123' })
676
+ await broadcasts.send('collectionId', 'br_spring', { pageSize: 200, hydrate: true })
677
+ ```
678
+
679
+ ---
680
+
681
+ ## Prerequisites
682
+
683
+ | Feature | Requirement |
684
+ |---------|-------------|
685
+ | Email | SendGrid credentials (env or collection comms settings) |
686
+ | Push | `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` env vars |
687
+ | SMS | Twilio credentials (env or collection comms settings) |
688
+ | Wallet | Google Wallet issuer + service account |
689
+ | Hydration | Set `hydrate: true` and populate `include` on broadcast/transactional sends |