@proveanything/smartlinks 2.1.39 → 2.1.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +754 -754
- package/dist/README.md +573 -573
- package/dist/adminCardsView.js +55 -55
- package/dist/adminViews.d.ts +1 -1
- package/dist/adminViews.js +3 -1
- package/dist/ai-tools.d.ts +2 -1
- package/dist/ai-tools.js +3 -0
- package/dist/api/ai.d.ts +2 -21
- package/dist/api/ai.js +0 -35
- package/dist/api/collection.d.ts +8 -1
- package/dist/api/collection.js +10 -0
- package/dist/api/index.d.ts +1 -0
- package/dist/api/index.js +1 -0
- package/dist/api/knowledge.d.ts +64 -0
- package/dist/api/knowledge.js +97 -0
- package/dist/baseline.css +194 -194
- package/dist/docs/API_SUMMARY.md +1046 -964
- package/dist/docs/admin-cards.md +189 -189
- package/dist/docs/admin-views.md +257 -255
- package/dist/docs/agent-tools.md +156 -156
- package/dist/docs/ai-tools-and-skills.md +180 -180
- package/dist/docs/ai.md +1721 -1834
- package/dist/docs/analytics.md +39 -39
- package/dist/docs/app-data-storage.md +277 -277
- package/dist/docs/app-docs.md +73 -73
- package/dist/docs/app-manifest.md +852 -852
- package/dist/docs/app-records-pattern.md +388 -388
- package/dist/docs/appConfig.md +550 -550
- package/dist/docs/assistant-apps.md +172 -172
- package/dist/docs/assistant-context.md +119 -119
- package/dist/docs/bookings.md +442 -442
- package/dist/docs/comms.md +686 -686
- package/dist/docs/connectors.md +340 -340
- package/dist/docs/css-baseline.md +133 -133
- package/dist/docs/customer-guide.md +70 -70
- package/dist/docs/deploying-apps.md +340 -340
- package/dist/docs/entitlements.md +90 -90
- package/dist/docs/files.md +69 -69
- package/dist/docs/host-dependency-contract.md +210 -210
- package/dist/docs/integrations.md +322 -322
- package/dist/docs/interactions.md +545 -545
- package/dist/docs/item-context.md +181 -181
- package/dist/docs/knowledge.md +102 -0
- package/dist/docs/lots.md +111 -111
- package/dist/docs/loyalty.md +352 -352
- package/dist/docs/members.md +182 -182
- package/dist/docs/mobile-admin-container.md +693 -693
- package/dist/docs/operations.md +281 -281
- package/dist/docs/overview.md +482 -482
- package/dist/docs/proof-comms-triggers.md +142 -142
- package/dist/docs/proof-ownership-transfer.md +155 -155
- package/dist/docs/proof-product-data-scoping.md +462 -462
- package/dist/docs/proof-share-grants.md +305 -305
- package/dist/docs/realtime.md +138 -138
- package/dist/docs/records-admin-pattern.md +304 -304
- package/dist/docs/standard-query.md +187 -187
- package/dist/docs/tag-codes.md +97 -97
- package/dist/docs/theme-tokens.md +252 -252
- package/dist/docs/wallet-passes.md +107 -107
- package/dist/docs/websites.md +123 -123
- package/dist/openapi.yaml +320 -306
- package/dist/theme-boot.js +78 -78
- package/dist/theme.css +75 -75
- package/dist/types/ai.d.ts +9 -91
- package/dist/types/appManifest.d.ts +21 -0
- package/dist/types/collection.d.ts +26 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +1 -0
- package/dist/types/knowledge.d.ts +120 -0
- package/dist/types/knowledge.js +2 -0
- package/docs/API_SUMMARY.md +1046 -964
- package/docs/admin-cards.md +189 -189
- package/docs/admin-views.md +257 -255
- package/docs/agent-tools.md +156 -156
- package/docs/ai-tools-and-skills.md +180 -180
- package/docs/ai.md +1721 -1834
- package/docs/analytics.md +39 -39
- package/docs/app-data-storage.md +277 -277
- package/docs/app-docs.md +73 -73
- package/docs/app-manifest.md +852 -852
- package/docs/app-records-pattern.md +388 -388
- package/docs/appConfig.md +550 -550
- package/docs/assistant-apps.md +172 -172
- package/docs/assistant-context.md +119 -119
- package/docs/bookings.md +442 -442
- package/docs/comms.md +686 -686
- package/docs/connectors.md +340 -340
- package/docs/css-baseline.md +133 -133
- package/docs/customer-guide.md +70 -70
- package/docs/deploying-apps.md +340 -340
- package/docs/entitlements.md +90 -90
- package/docs/files.md +69 -69
- package/docs/host-dependency-contract.md +210 -210
- package/docs/integrations.md +322 -322
- package/docs/interactions.md +545 -545
- package/docs/item-context.md +181 -181
- package/docs/knowledge.md +102 -0
- package/docs/lots.md +111 -111
- package/docs/loyalty.md +352 -352
- package/docs/members.md +182 -182
- package/docs/mobile-admin-container.md +693 -693
- package/docs/operations.md +281 -281
- package/docs/overview.md +482 -482
- package/docs/proof-comms-triggers.md +142 -142
- package/docs/proof-ownership-transfer.md +155 -155
- package/docs/proof-product-data-scoping.md +462 -462
- package/docs/proof-share-grants.md +305 -305
- package/docs/realtime.md +138 -138
- package/docs/standard-query.md +187 -187
- package/docs/tag-codes.md +97 -97
- package/docs/theme-lookbook.v1.json +120 -120
- package/docs/theme-tokens.md +252 -252
- package/docs/wallet-passes.md +107 -107
- package/docs/websites.md +123 -123
- package/openapi.yaml +320 -306
- package/package.json +87 -87
- package/scripts/headless-check.mjs +87 -87
- package/scripts/lib/bare-imports.mjs +57 -57
- package/scripts/lib/keyed-app-data.mjs +21 -21
- package/scripts/publish.mjs +272 -272
- package/scripts/register-release.mjs +91 -91
package/README.md
CHANGED
|
@@ -1,755 +1,755 @@
|
|
|
1
|
-
# @proveanything/smartlinks
|
|
2
|
-
|
|
3
|
-
Official JavaScript/TypeScript SDK for the Smartlinks API.
|
|
4
|
-
|
|
5
|
-
Build Smartlinks-powered apps in Node.js or the browser: list collections and products, authenticate users, manage assets and attestations, and call admin endpoints with a clean, typed API.
|
|
6
|
-
|
|
7
|
-
• TypeScript-first types and intellisense
|
|
8
|
-
• Works in Node.js and modern browsers
|
|
9
|
-
• Simple auth helpers (login, verify token, request admin/public JWTs)
|
|
10
|
-
• Rich resources: collections, products, proofs, assets, attestations, batches, variants, AI, and more
|
|
11
|
-
• Optional iframe proxy mode for embedded apps
|
|
12
|
-
|
|
13
|
-
## Start here
|
|
14
|
-
|
|
15
|
-
If you're new to the SDK, this is the easiest path:
|
|
16
|
-
|
|
17
|
-
1. Initialize the SDK with your SmartLinks API base URL.
|
|
18
|
-
2. Pick the guide that matches what you're building.
|
|
19
|
-
3. Copy one of the working examples and adapt it to your collection/product IDs.
|
|
20
|
-
|
|
21
|
-
### Pick a guide
|
|
22
|
-
|
|
23
|
-
- [docs/ai.md](docs/ai.md) — AI responses, chat, RAG, voice, streaming, and product assistants
|
|
24
|
-
- [docs/analytics.md](docs/analytics.md) — fire-and-forget web analytics, tag scan telemetry, and dashboard queries
|
|
25
|
-
- [docs/proof-share-grants.md](docs/proof-share-grants.md) — delegated, scoped, revocable share links for a proof (album sharing, guest comments, proof-of-ownership)
|
|
26
|
-
- [docs/assets.md](docs/assets.md) — asset uploads, including resumable uploads for large files (video)
|
|
27
|
-
- [docs/files.md](docs/files.md) — temporary files, fetching web pages and documents once, and extracting text, Markdown, OCR or fields from them
|
|
28
|
-
- [docs/app-objects.md](docs/app-objects.md) — cases, threads (comments), and records
|
|
29
|
-
- [docs/translations.md](docs/translations.md) — runtime translation lookup, browser-side caching, and translation admin flows
|
|
30
|
-
- [docs/widgets.md](docs/widgets.md) — embeddable React components
|
|
31
|
-
- [docs/realtime.md](docs/realtime.md) — subscriptions and live updates
|
|
32
|
-
- [docs/admin-cards.md](docs/admin-cards.md) — cards on the collection's Studio dashboard
|
|
33
|
-
- [docs/iframe-responder.md](docs/iframe-responder.md) — iframe integration and parent/child messaging
|
|
34
|
-
- [docs/utils.md](docs/utils.md) — helper utilities and portal path generation
|
|
35
|
-
|
|
36
|
-
### Most common use cases
|
|
37
|
-
|
|
38
|
-
- **Build an AI assistant** → start with [docs/ai.md](docs/ai.md)
|
|
39
|
-
- **Track page views, clicks, or tag scans** → start with [docs/analytics.md](docs/analytics.md)
|
|
40
|
-
- **Translate dynamic content with local browser caching** → start with [docs/translations.md](docs/translations.md)
|
|
41
|
-
- **Share a proof / album by link, or add guest comments** → start with [docs/proof-share-grants.md](docs/proof-share-grants.md)
|
|
42
|
-
- **Upload large video with resume-on-reconnect** → see [Resumable uploads](docs/assets.md#resumable-uploads-large-files-eg-video)
|
|
43
|
-
- **Fetch collections/products** → see [Quick start](README.md#quick-start)
|
|
44
|
-
- **Authenticate admins or end users** → see [Authentication](README.md#authentication)
|
|
45
|
-
- **Upload and manage files** → see [Assets](README.md#assets)
|
|
46
|
-
- **Browse the full surface area** → use [API_SUMMARY.md](docs/API_SUMMARY.md) as reference
|
|
47
|
-
|
|
48
|
-
For the full list of functions and types, see the API summary:
|
|
49
|
-
→ [API Summary](docs/API_SUMMARY.md)
|
|
50
|
-
|
|
51
|
-
**Documentation:**
|
|
52
|
-
- [AI & Chat Completions](docs/ai.md) - Chat completions, RAG, voice integration
|
|
53
|
-
- [Analytics](docs/analytics.md) - Fire-and-forget analytics tracking, tag scans, and dashboard queries
|
|
54
|
-
- [Proof Share Grants](docs/proof-share-grants.md) - Delegated, revocable share links; guest comments; proof-of-ownership
|
|
55
|
-
- [Assets](docs/assets.md) - Uploads, resumable large-file uploads, token uploads, replace/versioning
|
|
56
|
-
- [App Objects](docs/app-objects.md) - Cases, threads (comments), records
|
|
57
|
-
- [Translations](docs/translations.md) - Runtime translation lookup, browser-side IndexedDB caching, and admin translation management
|
|
58
|
-
- [Widgets](docs/widgets.md) - Embeddable React components
|
|
59
|
-
- [Realtime](docs/realtime.md) - Realtime data updates
|
|
60
|
-
- [iframe Responder](docs/iframe-responder.md) - iframe integration
|
|
61
|
-
- [Utilities](docs/utils.md) - Helper functions for paths, URLs, and common tasks
|
|
62
|
-
|
|
63
|
-
## Install
|
|
64
|
-
|
|
65
|
-
```bash
|
|
66
|
-
npm install @proveanything/smartlinks
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
## Quick start
|
|
70
|
-
|
|
71
|
-
Initialize once at app startup with your API base URL. Trailing slashes are optional (normalized). In Node, you can also provide an API key for server-to-server calls. You can enable an ngrok header or supply custom headers.
|
|
72
|
-
|
|
73
|
-
```ts
|
|
74
|
-
import { initializeApi } from '@proveanything/smartlinks'
|
|
75
|
-
|
|
76
|
-
initializeApi({
|
|
77
|
-
baseURL: 'https://smartlinks.app/api/v1', // or 'https://smartlinks.app/api/v1/'
|
|
78
|
-
// logger: console, // optional: verbose logging of requests/responses and proxy messages
|
|
79
|
-
// apiKey: process.env.SMARTLINKS_API_KEY, // Node/server only (optional)
|
|
80
|
-
// ngrokSkipBrowserWarning: true, // adds 'ngrok-skip-browser-warning: true'
|
|
81
|
-
// extraHeaders: { 'X-Debug': '1' } // merged into every request
|
|
82
|
-
})
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
List public collections and fetch products:
|
|
86
|
-
|
|
87
|
-
```ts
|
|
88
|
-
import { collection, products } from '@proveanything/smartlinks'
|
|
89
|
-
|
|
90
|
-
const collections = await collection.list(false) // public endpoint
|
|
91
|
-
const first = collections[0]
|
|
92
|
-
if (first) {
|
|
93
|
-
const items = await products.list(first.id, false) // public endpoint
|
|
94
|
-
console.log('First product:', items[0])
|
|
95
|
-
}
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
### Quick start by scenario
|
|
99
|
-
|
|
100
|
-
**Public storefront or portal experience**
|
|
101
|
-
|
|
102
|
-
```ts
|
|
103
|
-
import { initializeApi, collection, products } from '@proveanything/smartlinks'
|
|
104
|
-
|
|
105
|
-
initializeApi({ baseURL: 'https://smartlinks.app/api/v1' })
|
|
106
|
-
|
|
107
|
-
const collections = await collection.list(false)
|
|
108
|
-
const items = await products.list('collectionId', false)
|
|
109
|
-
```
|
|
110
|
-
|
|
111
|
-
**Server-side admin scripts or back office tools**
|
|
112
|
-
|
|
113
|
-
```ts
|
|
114
|
-
import { initializeApi, products } from '@proveanything/smartlinks'
|
|
115
|
-
|
|
116
|
-
initializeApi({
|
|
117
|
-
baseURL: 'https://smartlinks.app/api/v1',
|
|
118
|
-
apiKey: process.env.SMARTLINKS_API_KEY,
|
|
119
|
-
})
|
|
120
|
-
|
|
121
|
-
const created = await products.create('collectionId', { name: 'New product' })
|
|
122
|
-
console.log(created.id)
|
|
123
|
-
```
|
|
124
|
-
|
|
125
|
-
### Product API migration: use products (plural)
|
|
126
|
-
|
|
127
|
-
The SDK keeps `product` (singular) for backward compatibility, but it is deprecated.
|
|
128
|
-
For all new integrations, use `products` (plural).
|
|
129
|
-
|
|
130
|
-
```ts
|
|
131
|
-
// Preferred
|
|
132
|
-
import { products } from '@proveanything/smartlinks'
|
|
133
|
-
|
|
134
|
-
await products.get(collectionId, productId, false)
|
|
135
|
-
await products.list(collectionId, false)
|
|
136
|
-
await products.query(collectionId, { query: { search: 'cabernet' } }) // public
|
|
137
|
-
await products.query(collectionId, { query: { search: 'cabernet' } }, true) // admin
|
|
138
|
-
```
|
|
139
|
-
|
|
140
|
-
Quick mapping:
|
|
141
|
-
|
|
142
|
-
- `product.get` -> `products.get`
|
|
143
|
-
- `product.list` -> `products.list`
|
|
144
|
-
- `product.create` -> `products.create`
|
|
145
|
-
- `product.update` -> `products.update`
|
|
146
|
-
- `product.remove` -> `products.remove`
|
|
147
|
-
- `product.find` / `product.publicFind` -> `products.query` / `products.get`
|
|
148
|
-
|
|
149
|
-
**AI-powered assistant or setup flow**
|
|
150
|
-
|
|
151
|
-
```ts
|
|
152
|
-
import { initializeApi, ai } from '@proveanything/smartlinks'
|
|
153
|
-
|
|
154
|
-
initializeApi({
|
|
155
|
-
baseURL: 'https://smartlinks.app/api/v1',
|
|
156
|
-
apiKey: process.env.SMARTLINKS_API_KEY,
|
|
157
|
-
})
|
|
158
|
-
|
|
159
|
-
const response = await ai.chat.responses.create('collectionId', {
|
|
160
|
-
input: 'Write a concise onboarding checklist for a new product launch.'
|
|
161
|
-
})
|
|
162
|
-
|
|
163
|
-
console.log(response.output_text)
|
|
164
|
-
```
|
|
165
|
-
|
|
166
|
-
## Authentication
|
|
167
|
-
|
|
168
|
-
Use the built-in helpers to log in and verify tokens. After a successful login, the SDK stores the bearer token for subsequent calls.
|
|
169
|
-
|
|
170
|
-
```ts
|
|
171
|
-
import { initializeApi } from '@proveanything/smartlinks'
|
|
172
|
-
import { auth } from '@proveanything/smartlinks'
|
|
173
|
-
|
|
174
|
-
initializeApi({ baseURL: 'https://smartlinks.app/api/v1/' }) // trailing slash OK
|
|
175
|
-
|
|
176
|
-
// Email + password login (browser or Node)
|
|
177
|
-
const user = await auth.login('user@example.com', 'password')
|
|
178
|
-
console.log('Hello,', user.name)
|
|
179
|
-
|
|
180
|
-
// Verify an existing token (and set it if valid)
|
|
181
|
-
const verified = await auth.verifyToken(user.bearerToken)
|
|
182
|
-
console.log('Token valid?', verified.valid)
|
|
183
|
-
|
|
184
|
-
// Later, clear token
|
|
185
|
-
auth.logout()
|
|
186
|
-
```
|
|
187
|
-
|
|
188
|
-
Admin flows:
|
|
189
|
-
|
|
190
|
-
```ts
|
|
191
|
-
// Request an admin JWT for a collection (requires prior auth)
|
|
192
|
-
const jwt = await auth.requestAdminJWT('collectionId')
|
|
193
|
-
|
|
194
|
-
// Or request a public JWT authorized for a collection/product/proof
|
|
195
|
-
const publicJwt = await auth.requestPublicJWT('collectionId', 'productId', 'proofId')
|
|
196
|
-
```
|
|
197
|
-
|
|
198
|
-
## Error Handling
|
|
199
|
-
|
|
200
|
-
The SDK throws `SmartlinksApiError` for all API errors, providing structured access to:
|
|
201
|
-
- **HTTP status code** (`statusCode` / `code`) - Numeric HTTP status (400, 401, 500, etc.)
|
|
202
|
-
- **Server error code** (`errorCode`) - String identifier ("NOT_AUTHORIZED", "broadcasts.topic.invalid", etc.)
|
|
203
|
-
- **Error message** (`message`) - Human-readable description
|
|
204
|
-
- **Additional details** (`details`) - Server-specific fields
|
|
205
|
-
|
|
206
|
-
### Automatic Error Normalization
|
|
207
|
-
|
|
208
|
-
The SDK automatically normalizes various server error response formats into a consistent structure:
|
|
209
|
-
|
|
210
|
-
```ts
|
|
211
|
-
// Server may return errors in different formats:
|
|
212
|
-
// { errorText: "...", errorCode: "..." }
|
|
213
|
-
// { error: "...", message: "..." }
|
|
214
|
-
// { ok: false, error: "..." }
|
|
215
|
-
// { error: "..." }
|
|
216
|
-
|
|
217
|
-
// All are normalized to SmartlinksApiError with consistent access:
|
|
218
|
-
import { SmartlinksApiError, products } from '@proveanything/smartlinks'
|
|
219
|
-
|
|
220
|
-
try {
|
|
221
|
-
const item = await products.get('collectionId', 'productId', false)
|
|
222
|
-
} catch (error) {
|
|
223
|
-
if (error instanceof SmartlinksApiError) {
|
|
224
|
-
console.error({
|
|
225
|
-
message: error.message, // "Error 404: Product not found"
|
|
226
|
-
statusCode: error.statusCode, // 404 (HTTP status)
|
|
227
|
-
code: error.code, // 404 (same as statusCode)
|
|
228
|
-
errorCode: error.errorCode, // "NOT_FOUND" (server error code string)
|
|
229
|
-
details: error.details, // Additional server details
|
|
230
|
-
url: error.url, // Failed URL
|
|
231
|
-
})
|
|
232
|
-
|
|
233
|
-
// Handle specific server error codes (primary identifier)
|
|
234
|
-
switch (error.errorCode) {
|
|
235
|
-
case 'NOT_AUTHORIZED':
|
|
236
|
-
// Invalid credentials
|
|
237
|
-
break
|
|
238
|
-
case 'broadcasts.topic.invalid':
|
|
239
|
-
// Invalid broadcast topic
|
|
240
|
-
break
|
|
241
|
-
default:
|
|
242
|
-
// Fall back to HTTP status code
|
|
243
|
-
if (error.isNotFound()) {
|
|
244
|
-
// Handle 404
|
|
245
|
-
} else if (error.isAuthError()) {
|
|
246
|
-
// Handle 401/403 - redirect to login
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
// Use helper methods for HTTP status-based handling
|
|
251
|
-
if (error.isRateLimited()) {
|
|
252
|
-
// Handle 429 - implement retry logic
|
|
253
|
-
} else if (error.isServerError()) {
|
|
254
|
-
// Handle 5xx - show maintenance message
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
```
|
|
259
|
-
|
|
260
|
-
### Helper Methods
|
|
261
|
-
|
|
262
|
-
- `error.isClientError()` - 4xx status codes
|
|
263
|
-
- `error.isServerError()` - 5xx status codes
|
|
264
|
-
- `error.isAuthError()` - 401 or 403
|
|
265
|
-
- `error.isNotFound()` - 404
|
|
266
|
-
- `error.isRateLimited()` - 429
|
|
267
|
-
- `error.toJSON()` - Serializable object for logging
|
|
268
|
-
|
|
269
|
-
For comprehensive error handling examples and migration guidance, see [examples/error-handling-demo.ts](examples/error-handling-demo.ts).
|
|
270
|
-
|
|
271
|
-
## Utility Functions
|
|
272
|
-
|
|
273
|
-
The SDK includes a simple utility for building portal URLs. Pass in objects and it extracts what it needs:
|
|
274
|
-
|
|
275
|
-
### Build Portal Paths
|
|
276
|
-
|
|
277
|
-
```ts
|
|
278
|
-
import { utils } from '@proveanything/smartlinks'
|
|
279
|
-
|
|
280
|
-
// Pass in objects - extracts shortId, portalUrl, product ID, GTIN, etc.
|
|
281
|
-
const url = utils.buildPortalPath({
|
|
282
|
-
collection: myCollection,
|
|
283
|
-
product: myProduct // reads ownGtin from product
|
|
284
|
-
})
|
|
285
|
-
// Returns: https://portal.smartlinks.io/c/abc123/prod1
|
|
286
|
-
|
|
287
|
-
// With proof object
|
|
288
|
-
const withProof = utils.buildPortalPath({
|
|
289
|
-
collection: myCollection,
|
|
290
|
-
product: myProduct,
|
|
291
|
-
proof: myProof
|
|
292
|
-
})
|
|
293
|
-
// Returns: https://portal.smartlinks.io/c/abc123/prod1/proof1
|
|
294
|
-
|
|
295
|
-
// GTIN path (ownGtin read from product.ownGtin)
|
|
296
|
-
const gtinPath = utils.buildPortalPath({
|
|
297
|
-
collection: myCollection,
|
|
298
|
-
product: myProduct, // if product.ownGtin is true, uses /01/ format
|
|
299
|
-
batch: myBatch, // extracts batch ID and expiry date
|
|
300
|
-
variant: myVariant
|
|
301
|
-
})
|
|
302
|
-
// Returns: https://portal.smartlinks.io/01/1234567890123/10/batch1/22/var1?17=260630
|
|
303
|
-
|
|
304
|
-
// Or pass just IDs if you don't have full objects
|
|
305
|
-
const simple = utils.buildPortalPath({
|
|
306
|
-
collection: { shortId: 'abc123' },
|
|
307
|
-
productId: 'prod1',
|
|
308
|
-
batchId: 'batch1', // just string, no expiry
|
|
309
|
-
queryParams: { utm_source: 'email' }
|
|
310
|
-
})
|
|
311
|
-
// Returns: /c/abc123/prod1?utm_source=email
|
|
312
|
-
```
|
|
313
|
-
|
|
314
|
-
Pass objects where you have them (collection, product, batch, variant, proof) and the function extracts the needed properties. Or pass just IDs (productId, batchId) for simpler cases.
|
|
315
|
-
|
|
316
|
-
For complete documentation, see [docs/utils.md](docs/utils.md).
|
|
317
|
-
|
|
318
|
-
## Common tasks
|
|
319
|
-
|
|
320
|
-
### Products
|
|
321
|
-
|
|
322
|
-
```ts
|
|
323
|
-
import { products } from '@proveanything/smartlinks'
|
|
324
|
-
|
|
325
|
-
// Public fetch
|
|
326
|
-
const item = await products.get('collectionId', 'productId', false)
|
|
327
|
-
|
|
328
|
-
// Admin create/update/delete (requires auth)
|
|
329
|
-
await products.create('collectionId', { name: 'New product' })
|
|
330
|
-
await products.update('collectionId', 'productId', { description: 'Updated' })
|
|
331
|
-
await products.remove('collectionId', 'productId')
|
|
332
|
-
```
|
|
333
|
-
|
|
334
|
-
### Assets
|
|
335
|
-
|
|
336
|
-
Upload, list, get, and remove assets within a scope (collection/product/proof).
|
|
337
|
-
|
|
338
|
-
#### Upload (new)
|
|
339
|
-
|
|
340
|
-
```ts
|
|
341
|
-
import { asset } from '@proveanything/smartlinks'
|
|
342
|
-
|
|
343
|
-
const uploaded = await asset.upload({
|
|
344
|
-
file, // File from an <input type="file">
|
|
345
|
-
scope: { type: 'proof', collectionId, productId, proofId },
|
|
346
|
-
name: 'hero.png',
|
|
347
|
-
metadata: { description: 'Uploaded via SDK' },
|
|
348
|
-
onProgress: (p) => console.log(`Upload: ${p}%`),
|
|
349
|
-
// appId: 'microapp-123' // optional
|
|
350
|
-
})
|
|
351
|
-
console.log('Uploaded asset:', uploaded)
|
|
352
|
-
```
|
|
353
|
-
|
|
354
|
-
Deprecated upload helper (wraps to the new `upload` internally):
|
|
355
|
-
|
|
356
|
-
```ts
|
|
357
|
-
// @deprecated Use asset.upload(options)
|
|
358
|
-
const legacy = await asset.uploadAsset(collectionId, productId, proofId, file)
|
|
359
|
-
```
|
|
360
|
-
|
|
361
|
-
#### List
|
|
362
|
-
|
|
363
|
-
```ts
|
|
364
|
-
// Collection assets, first 20 images
|
|
365
|
-
const list1 = await asset.list({
|
|
366
|
-
scope: { type: 'collection', collectionId },
|
|
367
|
-
mimeTypePrefix: 'image/',
|
|
368
|
-
limit: 20,
|
|
369
|
-
})
|
|
370
|
-
|
|
371
|
-
// Product assets, filter by appId
|
|
372
|
-
const list2 = await asset.list({
|
|
373
|
-
scope: { type: 'product', collectionId, productId },
|
|
374
|
-
appId: 'microapp-123',
|
|
375
|
-
})
|
|
376
|
-
```
|
|
377
|
-
|
|
378
|
-
#### Get (scoped)
|
|
379
|
-
|
|
380
|
-
```ts
|
|
381
|
-
const a = await asset.get({
|
|
382
|
-
assetId,
|
|
383
|
-
scope: { type: 'proof', collectionId, productId, proofId },
|
|
384
|
-
})
|
|
385
|
-
```
|
|
386
|
-
|
|
387
|
-
#### Remove (scoped, admin)
|
|
388
|
-
|
|
389
|
-
```ts
|
|
390
|
-
await asset.remove({
|
|
391
|
-
assetId,
|
|
392
|
-
scope: { type: 'product', collectionId, productId },
|
|
393
|
-
})
|
|
394
|
-
```
|
|
395
|
-
|
|
396
|
-
#### Asset response example
|
|
397
|
-
|
|
398
|
-
```json
|
|
399
|
-
{
|
|
400
|
-
"id": "aBcDeFgHiJkLmNoPqRsT",
|
|
401
|
-
"collectionId": "acme-demo",
|
|
402
|
-
"site": "acme-demo",
|
|
403
|
-
"productId": null,
|
|
404
|
-
"proofId": null,
|
|
405
|
-
"appId": null,
|
|
406
|
-
"name": "product-hero-shot",
|
|
407
|
-
"cleanName": "product-hero-shot",
|
|
408
|
-
"assetType": "Image",
|
|
409
|
-
"fileType": "png",
|
|
410
|
-
"type": "png",
|
|
411
|
-
"url": "https://cdn.smartlinks.app/sites%2Facme-demo%2Fimages%2F2025%2F1%2Fproduct-hero-shot-1234567890123.png",
|
|
412
|
-
"thumbnail": "https://cdn.smartlinks.app/sites%2Facme-demo%2Fimages%2F2025%2F1%2Fproduct-hero-shot-1234567890123_thumb.webp",
|
|
413
|
-
"mimeType": "image/png",
|
|
414
|
-
"contentType": "image/png",
|
|
415
|
-
"size": 204800,
|
|
416
|
-
"width": 1440,
|
|
417
|
-
"height": 900,
|
|
418
|
-
"hash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
|
|
419
|
-
"labels": [],
|
|
420
|
-
"metadata": {},
|
|
421
|
-
"versions": [],
|
|
422
|
-
"uploadedBy": "uid_mock0001",
|
|
423
|
-
"uploaderContactId": null,
|
|
424
|
-
"uploadTokenId": null,
|
|
425
|
-
"uploaderIp": null,
|
|
426
|
-
"status": "active",
|
|
427
|
-
"createdAt": "2025-01-15T10:00:00Z",
|
|
428
|
-
"updatedAt": "2025-01-15T10:00:00Z",
|
|
429
|
-
"deletedAt": null
|
|
430
|
-
}
|
|
431
|
-
```
|
|
432
|
-
|
|
433
|
-
#### Proxy mode and uploads
|
|
434
|
-
|
|
435
|
-
When `initializeApi({ proxyMode: true })` is active (e.g., SDK runs inside an iframe and the parent performs API calls), the SDK serializes `FormData` for upload into a proxy-safe shape and posts a message to the parent window. The parent proxy handler should detect this payload and reconstruct a native `FormData` before performing the actual HTTP request.
|
|
436
|
-
|
|
437
|
-
- SDK proxy message body shape for uploads:
|
|
438
|
-
- `{ _isFormData: true, entries: Array<[name: string, value: string | File]> }`
|
|
439
|
-
- Each entry’s value is either a string or a `File` object (structured-cloneable).
|
|
440
|
-
- Direct XHR uploads are only used when NOT in proxy mode. In proxy mode, the SDK uses the proxy channel and `postMessage`.
|
|
441
|
-
|
|
442
|
-
Progress support in proxy mode:
|
|
443
|
-
|
|
444
|
-
- If you pass `onProgress`, the SDK uses an enhanced upload protocol with chunked messages and progress events.
|
|
445
|
-
- Unified envelope protocol (single message shape):
|
|
446
|
-
- Iframe → Parent
|
|
447
|
-
- `{ _smartlinksProxyUpload: true, phase: 'start', id, path, method: 'POST', headers, fields, fileInfo }`
|
|
448
|
-
- `{ _smartlinksProxyUpload: true, phase: 'chunk', id, seq, chunk: ArrayBuffer }`
|
|
449
|
-
- `{ _smartlinksProxyUpload: true, phase: 'end', id }`
|
|
450
|
-
- Parent → Iframe
|
|
451
|
-
- `{ _smartlinksProxyUpload: true, phase: 'ack', id, seq }` (reply via `event.source.postMessage`)
|
|
452
|
-
- `{ _smartlinksProxyUpload: true, phase: 'progress', id, percent }` (reply via `event.source.postMessage`)
|
|
453
|
-
- `{ _smartlinksProxyUpload: true, phase: 'done', id, ok, data? | error? }` (reply via `event.source.postMessage`)
|
|
454
|
-
|
|
455
|
-
Example parent handler (buffered, simple):
|
|
456
|
-
|
|
457
|
-
```html
|
|
458
|
-
<script>
|
|
459
|
-
const uploads = new Map();
|
|
460
|
-
window.addEventListener('message', async (e) => {
|
|
461
|
-
const m = e.data;
|
|
462
|
-
if (!m || m._smartlinksProxyUpload !== true) return;
|
|
463
|
-
const target = e.source; // reply to the sender iframe
|
|
464
|
-
const origin = e.origin; // consider validating and passing a strict origin
|
|
465
|
-
switch (m.phase) {
|
|
466
|
-
case 'start': {
|
|
467
|
-
uploads.set(m.id, { chunks: [], fields: m.fields, fileInfo: m.fileInfo, path: m.path, headers: m.headers });
|
|
468
|
-
break;
|
|
469
|
-
}
|
|
470
|
-
case 'chunk': {
|
|
471
|
-
const u = uploads.get(m.id);
|
|
472
|
-
if (!u) break;
|
|
473
|
-
u.chunks.push(new Uint8Array(m.chunk));
|
|
474
|
-
target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'ack', id: m.id, seq: m.seq }, origin);
|
|
475
|
-
break;
|
|
476
|
-
}
|
|
477
|
-
case 'end': {
|
|
478
|
-
const u = uploads.get(m.id);
|
|
479
|
-
if (!u) break;
|
|
480
|
-
const blob = new Blob(u.chunks, { type: u.fileInfo.type || 'application/octet-stream' });
|
|
481
|
-
const fd = new FormData();
|
|
482
|
-
for (const [k, v] of u.fields) fd.append(k, v);
|
|
483
|
-
fd.append(u.fileInfo.key || 'file', blob, u.fileInfo.name || 'upload.bin');
|
|
484
|
-
|
|
485
|
-
const xhr = new XMLHttpRequest();
|
|
486
|
-
xhr.open('POST', (window.SMARTLINKS_API_BASEURL || '') + u.path);
|
|
487
|
-
for (const [k, v] of Object.entries(u.headers || {})) xhr.setRequestHeader(k, v);
|
|
488
|
-
xhr.upload.onprogress = (ev) => {
|
|
489
|
-
if (ev.lengthComputable) {
|
|
490
|
-
const pct = Math.round((ev.loaded / ev.total) * 100);
|
|
491
|
-
target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'progress', id: m.id, percent: pct }, origin);
|
|
492
|
-
}
|
|
493
|
-
};
|
|
494
|
-
xhr.onload = () => {
|
|
495
|
-
const ok = xhr.status >= 200 && xhr.status < 300;
|
|
496
|
-
try {
|
|
497
|
-
const data = JSON.parse(xhr.responseText);
|
|
498
|
-
target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'done', id: m.id, ok, data, error: ok ? undefined : data?.message }, origin);
|
|
499
|
-
} catch (err) {
|
|
500
|
-
target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'done', id: m.id, ok: false, error: 'Invalid server response' }, origin);
|
|
501
|
-
}
|
|
502
|
-
};
|
|
503
|
-
xhr.onerror = () => target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'done', id: m.id, ok: false, error: 'Network error' }, origin);
|
|
504
|
-
xhr.send(fd);
|
|
505
|
-
uploads.delete(m.id);
|
|
506
|
-
break;
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
});
|
|
510
|
-
</script>
|
|
511
|
-
```
|
|
512
|
-
|
|
513
|
-
If you maintain the parent proxy, ensure its handler for `_smartlinksProxyRequest`:
|
|
514
|
-
- Detects `body._isFormData === true` and rebuilds `const fd = new FormData(); for (const [k,v] of body.entries) fd.append(k, v);`
|
|
515
|
-
- Issues the HTTP request with that `FormData` and returns the parsed JSON response back to the iframe.
|
|
516
|
-
|
|
517
|
-
### AI helpers
|
|
518
|
-
|
|
519
|
-
```ts
|
|
520
|
-
import { ai } from '@proveanything/smartlinks'
|
|
521
|
-
|
|
522
|
-
const content = await ai.generateContent('collectionId', {
|
|
523
|
-
contents: 'Write a friendly product blurb for our coffee beans.',
|
|
524
|
-
responseMimeType: 'text/plain',
|
|
525
|
-
provider: 'openai',
|
|
526
|
-
model: 'gpt-4o'
|
|
527
|
-
})
|
|
528
|
-
console.log(content)
|
|
529
|
-
```
|
|
530
|
-
|
|
531
|
-
### Analytics (Actions & Broadcasts)
|
|
532
|
-
|
|
533
|
-
Track user actions and broadcast deliveries per collection. These endpoints live under admin and require valid auth (API key or bearer token).
|
|
534
|
-
|
|
535
|
-
```ts
|
|
536
|
-
import { actions, broadcasts } from '@proveanything/smartlinks'
|
|
537
|
-
|
|
538
|
-
// List action events for a user
|
|
539
|
-
const actionEvents = await actions.byUser('collectionId', {
|
|
540
|
-
userId: 'user_123',
|
|
541
|
-
from: '2025-01-01T00:00:00Z',
|
|
542
|
-
to: '2025-12-31T23:59:59Z',
|
|
543
|
-
limit: 100,
|
|
544
|
-
})
|
|
545
|
-
|
|
546
|
-
// Outcome counts, optionally deduping latest per actor
|
|
547
|
-
const counts = await actions.countsByOutcome('collectionId', {
|
|
548
|
-
actionId: 'click',
|
|
549
|
-
dedupeLatest: true,
|
|
550
|
-
idField: 'userId',
|
|
551
|
-
})
|
|
552
|
-
|
|
553
|
-
// Append a single action event
|
|
554
|
-
await actions.append('collectionId', {
|
|
555
|
-
userId: 'user_123',
|
|
556
|
-
actionId: 'click',
|
|
557
|
-
outcome: 'success',
|
|
558
|
-
})
|
|
559
|
-
|
|
560
|
-
// Broadcast recipients and filters
|
|
561
|
-
const recipients = await broadcasts.recipientIds('collectionId', {
|
|
562
|
-
broadcastId: 'br_456',
|
|
563
|
-
idField: 'contactId',
|
|
564
|
-
})
|
|
565
|
-
|
|
566
|
-
// Append broadcast recipients in bulk (preferred shape)
|
|
567
|
-
await broadcasts.appendBulk('collectionId', {
|
|
568
|
-
params: { broadcastId: 'br_456', channel: 'email' },
|
|
569
|
-
ids: ['contact_1','contact_2'],
|
|
570
|
-
idField: 'contactId',
|
|
571
|
-
})
|
|
572
|
-
```
|
|
573
|
-
|
|
574
|
-
### Broadcast sending and previews
|
|
575
|
-
|
|
576
|
-
```ts
|
|
577
|
-
import { broadcasts } from '@proveanything/smartlinks'
|
|
578
|
-
|
|
579
|
-
// Preview a broadcast (HTML)
|
|
580
|
-
const preview = await broadcasts.preview('collectionId', 'broadcastId', {
|
|
581
|
-
contactId: 'contact_123',
|
|
582
|
-
props: { firstName: 'Sam' },
|
|
583
|
-
})
|
|
584
|
-
|
|
585
|
-
// Send a test email
|
|
586
|
-
await broadcasts.sendTest('collectionId', 'broadcastId', {
|
|
587
|
-
to: 'test@example.com',
|
|
588
|
-
subject: 'Test subject',
|
|
589
|
-
props: { foo: 'bar' },
|
|
590
|
-
})
|
|
591
|
-
|
|
592
|
-
// Enqueue broadcast sending (background)
|
|
593
|
-
await broadcasts.send('collectionId', 'broadcastId', {
|
|
594
|
-
pageSize: 100,
|
|
595
|
-
sharedContext: { campaign: 'summer' },
|
|
596
|
-
})
|
|
597
|
-
|
|
598
|
-
// Manual page send (for testing/UX)
|
|
599
|
-
const manual = await broadcasts.sendManual('collectionId', 'broadcastId', {
|
|
600
|
-
limit: 50,
|
|
601
|
-
dryRun: true,
|
|
602
|
-
})
|
|
603
|
-
```
|
|
604
|
-
|
|
605
|
-
## Communications Overview
|
|
606
|
-
|
|
607
|
-
End-to-end explainer covering comms settings (unsubscribe, types), Web Push registration, and multi-channel broadcasts with SDK examples: [src/docs/smartlinks/comms-explainer.md](src/docs/smartlinks/comms-explainer.md)
|
|
608
|
-
|
|
609
|
-
### Async jobs
|
|
610
|
-
|
|
611
|
-
```ts
|
|
612
|
-
import { async as slAsync, jobs } from '@proveanything/smartlinks'
|
|
613
|
-
|
|
614
|
-
// Enqueue an async job
|
|
615
|
-
const queued = await slAsync.enqueueAsyncJob('collectionId', {
|
|
616
|
-
task: 'email:daily-digest',
|
|
617
|
-
payload: { segmentId: 'seg_1' },
|
|
618
|
-
priority: 5,
|
|
619
|
-
key: 'digest:seg_1',
|
|
620
|
-
})
|
|
621
|
-
|
|
622
|
-
// Check job status
|
|
623
|
-
const status = await slAsync.getAsyncJobStatus('collectionId', queued.id)
|
|
624
|
-
|
|
625
|
-
// List recent jobs
|
|
626
|
-
const recent = await jobs.listJobs('collectionId', { state: 'queued', limit: 20 })
|
|
627
|
-
|
|
628
|
-
// Get a single job
|
|
629
|
-
const job = await jobs.getJob('collectionId', queued.id)
|
|
630
|
-
```
|
|
631
|
-
|
|
632
|
-
## Browser and React
|
|
633
|
-
|
|
634
|
-
The SDK works in modern browsers. Initialize once and call public endpoints without an API key; authenticate to access protected/admin endpoints.
|
|
635
|
-
|
|
636
|
-
```ts
|
|
637
|
-
import { initializeApi } from '@proveanything/smartlinks'
|
|
638
|
-
import { collection } from '@proveanything/smartlinks'
|
|
639
|
-
|
|
640
|
-
initializeApi({ baseURL: 'https://smartlinks.app/api/v1' })
|
|
641
|
-
const collections = await collection.list(false)
|
|
642
|
-
```
|
|
643
|
-
|
|
644
|
-
For a fuller UI example, see `examples/react-demo.tsx`.
|
|
645
|
-
|
|
646
|
-
## Iframe Integration
|
|
647
|
-
|
|
648
|
-
When embedding Smartlinks inside an iframe (set `proxyMode: true` in `initializeApi` if you need parent-proxy API calls), you can also send UI/control messages to the parent window. The SDK provides lightweight helpers in `iframe.ts`:
|
|
649
|
-
|
|
650
|
-
```ts
|
|
651
|
-
import { enableAutoIframeResize, disableAutoIframeResize, redirectParent, sendParentCustom, isIframe } from '@proveanything/smartlinks'
|
|
652
|
-
|
|
653
|
-
// Automatically push height changes to parent so it can resize the iframe.
|
|
654
|
-
enableAutoIframeResize({ intervalMs: 150 })
|
|
655
|
-
|
|
656
|
-
// Later disable if not needed:
|
|
657
|
-
disableAutoIframeResize()
|
|
658
|
-
|
|
659
|
-
// Redirect parent window to a URL (e.g. after login):
|
|
660
|
-
redirectParent('https://app.example.com/dashboard')
|
|
661
|
-
|
|
662
|
-
// Send any custom event + payload:
|
|
663
|
-
sendParentCustom('smartlinks:navigate', { url: '/profile' })
|
|
664
|
-
|
|
665
|
-
if (isIframe()) {
|
|
666
|
-
console.log('Running inside an iframe')
|
|
667
|
-
}
|
|
668
|
-
```
|
|
669
|
-
|
|
670
|
-
Parent page can listen for these messages:
|
|
671
|
-
|
|
672
|
-
```ts
|
|
673
|
-
window.addEventListener('message', (e) => {
|
|
674
|
-
const msg = e.data
|
|
675
|
-
if (!msg || !msg._smartlinksIframeMessage) return
|
|
676
|
-
switch (msg.type) {
|
|
677
|
-
case 'smartlinks:resize':
|
|
678
|
-
// adjust iframe height
|
|
679
|
-
const iframeEl = document.getElementById('smartlinks-frame') as HTMLIFrameElement
|
|
680
|
-
if (iframeEl) iframeEl.style.height = msg.payload.height + 'px'
|
|
681
|
-
break
|
|
682
|
-
case 'smartlinks:redirect':
|
|
683
|
-
window.location.href = msg.payload.url
|
|
684
|
-
break
|
|
685
|
-
case 'smartlinks:navigate':
|
|
686
|
-
// Custom example
|
|
687
|
-
console.log('Navigate request:', msg.payload.url)
|
|
688
|
-
break
|
|
689
|
-
}
|
|
690
|
-
})
|
|
691
|
-
```
|
|
692
|
-
|
|
693
|
-
Notes:
|
|
694
|
-
- Auto-resize uses `ResizeObserver` when available, falling back to `MutationObserver` + polling.
|
|
695
|
-
- In non-browser or Node environments these helpers safely no-op.
|
|
696
|
-
- Use `sendParentCustom` for any domain-specific integration events.
|
|
697
|
-
|
|
698
|
-
## Configuration reference
|
|
699
|
-
|
|
700
|
-
```ts
|
|
701
|
-
initializeApi({
|
|
702
|
-
baseURL: string, // with or without trailing slash
|
|
703
|
-
apiKey?: string, // Node/server only
|
|
704
|
-
bearerToken?: string, // optional at init; set by auth.login/verifyToken
|
|
705
|
-
proxyMode?: boolean // set true if running inside an iframe and using parent proxy
|
|
706
|
-
ngrokSkipBrowserWarning?: boolean // forces header 'ngrok-skip-browser-warning: true'
|
|
707
|
-
extraHeaders?: Record<string,string> // custom headers merged in each request
|
|
708
|
-
iframeAutoResize?: boolean // default true when embedded in an iframe
|
|
709
|
-
logger?: Function | { debug?: Function; info?: Function; warn?: Function; error?: Function; log?: Function } // optional verbose logging
|
|
710
|
-
})
|
|
711
|
-
|
|
712
|
-
// Auto-detection: If baseURL contains '.ngrok.io' or '.ngrok-free.dev' the header is added automatically
|
|
713
|
-
// unless you explicitly set ngrokSkipBrowserWarning: false.
|
|
714
|
-
// Auto iframe resize: When in an iframe, resize messages are sent by default unless iframeAutoResize: false.
|
|
715
|
-
// Verbose logging: Pass a logger (e.g. console) to log outbound requests/responses and proxy postMessages.
|
|
716
|
-
```
|
|
717
|
-
|
|
718
|
-
When embedding the SDK in an iframe with `proxyMode: true`, you can also use:
|
|
719
|
-
|
|
720
|
-
```ts
|
|
721
|
-
import { sendCustomProxyMessage } from '@proveanything/smartlinks'
|
|
722
|
-
const data = await sendCustomProxyMessage('my-action', { foo: 'bar' })
|
|
723
|
-
|
|
724
|
-
// Toggle ngrok header or update custom headers later:
|
|
725
|
-
import { setNgrokSkipBrowserWarning, setExtraHeaders } from '@proveanything/smartlinks'
|
|
726
|
-
setNgrokSkipBrowserWarning(true)
|
|
727
|
-
setExtraHeaders({ 'X-Debug': '1' })
|
|
728
|
-
```
|
|
729
|
-
|
|
730
|
-
## Full API surface
|
|
731
|
-
|
|
732
|
-
Explore every function, parameter, and type here:
|
|
733
|
-
|
|
734
|
-
- [API_SUMMARY.md](docs/API_SUMMARY.md) - Complete API reference
|
|
735
|
-
|
|
736
|
-
## Additional Documentation
|
|
737
|
-
|
|
738
|
-
The SDK includes comprehensive guides for advanced features:
|
|
739
|
-
|
|
740
|
-
- **[Liquid Templates](docs/liquid-templates.md)** - Dynamic templating for emails and notifications with personalized data
|
|
741
|
-
- **[Real-Time Messaging](docs/realtime.md)** - Ably integration for live chat, presence, and real-time updates
|
|
742
|
-
- **[Theme System](docs/theme.system.md)** - Dynamic theming for iframe apps with CSS variables and postMessage
|
|
743
|
-
- **[Theme Defaults](docs/theme-defaults.md)** - Default theme configuration reference
|
|
744
|
-
- **[Widgets](docs/widgets.md)** - React widget system for embeddable components
|
|
745
|
-
- **[Internationalization](docs/i18n.md)** - Multi-language support and localization
|
|
746
|
-
|
|
747
|
-
## Requirements
|
|
748
|
-
|
|
749
|
-
- Node.js 16+ or modern browsers
|
|
750
|
-
- TypeScript 4.9+ (if using TS)
|
|
751
|
-
|
|
752
|
-
## License
|
|
753
|
-
|
|
754
|
-
MIT © Prove Anything
|
|
1
|
+
# @proveanything/smartlinks
|
|
2
|
+
|
|
3
|
+
Official JavaScript/TypeScript SDK for the Smartlinks API.
|
|
4
|
+
|
|
5
|
+
Build Smartlinks-powered apps in Node.js or the browser: list collections and products, authenticate users, manage assets and attestations, and call admin endpoints with a clean, typed API.
|
|
6
|
+
|
|
7
|
+
• TypeScript-first types and intellisense
|
|
8
|
+
• Works in Node.js and modern browsers
|
|
9
|
+
• Simple auth helpers (login, verify token, request admin/public JWTs)
|
|
10
|
+
• Rich resources: collections, products, proofs, assets, attestations, batches, variants, AI, and more
|
|
11
|
+
• Optional iframe proxy mode for embedded apps
|
|
12
|
+
|
|
13
|
+
## Start here
|
|
14
|
+
|
|
15
|
+
If you're new to the SDK, this is the easiest path:
|
|
16
|
+
|
|
17
|
+
1. Initialize the SDK with your SmartLinks API base URL.
|
|
18
|
+
2. Pick the guide that matches what you're building.
|
|
19
|
+
3. Copy one of the working examples and adapt it to your collection/product IDs.
|
|
20
|
+
|
|
21
|
+
### Pick a guide
|
|
22
|
+
|
|
23
|
+
- [docs/ai.md](docs/ai.md) — AI responses, chat, RAG, voice, streaming, and product assistants
|
|
24
|
+
- [docs/analytics.md](docs/analytics.md) — fire-and-forget web analytics, tag scan telemetry, and dashboard queries
|
|
25
|
+
- [docs/proof-share-grants.md](docs/proof-share-grants.md) — delegated, scoped, revocable share links for a proof (album sharing, guest comments, proof-of-ownership)
|
|
26
|
+
- [docs/assets.md](docs/assets.md) — asset uploads, including resumable uploads for large files (video)
|
|
27
|
+
- [docs/files.md](docs/files.md) — temporary files, fetching web pages and documents once, and extracting text, Markdown, OCR or fields from them
|
|
28
|
+
- [docs/app-objects.md](docs/app-objects.md) — cases, threads (comments), and records
|
|
29
|
+
- [docs/translations.md](docs/translations.md) — runtime translation lookup, browser-side caching, and translation admin flows
|
|
30
|
+
- [docs/widgets.md](docs/widgets.md) — embeddable React components
|
|
31
|
+
- [docs/realtime.md](docs/realtime.md) — subscriptions and live updates
|
|
32
|
+
- [docs/admin-cards.md](docs/admin-cards.md) — cards on the collection's Studio dashboard
|
|
33
|
+
- [docs/iframe-responder.md](docs/iframe-responder.md) — iframe integration and parent/child messaging
|
|
34
|
+
- [docs/utils.md](docs/utils.md) — helper utilities and portal path generation
|
|
35
|
+
|
|
36
|
+
### Most common use cases
|
|
37
|
+
|
|
38
|
+
- **Build an AI assistant** → start with [docs/ai.md](docs/ai.md)
|
|
39
|
+
- **Track page views, clicks, or tag scans** → start with [docs/analytics.md](docs/analytics.md)
|
|
40
|
+
- **Translate dynamic content with local browser caching** → start with [docs/translations.md](docs/translations.md)
|
|
41
|
+
- **Share a proof / album by link, or add guest comments** → start with [docs/proof-share-grants.md](docs/proof-share-grants.md)
|
|
42
|
+
- **Upload large video with resume-on-reconnect** → see [Resumable uploads](docs/assets.md#resumable-uploads-large-files-eg-video)
|
|
43
|
+
- **Fetch collections/products** → see [Quick start](README.md#quick-start)
|
|
44
|
+
- **Authenticate admins or end users** → see [Authentication](README.md#authentication)
|
|
45
|
+
- **Upload and manage files** → see [Assets](README.md#assets)
|
|
46
|
+
- **Browse the full surface area** → use [API_SUMMARY.md](docs/API_SUMMARY.md) as reference
|
|
47
|
+
|
|
48
|
+
For the full list of functions and types, see the API summary:
|
|
49
|
+
→ [API Summary](docs/API_SUMMARY.md)
|
|
50
|
+
|
|
51
|
+
**Documentation:**
|
|
52
|
+
- [AI & Chat Completions](docs/ai.md) - Chat completions, RAG, voice integration
|
|
53
|
+
- [Analytics](docs/analytics.md) - Fire-and-forget analytics tracking, tag scans, and dashboard queries
|
|
54
|
+
- [Proof Share Grants](docs/proof-share-grants.md) - Delegated, revocable share links; guest comments; proof-of-ownership
|
|
55
|
+
- [Assets](docs/assets.md) - Uploads, resumable large-file uploads, token uploads, replace/versioning
|
|
56
|
+
- [App Objects](docs/app-objects.md) - Cases, threads (comments), records
|
|
57
|
+
- [Translations](docs/translations.md) - Runtime translation lookup, browser-side IndexedDB caching, and admin translation management
|
|
58
|
+
- [Widgets](docs/widgets.md) - Embeddable React components
|
|
59
|
+
- [Realtime](docs/realtime.md) - Realtime data updates
|
|
60
|
+
- [iframe Responder](docs/iframe-responder.md) - iframe integration
|
|
61
|
+
- [Utilities](docs/utils.md) - Helper functions for paths, URLs, and common tasks
|
|
62
|
+
|
|
63
|
+
## Install
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
npm install @proveanything/smartlinks
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Quick start
|
|
70
|
+
|
|
71
|
+
Initialize once at app startup with your API base URL. Trailing slashes are optional (normalized). In Node, you can also provide an API key for server-to-server calls. You can enable an ngrok header or supply custom headers.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { initializeApi } from '@proveanything/smartlinks'
|
|
75
|
+
|
|
76
|
+
initializeApi({
|
|
77
|
+
baseURL: 'https://smartlinks.app/api/v1', // or 'https://smartlinks.app/api/v1/'
|
|
78
|
+
// logger: console, // optional: verbose logging of requests/responses and proxy messages
|
|
79
|
+
// apiKey: process.env.SMARTLINKS_API_KEY, // Node/server only (optional)
|
|
80
|
+
// ngrokSkipBrowserWarning: true, // adds 'ngrok-skip-browser-warning: true'
|
|
81
|
+
// extraHeaders: { 'X-Debug': '1' } // merged into every request
|
|
82
|
+
})
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
List public collections and fetch products:
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { collection, products } from '@proveanything/smartlinks'
|
|
89
|
+
|
|
90
|
+
const collections = await collection.list(false) // public endpoint
|
|
91
|
+
const first = collections[0]
|
|
92
|
+
if (first) {
|
|
93
|
+
const items = await products.list(first.id, false) // public endpoint
|
|
94
|
+
console.log('First product:', items[0])
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Quick start by scenario
|
|
99
|
+
|
|
100
|
+
**Public storefront or portal experience**
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import { initializeApi, collection, products } from '@proveanything/smartlinks'
|
|
104
|
+
|
|
105
|
+
initializeApi({ baseURL: 'https://smartlinks.app/api/v1' })
|
|
106
|
+
|
|
107
|
+
const collections = await collection.list(false)
|
|
108
|
+
const items = await products.list('collectionId', false)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
**Server-side admin scripts or back office tools**
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { initializeApi, products } from '@proveanything/smartlinks'
|
|
115
|
+
|
|
116
|
+
initializeApi({
|
|
117
|
+
baseURL: 'https://smartlinks.app/api/v1',
|
|
118
|
+
apiKey: process.env.SMARTLINKS_API_KEY,
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
const created = await products.create('collectionId', { name: 'New product' })
|
|
122
|
+
console.log(created.id)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### Product API migration: use products (plural)
|
|
126
|
+
|
|
127
|
+
The SDK keeps `product` (singular) for backward compatibility, but it is deprecated.
|
|
128
|
+
For all new integrations, use `products` (plural).
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
// Preferred
|
|
132
|
+
import { products } from '@proveanything/smartlinks'
|
|
133
|
+
|
|
134
|
+
await products.get(collectionId, productId, false)
|
|
135
|
+
await products.list(collectionId, false)
|
|
136
|
+
await products.query(collectionId, { query: { search: 'cabernet' } }) // public
|
|
137
|
+
await products.query(collectionId, { query: { search: 'cabernet' } }, true) // admin
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Quick mapping:
|
|
141
|
+
|
|
142
|
+
- `product.get` -> `products.get`
|
|
143
|
+
- `product.list` -> `products.list`
|
|
144
|
+
- `product.create` -> `products.create`
|
|
145
|
+
- `product.update` -> `products.update`
|
|
146
|
+
- `product.remove` -> `products.remove`
|
|
147
|
+
- `product.find` / `product.publicFind` -> `products.query` / `products.get`
|
|
148
|
+
|
|
149
|
+
**AI-powered assistant or setup flow**
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
import { initializeApi, ai } from '@proveanything/smartlinks'
|
|
153
|
+
|
|
154
|
+
initializeApi({
|
|
155
|
+
baseURL: 'https://smartlinks.app/api/v1',
|
|
156
|
+
apiKey: process.env.SMARTLINKS_API_KEY,
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
const response = await ai.chat.responses.create('collectionId', {
|
|
160
|
+
input: 'Write a concise onboarding checklist for a new product launch.'
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
console.log(response.output_text)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
## Authentication
|
|
167
|
+
|
|
168
|
+
Use the built-in helpers to log in and verify tokens. After a successful login, the SDK stores the bearer token for subsequent calls.
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
import { initializeApi } from '@proveanything/smartlinks'
|
|
172
|
+
import { auth } from '@proveanything/smartlinks'
|
|
173
|
+
|
|
174
|
+
initializeApi({ baseURL: 'https://smartlinks.app/api/v1/' }) // trailing slash OK
|
|
175
|
+
|
|
176
|
+
// Email + password login (browser or Node)
|
|
177
|
+
const user = await auth.login('user@example.com', 'password')
|
|
178
|
+
console.log('Hello,', user.name)
|
|
179
|
+
|
|
180
|
+
// Verify an existing token (and set it if valid)
|
|
181
|
+
const verified = await auth.verifyToken(user.bearerToken)
|
|
182
|
+
console.log('Token valid?', verified.valid)
|
|
183
|
+
|
|
184
|
+
// Later, clear token
|
|
185
|
+
auth.logout()
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Admin flows:
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
// Request an admin JWT for a collection (requires prior auth)
|
|
192
|
+
const jwt = await auth.requestAdminJWT('collectionId')
|
|
193
|
+
|
|
194
|
+
// Or request a public JWT authorized for a collection/product/proof
|
|
195
|
+
const publicJwt = await auth.requestPublicJWT('collectionId', 'productId', 'proofId')
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## Error Handling
|
|
199
|
+
|
|
200
|
+
The SDK throws `SmartlinksApiError` for all API errors, providing structured access to:
|
|
201
|
+
- **HTTP status code** (`statusCode` / `code`) - Numeric HTTP status (400, 401, 500, etc.)
|
|
202
|
+
- **Server error code** (`errorCode`) - String identifier ("NOT_AUTHORIZED", "broadcasts.topic.invalid", etc.)
|
|
203
|
+
- **Error message** (`message`) - Human-readable description
|
|
204
|
+
- **Additional details** (`details`) - Server-specific fields
|
|
205
|
+
|
|
206
|
+
### Automatic Error Normalization
|
|
207
|
+
|
|
208
|
+
The SDK automatically normalizes various server error response formats into a consistent structure:
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
// Server may return errors in different formats:
|
|
212
|
+
// { errorText: "...", errorCode: "..." }
|
|
213
|
+
// { error: "...", message: "..." }
|
|
214
|
+
// { ok: false, error: "..." }
|
|
215
|
+
// { error: "..." }
|
|
216
|
+
|
|
217
|
+
// All are normalized to SmartlinksApiError with consistent access:
|
|
218
|
+
import { SmartlinksApiError, products } from '@proveanything/smartlinks'
|
|
219
|
+
|
|
220
|
+
try {
|
|
221
|
+
const item = await products.get('collectionId', 'productId', false)
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (error instanceof SmartlinksApiError) {
|
|
224
|
+
console.error({
|
|
225
|
+
message: error.message, // "Error 404: Product not found"
|
|
226
|
+
statusCode: error.statusCode, // 404 (HTTP status)
|
|
227
|
+
code: error.code, // 404 (same as statusCode)
|
|
228
|
+
errorCode: error.errorCode, // "NOT_FOUND" (server error code string)
|
|
229
|
+
details: error.details, // Additional server details
|
|
230
|
+
url: error.url, // Failed URL
|
|
231
|
+
})
|
|
232
|
+
|
|
233
|
+
// Handle specific server error codes (primary identifier)
|
|
234
|
+
switch (error.errorCode) {
|
|
235
|
+
case 'NOT_AUTHORIZED':
|
|
236
|
+
// Invalid credentials
|
|
237
|
+
break
|
|
238
|
+
case 'broadcasts.topic.invalid':
|
|
239
|
+
// Invalid broadcast topic
|
|
240
|
+
break
|
|
241
|
+
default:
|
|
242
|
+
// Fall back to HTTP status code
|
|
243
|
+
if (error.isNotFound()) {
|
|
244
|
+
// Handle 404
|
|
245
|
+
} else if (error.isAuthError()) {
|
|
246
|
+
// Handle 401/403 - redirect to login
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Use helper methods for HTTP status-based handling
|
|
251
|
+
if (error.isRateLimited()) {
|
|
252
|
+
// Handle 429 - implement retry logic
|
|
253
|
+
} else if (error.isServerError()) {
|
|
254
|
+
// Handle 5xx - show maintenance message
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
### Helper Methods
|
|
261
|
+
|
|
262
|
+
- `error.isClientError()` - 4xx status codes
|
|
263
|
+
- `error.isServerError()` - 5xx status codes
|
|
264
|
+
- `error.isAuthError()` - 401 or 403
|
|
265
|
+
- `error.isNotFound()` - 404
|
|
266
|
+
- `error.isRateLimited()` - 429
|
|
267
|
+
- `error.toJSON()` - Serializable object for logging
|
|
268
|
+
|
|
269
|
+
For comprehensive error handling examples and migration guidance, see [examples/error-handling-demo.ts](examples/error-handling-demo.ts).
|
|
270
|
+
|
|
271
|
+
## Utility Functions
|
|
272
|
+
|
|
273
|
+
The SDK includes a simple utility for building portal URLs. Pass in objects and it extracts what it needs:
|
|
274
|
+
|
|
275
|
+
### Build Portal Paths
|
|
276
|
+
|
|
277
|
+
```ts
|
|
278
|
+
import { utils } from '@proveanything/smartlinks'
|
|
279
|
+
|
|
280
|
+
// Pass in objects - extracts shortId, portalUrl, product ID, GTIN, etc.
|
|
281
|
+
const url = utils.buildPortalPath({
|
|
282
|
+
collection: myCollection,
|
|
283
|
+
product: myProduct // reads ownGtin from product
|
|
284
|
+
})
|
|
285
|
+
// Returns: https://portal.smartlinks.io/c/abc123/prod1
|
|
286
|
+
|
|
287
|
+
// With proof object
|
|
288
|
+
const withProof = utils.buildPortalPath({
|
|
289
|
+
collection: myCollection,
|
|
290
|
+
product: myProduct,
|
|
291
|
+
proof: myProof
|
|
292
|
+
})
|
|
293
|
+
// Returns: https://portal.smartlinks.io/c/abc123/prod1/proof1
|
|
294
|
+
|
|
295
|
+
// GTIN path (ownGtin read from product.ownGtin)
|
|
296
|
+
const gtinPath = utils.buildPortalPath({
|
|
297
|
+
collection: myCollection,
|
|
298
|
+
product: myProduct, // if product.ownGtin is true, uses /01/ format
|
|
299
|
+
batch: myBatch, // extracts batch ID and expiry date
|
|
300
|
+
variant: myVariant
|
|
301
|
+
})
|
|
302
|
+
// Returns: https://portal.smartlinks.io/01/1234567890123/10/batch1/22/var1?17=260630
|
|
303
|
+
|
|
304
|
+
// Or pass just IDs if you don't have full objects
|
|
305
|
+
const simple = utils.buildPortalPath({
|
|
306
|
+
collection: { shortId: 'abc123' },
|
|
307
|
+
productId: 'prod1',
|
|
308
|
+
batchId: 'batch1', // just string, no expiry
|
|
309
|
+
queryParams: { utm_source: 'email' }
|
|
310
|
+
})
|
|
311
|
+
// Returns: /c/abc123/prod1?utm_source=email
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
Pass objects where you have them (collection, product, batch, variant, proof) and the function extracts the needed properties. Or pass just IDs (productId, batchId) for simpler cases.
|
|
315
|
+
|
|
316
|
+
For complete documentation, see [docs/utils.md](docs/utils.md).
|
|
317
|
+
|
|
318
|
+
## Common tasks
|
|
319
|
+
|
|
320
|
+
### Products
|
|
321
|
+
|
|
322
|
+
```ts
|
|
323
|
+
import { products } from '@proveanything/smartlinks'
|
|
324
|
+
|
|
325
|
+
// Public fetch
|
|
326
|
+
const item = await products.get('collectionId', 'productId', false)
|
|
327
|
+
|
|
328
|
+
// Admin create/update/delete (requires auth)
|
|
329
|
+
await products.create('collectionId', { name: 'New product' })
|
|
330
|
+
await products.update('collectionId', 'productId', { description: 'Updated' })
|
|
331
|
+
await products.remove('collectionId', 'productId')
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
### Assets
|
|
335
|
+
|
|
336
|
+
Upload, list, get, and remove assets within a scope (collection/product/proof).
|
|
337
|
+
|
|
338
|
+
#### Upload (new)
|
|
339
|
+
|
|
340
|
+
```ts
|
|
341
|
+
import { asset } from '@proveanything/smartlinks'
|
|
342
|
+
|
|
343
|
+
const uploaded = await asset.upload({
|
|
344
|
+
file, // File from an <input type="file">
|
|
345
|
+
scope: { type: 'proof', collectionId, productId, proofId },
|
|
346
|
+
name: 'hero.png',
|
|
347
|
+
metadata: { description: 'Uploaded via SDK' },
|
|
348
|
+
onProgress: (p) => console.log(`Upload: ${p}%`),
|
|
349
|
+
// appId: 'microapp-123' // optional
|
|
350
|
+
})
|
|
351
|
+
console.log('Uploaded asset:', uploaded)
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
Deprecated upload helper (wraps to the new `upload` internally):
|
|
355
|
+
|
|
356
|
+
```ts
|
|
357
|
+
// @deprecated Use asset.upload(options)
|
|
358
|
+
const legacy = await asset.uploadAsset(collectionId, productId, proofId, file)
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
#### List
|
|
362
|
+
|
|
363
|
+
```ts
|
|
364
|
+
// Collection assets, first 20 images
|
|
365
|
+
const list1 = await asset.list({
|
|
366
|
+
scope: { type: 'collection', collectionId },
|
|
367
|
+
mimeTypePrefix: 'image/',
|
|
368
|
+
limit: 20,
|
|
369
|
+
})
|
|
370
|
+
|
|
371
|
+
// Product assets, filter by appId
|
|
372
|
+
const list2 = await asset.list({
|
|
373
|
+
scope: { type: 'product', collectionId, productId },
|
|
374
|
+
appId: 'microapp-123',
|
|
375
|
+
})
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
#### Get (scoped)
|
|
379
|
+
|
|
380
|
+
```ts
|
|
381
|
+
const a = await asset.get({
|
|
382
|
+
assetId,
|
|
383
|
+
scope: { type: 'proof', collectionId, productId, proofId },
|
|
384
|
+
})
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
#### Remove (scoped, admin)
|
|
388
|
+
|
|
389
|
+
```ts
|
|
390
|
+
await asset.remove({
|
|
391
|
+
assetId,
|
|
392
|
+
scope: { type: 'product', collectionId, productId },
|
|
393
|
+
})
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
#### Asset response example
|
|
397
|
+
|
|
398
|
+
```json
|
|
399
|
+
{
|
|
400
|
+
"id": "aBcDeFgHiJkLmNoPqRsT",
|
|
401
|
+
"collectionId": "acme-demo",
|
|
402
|
+
"site": "acme-demo",
|
|
403
|
+
"productId": null,
|
|
404
|
+
"proofId": null,
|
|
405
|
+
"appId": null,
|
|
406
|
+
"name": "product-hero-shot",
|
|
407
|
+
"cleanName": "product-hero-shot",
|
|
408
|
+
"assetType": "Image",
|
|
409
|
+
"fileType": "png",
|
|
410
|
+
"type": "png",
|
|
411
|
+
"url": "https://cdn.smartlinks.app/sites%2Facme-demo%2Fimages%2F2025%2F1%2Fproduct-hero-shot-1234567890123.png",
|
|
412
|
+
"thumbnail": "https://cdn.smartlinks.app/sites%2Facme-demo%2Fimages%2F2025%2F1%2Fproduct-hero-shot-1234567890123_thumb.webp",
|
|
413
|
+
"mimeType": "image/png",
|
|
414
|
+
"contentType": "image/png",
|
|
415
|
+
"size": 204800,
|
|
416
|
+
"width": 1440,
|
|
417
|
+
"height": 900,
|
|
418
|
+
"hash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
|
|
419
|
+
"labels": [],
|
|
420
|
+
"metadata": {},
|
|
421
|
+
"versions": [],
|
|
422
|
+
"uploadedBy": "uid_mock0001",
|
|
423
|
+
"uploaderContactId": null,
|
|
424
|
+
"uploadTokenId": null,
|
|
425
|
+
"uploaderIp": null,
|
|
426
|
+
"status": "active",
|
|
427
|
+
"createdAt": "2025-01-15T10:00:00Z",
|
|
428
|
+
"updatedAt": "2025-01-15T10:00:00Z",
|
|
429
|
+
"deletedAt": null
|
|
430
|
+
}
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
#### Proxy mode and uploads
|
|
434
|
+
|
|
435
|
+
When `initializeApi({ proxyMode: true })` is active (e.g., SDK runs inside an iframe and the parent performs API calls), the SDK serializes `FormData` for upload into a proxy-safe shape and posts a message to the parent window. The parent proxy handler should detect this payload and reconstruct a native `FormData` before performing the actual HTTP request.
|
|
436
|
+
|
|
437
|
+
- SDK proxy message body shape for uploads:
|
|
438
|
+
- `{ _isFormData: true, entries: Array<[name: string, value: string | File]> }`
|
|
439
|
+
- Each entry’s value is either a string or a `File` object (structured-cloneable).
|
|
440
|
+
- Direct XHR uploads are only used when NOT in proxy mode. In proxy mode, the SDK uses the proxy channel and `postMessage`.
|
|
441
|
+
|
|
442
|
+
Progress support in proxy mode:
|
|
443
|
+
|
|
444
|
+
- If you pass `onProgress`, the SDK uses an enhanced upload protocol with chunked messages and progress events.
|
|
445
|
+
- Unified envelope protocol (single message shape):
|
|
446
|
+
- Iframe → Parent
|
|
447
|
+
- `{ _smartlinksProxyUpload: true, phase: 'start', id, path, method: 'POST', headers, fields, fileInfo }`
|
|
448
|
+
- `{ _smartlinksProxyUpload: true, phase: 'chunk', id, seq, chunk: ArrayBuffer }`
|
|
449
|
+
- `{ _smartlinksProxyUpload: true, phase: 'end', id }`
|
|
450
|
+
- Parent → Iframe
|
|
451
|
+
- `{ _smartlinksProxyUpload: true, phase: 'ack', id, seq }` (reply via `event.source.postMessage`)
|
|
452
|
+
- `{ _smartlinksProxyUpload: true, phase: 'progress', id, percent }` (reply via `event.source.postMessage`)
|
|
453
|
+
- `{ _smartlinksProxyUpload: true, phase: 'done', id, ok, data? | error? }` (reply via `event.source.postMessage`)
|
|
454
|
+
|
|
455
|
+
Example parent handler (buffered, simple):
|
|
456
|
+
|
|
457
|
+
```html
|
|
458
|
+
<script>
|
|
459
|
+
const uploads = new Map();
|
|
460
|
+
window.addEventListener('message', async (e) => {
|
|
461
|
+
const m = e.data;
|
|
462
|
+
if (!m || m._smartlinksProxyUpload !== true) return;
|
|
463
|
+
const target = e.source; // reply to the sender iframe
|
|
464
|
+
const origin = e.origin; // consider validating and passing a strict origin
|
|
465
|
+
switch (m.phase) {
|
|
466
|
+
case 'start': {
|
|
467
|
+
uploads.set(m.id, { chunks: [], fields: m.fields, fileInfo: m.fileInfo, path: m.path, headers: m.headers });
|
|
468
|
+
break;
|
|
469
|
+
}
|
|
470
|
+
case 'chunk': {
|
|
471
|
+
const u = uploads.get(m.id);
|
|
472
|
+
if (!u) break;
|
|
473
|
+
u.chunks.push(new Uint8Array(m.chunk));
|
|
474
|
+
target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'ack', id: m.id, seq: m.seq }, origin);
|
|
475
|
+
break;
|
|
476
|
+
}
|
|
477
|
+
case 'end': {
|
|
478
|
+
const u = uploads.get(m.id);
|
|
479
|
+
if (!u) break;
|
|
480
|
+
const blob = new Blob(u.chunks, { type: u.fileInfo.type || 'application/octet-stream' });
|
|
481
|
+
const fd = new FormData();
|
|
482
|
+
for (const [k, v] of u.fields) fd.append(k, v);
|
|
483
|
+
fd.append(u.fileInfo.key || 'file', blob, u.fileInfo.name || 'upload.bin');
|
|
484
|
+
|
|
485
|
+
const xhr = new XMLHttpRequest();
|
|
486
|
+
xhr.open('POST', (window.SMARTLINKS_API_BASEURL || '') + u.path);
|
|
487
|
+
for (const [k, v] of Object.entries(u.headers || {})) xhr.setRequestHeader(k, v);
|
|
488
|
+
xhr.upload.onprogress = (ev) => {
|
|
489
|
+
if (ev.lengthComputable) {
|
|
490
|
+
const pct = Math.round((ev.loaded / ev.total) * 100);
|
|
491
|
+
target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'progress', id: m.id, percent: pct }, origin);
|
|
492
|
+
}
|
|
493
|
+
};
|
|
494
|
+
xhr.onload = () => {
|
|
495
|
+
const ok = xhr.status >= 200 && xhr.status < 300;
|
|
496
|
+
try {
|
|
497
|
+
const data = JSON.parse(xhr.responseText);
|
|
498
|
+
target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'done', id: m.id, ok, data, error: ok ? undefined : data?.message }, origin);
|
|
499
|
+
} catch (err) {
|
|
500
|
+
target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'done', id: m.id, ok: false, error: 'Invalid server response' }, origin);
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
xhr.onerror = () => target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'done', id: m.id, ok: false, error: 'Network error' }, origin);
|
|
504
|
+
xhr.send(fd);
|
|
505
|
+
uploads.delete(m.id);
|
|
506
|
+
break;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
</script>
|
|
511
|
+
```
|
|
512
|
+
|
|
513
|
+
If you maintain the parent proxy, ensure its handler for `_smartlinksProxyRequest`:
|
|
514
|
+
- Detects `body._isFormData === true` and rebuilds `const fd = new FormData(); for (const [k,v] of body.entries) fd.append(k, v);`
|
|
515
|
+
- Issues the HTTP request with that `FormData` and returns the parsed JSON response back to the iframe.
|
|
516
|
+
|
|
517
|
+
### AI helpers
|
|
518
|
+
|
|
519
|
+
```ts
|
|
520
|
+
import { ai } from '@proveanything/smartlinks'
|
|
521
|
+
|
|
522
|
+
const content = await ai.generateContent('collectionId', {
|
|
523
|
+
contents: 'Write a friendly product blurb for our coffee beans.',
|
|
524
|
+
responseMimeType: 'text/plain',
|
|
525
|
+
provider: 'openai',
|
|
526
|
+
model: 'gpt-4o'
|
|
527
|
+
})
|
|
528
|
+
console.log(content)
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
### Analytics (Actions & Broadcasts)
|
|
532
|
+
|
|
533
|
+
Track user actions and broadcast deliveries per collection. These endpoints live under admin and require valid auth (API key or bearer token).
|
|
534
|
+
|
|
535
|
+
```ts
|
|
536
|
+
import { actions, broadcasts } from '@proveanything/smartlinks'
|
|
537
|
+
|
|
538
|
+
// List action events for a user
|
|
539
|
+
const actionEvents = await actions.byUser('collectionId', {
|
|
540
|
+
userId: 'user_123',
|
|
541
|
+
from: '2025-01-01T00:00:00Z',
|
|
542
|
+
to: '2025-12-31T23:59:59Z',
|
|
543
|
+
limit: 100,
|
|
544
|
+
})
|
|
545
|
+
|
|
546
|
+
// Outcome counts, optionally deduping latest per actor
|
|
547
|
+
const counts = await actions.countsByOutcome('collectionId', {
|
|
548
|
+
actionId: 'click',
|
|
549
|
+
dedupeLatest: true,
|
|
550
|
+
idField: 'userId',
|
|
551
|
+
})
|
|
552
|
+
|
|
553
|
+
// Append a single action event
|
|
554
|
+
await actions.append('collectionId', {
|
|
555
|
+
userId: 'user_123',
|
|
556
|
+
actionId: 'click',
|
|
557
|
+
outcome: 'success',
|
|
558
|
+
})
|
|
559
|
+
|
|
560
|
+
// Broadcast recipients and filters
|
|
561
|
+
const recipients = await broadcasts.recipientIds('collectionId', {
|
|
562
|
+
broadcastId: 'br_456',
|
|
563
|
+
idField: 'contactId',
|
|
564
|
+
})
|
|
565
|
+
|
|
566
|
+
// Append broadcast recipients in bulk (preferred shape)
|
|
567
|
+
await broadcasts.appendBulk('collectionId', {
|
|
568
|
+
params: { broadcastId: 'br_456', channel: 'email' },
|
|
569
|
+
ids: ['contact_1','contact_2'],
|
|
570
|
+
idField: 'contactId',
|
|
571
|
+
})
|
|
572
|
+
```
|
|
573
|
+
|
|
574
|
+
### Broadcast sending and previews
|
|
575
|
+
|
|
576
|
+
```ts
|
|
577
|
+
import { broadcasts } from '@proveanything/smartlinks'
|
|
578
|
+
|
|
579
|
+
// Preview a broadcast (HTML)
|
|
580
|
+
const preview = await broadcasts.preview('collectionId', 'broadcastId', {
|
|
581
|
+
contactId: 'contact_123',
|
|
582
|
+
props: { firstName: 'Sam' },
|
|
583
|
+
})
|
|
584
|
+
|
|
585
|
+
// Send a test email
|
|
586
|
+
await broadcasts.sendTest('collectionId', 'broadcastId', {
|
|
587
|
+
to: 'test@example.com',
|
|
588
|
+
subject: 'Test subject',
|
|
589
|
+
props: { foo: 'bar' },
|
|
590
|
+
})
|
|
591
|
+
|
|
592
|
+
// Enqueue broadcast sending (background)
|
|
593
|
+
await broadcasts.send('collectionId', 'broadcastId', {
|
|
594
|
+
pageSize: 100,
|
|
595
|
+
sharedContext: { campaign: 'summer' },
|
|
596
|
+
})
|
|
597
|
+
|
|
598
|
+
// Manual page send (for testing/UX)
|
|
599
|
+
const manual = await broadcasts.sendManual('collectionId', 'broadcastId', {
|
|
600
|
+
limit: 50,
|
|
601
|
+
dryRun: true,
|
|
602
|
+
})
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
## Communications Overview
|
|
606
|
+
|
|
607
|
+
End-to-end explainer covering comms settings (unsubscribe, types), Web Push registration, and multi-channel broadcasts with SDK examples: [src/docs/smartlinks/comms-explainer.md](src/docs/smartlinks/comms-explainer.md)
|
|
608
|
+
|
|
609
|
+
### Async jobs
|
|
610
|
+
|
|
611
|
+
```ts
|
|
612
|
+
import { async as slAsync, jobs } from '@proveanything/smartlinks'
|
|
613
|
+
|
|
614
|
+
// Enqueue an async job
|
|
615
|
+
const queued = await slAsync.enqueueAsyncJob('collectionId', {
|
|
616
|
+
task: 'email:daily-digest',
|
|
617
|
+
payload: { segmentId: 'seg_1' },
|
|
618
|
+
priority: 5,
|
|
619
|
+
key: 'digest:seg_1',
|
|
620
|
+
})
|
|
621
|
+
|
|
622
|
+
// Check job status
|
|
623
|
+
const status = await slAsync.getAsyncJobStatus('collectionId', queued.id)
|
|
624
|
+
|
|
625
|
+
// List recent jobs
|
|
626
|
+
const recent = await jobs.listJobs('collectionId', { state: 'queued', limit: 20 })
|
|
627
|
+
|
|
628
|
+
// Get a single job
|
|
629
|
+
const job = await jobs.getJob('collectionId', queued.id)
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
## Browser and React
|
|
633
|
+
|
|
634
|
+
The SDK works in modern browsers. Initialize once and call public endpoints without an API key; authenticate to access protected/admin endpoints.
|
|
635
|
+
|
|
636
|
+
```ts
|
|
637
|
+
import { initializeApi } from '@proveanything/smartlinks'
|
|
638
|
+
import { collection } from '@proveanything/smartlinks'
|
|
639
|
+
|
|
640
|
+
initializeApi({ baseURL: 'https://smartlinks.app/api/v1' })
|
|
641
|
+
const collections = await collection.list(false)
|
|
642
|
+
```
|
|
643
|
+
|
|
644
|
+
For a fuller UI example, see `examples/react-demo.tsx`.
|
|
645
|
+
|
|
646
|
+
## Iframe Integration
|
|
647
|
+
|
|
648
|
+
When embedding Smartlinks inside an iframe (set `proxyMode: true` in `initializeApi` if you need parent-proxy API calls), you can also send UI/control messages to the parent window. The SDK provides lightweight helpers in `iframe.ts`:
|
|
649
|
+
|
|
650
|
+
```ts
|
|
651
|
+
import { enableAutoIframeResize, disableAutoIframeResize, redirectParent, sendParentCustom, isIframe } from '@proveanything/smartlinks'
|
|
652
|
+
|
|
653
|
+
// Automatically push height changes to parent so it can resize the iframe.
|
|
654
|
+
enableAutoIframeResize({ intervalMs: 150 })
|
|
655
|
+
|
|
656
|
+
// Later disable if not needed:
|
|
657
|
+
disableAutoIframeResize()
|
|
658
|
+
|
|
659
|
+
// Redirect parent window to a URL (e.g. after login):
|
|
660
|
+
redirectParent('https://app.example.com/dashboard')
|
|
661
|
+
|
|
662
|
+
// Send any custom event + payload:
|
|
663
|
+
sendParentCustom('smartlinks:navigate', { url: '/profile' })
|
|
664
|
+
|
|
665
|
+
if (isIframe()) {
|
|
666
|
+
console.log('Running inside an iframe')
|
|
667
|
+
}
|
|
668
|
+
```
|
|
669
|
+
|
|
670
|
+
Parent page can listen for these messages:
|
|
671
|
+
|
|
672
|
+
```ts
|
|
673
|
+
window.addEventListener('message', (e) => {
|
|
674
|
+
const msg = e.data
|
|
675
|
+
if (!msg || !msg._smartlinksIframeMessage) return
|
|
676
|
+
switch (msg.type) {
|
|
677
|
+
case 'smartlinks:resize':
|
|
678
|
+
// adjust iframe height
|
|
679
|
+
const iframeEl = document.getElementById('smartlinks-frame') as HTMLIFrameElement
|
|
680
|
+
if (iframeEl) iframeEl.style.height = msg.payload.height + 'px'
|
|
681
|
+
break
|
|
682
|
+
case 'smartlinks:redirect':
|
|
683
|
+
window.location.href = msg.payload.url
|
|
684
|
+
break
|
|
685
|
+
case 'smartlinks:navigate':
|
|
686
|
+
// Custom example
|
|
687
|
+
console.log('Navigate request:', msg.payload.url)
|
|
688
|
+
break
|
|
689
|
+
}
|
|
690
|
+
})
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
Notes:
|
|
694
|
+
- Auto-resize uses `ResizeObserver` when available, falling back to `MutationObserver` + polling.
|
|
695
|
+
- In non-browser or Node environments these helpers safely no-op.
|
|
696
|
+
- Use `sendParentCustom` for any domain-specific integration events.
|
|
697
|
+
|
|
698
|
+
## Configuration reference
|
|
699
|
+
|
|
700
|
+
```ts
|
|
701
|
+
initializeApi({
|
|
702
|
+
baseURL: string, // with or without trailing slash
|
|
703
|
+
apiKey?: string, // Node/server only
|
|
704
|
+
bearerToken?: string, // optional at init; set by auth.login/verifyToken
|
|
705
|
+
proxyMode?: boolean // set true if running inside an iframe and using parent proxy
|
|
706
|
+
ngrokSkipBrowserWarning?: boolean // forces header 'ngrok-skip-browser-warning: true'
|
|
707
|
+
extraHeaders?: Record<string,string> // custom headers merged in each request
|
|
708
|
+
iframeAutoResize?: boolean // default true when embedded in an iframe
|
|
709
|
+
logger?: Function | { debug?: Function; info?: Function; warn?: Function; error?: Function; log?: Function } // optional verbose logging
|
|
710
|
+
})
|
|
711
|
+
|
|
712
|
+
// Auto-detection: If baseURL contains '.ngrok.io' or '.ngrok-free.dev' the header is added automatically
|
|
713
|
+
// unless you explicitly set ngrokSkipBrowserWarning: false.
|
|
714
|
+
// Auto iframe resize: When in an iframe, resize messages are sent by default unless iframeAutoResize: false.
|
|
715
|
+
// Verbose logging: Pass a logger (e.g. console) to log outbound requests/responses and proxy postMessages.
|
|
716
|
+
```
|
|
717
|
+
|
|
718
|
+
When embedding the SDK in an iframe with `proxyMode: true`, you can also use:
|
|
719
|
+
|
|
720
|
+
```ts
|
|
721
|
+
import { sendCustomProxyMessage } from '@proveanything/smartlinks'
|
|
722
|
+
const data = await sendCustomProxyMessage('my-action', { foo: 'bar' })
|
|
723
|
+
|
|
724
|
+
// Toggle ngrok header or update custom headers later:
|
|
725
|
+
import { setNgrokSkipBrowserWarning, setExtraHeaders } from '@proveanything/smartlinks'
|
|
726
|
+
setNgrokSkipBrowserWarning(true)
|
|
727
|
+
setExtraHeaders({ 'X-Debug': '1' })
|
|
728
|
+
```
|
|
729
|
+
|
|
730
|
+
## Full API surface
|
|
731
|
+
|
|
732
|
+
Explore every function, parameter, and type here:
|
|
733
|
+
|
|
734
|
+
- [API_SUMMARY.md](docs/API_SUMMARY.md) - Complete API reference
|
|
735
|
+
|
|
736
|
+
## Additional Documentation
|
|
737
|
+
|
|
738
|
+
The SDK includes comprehensive guides for advanced features:
|
|
739
|
+
|
|
740
|
+
- **[Liquid Templates](docs/liquid-templates.md)** - Dynamic templating for emails and notifications with personalized data
|
|
741
|
+
- **[Real-Time Messaging](docs/realtime.md)** - Ably integration for live chat, presence, and real-time updates
|
|
742
|
+
- **[Theme System](docs/theme.system.md)** - Dynamic theming for iframe apps with CSS variables and postMessage
|
|
743
|
+
- **[Theme Defaults](docs/theme-defaults.md)** - Default theme configuration reference
|
|
744
|
+
- **[Widgets](docs/widgets.md)** - React widget system for embeddable components
|
|
745
|
+
- **[Internationalization](docs/i18n.md)** - Multi-language support and localization
|
|
746
|
+
|
|
747
|
+
## Requirements
|
|
748
|
+
|
|
749
|
+
- Node.js 16+ or modern browsers
|
|
750
|
+
- TypeScript 4.9+ (if using TS)
|
|
751
|
+
|
|
752
|
+
## License
|
|
753
|
+
|
|
754
|
+
MIT © Prove Anything
|
|
755
755
|
|