@proveanything/smartlinks 2.0.69 → 2.0.71

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/docs/overview.md CHANGED
@@ -1,475 +1,477 @@
1
- # SmartLinks Microapp Development Guide
2
-
3
- > **Platform revision:** R5 · **SDK:** `@proveanything/smartlinks@^2` · React 19 · Vite 8 · Router 7 · Tailwind 4 · TS 6.
4
- > The canonical version/host stack lives in [host-dependency-contract.md](host-dependency-contract.md).
5
-
6
- ---
7
-
8
- ## What Is a SmartLinks Microapp?
9
-
10
- SmartLinks connects **physical products to digital experiences**: each item has a digital identity — a **proof** — that a consumer reaches by scanning a QR / NFC tag, then claims and enriches over time. A **microapp** is a focused, embeddable React experience a brand adds to that product's digital life: product info, warranty registration, authenticity checks, manuals, competitions, loyalty, post-purchase support, and more.
11
-
12
- Rather than baking every feature into the core platform, functionality is distributed across purpose-built apps, so a brand adds exactly the experiences its product needs. Each app:
13
-
14
- - **Embeds** in the SmartLinks Portal (public) and Admin Console (management)
15
- - **Shares context** through URL parameters (collection, product, proof)
16
- - **Inherits identity** from the parent platform's auth
17
- - **Adapts** to the brand's theme
18
- - **Communicates** with the parent via postMessage for deep linking and navigation
19
-
20
- ### Deployment Modes
21
-
22
- Each microapp can be consumed in one or more of the following ways:
23
-
24
- | Mode | Description |
25
- |------|-------------|
26
- | **Container** | Full app in parent React tree. ~150 KB+ lazy-loaded. The primary consumer surface. |
27
- | **Iframe App** | Full React app inside an iframe. Fallback when sandboxing is required; still the standard for setup admin screens. |
28
- | **Widget** | Lightweight React component in parent tree. ~10 KB, loaded immediately alongside the page. |
29
- | **Mobile Admin Container** | Separate bundle for in-the-field operator/admin workflows on mobile. Built independently; may use Capacitor, Preact, or any other runtime. |
30
- | **Executor** | JS library, no UI. Programmatic config, SEO metadata, LLM content for AI/server. |
31
-
32
- Widgets and containers run in the parent's React tree (not iframes). Mobile Admin Containers are a separate bundle loaded by a dedicated mobile shell (Capacitor or PWA). Executors have no UI — they expose functions that AI orchestrators and the server call directly.
33
-
34
- > **Admin vs consumer:** Admin experiences always ship as a **separate bundle** (`mobileAdmin` or iframe). The `containers` bundle is for consumer-facing surfaces only.
35
-
36
- ---
37
-
38
- ## SDK Documentation Reference
39
-
40
- The SmartLinks SDK (`@proveanything/smartlinks`) includes comprehensive documentation in `node_modules/@proveanything/smartlinks/docs/`. **Always read these files for detailed implementation guidance.**
41
-
42
- > Product endpoints: use `products` (plural) for new integrations. The older `product` (singular) namespace remains for backward compatibility and is deprecated.
43
-
44
- > **SDK baseline: `@proveanything/smartlinks@^2.0`** (R5). Install/update with `npm install @proveanything/smartlinks@^2.0`. Individual features may need a higher minor — see the relevant doc. The single source of truth for the R5 host/version stack is [`host-dependency-contract.md`](host-dependency-contract.md).
45
-
46
- | Topic | File | When to Use |
47
- |-------|------|-------------|
48
- | **API Reference** | `docs/API_SUMMARY.md` | Complete SDK function reference, types, error handling |
49
- | **Assets** | `docs/assets.md` | Asset object, AssetRef, upload, replace, soft-delete, restore, bulk-delete, public token-based uploads |
50
- | **Building React Components** | `docs/building-react-components.md` | **READ THIS FIRST** — Dual-mode rendering, router rules, useAppContext pattern |
51
- | **Multi-Page Architecture** | `docs/mpa.md` | Build pipeline, entry points, multi-page setup, content hashing |
52
- | **AI & Chat** | `docs/ai.md` | Chat completions, RAG, streaming, tool calling, voice, podcasts, TTS |
53
- | **Analytics** | `docs/analytics.md` | Fire-and-forget page/click/tag analytics plus admin dashboard queries |
54
- | **Translations** | `docs/translations.md` | Runtime translation lookup, local-first IndexedDB caching, and translation admin APIs |
55
- | **Theming** | `docs/theme.system.md` | Implementing dynamic themes via URL params or postMessage |
56
- | **Theme Defaults** | `docs/theme-defaults.md` | Default colour values for light/dark modes |
57
- | **Internationalization** | `docs/i18n.md` | Adding multi-language support, translation patterns |
58
- | **Widgets** | `docs/widgets.md` | Building widgets, shared deps contract, settings schema |
59
- | **Containers** | `docs/containers.md` | Building full-app embeddable containers (lazy-loaded) |
60
- | **Mobile Admin Container** | `docs/mobile-admin-container.md` | Building a separate Capacitor-aware mobile admin bundle for field operators |
61
- | **Executors** | `docs/executor.md` | Building executor bundles for SEO, LLM content, programmatic config |
62
- | **Server Functions** | `docs/server-functions.md` | App-authored server-side functions `(ctx, event) ⇒ result`: security model, runtime surface, invoking |
63
- | **Agent Tools** | `docs/agent-tools.md` | Exposing your app's actions to the SmartLinks agent — an MCP facade over server functions; **opt-in per app, additive, no migration**; complements `app.admin.json` (functions serve/adapt it, don't replace it); live loop staged |
64
- | **Deploying & Registering** | `docs/deploying-apps.md` | Getting your app into the platform: fast dev publish, channels, deploy keys, registering releases |
65
- | **Host Dependency Contract (R5)** | `docs/host-dependency-contract.md` | The libraries the host provides (React 19, Router 7, Radix, liquidjs, …), the externalise-don't-bundle rule + Vite config, and React-18 backwards-compat |
66
- | **CSS Baseline** (`sl-baseline` v1) | `docs/css-baseline.md` | A small, frozen, `sl-`-namespaced set of structural helpers (layout, spacing, responsive flow, type scale, motion) the SDK ships (`@proveanything/smartlinks/baseline.css`) and the host guarantees — a teachable floor for apps + AI content. No colours/fonts/components. Opt-in via `meta.cssBaseline` |
67
- | **Deep Linking** | `docs/deep-link-discovery.md` | URL state management, navigable states, portal menus, AI nav |
68
- | **Portal Back Button** | `docs/portal-back-button.md` | Hierarchy-aware "up" navigation inside embedded apps |
69
- | **Portal Request Action** | `docs/portal-request-action.md` | Triggering portal built-in actions (__qrScanner, __share, __logout, etc.) from sub-apps |
70
- | **Interactions** | `docs/interactions.md` | Business events, outcomes, voting, competitions, and journey triggers |
71
- | **App Config Files** | `docs/app-manifest.md` | Full field-by-field reference for both JSON config files |
72
- | **Admin cards** | `docs/admin-cards.md` | Cards on the collection's dashboard in Studio: declare a card + an admin function returning its data; cached, refreshed only when its data changes |
73
- | **Realtime** | `docs/realtime.md` | Live updates: change events (refetch when something changes) and declared app channels (a draw, a status) — no provider library or keys |
74
- | **Liquid Templates** | `docs/liquid-templates.md` | Dynamic content rendering with LiquidJS |
75
- | **Iframe Responder** | `docs/iframe-responder.md` | Iframe communication and proxy mode internals |
76
- | **AI Guide Template** | `docs/ai-guide-template.md` | Template for creating `public/ai-guide.md` — customise per app |
77
- | **Forms** | `docs/forms.md` | Form definitions, schema-driven rendering, submission patterns |
78
- | **Auth Kit** | `docs/auth-kit.md` | End-user sign-in: email/password, magic links, phone OTP, Google OAuth |
79
- | **Portal Request Login** | `docs/portal-request-login.md` | How sub-apps ask the portal to authenticate the user; hook and iframe postMessage contracts |
80
- | **Portal Auth Broadcast** | `docs/portal-auth-broadcast.md` | Publishing custom auth flows to the portal; syncing sessions across containers and iframes |
81
- | **Contact Search** | `docs/contact-search.md` | Admin contact search: free-text, typeahead, identity/tag/JSONB filters, and pagination |
82
- | **App Records Pattern** | `docs/app-records-pattern.md` | Standard pattern for per-product/facet/variant/batch admin + public widget UIs |
83
- | **UI Utils** | `docs/ui-utils.md` | `@proveanything/smartlinks-utils-ui` — React shells, hooks, and primitives for records-based apps |
84
- | **Product/Proof Data Scoping** | `docs/proof-product-data-scoping.md` | Canonical spec for `product.data`/`.admin` and `proof.data`/`.admin`/`.values` (owner/personal) — who can read and write each bucket |
85
- | **Proof Claiming** | `docs/proof-claiming-methods.md` | The ways a user claims a proof (serial, NFC, claim-set, auto-generate) |
86
- | **Proof Share Grants** | `docs/proof-share-grants.md` | Delegated, scoped, revocable bearer access to a single proof (read/comment/verify-owner) |
87
- | **Proof Ownership Transfer** | `docs/proof-ownership-transfer.md` | Moving a proof's single owner (directed transfer / open release), accept/cancel, and the state machine |
88
- | **appConfig / Feature Flags** | `docs/appConfig.md` | `appConfig` settings contract — installed apps, `system.features`/`entitledAppGroups`/`meters`, `isFeatureEnabled()` helper |
89
- | **App Objects** | `docs/app-objects.md` | Queryable domain objects — `app.records` / `app.cases` / `app.threads`: JSONB zones, visibility, policies, aggregations |
90
- | **App Data Storage** | `docs/app-data-storage.md` | Decision guide: pick between `appConfiguration` / `userAppData` / `app.records` |
91
- | **Attestations** | `docs/attestations.md` | Postgres attestations API (proof-level user/admin data; replaces the legacy Firestore path) |
92
- | **Caching** | `docs/caching.md` | SDK GET cache tiers + TTLs, `invalidateCache({ exact })`, and `force`/push guidance |
93
- | **Comms & Broadcasts** | `docs/comms.md` | Transactional comms, campaigns, consent, push |
94
- | **Container Tracking** | `docs/container-tracking.md` | Physical/logical **item** container groupings — *not* app containers (see containers.md) |
95
- | **Lots** | `docs/lots.md` | Cross-SKU production "Lot" entity |
96
- | **Loyalty** | `docs/loyalty.md` | Points, members, earning rules |
97
- | **Integrations** | `docs/integrations.md` | Inbound/outbound external-system integration flows |
98
- | **Connectors** | `docs/connectors.md` | Connector apps: the manifest `connector` block + the functions the integration engine calls |
99
- | **Item Context** | `docs/item-context.md` | The `itemContext` container prop (serial / NFC authenticity context) |
100
- | **Native Facade** | `docs/native-facade.md` | `host.native` / `SL.native` device-capability facade |
101
- | **Product Facets** | `docs/PRODUCT_FACETS_SDK.md` | Facet API reference (admin + public endpoints, types) |
102
- | **AI Tools & Skills** | `docs/ai-tools-and-skills.md` | Platform AI capability registry (web research, extraction, images) |
103
- | **Proof Comms Triggers** | `docs/proof-comms-triggers.md` | Transactional comms fired as a side-effect of proof actions |
104
-
105
- ---
106
-
107
- ## Technical Overview
108
-
109
- - **Iframe-based** — Apps run inside iframes in both the public Portal and Admin Console
110
- - **Hash routing** — Uses `/#/` routes for iframe compatibility (e.g., `/#/`, `/#/admin`)
111
- - **Context via URL params** — All contextual data is passed through URL parameters
112
- - **SmartLinks NPM module** — All data access and platform interaction goes through `@proveanything/smartlinks`
113
- - **No standalone auth** — Authentication is handled by the parent SmartLinks platform
114
-
115
- > **Use the host-provided `SL`, don't instantiate your own.** When your app runs in a
116
- > container/iframe, the host injects an already-initialized, authenticated SDK instance (the
117
- > `SL` prop / the externalized `@proveanything/smartlinks` singleton). Import and use *that*.
118
- > Calling `initializeApi()` yourself to spin up a **second** SDK instance is a common source
119
- > of bugs: it won't share the host's auth (so it looks signed-out), won't share the host's
120
- > cache (duplicate requests, stale data), and in proxy mode it bypasses the host's request
121
- > routing. Rule of thumb: **host-provided `SL` for anything the platform owns** (auth, config,
122
- > data, cache); only app-owned state is yours.
123
- - **Multi-page build** — Separate bundles for public and admin — see `docs/mpa.md`
124
- - **Embedded back navigation** — Use `docs/portal-back-button.md` when a sub-app has a real content hierarchy
125
-
126
- ---
127
-
128
- ## Data Model Hierarchy
129
-
130
- ```
131
- Collection (Business/Brand)
132
- └── Product (Product Type/Definition)
133
- └── Proof (Specific Instance with Owner)
134
- └── Attestation (User/Admin Data on Proof)
135
- ```
136
-
137
- | Entity | Description | Example |
138
- |--------|-------------|---------|
139
- | **Collection** | Top-level container representing a business or brand | "Acme Wine Co." |
140
- | **Product** | A type of product (not a specific item) | "2023 Cabernet Sauvignon" |
141
- | **Proof** | A specific instance of a product, often with an owner | Bottle #12345 claimed by user@email.com |
142
- | **Attestation** | Data attached to a proof by users or admins | Warranty registration, tasting notes |
143
-
144
- ### URL Parameters
145
-
146
- | Parameter | Type | Description |
147
- |-----------|------|-------------|
148
- | `collectionId` | string | The collection being viewed/managed |
149
- | `productId` | string | The specific product (within collection) |
150
- | `proofId` | string | The specific proof instance |
151
- | `appId` | string | This app's unique identifier (for data scoping) |
152
- | `dark` | `1` or `0` | Whether to use dark mode |
153
- | `theme` | base64 | Full theme configuration (see `docs/theme.system.md`) |
154
-
155
- ---
156
-
157
- ## Authentication & Permissions
158
-
159
- SmartLinks apps do **not** implement their own authentication. The parent platform handles all auth:
160
-
161
- - Use `SL.auth.getAccount()` to check if a user is logged in
162
- - The response includes whether the user is an `admin` or regular user
163
- - Many SmartLinks API functions behave differently based on admin status
164
-
165
- | Capability | Admin | Regular User |
166
- |------------|-------|-------------|
167
- | Read collection/product data | ✅ | ✅ |
168
- | Write app configuration | ✅ | ❌ |
169
- | Write attestations | ✅ | ✅ (own proofs only) |
170
- | Access admin-only API fields | ✅ | ❌ |
171
-
172
- ---
173
-
174
- ## Data Storage Patterns
175
-
176
- ### ⚠️ Critical: Admin Mode Flag
177
-
178
- **When building admin interfaces, you MUST pass `admin: true` in API options.**
179
-
180
- Without this flag, API calls use the public endpoint and will fail to write data:
181
-
182
- ```typescript
183
- // ❌ WRONG — will fail in admin interface
184
- await SL.appConfiguration.setConfig({ collectionId, appId, config: myConfig });
185
-
186
- // ✅ CORRECT — include admin: true
187
- await SL.appConfiguration.setConfig({ collectionId, appId, config: myConfig, admin: true });
188
- ```
189
-
190
- This applies to all write operations: `setConfig`, `setDataItem`, `updateDataItem`, etc.
191
-
192
- ### Endpoint Auth vs Data Visibility
193
-
194
- `admin: true` is an endpoint selector, not a privacy marker.
195
-
196
- - It tells the SDK to call the admin endpoint.
197
- - It allows writes and admin reads.
198
- - It does **not** mean every root-level field you save becomes admin-only.
199
-
200
- For `appConfiguration` config blobs and `collection.getSettings()` groups, root-level fields are typically the public-facing settings. If you need private values such as tokens or secrets, store them inside a top-level `admin` object:
201
-
202
- ```typescript
203
- await SL.appConfiguration.setConfig({
204
- collectionId,
205
- appId,
206
- admin: true,
207
- config: {
208
- publicLabel: 'Warranty Portal',
209
- color: '#B68C2A',
210
- admin: {
211
- accessToken: 'secret-token'
212
- }
213
- }
214
- })
215
- ```
216
-
217
- Public reads omit the `admin` block. Admin reads include it.
218
-
219
- ### Config vs Data
220
-
221
- | Storage Type | Function | Use Case |
222
- |-------------|---------|---------|
223
- | **Config** (`getConfig`/`setConfig`) | Single JSON document | App settings, feature flags, global options |
224
- | **Data** (`getData`/`setDataItem`) | Array of documents with IDs | Lists of items, records, entries |
225
- | **App Objects** (`app.records` / `app.cases` / `app.threads`) | Queryable domain objects | Real app entities, workflows, conversations, richer access control |
226
-
227
- Both can be scoped to **collection level** or **product level** by including `productId`.
228
-
229
- For config/settings visibility, remember: root fields are the normal shared payload, while a reserved top-level `admin` object is the place for admin-only values.
230
-
231
- Prefer `app.records` over `setDataItem` when the data is becoming a real entity that needs lifecycle, ownership, visibility, relationships, or filtering. Keep `setDataItem` for simple keyed scoped documents and config-adjacent content.
232
-
233
- ### Feature Flags & Entitlements (`appConfig`)
234
-
235
- The platform-owned `appConfig` settings group (`system.features`, `system.meters`, `system.entitledAppGroups`, installed `apps[]`) tells a microapp what's installed and entitled for a collection. Use `SL.appConfiguration.isFeatureEnabled(collectionId, flag)` to gate a feature — it's the standard, cache-backed way to do this rather than hand-rolling a `getConfig` call:
236
-
237
- ```ts
238
- if (await SL.appConfiguration.isFeatureEnabled(collectionId, 'custom_domain')) {
239
- enableCustomDomainUI();
240
- }
241
- ```
242
-
243
- It's async (the first check for a collection has nothing cached yet); `SL.appConfiguration.isFeatureEnabledSync()` gives a synchronous, cache-only read (`boolean | undefined`) for callers that warmed the cache earlier and can't await. See `docs/appConfig.md` for the full contract, including `systemPrivate` (admin-only overrides, always stripped for non-admin reads).
244
-
245
- ### Attestations (Proof-level data)
246
-
247
- For data attached to specific proof instances, use `SL.attestation.create()` and `SL.attestation.list()`.
248
-
249
- ### Custom Data Scoping (Product & Proof)
250
-
251
- `product.data`/`product.admin` and `proof.data`/`proof.admin`/`proof.values` are the canonical buckets for custom fields on products and proofs — `data` is public and business-writable, `admin` is business-only, and `proof.values` additionally supports owner-scoped (`values.owner`) and per-user (`values.personal[userId]`) sub-keys. This is a different mechanism from the app-scoped storage in `docs/app-data-storage.md` (which is for app-owned config/records, not the product/proof documents themselves).
252
-
253
- See `docs/proof-product-data-scoping.md` for the full read/write authority matrix, worked examples, and the `productFields`/`proofFields` collection-settings schemas that drive field-config editors.
254
-
255
- ---
256
-
257
- ## Error Handling
258
-
259
- The SmartLinks SDK returns structured `SmartlinksApiError` objects. Use `instanceof SmartlinksApiError` to access `.statusCode`, `.message`, and helper methods:
260
-
261
- - `.isAuthError()` — 401/403 responses
262
- - `.isNotFound()` — 404 responses
263
- - `.isRateLimited()` — 429 responses
264
- - `.isServerError()` — 5xx responses
265
-
266
- See `docs/API_SUMMARY.md` for complete error handling documentation.
267
-
268
- ---
269
-
270
- ## AI Integration
271
-
272
- SmartLinks provides comprehensive AI capabilities through the `SL.ai` namespace. **Always use SmartLinks AI for microapps** — do not integrate external AI services (OpenAI, Anthropic, Lovable Cloud AI, etc.) directly.
273
-
274
- Key capabilities: chat completions (streaming + tool calling), RAG document Q&A, voice input/output, podcast generation, text-to-speech, model listing.
275
-
276
- See `docs/ai.md` for complete documentation.
277
-
278
- ---
279
-
280
- ## Interactions & Event Tracking
281
-
282
- The `SL.interactions` namespace tracks user engagement — competition entries, votes, form submissions, warranty registrations. Events can trigger automated journeys and communications.
283
-
284
- **The one rule:** you never choose an interaction id. In admin, `SL.interactions.ensureType(collectionId, { appId, key: 'vote', … })` finds-or-creates the type and returns its server-minted `id`; store it in app config (`interactionIds: { vote: type.id }`); everywhere else — public widgets included — read `interactionIds.vote` from config and pass that as `interactionId`. Never write an interactionId as a string literal.
285
-
286
- Key functions: `submitPublicEvent()`, `appendEvent()` (admin), `countsByOutcome()`, `query()`.
287
-
288
- See `docs/interactions.md` for complete documentation.
289
-
290
- ---
291
-
292
- ## Liquid Templating
293
-
294
- Use the `<LiquidContent>` component, `useLiquidTemplate` hook, and `renderLiquid` utility for admin-configured dynamic content using Liquid syntax.
295
-
296
- See `docs/liquid-templates.md` for full context variables, filters, and examples.
297
-
298
- ---
299
-
300
- ## Design Principles
301
-
302
- ### Public Interface (Portal)
303
-
304
- - **Mobile-first** — Assume users are on phones
305
- - **Non-technical** — Never show raw IDs or technical data
306
- - **Accessible** — Follow WCAG guidelines
307
-
308
- ### Admin Interface
309
-
310
- - **Feature-rich** — Power users expect advanced controls
311
- - **Efficient** — Minimise clicks for common tasks
312
- - **Desktop-optimised** — Admins typically use desktop browsers
313
-
314
- ### Theming
315
-
316
- Apps receive theme configuration from the parent platform via URL parameter (`?theme=base64…`) and PostMessage updates. See `docs/theme.system.md`.
317
-
318
- ---
319
-
320
- ## Common Hooks
321
-
322
- ```typescript
323
- // Fetch collection/product/proof data
324
- useCollectionData(collectionId)
325
- useProductData(collectionId, productId)
326
- useProofData(collectionId, productId, proofId)
327
-
328
- // Fetch app configuration
329
- useCollectionAppConfig(collectionId, appId)
330
- useProductAppConfig(collectionId, productId, appId)
331
-
332
- // Fetch app data (array of items)
333
- useCollectionAppData(collectionId, appId)
334
- useProductAppData(collectionId, productId, appId)
335
-
336
- // Fetch attestations
337
- useAttestationsData(collectionId, productId, proofId)
338
-
339
- // URL parameter management
340
- usePersistentQueryParams()
341
-
342
- // Theme management
343
- useSmartLinksTheme()
344
-
345
- // Liquid templating
346
- useLiquidTemplate(templateString, contextData)
347
- ```
348
-
349
- ---
350
-
351
- ## API Namespaces
352
-
353
- The SmartLinks SDK is organised into namespaces. See `docs/API_SUMMARY.md` for the complete reference. Key namespaces:
354
-
355
- - `appConfiguration` — Config and data storage (most apps use this)
356
- - `attestation` — Proof-level user/admin data
357
- - `interactions` — Event tracking and analytics
358
- - `ai` — AI content generation, chat, RAG (see `docs/ai.md`)
359
- - `auth` / `authKit` — Admin and end-user authentication
360
- - `contact` — Customer contact management
361
- - `comms` / `broadcasts` — Notifications and campaigns
362
- - `asset` — File/image uploads
363
- - `adminCards` — the collection's dashboard: `list`, `refresh`, `saveLayout` (see `docs/admin-cards.md`)
364
- - `realtime` — SmartLinks Realtime: `onChange`, `channel`, `onMine` (see `docs/realtime.md`)
365
-
366
- ---
367
-
368
- ## File Structure
369
-
370
- ```
371
- ├── index.html ← Public portal entry
372
- ├── admin.html ← Admin console entry
373
- ├── public/
374
- │ ├── app.manifest.json ← Public discovery manifest
375
- │ ├── app.admin.json ← Admin manifest (on-demand)
376
- │ └── ai-guide.md ← AI orchestrator prose guide
377
- ├── src/
378
- │ ├── main.tsx ← Public React entry
379
- │ ├── admin-main.tsx ← Admin React entry
380
- │ ├── App.tsx ← Shared providers (QueryClient, Toaster, etc.)
381
- │ ├── PublicApp.tsx ← Public app shell (routes only public pages)
382
- │ ├── AdminApp.tsx ← Admin app shell (routes only admin pages)
383
- │ ├── components/ ← Reusable UI components
384
- │ ├── containers/ ← Embeddable full-app containers
385
- │ ├── executor/ ← Executor bundle (SEO, LLM content, config API)
386
- │ ├── hooks/ ← React hooks (data fetching, state)
387
- │ ├── pages/
388
- │ │ ├── PublicPage.tsx ← Portal content (/#/)
389
- │ │ ├── AdminPage.tsx ← Admin content (admin.html#/)
390
- │ │ └── DevPage.tsx ← Development helper (dev only)
391
- │ ├── widgets/ ← Embeddable widget components
392
- │ └── utils/
393
- │ ├── smartlinks/ ← SmartLinks utilities
394
- │ └── theme.ts ← Theme utilities
395
- ├── vite.config.ts ← Multi-page build config
396
- ├── vite.config.widget.ts ← Widget library build config
397
- ├── vite.config.container.ts ← Container library build config
398
- └── vite.config.executor.ts ← Executor library build config
399
- ```
400
-
401
- ---
402
-
403
- ## Anti-Patterns to Avoid
404
-
405
- ❌ **Don't implement custom auth** — Use SmartLinks auth via `SL.auth.getAccount()`
406
-
407
- ❌ **Don't use BrowserRouter** — Always use HashRouter for iframe compatibility
408
-
409
- ❌ **Don't hardcode URLs** — Use relative paths and let the platform provide context
410
-
411
- ❌ **Don't store secrets in code** — Use environment variables or platform configuration
412
-
413
- ❌ **Don't assume screen size** — Support both mobile (Portal) and desktop (Admin)
414
-
415
- ❌ **Don't expose technical IDs** — Show human-readable names to users
416
-
417
- ❌ **Don't import AdminPage in PublicApp** — Keep bundles separate for optimal size
418
-
419
- ❌ **Don't use external AI services** — Use SmartLinks AI via `SL.ai`, not OpenAI/Anthropic/Lovable Cloud AI directly
420
-
421
- ❌ **Don't forget `admin: true`** — All admin write operations require this flag
422
-
423
- ---
424
-
425
- ## Quick Reference
426
-
427
- ### Initialise the API
428
-
429
- ```typescript
430
- import { initializeAPI } from '@/utils/smartlinks/initialization';
431
- initializeAPI(); // Call once at app startup
432
- ```
433
-
434
- ### Get Context from URL
435
-
436
- ```typescript
437
- const { persistentQueryParams } = usePersistentQueryParams();
438
- const { collectionId, productId, appId } = persistentQueryParams;
439
- ```
440
-
441
- ### Check Admin Status
442
-
443
- ```typescript
444
- const account = await SL.auth.getAccount();
445
- const isAdmin = account?.admin === true;
446
- ```
447
-
448
- ### Save Configuration (Admin Only)
449
-
450
- ```typescript
451
- await SL.appConfiguration.setConfig({
452
- collectionId, appId,
453
- config: { myKey: 'myValue' },
454
- admin: true // Required!
455
- });
456
- ```
457
-
458
- ### Handle Dark Mode + Theming
459
-
460
- ```typescript
461
- // In App.tsx — already integrated in the template
462
- useDarkMode(); // Handles ?dark=1 parameter
463
- useSmartLinksTheme(); // Handles ?theme=base64 parameter
464
- useDeepLinkSync(); // Syncs route changes to parent
465
- ```
466
-
467
- ### Deep Linking
468
-
469
- ```typescript
470
- const { navigateWithState, getAppState } = usePersistentQueryParams();
471
- const { tab = 'general' } = getAppState();
472
- navigateWithState('/', { tab: 'advanced' });
473
- ```
474
-
475
- See `docs/deep-link-discovery.md` for full implementation details.
1
+ # SmartLinks Microapp Development Guide
2
+
3
+ > **Platform revision:** R5 · **SDK:** `@proveanything/smartlinks@^2` · React 19 · Vite 8 · Router 7 · Tailwind 4 · TS 6.
4
+ > The canonical version/host stack lives in [host-dependency-contract.md](host-dependency-contract.md).
5
+
6
+ ---
7
+
8
+ ## What Is a SmartLinks Microapp?
9
+
10
+ SmartLinks connects **physical products to digital experiences**: each item has a digital identity — a **proof** — that a consumer reaches by scanning a QR / NFC tag, then claims and enriches over time. A **microapp** is a focused, embeddable React experience a brand adds to that product's digital life: product info, warranty registration, authenticity checks, manuals, competitions, loyalty, post-purchase support, and more.
11
+
12
+ Rather than baking every feature into the core platform, functionality is distributed across purpose-built apps, so a brand adds exactly the experiences its product needs. Each app:
13
+
14
+ - **Embeds** in the SmartLinks Portal (public) and Admin Console (management)
15
+ - **Shares context** through URL parameters (collection, product, proof)
16
+ - **Inherits identity** from the parent platform's auth
17
+ - **Adapts** to the brand's theme
18
+ - **Communicates** with the parent via postMessage for deep linking and navigation
19
+
20
+ ### Deployment Modes
21
+
22
+ Each microapp can be consumed in one or more of the following ways:
23
+
24
+ | Mode | Description |
25
+ |------|-------------|
26
+ | **Container** | Full app in parent React tree. ~150 KB+ lazy-loaded. The primary consumer surface. |
27
+ | **Iframe App** | Full React app inside an iframe. Fallback when sandboxing is required; still the standard for setup admin screens. |
28
+ | **Widget** | Lightweight React component in parent tree. ~10 KB, loaded immediately alongside the page. |
29
+ | **Mobile Admin Container** | Separate bundle for in-the-field operator/admin workflows on mobile. Built independently; may use Capacitor, Preact, or any other runtime. |
30
+ | **Executor** | JS library, no UI. Programmatic config, SEO metadata, LLM content for AI/server. |
31
+
32
+ Widgets and containers run in the parent's React tree (not iframes). Mobile Admin Containers are a separate bundle loaded by a dedicated mobile shell (Capacitor or PWA). Executors have no UI — they expose functions that AI orchestrators and the server call directly.
33
+
34
+ > **Admin vs consumer:** Admin experiences always ship as a **separate bundle** (`mobileAdmin` or iframe). The `containers` bundle is for consumer-facing surfaces only.
35
+
36
+ ---
37
+
38
+ ## SDK Documentation Reference
39
+
40
+ The SmartLinks SDK (`@proveanything/smartlinks`) includes comprehensive documentation in `node_modules/@proveanything/smartlinks/docs/`. **Always read these files for detailed implementation guidance.**
41
+
42
+ > Product endpoints: use `products` (plural) for new integrations. The older `product` (singular) namespace remains for backward compatibility and is deprecated.
43
+
44
+ > **SDK baseline: `@proveanything/smartlinks@^2.0`** (R5). Install/update with `npm install @proveanything/smartlinks@^2.0`. Individual features may need a higher minor — see the relevant doc. The single source of truth for the R5 host/version stack is [`host-dependency-contract.md`](host-dependency-contract.md).
45
+
46
+ | Topic | File | When to Use |
47
+ |-------|------|-------------|
48
+ | **API Reference** | `docs/API_SUMMARY.md` | Complete SDK function reference, types, error handling |
49
+ | **Assets** | `docs/assets.md` | Asset object, AssetRef, upload, replace, soft-delete, restore, bulk-delete, public token-based uploads |
50
+ | **Building React Components** | `docs/building-react-components.md` | **READ THIS FIRST** — Dual-mode rendering, router rules, useAppContext pattern |
51
+ | **Multi-Page Architecture** | `docs/mpa.md` | Build pipeline, entry points, multi-page setup, content hashing |
52
+ | **AI & Chat** | `docs/ai.md` | Chat completions, RAG, streaming, tool calling, voice, podcasts, TTS |
53
+ | **Analytics** | `docs/analytics.md` | Fire-and-forget page/click/tag analytics plus admin dashboard queries |
54
+ | **Translations** | `docs/translations.md` | Runtime translation lookup, local-first IndexedDB caching, and translation admin APIs |
55
+ | **Theming** | `docs/theme.system.md` | Implementing dynamic themes via URL params or postMessage |
56
+ | **Theme Defaults** | `docs/theme-defaults.md` | Default colour values for light/dark modes |
57
+ | **Internationalization** | `docs/i18n.md` | Adding multi-language support, translation patterns |
58
+ | **Widgets** | `docs/widgets.md` | Building widgets, shared deps contract, settings schema |
59
+ | **Containers** | `docs/containers.md` | Building full-app embeddable containers (lazy-loaded) |
60
+ | **Mobile Admin Container** | `docs/mobile-admin-container.md` | Building a separate Capacitor-aware mobile admin bundle for field operators |
61
+ | **Executors** | `docs/executor.md` | Building executor bundles for SEO, LLM content, programmatic config |
62
+ | **Server Functions** | `docs/server-functions.md` | App-authored server-side functions `(ctx, event) ⇒ result`: security model, runtime surface, invoking |
63
+ | **Agent Tools** | `docs/agent-tools.md` | Exposing your app's actions to the SmartLinks agent — an MCP facade over server functions; **opt-in per app, additive, no migration**; complements `app.admin.json` (functions serve/adapt it, don't replace it); live loop staged |
64
+ | **Deploying & Registering** | `docs/deploying-apps.md` | Getting your app into the platform: fast dev publish, channels, deploy keys, registering releases |
65
+ | **Host Dependency Contract (R5)** | `docs/host-dependency-contract.md` | The libraries the host provides (React 19, Router 7, Radix, liquidjs, …), the externalise-don't-bundle rule + Vite config, and React-18 backwards-compat |
66
+ | **CSS Baseline** (`sl-baseline` v1) | `docs/css-baseline.md` | A small, frozen, `sl-`-namespaced set of structural helpers (layout, spacing, responsive flow, type scale, motion) the SDK ships (`@proveanything/smartlinks/baseline.css`) and the host guarantees — a teachable floor for apps + AI content. No colours/fonts/components. Opt-in via `meta.cssBaseline` |
67
+ | **Deep Linking** | `docs/deep-link-discovery.md` | URL state management, navigable states, portal menus, AI nav |
68
+ | **Portal Back Button** | `docs/portal-back-button.md` | Hierarchy-aware "up" navigation inside embedded apps |
69
+ | **Portal Request Action** | `docs/portal-request-action.md` | Triggering portal built-in actions (__qrScanner, __share, __logout, etc.) from sub-apps |
70
+ | **Interactions** | `docs/interactions.md` | Business events, outcomes, voting, competitions, and journey triggers |
71
+ | **App Config Files** | `docs/app-manifest.md` | Full field-by-field reference for both JSON config files |
72
+ | **Admin cards** | `docs/admin-cards.md` | Cards on the collection's dashboard in Studio: declare a card + an admin function returning its data; cached, refreshed only when its data changes |
73
+ | **Realtime** | `docs/realtime.md` | Live updates: change events (refetch when something changes) and declared app channels (a draw, a status) — no provider library or keys |
74
+ | **Liquid Templates** | `docs/liquid-templates.md` | Dynamic content rendering with LiquidJS |
75
+ | **Iframe Responder** | `docs/iframe-responder.md` | Iframe communication and proxy mode internals |
76
+ | **AI Guide Template** | `docs/ai-guide-template.md` | Template for creating `public/ai-guide.md` — customise per app |
77
+ | **Forms** | `docs/forms.md` | Form definitions, schema-driven rendering, submission patterns |
78
+ | **Auth Kit** | `docs/auth-kit.md` | End-user sign-in: email/password, magic links, phone OTP, Google OAuth |
79
+ | **Members** | `docs/members.md` | Signed-in members with a level (clubs, leagues, members' areas): the level field, members-only functions, joining rules |
80
+ | **Portal Request Login** | `docs/portal-request-login.md` | How sub-apps ask the portal to authenticate the user; hook and iframe postMessage contracts |
81
+ | **Portal Auth Broadcast** | `docs/portal-auth-broadcast.md` | Publishing custom auth flows to the portal; syncing sessions across containers and iframes |
82
+ | **Contact Search** | `docs/contact-search.md` | Admin contact search: free-text, typeahead, identity/tag/JSONB filters, and pagination |
83
+ | **App Records Pattern** | `docs/app-records-pattern.md` | Standard pattern for per-product/facet/variant/batch admin + public widget UIs |
84
+ | **UI Utils** | `docs/ui-utils.md` | `@proveanything/smartlinks-utils-ui` — React shells, hooks, and primitives for records-based apps |
85
+ | **Product/Proof Data Scoping** | `docs/proof-product-data-scoping.md` | Canonical spec for `product.data`/`.admin` and `proof.data`/`.admin`/`.values` (owner/personal) — who can read and write each bucket |
86
+ | **Proof Claiming** | `docs/proof-claiming-methods.md` | The ways a user claims a proof (serial, NFC, claim-set, auto-generate) |
87
+ | **Proof Share Grants** | `docs/proof-share-grants.md` | Delegated, scoped, revocable bearer access to a single proof (read/comment/verify-owner) |
88
+ | **Proof Ownership Transfer** | `docs/proof-ownership-transfer.md` | Moving a proof's single owner (directed transfer / open release), accept/cancel, and the state machine |
89
+ | **appConfig / Feature Flags** | `docs/appConfig.md` | `appConfig` settings contract — installed apps, `system.features`/`entitledAppGroups`/`meters`, `isFeatureEnabled()` helper |
90
+ | **App Objects** | `docs/app-objects.md` | Queryable domain objects — `app.records` / `app.cases` / `app.threads`: JSONB zones, visibility, policies, aggregations |
91
+ | **Bookings** | `docs/bookings.md` | Slots, bookings and allocations for events and appointments: no double-booking, holds, per-app public rules, `utils.freeTimes` |
92
+ | **App Data Storage** | `docs/app-data-storage.md` | Decision guide: pick between `appConfiguration` / `userAppData` / `app.records` |
93
+ | **Attestations** | `docs/attestations.md` | Postgres attestations API (proof-level user/admin data; replaces the legacy Firestore path) |
94
+ | **Caching** | `docs/caching.md` | SDK GET cache tiers + TTLs, `invalidateCache({ exact })`, and `force`/push guidance |
95
+ | **Comms & Broadcasts** | `docs/comms.md` | Transactional comms, campaigns, consent, push |
96
+ | **Container Tracking** | `docs/container-tracking.md` | Physical/logical **item** container groupings — *not* app containers (see containers.md) |
97
+ | **Lots** | `docs/lots.md` | Cross-SKU production "Lot" entity |
98
+ | **Loyalty** | `docs/loyalty.md` | Points, members, earning rules |
99
+ | **Integrations** | `docs/integrations.md` | Inbound/outbound external-system integration flows |
100
+ | **Connectors** | `docs/connectors.md` | Connector apps: the manifest `connector` block + the functions the integration engine calls |
101
+ | **Item Context** | `docs/item-context.md` | The `itemContext` container prop (serial / NFC authenticity context) |
102
+ | **Native Facade** | `docs/native-facade.md` | `host.native` / `SL.native` device-capability facade |
103
+ | **Product Facets** | `docs/PRODUCT_FACETS_SDK.md` | Facet API reference (admin + public endpoints, types) |
104
+ | **AI Tools & Skills** | `docs/ai-tools-and-skills.md` | Platform AI capability registry (web research, extraction, images) |
105
+ | **Proof Comms Triggers** | `docs/proof-comms-triggers.md` | Transactional comms fired as a side-effect of proof actions |
106
+
107
+ ---
108
+
109
+ ## Technical Overview
110
+
111
+ - **Iframe-based** — Apps run inside iframes in both the public Portal and Admin Console
112
+ - **Hash routing** — Uses `/#/` routes for iframe compatibility (e.g., `/#/`, `/#/admin`)
113
+ - **Context via URL params** — All contextual data is passed through URL parameters
114
+ - **SmartLinks NPM module** — All data access and platform interaction goes through `@proveanything/smartlinks`
115
+ - **No standalone auth** — Authentication is handled by the parent SmartLinks platform
116
+
117
+ > **Use the host-provided `SL`, don't instantiate your own.** When your app runs in a
118
+ > container/iframe, the host injects an already-initialized, authenticated SDK instance (the
119
+ > `SL` prop / the externalized `@proveanything/smartlinks` singleton). Import and use *that*.
120
+ > Calling `initializeApi()` yourself to spin up a **second** SDK instance is a common source
121
+ > of bugs: it won't share the host's auth (so it looks signed-out), won't share the host's
122
+ > cache (duplicate requests, stale data), and in proxy mode it bypasses the host's request
123
+ > routing. Rule of thumb: **host-provided `SL` for anything the platform owns** (auth, config,
124
+ > data, cache); only app-owned state is yours.
125
+ - **Multi-page build** — Separate bundles for public and admin — see `docs/mpa.md`
126
+ - **Embedded back navigation** — Use `docs/portal-back-button.md` when a sub-app has a real content hierarchy
127
+
128
+ ---
129
+
130
+ ## Data Model Hierarchy
131
+
132
+ ```
133
+ Collection (Business/Brand)
134
+ └── Product (Product Type/Definition)
135
+ └── Proof (Specific Instance with Owner)
136
+ └── Attestation (User/Admin Data on Proof)
137
+ ```
138
+
139
+ | Entity | Description | Example |
140
+ |--------|-------------|---------|
141
+ | **Collection** | Top-level container representing a business or brand | "Acme Wine Co." |
142
+ | **Product** | A type of product (not a specific item) | "2023 Cabernet Sauvignon" |
143
+ | **Proof** | A specific instance of a product, often with an owner | Bottle #12345 claimed by user@email.com |
144
+ | **Attestation** | Data attached to a proof by users or admins | Warranty registration, tasting notes |
145
+
146
+ ### URL Parameters
147
+
148
+ | Parameter | Type | Description |
149
+ |-----------|------|-------------|
150
+ | `collectionId` | string | The collection being viewed/managed |
151
+ | `productId` | string | The specific product (within collection) |
152
+ | `proofId` | string | The specific proof instance |
153
+ | `appId` | string | This app's unique identifier (for data scoping) |
154
+ | `dark` | `1` or `0` | Whether to use dark mode |
155
+ | `theme` | base64 | Full theme configuration (see `docs/theme.system.md`) |
156
+
157
+ ---
158
+
159
+ ## Authentication & Permissions
160
+
161
+ SmartLinks apps do **not** implement their own authentication. The parent platform handles all auth:
162
+
163
+ - Use `SL.auth.getAccount()` to check if a user is logged in
164
+ - The response includes whether the user is an `admin` or regular user
165
+ - Many SmartLinks API functions behave differently based on admin status
166
+
167
+ | Capability | Admin | Regular User |
168
+ |------------|-------|-------------|
169
+ | Read collection/product data | ✅ | ✅ |
170
+ | Write app configuration | ✅ | ❌ |
171
+ | Write attestations | ✅ | ✅ (own proofs only) |
172
+ | Access admin-only API fields | ✅ | ❌ |
173
+
174
+ ---
175
+
176
+ ## Data Storage Patterns
177
+
178
+ ### ⚠️ Critical: Admin Mode Flag
179
+
180
+ **When building admin interfaces, you MUST pass `admin: true` in API options.**
181
+
182
+ Without this flag, API calls use the public endpoint and will fail to write data:
183
+
184
+ ```typescript
185
+ // ❌ WRONG — will fail in admin interface
186
+ await SL.appConfiguration.setConfig({ collectionId, appId, config: myConfig });
187
+
188
+ // ✅ CORRECT — include admin: true
189
+ await SL.appConfiguration.setConfig({ collectionId, appId, config: myConfig, admin: true });
190
+ ```
191
+
192
+ This applies to all write operations: `setConfig`, `setDataItem`, `updateDataItem`, etc.
193
+
194
+ ### Endpoint Auth vs Data Visibility
195
+
196
+ `admin: true` is an endpoint selector, not a privacy marker.
197
+
198
+ - It tells the SDK to call the admin endpoint.
199
+ - It allows writes and admin reads.
200
+ - It does **not** mean every root-level field you save becomes admin-only.
201
+
202
+ For `appConfiguration` config blobs and `collection.getSettings()` groups, root-level fields are typically the public-facing settings. If you need private values such as tokens or secrets, store them inside a top-level `admin` object:
203
+
204
+ ```typescript
205
+ await SL.appConfiguration.setConfig({
206
+ collectionId,
207
+ appId,
208
+ admin: true,
209
+ config: {
210
+ publicLabel: 'Warranty Portal',
211
+ color: '#B68C2A',
212
+ admin: {
213
+ accessToken: 'secret-token'
214
+ }
215
+ }
216
+ })
217
+ ```
218
+
219
+ Public reads omit the `admin` block. Admin reads include it.
220
+
221
+ ### Config vs Data
222
+
223
+ | Storage Type | Function | Use Case |
224
+ |-------------|---------|---------|
225
+ | **Config** (`getConfig`/`setConfig`) | Single JSON document | App settings, feature flags, global options |
226
+ | **Data** (`getData`/`setDataItem`) | Array of documents with IDs | Lists of items, records, entries |
227
+ | **App Objects** (`app.records` / `app.cases` / `app.threads`) | Queryable domain objects | Real app entities, workflows, conversations, richer access control |
228
+
229
+ Both can be scoped to **collection level** or **product level** by including `productId`.
230
+
231
+ For config/settings visibility, remember: root fields are the normal shared payload, while a reserved top-level `admin` object is the place for admin-only values.
232
+
233
+ Prefer `app.records` over `setDataItem` when the data is becoming a real entity that needs lifecycle, ownership, visibility, relationships, or filtering. Keep `setDataItem` for simple keyed scoped documents and config-adjacent content.
234
+
235
+ ### Feature Flags & Entitlements (`appConfig`)
236
+
237
+ The platform-owned `appConfig` settings group (`system.features`, `system.meters`, `system.entitledAppGroups`, installed `apps[]`) tells a microapp what's installed and entitled for a collection. Use `SL.appConfiguration.isFeatureEnabled(collectionId, flag)` to gate a feature — it's the standard, cache-backed way to do this rather than hand-rolling a `getConfig` call:
238
+
239
+ ```ts
240
+ if (await SL.appConfiguration.isFeatureEnabled(collectionId, 'custom_domain')) {
241
+ enableCustomDomainUI();
242
+ }
243
+ ```
244
+
245
+ It's async (the first check for a collection has nothing cached yet); `SL.appConfiguration.isFeatureEnabledSync()` gives a synchronous, cache-only read (`boolean | undefined`) for callers that warmed the cache earlier and can't await. See `docs/appConfig.md` for the full contract, including `systemPrivate` (admin-only overrides, always stripped for non-admin reads).
246
+
247
+ ### Attestations (Proof-level data)
248
+
249
+ For data attached to specific proof instances, use `SL.attestation.create()` and `SL.attestation.list()`.
250
+
251
+ ### Custom Data Scoping (Product & Proof)
252
+
253
+ `product.data`/`product.admin` and `proof.data`/`proof.admin`/`proof.values` are the canonical buckets for custom fields on products and proofs — `data` is public and business-writable, `admin` is business-only, and `proof.values` additionally supports owner-scoped (`values.owner`) and per-user (`values.personal[userId]`) sub-keys. This is a different mechanism from the app-scoped storage in `docs/app-data-storage.md` (which is for app-owned config/records, not the product/proof documents themselves).
254
+
255
+ See `docs/proof-product-data-scoping.md` for the full read/write authority matrix, worked examples, and the `productFields`/`proofFields` collection-settings schemas that drive field-config editors.
256
+
257
+ ---
258
+
259
+ ## Error Handling
260
+
261
+ The SmartLinks SDK returns structured `SmartlinksApiError` objects. Use `instanceof SmartlinksApiError` to access `.statusCode`, `.message`, and helper methods:
262
+
263
+ - `.isAuthError()` — 401/403 responses
264
+ - `.isNotFound()` — 404 responses
265
+ - `.isRateLimited()` — 429 responses
266
+ - `.isServerError()` — 5xx responses
267
+
268
+ See `docs/API_SUMMARY.md` for complete error handling documentation.
269
+
270
+ ---
271
+
272
+ ## AI Integration
273
+
274
+ SmartLinks provides comprehensive AI capabilities through the `SL.ai` namespace. **Always use SmartLinks AI for microapps** — do not integrate external AI services (OpenAI, Anthropic, Lovable Cloud AI, etc.) directly.
275
+
276
+ Key capabilities: chat completions (streaming + tool calling), RAG document Q&A, voice input/output, podcast generation, text-to-speech, model listing.
277
+
278
+ See `docs/ai.md` for complete documentation.
279
+
280
+ ---
281
+
282
+ ## Interactions & Event Tracking
283
+
284
+ The `SL.interactions` namespace tracks user engagement — competition entries, votes, form submissions, warranty registrations. Events can trigger automated journeys and communications.
285
+
286
+ **The one rule:** you never choose an interaction id. In admin, `SL.interactions.ensureType(collectionId, { appId, key: 'vote', … })` finds-or-creates the type and returns its server-minted `id`; store it in app config (`interactionIds: { vote: type.id }`); everywhere else — public widgets included — read `interactionIds.vote` from config and pass that as `interactionId`. Never write an interactionId as a string literal.
287
+
288
+ Key functions: `submitPublicEvent()`, `appendEvent()` (admin), `countsByOutcome()`, `query()`.
289
+
290
+ See `docs/interactions.md` for complete documentation.
291
+
292
+ ---
293
+
294
+ ## Liquid Templating
295
+
296
+ Use the `<LiquidContent>` component, `useLiquidTemplate` hook, and `renderLiquid` utility for admin-configured dynamic content using Liquid syntax.
297
+
298
+ See `docs/liquid-templates.md` for full context variables, filters, and examples.
299
+
300
+ ---
301
+
302
+ ## Design Principles
303
+
304
+ ### Public Interface (Portal)
305
+
306
+ - **Mobile-first** — Assume users are on phones
307
+ - **Non-technical** — Never show raw IDs or technical data
308
+ - **Accessible** — Follow WCAG guidelines
309
+
310
+ ### Admin Interface
311
+
312
+ - **Feature-rich** — Power users expect advanced controls
313
+ - **Efficient** — Minimise clicks for common tasks
314
+ - **Desktop-optimised** — Admins typically use desktop browsers
315
+
316
+ ### Theming
317
+
318
+ Apps receive theme configuration from the parent platform via URL parameter (`?theme=base64…`) and PostMessage updates. See `docs/theme.system.md`.
319
+
320
+ ---
321
+
322
+ ## Common Hooks
323
+
324
+ ```typescript
325
+ // Fetch collection/product/proof data
326
+ useCollectionData(collectionId)
327
+ useProductData(collectionId, productId)
328
+ useProofData(collectionId, productId, proofId)
329
+
330
+ // Fetch app configuration
331
+ useCollectionAppConfig(collectionId, appId)
332
+ useProductAppConfig(collectionId, productId, appId)
333
+
334
+ // Fetch app data (array of items)
335
+ useCollectionAppData(collectionId, appId)
336
+ useProductAppData(collectionId, productId, appId)
337
+
338
+ // Fetch attestations
339
+ useAttestationsData(collectionId, productId, proofId)
340
+
341
+ // URL parameter management
342
+ usePersistentQueryParams()
343
+
344
+ // Theme management
345
+ useSmartLinksTheme()
346
+
347
+ // Liquid templating
348
+ useLiquidTemplate(templateString, contextData)
349
+ ```
350
+
351
+ ---
352
+
353
+ ## API Namespaces
354
+
355
+ The SmartLinks SDK is organised into namespaces. See `docs/API_SUMMARY.md` for the complete reference. Key namespaces:
356
+
357
+ - `appConfiguration` — Config and data storage (most apps use this)
358
+ - `attestation` — Proof-level user/admin data
359
+ - `interactions` — Event tracking and analytics
360
+ - `ai` — AI content generation, chat, RAG (see `docs/ai.md`)
361
+ - `auth` / `authKit` — Admin and end-user authentication
362
+ - `contact` — Customer contact management
363
+ - `comms` / `broadcasts` — Notifications and campaigns
364
+ - `asset` — File/image uploads
365
+ - `adminCards` — the collection's dashboard: `list`, `refresh`, `saveLayout` (see `docs/admin-cards.md`)
366
+ - `realtime` — SmartLinks Realtime: `onChange`, `channel`, `onMine` (see `docs/realtime.md`)
367
+
368
+ ---
369
+
370
+ ## File Structure
371
+
372
+ ```
373
+ ├── index.html ← Public portal entry
374
+ ├── admin.html ← Admin console entry
375
+ ├── public/
376
+ │ ├── app.manifest.json ← Public discovery manifest
377
+ │ ├── app.admin.json ← Admin manifest (on-demand)
378
+ │ └── ai-guide.md ← AI orchestrator prose guide
379
+ ├── src/
380
+ │ ├── main.tsx ← Public React entry
381
+ │ ├── admin-main.tsx ← Admin React entry
382
+ │ ├── App.tsx ← Shared providers (QueryClient, Toaster, etc.)
383
+ │ ├── PublicApp.tsx ← Public app shell (routes only public pages)
384
+ │ ├── AdminApp.tsx ← Admin app shell (routes only admin pages)
385
+ │ ├── components/ ← Reusable UI components
386
+ │ ├── containers/ ← Embeddable full-app containers
387
+ │ ├── executor/ ← Executor bundle (SEO, LLM content, config API)
388
+ │ ├── hooks/ ← React hooks (data fetching, state)
389
+ │ ├── pages/
390
+ │ │ ├── PublicPage.tsx ← Portal content (/#/)
391
+ │ │ ├── AdminPage.tsx ← Admin content (admin.html#/)
392
+ │ │ └── DevPage.tsx ← Development helper (dev only)
393
+ │ ├── widgets/ ← Embeddable widget components
394
+ │ └── utils/
395
+ │ ├── smartlinks/ ← SmartLinks utilities
396
+ │ └── theme.ts ← Theme utilities
397
+ ├── vite.config.ts ← Multi-page build config
398
+ ├── vite.config.widget.ts ← Widget library build config
399
+ ├── vite.config.container.ts ← Container library build config
400
+ └── vite.config.executor.ts ← Executor library build config
401
+ ```
402
+
403
+ ---
404
+
405
+ ## Anti-Patterns to Avoid
406
+
407
+ ❌ **Don't implement custom auth** — Use SmartLinks auth via `SL.auth.getAccount()`
408
+
409
+ ❌ **Don't use BrowserRouter** — Always use HashRouter for iframe compatibility
410
+
411
+ ❌ **Don't hardcode URLs** — Use relative paths and let the platform provide context
412
+
413
+ ❌ **Don't store secrets in code** — Use environment variables or platform configuration
414
+
415
+ ❌ **Don't assume screen size** — Support both mobile (Portal) and desktop (Admin)
416
+
417
+ ❌ **Don't expose technical IDs** — Show human-readable names to users
418
+
419
+ ❌ **Don't import AdminPage in PublicApp** — Keep bundles separate for optimal size
420
+
421
+ ❌ **Don't use external AI services** — Use SmartLinks AI via `SL.ai`, not OpenAI/Anthropic/Lovable Cloud AI directly
422
+
423
+ ❌ **Don't forget `admin: true`** — All admin write operations require this flag
424
+
425
+ ---
426
+
427
+ ## Quick Reference
428
+
429
+ ### Initialise the API
430
+
431
+ ```typescript
432
+ import { initializeAPI } from '@/utils/smartlinks/initialization';
433
+ initializeAPI(); // Call once at app startup
434
+ ```
435
+
436
+ ### Get Context from URL
437
+
438
+ ```typescript
439
+ const { persistentQueryParams } = usePersistentQueryParams();
440
+ const { collectionId, productId, appId } = persistentQueryParams;
441
+ ```
442
+
443
+ ### Check Admin Status
444
+
445
+ ```typescript
446
+ const account = await SL.auth.getAccount();
447
+ const isAdmin = account?.admin === true;
448
+ ```
449
+
450
+ ### Save Configuration (Admin Only)
451
+
452
+ ```typescript
453
+ await SL.appConfiguration.setConfig({
454
+ collectionId, appId,
455
+ config: { myKey: 'myValue' },
456
+ admin: true // Required!
457
+ });
458
+ ```
459
+
460
+ ### Handle Dark Mode + Theming
461
+
462
+ ```typescript
463
+ // In App.tsx — already integrated in the template
464
+ useDarkMode(); // Handles ?dark=1 parameter
465
+ useSmartLinksTheme(); // Handles ?theme=base64 parameter
466
+ useDeepLinkSync(); // Syncs route changes to parent
467
+ ```
468
+
469
+ ### Deep Linking
470
+
471
+ ```typescript
472
+ const { navigateWithState, getAppState } = usePersistentQueryParams();
473
+ const { tab = 'general' } = getAppState();
474
+ navigateWithState('/', { tab: 'advanced' });
475
+ ```
476
+
477
+ See `docs/deep-link-discovery.md` for full implementation details.