@proveanything/smartlinks 2.1.36 → 2.1.37

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,480 +1,481 @@
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
- | **Admin Views** | `docs/admin-views.md` | The admin side's screens by name (`adminViews`): the app's side menu, Studio's menu and the assistant; host → app `smartlinks:navigate`; `chrome=none` |
69
- | **Portal Back Button** | `docs/portal-back-button.md` | Hierarchy-aware "up" navigation inside embedded apps |
70
- | **Portal Request Action** | `docs/portal-request-action.md` | Triggering portal built-in actions (__qrScanner, __share, __logout, etc.) from sub-apps |
71
- | **Interactions** | `docs/interactions.md` | Business events, outcomes, voting, competitions, and journey triggers |
72
- | **App Config Files** | `docs/app-manifest.md` | Full field-by-field reference for both JSON config files |
73
- | **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 |
74
- | **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 |
75
- | **Liquid Templates** | `docs/liquid-templates.md` | Dynamic content rendering with LiquidJS |
76
- | **Iframe Responder** | `docs/iframe-responder.md` | Iframe communication and proxy mode internals |
77
- | **AI Guide Template** | `docs/ai-guide-template.md` | Template for creating `public/ai-guide.md` — customise per app |
78
- | **Forms** | `docs/forms.md` | Form definitions, schema-driven rendering, submission patterns |
79
- | **Auth Kit** | `docs/auth-kit.md` | End-user sign-in: email/password, magic links, phone OTP, Google OAuth |
80
- | **Members** | `docs/members.md` | Signed-in members with a level (clubs, leagues, members' areas): the level field, members-only functions, joining rules |
81
- | **Portal Request Login** | `docs/portal-request-login.md` | How sub-apps ask the portal to authenticate the user; hook and iframe postMessage contracts |
82
- | **Portal Auth Broadcast** | `docs/portal-auth-broadcast.md` | Publishing custom auth flows to the portal; syncing sessions across containers and iframes |
83
- | **Contact Search** | `docs/contact-search.md` | Admin contact search: free-text, typeahead, identity/tag/JSONB filters, and pagination |
84
- | **App Records Pattern** | `docs/app-records-pattern.md` | Standard pattern for per-product/facet/variant/batch admin + public widget UIs |
85
- | **UI Utils** | `docs/ui-utils.md` | `@proveanything/smartlinks-utils-ui` — React shells, hooks, and primitives for records-based apps |
86
- | **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 |
87
- | **Proof Claiming** | `docs/proof-claiming-methods.md` | The ways a user claims a proof (serial, NFC, claim-set, auto-generate) |
88
- | **Proof Share Grants** | `docs/proof-share-grants.md` | Delegated, scoped, revocable bearer access to a single proof (read/comment/verify-owner) |
89
- | **Proof Ownership Transfer** | `docs/proof-ownership-transfer.md` | Moving a proof's single owner (directed transfer / open release), accept/cancel, and the state machine |
90
- | **appConfig / Feature Flags** | `docs/appConfig.md` | `appConfig` settings contract — installed apps, `system.features`/`entitledAppGroups`/`meters`, `isFeatureEnabled()` helper |
91
- | **App Objects** | `docs/app-objects.md` | Queryable domain objects — `app.records` / `app.cases` / `app.threads`: JSONB zones, visibility, policies, aggregations |
92
- | **Bookings** | `docs/bookings.md` | Slots, bookings and allocations for events and appointments: no double-booking, holds, per-app public rules, `utils.freeTimes` |
93
- | **User groups** | `docs/user-groups.md` | Who may do what: named lists of people (staff who aren't admins, third parties), `userGroups` on a server function, `ctx.caller.userGroups`, `userGroups.mine()` |
94
- | **Operations** | `docs/operations.md` | Factory floor and warehouse: work orders with stages, stock as quantities in containers, movements, bills of materials, made-from, sales and purchase orders, and a product's position (on hand, on order, needed, when it runs short) |
95
- | **App Data Storage** | `docs/app-data-storage.md` | Decision guide: pick between `appConfiguration` / `userAppData` / `app.records` |
96
- | **Attestations** | `docs/attestations.md` | Postgres attestations API (proof-level user/admin data; replaces the legacy Firestore path) |
97
- | **Caching** | `docs/caching.md` | SDK GET cache tiers + TTLs, `invalidateCache({ exact })`, and `force`/push guidance |
98
- | **Comms & Broadcasts** | `docs/comms.md` | Transactional comms, campaigns, consent, push |
99
- | **Container Tracking** | `docs/container-tracking.md` | Physical/logical **item** container groupings — *not* app containers (see containers.md) |
100
- | **Lots** | `docs/lots.md` | Cross-SKU production "Lot" entity |
101
- | **Loyalty** | `docs/loyalty.md` | Points, members, earning rules |
102
- | **Integrations** | `docs/integrations.md` | Inbound/outbound external-system integration flows |
103
- | **Connectors** | `docs/connectors.md` | Connector apps: the manifest `connector` block + the functions the integration engine calls |
104
- | **Item Context** | `docs/item-context.md` | The `itemContext` container prop (serial / NFC authenticity context) |
105
- | **Native Facade** | `docs/native-facade.md` | `host.native` / `SL.native` device-capability facade |
106
- | **Product Facets** | `docs/PRODUCT_FACETS_SDK.md` | Facet API reference (admin + public endpoints, types) |
107
- | **AI Tools & Skills** | `docs/ai-tools-and-skills.md` | Platform AI capability registry (web research, extraction, images) |
108
- | **Proof Comms Triggers** | `docs/proof-comms-triggers.md` | Transactional comms fired as a side-effect of proof actions |
109
-
110
- ---
111
-
112
- ## Technical Overview
113
-
114
- - **Iframe-based** — Apps run inside iframes in both the public Portal and Admin Console
115
- - **Hash routing** — Uses `/#/` routes for iframe compatibility (e.g., `/#/`, `/#/admin`)
116
- - **Context via URL params** — All contextual data is passed through URL parameters
117
- - **SmartLinks NPM module** — All data access and platform interaction goes through `@proveanything/smartlinks`
118
- - **No standalone auth** — Authentication is handled by the parent SmartLinks platform
119
-
120
- > **Use the host-provided `SL`, don't instantiate your own.** When your app runs in a
121
- > container/iframe, the host injects an already-initialized, authenticated SDK instance (the
122
- > `SL` prop / the externalized `@proveanything/smartlinks` singleton). Import and use *that*.
123
- > Calling `initializeApi()` yourself to spin up a **second** SDK instance is a common source
124
- > of bugs: it won't share the host's auth (so it looks signed-out), won't share the host's
125
- > cache (duplicate requests, stale data), and in proxy mode it bypasses the host's request
126
- > routing. Rule of thumb: **host-provided `SL` for anything the platform owns** (auth, config,
127
- > data, cache); only app-owned state is yours.
128
- - **Multi-page build** — Separate bundles for public and admin — see `docs/mpa.md`
129
- - **Embedded back navigation** — Use `docs/portal-back-button.md` when a sub-app has a real content hierarchy
130
-
131
- ---
132
-
133
- ## Data Model Hierarchy
134
-
135
- ```
136
- Collection (Business/Brand)
137
- └── Product (Product Type/Definition)
138
- └── Proof (Specific Instance with Owner)
139
- └── Attestation (User/Admin Data on Proof)
140
- ```
141
-
142
- | Entity | Description | Example |
143
- |--------|-------------|---------|
144
- | **Collection** | Top-level container representing a business or brand | "Acme Wine Co." |
145
- | **Product** | A type of product (not a specific item) | "2023 Cabernet Sauvignon" |
146
- | **Proof** | A specific instance of a product, often with an owner | Bottle #12345 claimed by user@email.com |
147
- | **Attestation** | Data attached to a proof by users or admins | Warranty registration, tasting notes |
148
-
149
- ### URL Parameters
150
-
151
- | Parameter | Type | Description |
152
- |-----------|------|-------------|
153
- | `collectionId` | string | The collection being viewed/managed |
154
- | `productId` | string | The specific product (within collection) |
155
- | `proofId` | string | The specific proof instance |
156
- | `appId` | string | This app's unique identifier (for data scoping) |
157
- | `dark` | `1` or `0` | Whether to use dark mode |
158
- | `theme` | base64 | Full theme configuration (see `docs/theme.system.md`) |
159
-
160
- ---
161
-
162
- ## Authentication & Permissions
163
-
164
- SmartLinks apps do **not** implement their own authentication. The parent platform handles all auth:
165
-
166
- - Use `SL.auth.getAccount()` to check if a user is logged in
167
- - The response includes whether the user is an `admin` or regular user
168
- - Many SmartLinks API functions behave differently based on admin status
169
-
170
- | Capability | Admin | Regular User |
171
- |------------|-------|-------------|
172
- | Read collection/product data | ✅ | ✅ |
173
- | Write app configuration | ✅ | ❌ |
174
- | Write attestations | ✅ | ✅ (own proofs only) |
175
- | Access admin-only API fields | ✅ | ❌ |
176
-
177
- ---
178
-
179
- ## Data Storage Patterns
180
-
181
- ### ⚠️ Critical: Admin Mode Flag
182
-
183
- **When building admin interfaces, you MUST pass `admin: true` in API options.**
184
-
185
- Without this flag, API calls use the public endpoint and will fail to write data:
186
-
187
- ```typescript
188
- // ❌ WRONG — will fail in admin interface
189
- await SL.appConfiguration.setConfig({ collectionId, appId, config: myConfig });
190
-
191
- // ✅ CORRECT — include admin: true
192
- await SL.appConfiguration.setConfig({ collectionId, appId, config: myConfig, admin: true });
193
- ```
194
-
195
- This applies to all write operations: `setConfig`, `setDataItem`, `updateDataItem`, etc.
196
-
197
- ### Endpoint Auth vs Data Visibility
198
-
199
- `admin: true` is an endpoint selector, not a privacy marker.
200
-
201
- - It tells the SDK to call the admin endpoint.
202
- - It allows writes and admin reads.
203
- - It does **not** mean every root-level field you save becomes admin-only.
204
-
205
- 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:
206
-
207
- ```typescript
208
- await SL.appConfiguration.setConfig({
209
- collectionId,
210
- appId,
211
- admin: true,
212
- config: {
213
- publicLabel: 'Warranty Portal',
214
- color: '#B68C2A',
215
- admin: {
216
- accessToken: 'secret-token'
217
- }
218
- }
219
- })
220
- ```
221
-
222
- Public reads omit the `admin` block. Admin reads include it.
223
-
224
- ### Config vs Data
225
-
226
- | Storage Type | Function | Use Case |
227
- |-------------|---------|---------|
228
- | **Config** (`getConfig`/`setConfig`) | Single JSON document | App settings, feature flags, global options |
229
- | **Data** (`getData`/`setDataItem`) | Array of documents with IDs | Lists of items, records, entries |
230
- | **App Objects** (`app.records` / `app.cases` / `app.threads`) | Queryable domain objects | Real app entities, workflows, conversations, richer access control |
231
-
232
- Both can be scoped to **collection level** or **product level** by including `productId`.
233
-
234
- 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.
235
-
236
- 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.
237
-
238
- ### Feature Flags & Entitlements (`appConfig`)
239
-
240
- 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:
241
-
242
- ```ts
243
- if (await SL.appConfiguration.isFeatureEnabled(collectionId, 'custom_domain')) {
244
- enableCustomDomainUI();
245
- }
246
- ```
247
-
248
- 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).
249
-
250
- ### Attestations (Proof-level data)
251
-
252
- For data attached to specific proof instances, use `SL.attestation.create()` and `SL.attestation.list()`.
253
-
254
- ### Custom Data Scoping (Product & Proof)
255
-
256
- `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).
257
-
258
- 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.
259
-
260
- ---
261
-
262
- ## Error Handling
263
-
264
- The SmartLinks SDK returns structured `SmartlinksApiError` objects. Use `instanceof SmartlinksApiError` to access `.statusCode`, `.message`, and helper methods:
265
-
266
- - `.isAuthError()` — 401/403 responses
267
- - `.isNotFound()` — 404 responses
268
- - `.isRateLimited()` — 429 responses
269
- - `.isServerError()` — 5xx responses
270
-
271
- See `docs/API_SUMMARY.md` for complete error handling documentation.
272
-
273
- ---
274
-
275
- ## AI Integration
276
-
277
- 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.
278
-
279
- Key capabilities: chat completions (streaming + tool calling), RAG document Q&A, voice input/output, podcast generation, text-to-speech, model listing.
280
-
281
- See `docs/ai.md` for complete documentation.
282
-
283
- ---
284
-
285
- ## Interactions & Event Tracking
286
-
287
- The `SL.interactions` namespace tracks user engagement — competition entries, votes, form submissions, warranty registrations. Events can trigger automated journeys and communications.
288
-
289
- **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.
290
-
291
- Key functions: `submitPublicEvent()`, `appendEvent()` (admin), `countsByOutcome()`, `query()`.
292
-
293
- See `docs/interactions.md` for complete documentation.
294
-
295
- ---
296
-
297
- ## Liquid Templating
298
-
299
- Use the `<LiquidContent>` component, `useLiquidTemplate` hook, and `renderLiquid` utility for admin-configured dynamic content using Liquid syntax.
300
-
301
- See `docs/liquid-templates.md` for full context variables, filters, and examples.
302
-
303
- ---
304
-
305
- ## Design Principles
306
-
307
- ### Public Interface (Portal)
308
-
309
- - **Mobile-first** — Assume users are on phones
310
- - **Non-technical** — Never show raw IDs or technical data
311
- - **Accessible** — Follow WCAG guidelines
312
-
313
- ### Admin Interface
314
-
315
- - **Feature-rich** — Power users expect advanced controls
316
- - **Efficient** — Minimise clicks for common tasks
317
- - **Desktop-optimised** — Admins typically use desktop browsers
318
-
319
- ### Theming
320
-
321
- Apps receive theme configuration from the parent platform via URL parameter (`?theme=base64…`) and PostMessage updates. See `docs/theme.system.md`.
322
-
323
- ---
324
-
325
- ## Common Hooks
326
-
327
- ```typescript
328
- // Fetch collection/product/proof data
329
- useCollectionData(collectionId)
330
- useProductData(collectionId, productId)
331
- useProofData(collectionId, productId, proofId)
332
-
333
- // Fetch app configuration
334
- useCollectionAppConfig(collectionId, appId)
335
- useProductAppConfig(collectionId, productId, appId)
336
-
337
- // Fetch app data (array of items)
338
- useCollectionAppData(collectionId, appId)
339
- useProductAppData(collectionId, productId, appId)
340
-
341
- // Fetch attestations
342
- useAttestationsData(collectionId, productId, proofId)
343
-
344
- // URL parameter management
345
- usePersistentQueryParams()
346
-
347
- // Theme management
348
- useSmartLinksTheme()
349
-
350
- // Liquid templating
351
- useLiquidTemplate(templateString, contextData)
352
- ```
353
-
354
- ---
355
-
356
- ## API Namespaces
357
-
358
- The SmartLinks SDK is organised into namespaces. See `docs/API_SUMMARY.md` for the complete reference. Key namespaces:
359
-
360
- - `appConfiguration` — Config and data storage (most apps use this)
361
- - `attestation` — Proof-level user/admin data
362
- - `interactions` — Event tracking and analytics
363
- - `ai` — AI content generation, chat, RAG (see `docs/ai.md`)
364
- - `auth` / `authKit` — Admin and end-user authentication
365
- - `contact` — Customer contact management
366
- - `comms` / `broadcasts` — Notifications and campaigns
367
- - `asset` — File/image uploads
368
- - `adminCards` — the collection's dashboard: `list`, `refresh`, `saveLayout` (see `docs/admin-cards.md`)
369
- - `realtime` — SmartLinks Realtime: `onChange`, `channel`, `onMine` (see `docs/realtime.md`)
370
-
371
- ---
372
-
373
- ## File Structure
374
-
375
- ```
376
- ├── index.html ← Public portal entry
377
- ├── admin.html ← Admin console entry
378
- ├── public/
379
- │ ├── app.manifest.json ← Public discovery manifest
380
- │ ├── app.admin.json ← Admin manifest (on-demand)
381
- │ └── ai-guide.md ← AI orchestrator prose guide
382
- ├── src/
383
- │ ├── main.tsx ← Public React entry
384
- │ ├── admin-main.tsx ← Admin React entry
385
- │ ├── App.tsx ← Shared providers (QueryClient, Toaster, etc.)
386
- │ ├── PublicApp.tsx ← Public app shell (routes only public pages)
387
- │ ├── AdminApp.tsx ← Admin app shell (routes only admin pages)
388
- │ ├── components/ ← Reusable UI components
389
- │ ├── containers/ ← Embeddable full-app containers
390
- │ ├── executor/ ← Executor bundle (SEO, LLM content, config API)
391
- │ ├── hooks/ ← React hooks (data fetching, state)
392
- │ ├── pages/
393
- │ │ ├── PublicPage.tsx ← Portal content (/#/)
394
- │ │ ├── AdminPage.tsx ← Admin content (admin.html#/)
395
- │ │ └── DevPage.tsx ← Development helper (dev only)
396
- │ ├── widgets/ ← Embeddable widget components
397
- │ └── utils/
398
- │ ├── smartlinks/ ← SmartLinks utilities
399
- │ └── theme.ts ← Theme utilities
400
- ├── vite.config.ts ← Multi-page build config
401
- ├── vite.config.widget.ts ← Widget library build config
402
- ├── vite.config.container.ts ← Container library build config
403
- └── vite.config.executor.ts ← Executor library build config
404
- ```
405
-
406
- ---
407
-
408
- ## Anti-Patterns to Avoid
409
-
410
- ❌ **Don't implement custom auth** — Use SmartLinks auth via `SL.auth.getAccount()`
411
-
412
- ❌ **Don't use BrowserRouter** — Always use HashRouter for iframe compatibility
413
-
414
- ❌ **Don't hardcode URLs** — Use relative paths and let the platform provide context
415
-
416
- ❌ **Don't store secrets in code** — Use environment variables or platform configuration
417
-
418
- ❌ **Don't assume screen size** — Support both mobile (Portal) and desktop (Admin)
419
-
420
- ❌ **Don't expose technical IDs** — Show human-readable names to users
421
-
422
- ❌ **Don't import AdminPage in PublicApp** — Keep bundles separate for optimal size
423
-
424
- ❌ **Don't use external AI services** — Use SmartLinks AI via `SL.ai`, not OpenAI/Anthropic/Lovable Cloud AI directly
425
-
426
- ❌ **Don't forget `admin: true`** — All admin write operations require this flag
427
-
428
- ---
429
-
430
- ## Quick Reference
431
-
432
- ### Initialise the API
433
-
434
- ```typescript
435
- import { initializeAPI } from '@/utils/smartlinks/initialization';
436
- initializeAPI(); // Call once at app startup
437
- ```
438
-
439
- ### Get Context from URL
440
-
441
- ```typescript
442
- const { persistentQueryParams } = usePersistentQueryParams();
443
- const { collectionId, productId, appId } = persistentQueryParams;
444
- ```
445
-
446
- ### Check Admin Status
447
-
448
- ```typescript
449
- const account = await SL.auth.getAccount();
450
- const isAdmin = account?.admin === true;
451
- ```
452
-
453
- ### Save Configuration (Admin Only)
454
-
455
- ```typescript
456
- await SL.appConfiguration.setConfig({
457
- collectionId, appId,
458
- config: { myKey: 'myValue' },
459
- admin: true // Required!
460
- });
461
- ```
462
-
463
- ### Handle Dark Mode + Theming
464
-
465
- ```typescript
466
- // In App.tsx — already integrated in the template
467
- useDarkMode(); // Handles ?dark=1 parameter
468
- useSmartLinksTheme(); // Handles ?theme=base64 parameter
469
- useDeepLinkSync(); // Syncs route changes to parent
470
- ```
471
-
472
- ### Deep Linking
473
-
474
- ```typescript
475
- const { navigateWithState, getAppState } = usePersistentQueryParams();
476
- const { tab = 'general' } = getAppState();
477
- navigateWithState('/', { tab: 'advanced' });
478
- ```
479
-
480
- 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
+ | **Admin Views** | `docs/admin-views.md` | The admin side's screens by name (`adminViews`): the app's side menu, Studio's menu and the assistant; host → app `smartlinks:navigate`; `chrome=none` |
69
+ | **Portal Back Button** | `docs/portal-back-button.md` | Hierarchy-aware "up" navigation inside embedded apps |
70
+ | **Portal Request Action** | `docs/portal-request-action.md` | Triggering portal built-in actions (__qrScanner, __share, __logout, etc.) from sub-apps |
71
+ | **Interactions** | `docs/interactions.md` | Business events, outcomes, voting, competitions, and journey triggers |
72
+ | **App Config Files** | `docs/app-manifest.md` | Full field-by-field reference for both JSON config files |
73
+ | **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 |
74
+ | **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 |
75
+ | **Liquid Templates** | `docs/liquid-templates.md` | Dynamic content rendering with LiquidJS |
76
+ | **Iframe Responder** | `docs/iframe-responder.md` | Iframe communication and proxy mode internals |
77
+ | **AI Guide Template** | `docs/ai-guide-template.md` | Template for creating `public/ai-guide.md` — customise per app |
78
+ | **Forms** | `docs/forms.md` | Form definitions, schema-driven rendering, submission patterns |
79
+ | **Auth Kit** | `docs/auth-kit.md` | End-user sign-in: email/password, magic links, phone OTP, Google OAuth |
80
+ | **Members** | `docs/members.md` | Signed-in members with a level (clubs, leagues, members' areas): the level field, members-only functions, joining rules |
81
+ | **Portal Request Login** | `docs/portal-request-login.md` | How sub-apps ask the portal to authenticate the user; hook and iframe postMessage contracts |
82
+ | **Portal Auth Broadcast** | `docs/portal-auth-broadcast.md` | Publishing custom auth flows to the portal; syncing sessions across containers and iframes |
83
+ | **Contact Search** | `docs/contact-search.md` | Admin contact search: free-text, typeahead, identity/tag/JSONB filters, and pagination |
84
+ | **App Records Pattern** | `docs/app-records-pattern.md` | Standard pattern for per-product/facet/variant/batch admin + public widget UIs |
85
+ | **UI Utils** | `docs/ui-utils.md` | `@proveanything/smartlinks-utils-ui` — React shells, hooks, and primitives for records-based apps |
86
+ | **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 |
87
+ | **Proof Claiming** | `docs/proof-claiming-methods.md` | The ways a user claims a proof (serial, NFC, claim-set, auto-generate) |
88
+ | **Proof Share Grants** | `docs/proof-share-grants.md` | Delegated, scoped, revocable bearer access to a single proof (read/comment/verify-owner) |
89
+ | **Proof Ownership Transfer** | `docs/proof-ownership-transfer.md` | Moving a proof's single owner (directed transfer / open release), accept/cancel, and the state machine |
90
+ | **appConfig / Feature Flags** | `docs/appConfig.md` | `appConfig` settings contract — installed apps, `system.features`/`entitledAppGroups`/`meters`, `isFeatureEnabled()` helper |
91
+ | **App Objects** | `docs/app-objects.md` | Queryable domain objects — `app.records` / `app.cases` / `app.threads`: JSONB zones, visibility, policies, aggregations |
92
+ | **Bookings** | `docs/bookings.md` | Slots, bookings and allocations for events and appointments: no double-booking, holds, per-app public rules, `utils.freeTimes` |
93
+ | **Shop** | `docs/shop.md` | Sell from any site: prices, Stripe checkout into the seller's account, stock held while paying, physical and digital delivery (files, proofs, access), orders, shipping, refunds, order events for emails and integrations |
94
+ | **User groups** | `docs/user-groups.md` | Who may do what: named lists of people (staff who aren't admins, third parties), `userGroups` on a server function, `ctx.caller.userGroups`, `userGroups.mine()` |
95
+ | **Operations** | `docs/operations.md` | Factory floor and warehouse: work orders with stages, stock as quantities in containers, movements, bills of materials, made-from, sales and purchase orders, and a product's position (on hand, on order, needed, when it runs short) |
96
+ | **App Data Storage** | `docs/app-data-storage.md` | Decision guide: pick between `appConfiguration` / `userAppData` / `app.records` |
97
+ | **Attestations** | `docs/attestations.md` | Postgres attestations API (proof-level user/admin data; replaces the legacy Firestore path) |
98
+ | **Caching** | `docs/caching.md` | SDK GET cache tiers + TTLs, `invalidateCache({ exact })`, and `force`/push guidance |
99
+ | **Comms & Broadcasts** | `docs/comms.md` | Transactional comms, campaigns, consent, push |
100
+ | **Container Tracking** | `docs/container-tracking.md` | Physical/logical **item** container groupings — *not* app containers (see containers.md) |
101
+ | **Lots** | `docs/lots.md` | Cross-SKU production "Lot" entity |
102
+ | **Loyalty** | `docs/loyalty.md` | Points, members, earning rules |
103
+ | **Integrations** | `docs/integrations.md` | Inbound/outbound external-system integration flows |
104
+ | **Connectors** | `docs/connectors.md` | Connector apps: the manifest `connector` block + the functions the integration engine calls |
105
+ | **Item Context** | `docs/item-context.md` | The `itemContext` container prop (serial / NFC authenticity context) |
106
+ | **Native Facade** | `docs/native-facade.md` | `host.native` / `SL.native` device-capability facade |
107
+ | **Product Facets** | `docs/PRODUCT_FACETS_SDK.md` | Facet API reference (admin + public endpoints, types) |
108
+ | **AI Tools & Skills** | `docs/ai-tools-and-skills.md` | Platform AI capability registry (web research, extraction, images) |
109
+ | **Proof Comms Triggers** | `docs/proof-comms-triggers.md` | Transactional comms fired as a side-effect of proof actions |
110
+
111
+ ---
112
+
113
+ ## Technical Overview
114
+
115
+ - **Iframe-based** — Apps run inside iframes in both the public Portal and Admin Console
116
+ - **Hash routing** — Uses `/#/` routes for iframe compatibility (e.g., `/#/`, `/#/admin`)
117
+ - **Context via URL params** — All contextual data is passed through URL parameters
118
+ - **SmartLinks NPM module** — All data access and platform interaction goes through `@proveanything/smartlinks`
119
+ - **No standalone auth** — Authentication is handled by the parent SmartLinks platform
120
+
121
+ > **Use the host-provided `SL`, don't instantiate your own.** When your app runs in a
122
+ > container/iframe, the host injects an already-initialized, authenticated SDK instance (the
123
+ > `SL` prop / the externalized `@proveanything/smartlinks` singleton). Import and use *that*.
124
+ > Calling `initializeApi()` yourself to spin up a **second** SDK instance is a common source
125
+ > of bugs: it won't share the host's auth (so it looks signed-out), won't share the host's
126
+ > cache (duplicate requests, stale data), and in proxy mode it bypasses the host's request
127
+ > routing. Rule of thumb: **host-provided `SL` for anything the platform owns** (auth, config,
128
+ > data, cache); only app-owned state is yours.
129
+ - **Multi-page build** — Separate bundles for public and admin — see `docs/mpa.md`
130
+ - **Embedded back navigation** — Use `docs/portal-back-button.md` when a sub-app has a real content hierarchy
131
+
132
+ ---
133
+
134
+ ## Data Model Hierarchy
135
+
136
+ ```
137
+ Collection (Business/Brand)
138
+ └── Product (Product Type/Definition)
139
+ └── Proof (Specific Instance with Owner)
140
+ └── Attestation (User/Admin Data on Proof)
141
+ ```
142
+
143
+ | Entity | Description | Example |
144
+ |--------|-------------|---------|
145
+ | **Collection** | Top-level container representing a business or brand | "Acme Wine Co." |
146
+ | **Product** | A type of product (not a specific item) | "2023 Cabernet Sauvignon" |
147
+ | **Proof** | A specific instance of a product, often with an owner | Bottle #12345 claimed by user@email.com |
148
+ | **Attestation** | Data attached to a proof by users or admins | Warranty registration, tasting notes |
149
+
150
+ ### URL Parameters
151
+
152
+ | Parameter | Type | Description |
153
+ |-----------|------|-------------|
154
+ | `collectionId` | string | The collection being viewed/managed |
155
+ | `productId` | string | The specific product (within collection) |
156
+ | `proofId` | string | The specific proof instance |
157
+ | `appId` | string | This app's unique identifier (for data scoping) |
158
+ | `dark` | `1` or `0` | Whether to use dark mode |
159
+ | `theme` | base64 | Full theme configuration (see `docs/theme.system.md`) |
160
+
161
+ ---
162
+
163
+ ## Authentication & Permissions
164
+
165
+ SmartLinks apps do **not** implement their own authentication. The parent platform handles all auth:
166
+
167
+ - Use `SL.auth.getAccount()` to check if a user is logged in
168
+ - The response includes whether the user is an `admin` or regular user
169
+ - Many SmartLinks API functions behave differently based on admin status
170
+
171
+ | Capability | Admin | Regular User |
172
+ |------------|-------|-------------|
173
+ | Read collection/product data | ✅ | ✅ |
174
+ | Write app configuration | ✅ | ❌ |
175
+ | Write attestations | ✅ | ✅ (own proofs only) |
176
+ | Access admin-only API fields | ✅ | ❌ |
177
+
178
+ ---
179
+
180
+ ## Data Storage Patterns
181
+
182
+ ### ⚠️ Critical: Admin Mode Flag
183
+
184
+ **When building admin interfaces, you MUST pass `admin: true` in API options.**
185
+
186
+ Without this flag, API calls use the public endpoint and will fail to write data:
187
+
188
+ ```typescript
189
+ // ❌ WRONG — will fail in admin interface
190
+ await SL.appConfiguration.setConfig({ collectionId, appId, config: myConfig });
191
+
192
+ // ✅ CORRECT — include admin: true
193
+ await SL.appConfiguration.setConfig({ collectionId, appId, config: myConfig, admin: true });
194
+ ```
195
+
196
+ This applies to all write operations: `setConfig`, `setDataItem`, `updateDataItem`, etc.
197
+
198
+ ### Endpoint Auth vs Data Visibility
199
+
200
+ `admin: true` is an endpoint selector, not a privacy marker.
201
+
202
+ - It tells the SDK to call the admin endpoint.
203
+ - It allows writes and admin reads.
204
+ - It does **not** mean every root-level field you save becomes admin-only.
205
+
206
+ 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:
207
+
208
+ ```typescript
209
+ await SL.appConfiguration.setConfig({
210
+ collectionId,
211
+ appId,
212
+ admin: true,
213
+ config: {
214
+ publicLabel: 'Warranty Portal',
215
+ color: '#B68C2A',
216
+ admin: {
217
+ accessToken: 'secret-token'
218
+ }
219
+ }
220
+ })
221
+ ```
222
+
223
+ Public reads omit the `admin` block. Admin reads include it.
224
+
225
+ ### Config vs Data
226
+
227
+ | Storage Type | Function | Use Case |
228
+ |-------------|---------|---------|
229
+ | **Config** (`getConfig`/`setConfig`) | Single JSON document | App settings, feature flags, global options |
230
+ | **Data** (`getData`/`setDataItem`) | Array of documents with IDs | Lists of items, records, entries |
231
+ | **App Objects** (`app.records` / `app.cases` / `app.threads`) | Queryable domain objects | Real app entities, workflows, conversations, richer access control |
232
+
233
+ Both can be scoped to **collection level** or **product level** by including `productId`.
234
+
235
+ 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.
236
+
237
+ 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.
238
+
239
+ ### Feature Flags & Entitlements (`appConfig`)
240
+
241
+ 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:
242
+
243
+ ```ts
244
+ if (await SL.appConfiguration.isFeatureEnabled(collectionId, 'custom_domain')) {
245
+ enableCustomDomainUI();
246
+ }
247
+ ```
248
+
249
+ 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).
250
+
251
+ ### Attestations (Proof-level data)
252
+
253
+ For data attached to specific proof instances, use `SL.attestation.create()` and `SL.attestation.list()`.
254
+
255
+ ### Custom Data Scoping (Product & Proof)
256
+
257
+ `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).
258
+
259
+ 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.
260
+
261
+ ---
262
+
263
+ ## Error Handling
264
+
265
+ The SmartLinks SDK returns structured `SmartlinksApiError` objects. Use `instanceof SmartlinksApiError` to access `.statusCode`, `.message`, and helper methods:
266
+
267
+ - `.isAuthError()` — 401/403 responses
268
+ - `.isNotFound()` — 404 responses
269
+ - `.isRateLimited()` — 429 responses
270
+ - `.isServerError()` — 5xx responses
271
+
272
+ See `docs/API_SUMMARY.md` for complete error handling documentation.
273
+
274
+ ---
275
+
276
+ ## AI Integration
277
+
278
+ 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.
279
+
280
+ Key capabilities: chat completions (streaming + tool calling), RAG document Q&A, voice input/output, podcast generation, text-to-speech, model listing.
281
+
282
+ See `docs/ai.md` for complete documentation.
283
+
284
+ ---
285
+
286
+ ## Interactions & Event Tracking
287
+
288
+ The `SL.interactions` namespace tracks user engagement — competition entries, votes, form submissions, warranty registrations. Events can trigger automated journeys and communications.
289
+
290
+ **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.
291
+
292
+ Key functions: `submitPublicEvent()`, `appendEvent()` (admin), `countsByOutcome()`, `query()`.
293
+
294
+ See `docs/interactions.md` for complete documentation.
295
+
296
+ ---
297
+
298
+ ## Liquid Templating
299
+
300
+ Use the `<LiquidContent>` component, `useLiquidTemplate` hook, and `renderLiquid` utility for admin-configured dynamic content using Liquid syntax.
301
+
302
+ See `docs/liquid-templates.md` for full context variables, filters, and examples.
303
+
304
+ ---
305
+
306
+ ## Design Principles
307
+
308
+ ### Public Interface (Portal)
309
+
310
+ - **Mobile-first** — Assume users are on phones
311
+ - **Non-technical** — Never show raw IDs or technical data
312
+ - **Accessible** — Follow WCAG guidelines
313
+
314
+ ### Admin Interface
315
+
316
+ - **Feature-rich** — Power users expect advanced controls
317
+ - **Efficient** — Minimise clicks for common tasks
318
+ - **Desktop-optimised** — Admins typically use desktop browsers
319
+
320
+ ### Theming
321
+
322
+ Apps receive theme configuration from the parent platform via URL parameter (`?theme=base64…`) and PostMessage updates. See `docs/theme.system.md`.
323
+
324
+ ---
325
+
326
+ ## Common Hooks
327
+
328
+ ```typescript
329
+ // Fetch collection/product/proof data
330
+ useCollectionData(collectionId)
331
+ useProductData(collectionId, productId)
332
+ useProofData(collectionId, productId, proofId)
333
+
334
+ // Fetch app configuration
335
+ useCollectionAppConfig(collectionId, appId)
336
+ useProductAppConfig(collectionId, productId, appId)
337
+
338
+ // Fetch app data (array of items)
339
+ useCollectionAppData(collectionId, appId)
340
+ useProductAppData(collectionId, productId, appId)
341
+
342
+ // Fetch attestations
343
+ useAttestationsData(collectionId, productId, proofId)
344
+
345
+ // URL parameter management
346
+ usePersistentQueryParams()
347
+
348
+ // Theme management
349
+ useSmartLinksTheme()
350
+
351
+ // Liquid templating
352
+ useLiquidTemplate(templateString, contextData)
353
+ ```
354
+
355
+ ---
356
+
357
+ ## API Namespaces
358
+
359
+ The SmartLinks SDK is organised into namespaces. See `docs/API_SUMMARY.md` for the complete reference. Key namespaces:
360
+
361
+ - `appConfiguration` — Config and data storage (most apps use this)
362
+ - `attestation` — Proof-level user/admin data
363
+ - `interactions` — Event tracking and analytics
364
+ - `ai` — AI content generation, chat, RAG (see `docs/ai.md`)
365
+ - `auth` / `authKit` — Admin and end-user authentication
366
+ - `contact` — Customer contact management
367
+ - `comms` / `broadcasts` — Notifications and campaigns
368
+ - `asset` — File/image uploads
369
+ - `adminCards` — the collection's dashboard: `list`, `refresh`, `saveLayout` (see `docs/admin-cards.md`)
370
+ - `realtime` — SmartLinks Realtime: `onChange`, `channel`, `onMine` (see `docs/realtime.md`)
371
+
372
+ ---
373
+
374
+ ## File Structure
375
+
376
+ ```
377
+ ├── index.html ← Public portal entry
378
+ ├── admin.html ← Admin console entry
379
+ ├── public/
380
+ │ ├── app.manifest.json ← Public discovery manifest
381
+ │ ├── app.admin.json ← Admin manifest (on-demand)
382
+ │ └── ai-guide.md ← AI orchestrator prose guide
383
+ ├── src/
384
+ │ ├── main.tsx ← Public React entry
385
+ │ ├── admin-main.tsx ← Admin React entry
386
+ │ ├── App.tsx ← Shared providers (QueryClient, Toaster, etc.)
387
+ │ ├── PublicApp.tsx ← Public app shell (routes only public pages)
388
+ │ ├── AdminApp.tsx ← Admin app shell (routes only admin pages)
389
+ │ ├── components/ ← Reusable UI components
390
+ │ ├── containers/ ← Embeddable full-app containers
391
+ │ ├── executor/ ← Executor bundle (SEO, LLM content, config API)
392
+ │ ├── hooks/ ← React hooks (data fetching, state)
393
+ │ ├── pages/
394
+ │ │ ├── PublicPage.tsx ← Portal content (/#/)
395
+ │ │ ├── AdminPage.tsx ← Admin content (admin.html#/)
396
+ │ │ └── DevPage.tsx ← Development helper (dev only)
397
+ │ ├── widgets/ ← Embeddable widget components
398
+ │ └── utils/
399
+ │ ├── smartlinks/ ← SmartLinks utilities
400
+ │ └── theme.ts ← Theme utilities
401
+ ├── vite.config.ts ← Multi-page build config
402
+ ├── vite.config.widget.ts ← Widget library build config
403
+ ├── vite.config.container.ts ← Container library build config
404
+ └── vite.config.executor.ts ← Executor library build config
405
+ ```
406
+
407
+ ---
408
+
409
+ ## Anti-Patterns to Avoid
410
+
411
+ ❌ **Don't implement custom auth** — Use SmartLinks auth via `SL.auth.getAccount()`
412
+
413
+ ❌ **Don't use BrowserRouter** — Always use HashRouter for iframe compatibility
414
+
415
+ ❌ **Don't hardcode URLs** — Use relative paths and let the platform provide context
416
+
417
+ ❌ **Don't store secrets in code** — Use environment variables or platform configuration
418
+
419
+ ❌ **Don't assume screen size** — Support both mobile (Portal) and desktop (Admin)
420
+
421
+ ❌ **Don't expose technical IDs** — Show human-readable names to users
422
+
423
+ ❌ **Don't import AdminPage in PublicApp** — Keep bundles separate for optimal size
424
+
425
+ ❌ **Don't use external AI services** — Use SmartLinks AI via `SL.ai`, not OpenAI/Anthropic/Lovable Cloud AI directly
426
+
427
+ ❌ **Don't forget `admin: true`** — All admin write operations require this flag
428
+
429
+ ---
430
+
431
+ ## Quick Reference
432
+
433
+ ### Initialise the API
434
+
435
+ ```typescript
436
+ import { initializeAPI } from '@/utils/smartlinks/initialization';
437
+ initializeAPI(); // Call once at app startup
438
+ ```
439
+
440
+ ### Get Context from URL
441
+
442
+ ```typescript
443
+ const { persistentQueryParams } = usePersistentQueryParams();
444
+ const { collectionId, productId, appId } = persistentQueryParams;
445
+ ```
446
+
447
+ ### Check Admin Status
448
+
449
+ ```typescript
450
+ const account = await SL.auth.getAccount();
451
+ const isAdmin = account?.admin === true;
452
+ ```
453
+
454
+ ### Save Configuration (Admin Only)
455
+
456
+ ```typescript
457
+ await SL.appConfiguration.setConfig({
458
+ collectionId, appId,
459
+ config: { myKey: 'myValue' },
460
+ admin: true // Required!
461
+ });
462
+ ```
463
+
464
+ ### Handle Dark Mode + Theming
465
+
466
+ ```typescript
467
+ // In App.tsx — already integrated in the template
468
+ useDarkMode(); // Handles ?dark=1 parameter
469
+ useSmartLinksTheme(); // Handles ?theme=base64 parameter
470
+ useDeepLinkSync(); // Syncs route changes to parent
471
+ ```
472
+
473
+ ### Deep Linking
474
+
475
+ ```typescript
476
+ const { navigateWithState, getAppState } = usePersistentQueryParams();
477
+ const { tab = 'general' } = getAppState();
478
+ navigateWithState('/', { tab: 'advanced' });
479
+ ```
480
+
481
+ See `docs/deep-link-discovery.md` for full implementation details.