@proveanything/smartlinks 2.1.39 → 2.1.41

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