@proveanything/smartlinks 2.2.0 → 3.0.0-alpha.0

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 (328) hide show
  1. package/README.md +741 -754
  2. package/dist/README.md +573 -573
  3. package/dist/adminCardsView.js +55 -55
  4. package/dist/api/adminCards.d.ts +8 -0
  5. package/dist/api/adminCards.js +9 -1
  6. package/dist/api/ai.d.ts +22 -11
  7. package/dist/api/ai.js +18 -14
  8. package/dist/api/analytics.d.ts +13 -0
  9. package/dist/api/analytics.js +13 -0
  10. package/dist/api/appConfiguration.d.ts +17 -14
  11. package/dist/api/appConfiguration.js +14 -12
  12. package/dist/api/appObjects.d.ts +80 -16
  13. package/dist/api/appObjects.js +74 -11
  14. package/dist/api/asset.d.ts +55 -19
  15. package/dist/api/asset.js +52 -32
  16. package/dist/api/attestation.d.ts +3 -2
  17. package/dist/api/attestation.js +1 -1
  18. package/dist/api/attestations.d.ts +22 -7
  19. package/dist/api/attestations.js +22 -7
  20. package/dist/api/authKit.d.ts +22 -5
  21. package/dist/api/authKit.js +21 -4
  22. package/dist/api/batch.d.ts +23 -16
  23. package/dist/api/batch.js +19 -13
  24. package/dist/api/bookings.d.ts +45 -9
  25. package/dist/api/bookings.js +39 -3
  26. package/dist/api/broadcasts.d.ts +26 -6
  27. package/dist/api/broadcasts.js +22 -2
  28. package/dist/api/claimSet.d.ts +48 -13
  29. package/dist/api/claimSet.js +43 -7
  30. package/dist/api/collection.d.ts +20 -6
  31. package/dist/api/collection.js +19 -8
  32. package/dist/api/comms.d.ts +43 -12
  33. package/dist/api/comms.js +43 -13
  34. package/dist/api/conditions.d.ts +12 -2
  35. package/dist/api/conditions.js +10 -1
  36. package/dist/api/config.d.ts +15 -2
  37. package/dist/api/config.js +12 -0
  38. package/dist/api/contact.d.ts +34 -13
  39. package/dist/api/contact.js +35 -10
  40. package/dist/api/containers.d.ts +41 -23
  41. package/dist/api/containers.js +37 -21
  42. package/dist/api/crate.d.ts +9 -8
  43. package/dist/api/crate.js +8 -8
  44. package/dist/api/dpp.d.ts +58 -10
  45. package/dist/api/dpp.js +57 -15
  46. package/dist/api/facets.d.ts +71 -0
  47. package/dist/api/facets.js +71 -0
  48. package/dist/api/files.d.ts +11 -5
  49. package/dist/api/files.js +9 -1
  50. package/dist/api/form.d.ts +9 -2
  51. package/dist/api/form.js +7 -1
  52. package/dist/api/index.d.ts +0 -1
  53. package/dist/api/index.js +0 -1
  54. package/dist/api/integrations.d.ts +82 -27
  55. package/dist/api/integrations.js +63 -7
  56. package/dist/api/interactions.d.ts +42 -6
  57. package/dist/api/interactions.js +41 -5
  58. package/dist/api/jobs.d.ts +9 -2
  59. package/dist/api/jobs.js +6 -0
  60. package/dist/api/journeys.d.ts +13 -2
  61. package/dist/api/journeys.js +10 -1
  62. package/dist/api/journeysAnalytics.d.ts +12 -3
  63. package/dist/api/journeysAnalytics.js +9 -1
  64. package/dist/api/knowledge.d.ts +43 -10
  65. package/dist/api/knowledge.js +37 -5
  66. package/dist/api/location.d.ts +10 -3
  67. package/dist/api/location.js +7 -1
  68. package/dist/api/lots.d.ts +40 -13
  69. package/dist/api/lots.js +38 -8
  70. package/dist/api/loyalty.d.ts +70 -12
  71. package/dist/api/loyalty.js +60 -3
  72. package/dist/api/nfc.d.ts +8 -2
  73. package/dist/api/nfc.js +6 -1
  74. package/dist/api/order.d.ts +51 -160
  75. package/dist/api/order.js +46 -208
  76. package/dist/api/partner.d.ts +41 -8
  77. package/dist/api/partner.js +36 -4
  78. package/dist/api/products.d.ts +41 -8
  79. package/dist/api/products.js +33 -4
  80. package/dist/api/proof.d.ts +50 -13
  81. package/dist/api/proof.js +43 -7
  82. package/dist/api/realtime.d.ts +1 -11
  83. package/dist/api/realtime.js +1 -22
  84. package/dist/api/secrets.d.ts +25 -5
  85. package/dist/api/secrets.js +21 -2
  86. package/dist/api/segments.d.ts +26 -6
  87. package/dist/api/segments.js +22 -2
  88. package/dist/api/serviceAccounts.d.ts +8 -1
  89. package/dist/api/serviceAccounts.js +8 -1
  90. package/dist/api/shop.d.ts +41 -13
  91. package/dist/api/shop.js +35 -4
  92. package/dist/api/subscriptions.d.ts +47 -12
  93. package/dist/api/subscriptions.js +40 -4
  94. package/dist/api/tags.d.ts +40 -19
  95. package/dist/api/tags.js +38 -18
  96. package/dist/api/template.d.ts +31 -3
  97. package/dist/api/template.js +27 -0
  98. package/dist/api/translations.d.ts +17 -2
  99. package/dist/api/translations.js +14 -0
  100. package/dist/api/userGroups.d.ts +35 -9
  101. package/dist/api/userGroups.js +30 -5
  102. package/dist/api/variant.d.ts +11 -3
  103. package/dist/api/variant.js +9 -2
  104. package/dist/api/wallet.d.ts +23 -10
  105. package/dist/api/wallet.js +20 -2
  106. package/dist/apiVersion.d.ts +1 -1
  107. package/dist/apiVersion.js +1 -1
  108. package/dist/baseline.css +194 -194
  109. package/dist/docs/API_SUMMARY.md +1389 -2298
  110. package/dist/docs/PRODUCT_FACETS_SDK.md +10 -15
  111. package/dist/docs/admin-cards.md +189 -189
  112. package/dist/docs/admin-lists-and-pickers.md +1 -1
  113. package/dist/docs/agent-tools.md +156 -156
  114. package/dist/docs/ai-tools-and-skills.md +180 -180
  115. package/dist/docs/ai.md +1721 -1721
  116. package/dist/docs/analytics.md +3 -2
  117. package/dist/docs/api-versions.md +85 -76
  118. package/dist/docs/app-data-storage.md +277 -277
  119. package/dist/docs/app-docs.md +73 -73
  120. package/dist/docs/app-manifest.md +852 -852
  121. package/dist/docs/app-objects.md +38 -50
  122. package/dist/docs/app-records-pattern.md +388 -388
  123. package/dist/docs/appConfig.md +550 -550
  124. package/dist/docs/assets.md +17 -3
  125. package/dist/docs/assistant-apps.md +172 -172
  126. package/dist/docs/assistant-context.md +119 -119
  127. package/dist/docs/attestations.md +5 -4
  128. package/dist/docs/auth-kit.md +1 -1
  129. package/dist/docs/bookings.md +442 -442
  130. package/dist/docs/comms.md +689 -686
  131. package/dist/docs/connectors.md +340 -340
  132. package/dist/docs/contact-search.md +4 -3
  133. package/dist/docs/container-tracking.md +7 -7
  134. package/dist/docs/css-baseline.md +133 -133
  135. package/dist/docs/customer-guide.md +70 -70
  136. package/dist/docs/deploying-apps.md +340 -340
  137. package/dist/docs/dpp.md +115 -115
  138. package/dist/docs/entitlements.md +90 -90
  139. package/dist/docs/executor.md +1 -1
  140. package/dist/docs/files.md +69 -69
  141. package/dist/docs/forms.md +1 -1
  142. package/dist/docs/headless-providers.md +3 -3
  143. package/dist/docs/host-dependency-contract.md +252 -210
  144. package/dist/docs/i18n.md +9 -9
  145. package/dist/docs/integrations.md +322 -322
  146. package/dist/docs/interactions.md +544 -545
  147. package/dist/docs/item-context.md +181 -181
  148. package/dist/docs/knowledge.md +105 -102
  149. package/dist/docs/lists.md +114 -0
  150. package/dist/docs/lots.md +112 -111
  151. package/dist/docs/loyalty.md +348 -352
  152. package/dist/docs/members.md +183 -183
  153. package/dist/docs/memberships.md +150 -149
  154. package/dist/docs/mobile-admin-container.md +693 -693
  155. package/dist/docs/operations.md +281 -281
  156. package/dist/docs/overview.md +485 -485
  157. package/dist/docs/proof-claiming-methods.md +6 -6
  158. package/dist/docs/proof-comms-triggers.md +142 -142
  159. package/dist/docs/proof-ownership-transfer.md +155 -155
  160. package/dist/docs/proof-product-data-scoping.md +462 -462
  161. package/dist/docs/proof-share-grants.md +305 -305
  162. package/dist/docs/realtime.md +139 -138
  163. package/dist/docs/records-admin-pattern.md +304 -304
  164. package/dist/docs/server-functions.md +2 -2
  165. package/dist/docs/service-accounts.md +64 -64
  166. package/dist/docs/shop.md +4 -2
  167. package/dist/docs/site-seo.md +2 -1
  168. package/dist/docs/standard-query.md +187 -187
  169. package/dist/docs/tag-codes.md +97 -97
  170. package/dist/docs/tag-ranges.md +106 -106
  171. package/dist/docs/theme-tokens.md +252 -252
  172. package/dist/docs/translations.md +6 -1
  173. package/dist/docs/upgrading-to-3.md +430 -0
  174. package/dist/docs/user-groups.md +4 -4
  175. package/dist/docs/utils.md +1 -1
  176. package/dist/docs/wallet-passes.md +107 -107
  177. package/dist/docs/websites.md +123 -123
  178. package/dist/headless.d.ts +1 -1
  179. package/dist/headless.js +2 -2
  180. package/dist/http.d.ts +15 -2
  181. package/dist/http.js +60 -2
  182. package/dist/index.d.ts +7 -8
  183. package/dist/index.js +2 -0
  184. package/dist/list.d.ts +24 -0
  185. package/dist/list.js +80 -0
  186. package/dist/mobile-admin/types.d.ts +0 -16
  187. package/dist/openapi.yaml +290 -2723
  188. package/dist/shared-dependencies.d.ts +3 -3
  189. package/dist/shared-dependencies.js +13 -5
  190. package/dist/site.d.ts +1 -7
  191. package/dist/site.js +1 -14
  192. package/dist/theme-boot.js +82 -82
  193. package/dist/theme.css +75 -75
  194. package/dist/types/adminCards.d.ts +6 -3
  195. package/dist/types/ai.d.ts +0 -6
  196. package/dist/types/analytics.d.ts +5 -8
  197. package/dist/types/appManifest.d.ts +4 -5
  198. package/dist/types/appObjects.d.ts +14 -18
  199. package/dist/types/appObjects.js +0 -1
  200. package/dist/types/appOptions.d.ts +18 -0
  201. package/dist/types/asset.d.ts +3 -22
  202. package/dist/types/attestations.d.ts +7 -10
  203. package/dist/types/batch.d.ts +6 -14
  204. package/dist/types/bookings.d.ts +22 -4
  205. package/dist/types/broadcasts.d.ts +5 -13
  206. package/dist/types/broadcasts.js +0 -1
  207. package/dist/types/claimSet.d.ts +0 -5
  208. package/dist/types/comms.d.ts +11 -9
  209. package/dist/types/contact.d.ts +5 -29
  210. package/dist/types/contact.js +0 -13
  211. package/dist/types/containers.d.ts +15 -26
  212. package/dist/types/crate.d.ts +4 -12
  213. package/dist/types/dpp.d.ts +3 -3
  214. package/dist/types/dpp.js +0 -1
  215. package/dist/types/error.d.ts +8 -5
  216. package/dist/types/error.js +12 -5
  217. package/dist/types/facets.d.ts +15 -15
  218. package/dist/types/index.d.ts +1 -0
  219. package/dist/types/index.js +1 -0
  220. package/dist/types/integrations.d.ts +3 -28
  221. package/dist/types/interaction.d.ts +3 -9
  222. package/dist/types/jobs.d.ts +3 -8
  223. package/dist/types/jobs.js +0 -1
  224. package/dist/types/journeys.d.ts +3 -8
  225. package/dist/types/journeys.js +0 -1
  226. package/dist/types/journeysAnalytics.d.ts +0 -1
  227. package/dist/types/list.d.ts +24 -0
  228. package/dist/types/list.js +2 -0
  229. package/dist/types/location.d.ts +0 -4
  230. package/dist/types/lots.d.ts +0 -9
  231. package/dist/types/loyalty.d.ts +0 -9
  232. package/dist/types/order.d.ts +7 -134
  233. package/dist/types/product.d.ts +11 -24
  234. package/dist/types/proof.d.ts +16 -0
  235. package/dist/types/realtime.d.ts +0 -29
  236. package/dist/types/segments.d.ts +5 -13
  237. package/dist/types/segments.js +0 -1
  238. package/dist/types/serviceAccounts.d.ts +3 -2
  239. package/dist/types/serviceAccounts.js +0 -1
  240. package/dist/types/shop.d.ts +5 -12
  241. package/dist/types/shop.js +0 -4
  242. package/dist/types/subscriptions.d.ts +18 -0
  243. package/dist/types/subscriptions.js +0 -8
  244. package/dist/types/tags.d.ts +6 -16
  245. package/dist/types/tags.js +0 -7
  246. package/dist/types/translations.d.ts +3 -9
  247. package/dist/types/variant.d.ts +0 -2
  248. package/dist/version.d.ts +1 -1
  249. package/dist/version.js +1 -1
  250. package/docs/API_SUMMARY.md +1389 -2298
  251. package/docs/PRODUCT_FACETS_SDK.md +10 -15
  252. package/docs/admin-cards.md +189 -189
  253. package/docs/admin-lists-and-pickers.md +1 -1
  254. package/docs/agent-tools.md +156 -156
  255. package/docs/ai-tools-and-skills.md +180 -180
  256. package/docs/ai.md +1721 -1721
  257. package/docs/analytics.md +3 -2
  258. package/docs/api-versions.md +85 -76
  259. package/docs/app-data-storage.md +277 -277
  260. package/docs/app-docs.md +73 -73
  261. package/docs/app-manifest.md +852 -852
  262. package/docs/app-objects.md +38 -50
  263. package/docs/app-records-pattern.md +388 -388
  264. package/docs/appConfig.md +550 -550
  265. package/docs/assets.md +17 -3
  266. package/docs/assistant-apps.md +172 -172
  267. package/docs/assistant-context.md +119 -119
  268. package/docs/attestations.md +5 -4
  269. package/docs/auth-kit.md +1 -1
  270. package/docs/bookings.md +442 -442
  271. package/docs/comms.md +689 -686
  272. package/docs/connectors.md +340 -340
  273. package/docs/contact-search.md +4 -3
  274. package/docs/container-tracking.md +7 -7
  275. package/docs/css-baseline.md +133 -133
  276. package/docs/customer-guide.md +70 -70
  277. package/docs/deploying-apps.md +340 -340
  278. package/docs/dpp.md +115 -115
  279. package/docs/entitlements.md +90 -90
  280. package/docs/executor.md +1 -1
  281. package/docs/files.md +69 -69
  282. package/docs/forms.md +1 -1
  283. package/docs/headless-providers.md +3 -3
  284. package/docs/host-dependency-contract.md +252 -210
  285. package/docs/i18n.md +9 -9
  286. package/docs/integrations.md +322 -322
  287. package/docs/interactions.md +544 -545
  288. package/docs/item-context.md +181 -181
  289. package/docs/knowledge.md +105 -102
  290. package/docs/lists.md +114 -0
  291. package/docs/lots.md +112 -111
  292. package/docs/loyalty.md +348 -352
  293. package/docs/members.md +183 -183
  294. package/docs/memberships.md +150 -149
  295. package/docs/mobile-admin-container.md +693 -693
  296. package/docs/operations.md +281 -281
  297. package/docs/overview.md +485 -485
  298. package/docs/proof-claiming-methods.md +6 -6
  299. package/docs/proof-comms-triggers.md +142 -142
  300. package/docs/proof-ownership-transfer.md +155 -155
  301. package/docs/proof-product-data-scoping.md +462 -462
  302. package/docs/proof-share-grants.md +305 -305
  303. package/docs/realtime.md +139 -138
  304. package/docs/server-functions.md +2 -2
  305. package/docs/service-accounts.md +64 -64
  306. package/docs/shop.md +4 -2
  307. package/docs/site-seo.md +2 -1
  308. package/docs/standard-query.md +187 -187
  309. package/docs/tag-codes.md +97 -97
  310. package/docs/tag-ranges.md +106 -106
  311. package/docs/theme-lookbook.v1.json +120 -120
  312. package/docs/theme-tokens.md +252 -252
  313. package/docs/translations.md +6 -1
  314. package/docs/upgrading-to-3.md +430 -0
  315. package/docs/user-groups.md +4 -4
  316. package/docs/utils.md +1 -1
  317. package/docs/wallet-passes.md +107 -107
  318. package/docs/websites.md +123 -123
  319. package/openapi.yaml +290 -2723
  320. package/package.json +91 -87
  321. package/scripts/headless-check.mjs +87 -87
  322. package/scripts/lib/bare-imports.mjs +57 -57
  323. package/scripts/lib/keyed-app-data.mjs +21 -21
  324. package/scripts/lib/upgrade.mjs +512 -0
  325. package/scripts/publish.mjs +272 -272
  326. package/scripts/register-release.mjs +91 -91
  327. package/scripts/upgrade.mjs +56 -0
  328. package/upgrade/3.json +2213 -0
@@ -1,693 +1,693 @@
1
- # Mobile Admin Container SDK
2
-
3
- > **Version:** 1.0 · **Platform:** SmartLinks R5 · **Last updated:** 2026-09-21
4
-
5
- This document describes how to build a **Mobile Admin Container** — a SmartLinks microapp that provides an in-the-field operator/admin surface optimised for mobile devices. These containers ship as a **separate `mobileAdmin` bundle** (not inside the `containers` bundle) so that Capacitor plugins, offline helpers, and operator-only code never reach the public consumer bundle.
6
-
7
- > **See also:** [containers.md](containers.md) covers the public consumer container. The [Multiple Consumer Components](containers.md#multiple-consumer-components) section explains the consumer vs. admin bundle split. For the full `host.native` facade contract (share, clipboard, haptics, NFC, RFID, storage, etc.) see [native-facade.md](native-facade.md).
8
-
9
- ---
10
-
11
- ## Table of Contents
12
-
13
- 1. [When to Build a Mobile Admin Container](#when-to-build-a-mobile-admin-container)
14
- 2. [Host Environment](#host-environment)
15
- 3. [The `host` Prop](#the-host-prop)
16
- 4. [Hardware Capabilities & the Capability Matrix](#hardware-capabilities--the-capability-matrix)
17
- 5. [Capacitor Plugin Baseline](#capacitor-plugin-baseline)
18
- 6. [Manifest Declaration](#manifest-declaration)
19
- 7. [Launcher Discovery](#launcher-discovery)
20
- 8. [Event Stream](#event-stream)
21
- 9. [Error Handling](#error-handling)
22
- 10. [Lifecycle](#lifecycle)
23
- 11. [Build & Bundle Requirements](#build--bundle-requirements)
24
- 12. [Example: Minimal Mobile Admin Container](#example-minimal-mobile-admin-container)
25
- 13. [Best Practices](#best-practices)
26
- 14. [Native Capability Facade](#native-capability-facade)
27
-
28
- ---
29
-
30
- ## When to Build a Mobile Admin Container
31
-
32
- Build a Mobile Admin Container when the surface is intended for **field operators or admins** rather than consumers — especially when:
33
-
34
- - You need native hardware: NFC, RFID, camera/barcode, haptics, geolocation
35
- - The surface must work offline or in flaky network conditions
36
- - You want the bundle to version independently from the public consumer app
37
-
38
- All admin-mobile containers ship in the `mobileAdmin` bundle and are never loaded by the public portal. The mobile launcher loads them via the `mobileAdmin` manifest key.
39
-
40
- ---
41
-
42
- ## Host Environment
43
-
44
- The SmartLinks Mobile launcher runs on five host environments:
45
-
46
- | Host ID | Description | Hardware bridge |
47
- |---------|-------------|-----------------|
48
- | `custom-android` | Original Kotlin WebView app — full RFID + NTAG-advanced | `window.SmartlinksScanner` |
49
- | `capacitor-ios` | iOS app built via Capacitor | Capacitor plugins |
50
- | `capacitor-android` | Generic Android Capacitor build (no RFID) | Capacitor plugins |
51
- | `pwa` | Installed Progressive Web App | Web APIs only |
52
- | `browser` | Regular browser tab | Web APIs only |
53
-
54
- Your container **never** detects the host directly. It receives a `host` prop from the launcher and reads `host.hardware.*` capability flags. The launcher handles the rest.
55
-
56
- ---
57
-
58
- ## The `host` Prop
59
-
60
- Every container mounted by the SmartLinks Mobile launcher receives a single `host` prop — `AdminMobileHostContext`. Do not reach for `window.SmartlinksScanner` or `window.Capacitor` directly; both are wrapped here.
61
-
62
- > **SDK export** — `AdminMobileHostContext`, `AdminMobileCapability`, `ActionableCapability`, `AdminMobileHostId`, `AdminMobileEvent`, `AdminMobileEventCallback`, `AdminMobileEventSubscriber`, `AdminMobileComponentManifest`, `AdminMobileBundleManifest`, and `NativeFacade` (plus all sub-facade interfaces) are exported from `@proveanything/smartlinks`. Import via `import type { AdminMobileHostContext } from '@proveanything/smartlinks'` — no local mirror needed. `ScannerEventSubscriber`, `MobileAdminComponentManifest`, and `MobileAdminBundleManifest` still export as deprecated aliases.
63
-
64
- ```typescript
65
- interface AdminMobileHostContext {
66
- // Identity
67
- collectionId: string
68
- appId: string
69
- user: { uid?: string; email?: string; displayName?: string; isAdmin: boolean } | null
70
-
71
- // SDK — already initialised. Do NOT call initializeApi again.
72
- SL: typeof import('@proveanything/smartlinks')
73
-
74
- // Capabilities declared by this container in its manifest
75
- capabilities: AdminMobileCapability[]
76
-
77
- // Live capability flags for the current device
78
- hardware: {
79
- nfc: boolean
80
- rfid: boolean
81
- qr: boolean
82
- camera: boolean
83
- keyboard: boolean
84
- }
85
-
86
- // Unified hardware event stream — callback type: AdminMobileEventCallback
87
- events: { subscribe: (cb: AdminMobileEventCallback) => () => void }
88
-
89
- // Promise-based hardware actions — reject with a structured error when unavailable or cancelled
90
- actions: {
91
- requestQrScan: (opts?: { signal?: AbortSignal; heightPercent?: number; prompt?: string }) => Promise<string>
92
- requestNfcTap: (opts?: { timeoutMs?: number; signal?: AbortSignal; prompt?: string } | number) => Promise<{ uid: string; ndef?: string }>
93
- requestCameraPhoto: (opts?: { signal?: AbortSignal }) => Promise<Blob>
94
- share: (payload: { title: string; url: string; text?: string }) => Promise<void>
95
- clipboard: {
96
- read: () => Promise<string>
97
- write: (text: string) => Promise<void>
98
- }
99
- }
100
-
101
- // Host-provided UI helpers — all optional, see §3 note
102
- ui: {
103
- toast?: (opts: { title: string; description?: string; variant?: 'default' | 'destructive' }) => void
104
- haptic?: (style?: 'light' | 'success' | 'error') => void
105
- setHeaderTitle?: (title: string | null) => void
106
- navigateBack?: () => void
107
- }
108
-
109
- // UHF RFID reader — only on hosts with one (feature-detect). See "RFID" below.
110
- rfid?: AdminMobileRfid
111
-
112
- // Network & device info
113
- network: { isOnline: () => boolean }
114
- device: { info: () => Promise<{ model: string; platform: string }> }
115
-
116
- // Informational host version — use for logging/diagnostics, not feature detection.
117
- // For feature detection prefer existence checks: 'requestNfcTap' in host.actions
118
- _version: number
119
-
120
- // Full native capability facade — share, clipboard, haptics, NFC, RFID, storage, etc.
121
- // Optional: not every host stub populates it. See native-facade.md.
122
- native?: NativeFacade
123
- }
124
- ```
125
-
126
- ### Contract rules
127
-
128
- 1. **Check `host.hardware.X` before calling `host.actions.X`.** Calls to unavailable capabilities reject with `HostCapabilityUnavailableError`.
129
- 2. **Do not call `initializeApi`, and do not use top-level SDK imports for API calls.** `host.SL` is already configured with the right `baseURL`, auth, and logger. Code that does `import * as SL from "@proveanything/smartlinks"` and calls `SL.attestation.create(...)` will silently hit the wrong base URL — the top-level import is uninitialised in the launcher's runtime and produces no loud error. Always go through `host.SL`:
130
- ```typescript
131
- // ❌ Silent footgun — uninitialised SDK, wrong baseURL
132
- import * as SL from '@proveanything/smartlinks'
133
- await SL.attestation.create(...)
134
-
135
- // ✅ Correct
136
- await host.SL.attestation.create(...)
137
- ```
138
- 3. **Do not access `window.SmartlinksScanner` or `window.Capacitor` directly.** The host wraps both; direct access produces containers that only work on one shell.
139
- 4. **Externalise all shared deps** (React, ReactDOM, SL, Radix, etc.) — the launcher provides them as globals. See [Build & Bundle Requirements](#build--bundle-requirements).
140
-
141
- ```typescript
142
- // Example — always check hardware flags first
143
- const { host } = props
144
-
145
- if (host.hardware.nfc) {
146
- host.ui.setHeaderTitle('Scan NFC tag')
147
- const { uid } = await host.actions.requestNfcTap(5000)
148
- // ...
149
- }
150
- ```
151
-
152
- ### `host.ui` — native helpers vs. your own components
153
-
154
- All four `host.ui` methods are **optional by design**. A container may run in the Sidekick mobile shell, a standalone PWA or browser tab, Storybook, or a screenshot harness — none of those environments is guaranteed to have a native toast system, a managed header, or a back stack. Forcing every host implementer to provide them would exclude the web and desktop use-cases the rest of the contract explicitly supports. Always guard with `?.`:
155
-
156
- - `host.ui.toast?.({...})` / `host.ui.haptic?.('success')` — optional native feedback. Fall back to your own `<Toaster />` when absent.
157
- - `host.ui.setHeaderTitle?.('Scanning…')` / `host.ui.navigateBack?.()` — host-shell integrations with no in-container equivalent. Silently no-op when the host doesn't implement them.
158
-
159
- **Stub pattern for testing and Storybook:**
160
-
161
- ```typescript
162
- const stubHost: Partial<AdminMobileHostContext> = {
163
- hardware: { nfc: false, rfid: false, qr: true, camera: true, keyboard: false },
164
- actions: {
165
- requestQrScan: async () => 'STUB_QR_CODE',
166
- requestNfcTap: async () => ({ uid: 'STUB_UID' }),
167
- requestCameraPhoto: async () => new Blob(),
168
- share: async () => {},
169
- clipboard: { read: async () => '', write: async () => {} },
170
- },
171
- ui: {
172
- toast: (opts) => console.log('[stub toast]', opts.title),
173
- haptic: () => {},
174
- setHeaderTitle: (t) => { if (t) document.title = t },
175
- navigateBack: () => history.back(),
176
- },
177
- network: { isOnline: () => true },
178
- user: { isAdmin: true, displayName: 'Test User', email: 'test@example.com' },
179
- SL: undefined as any, // replace with your test SL instance
180
- }
181
- ```
182
-
183
- ---
184
-
185
- ## Hardware Capabilities & the Capability Matrix
186
-
187
- Containers declare which capabilities they need (or can use) in the manifest `capabilities` array. The launcher uses this list to:
188
-
189
- 1. **Filter availability** — hide containers whose required hardware is not on this device
190
- 2. **Pre-warm** — start the right reader as soon as the container mounts
191
- 3. **Permission prompts** — request only the permissions the container actually needs
192
-
193
- | Capability | Description |
194
- |------------|-------------|
195
- | `"nfc"` | NFC tap — UID + NDEF read |
196
- | `"nfc-advanced"` | NTAG 21x mirror config, NTAG 424 SUN, key rotation (`custom-android` only) |
197
- | `"rfid"` | UHF RFID mass scan (`custom-android` only) |
198
- | `"qr"` | QR / barcode scanning (camera-based) |
199
- | `"camera"` | Photo capture, gallery picker |
200
- | `"keyboard"` | Physical hardware trigger/action buttons |
201
- | `"geolocation"` | GPS coordinates |
202
- | `"push"` | Remote push notifications (FCM/APNs) |
203
-
204
- The full hardware capability matrix by host:
205
-
206
- | Capability | custom-android | capacitor-ios | capacitor-android | pwa | browser |
207
- |------------|:-:|:-:|:-:|:-:|:-:|
208
- | NFC tap (UID + NDEF read) | ✅ | ✅ | ✅ | ⚠️ Chrome Android | ⚠️ |
209
- | NFC NDEF write | ✅ | ❌ | ✅ | ⚠️ | ⚠️ |
210
- | NFC advanced (NTAG 21x / 424) | ✅ | ❌ | ❌ | ❌ | ❌ |
211
- | RFID mass scan | ✅ | ❌ | ❌ | ❌ | ❌ |
212
- | QR / barcode scan | ✅ | ✅ | ✅ | ✅ | ✅ |
213
- | Camera photo | ✅ | ✅ | ✅ | ✅ | ✅ |
214
- | Hardware key events | ✅ | ❌ | ❌ | ❌ | ❌ |
215
- | Haptics | ✅ | ✅ | ✅ | ⚠️ visual only | ⚠️ |
216
-
217
- > Containers that declare `"rfid"` or `"nfc-advanced"` are only offered on `custom-android`. All others are assumed to run on all five hosts — design for the lowest common denominator and use `host.hardware.*` flags to unlock richer UI on capable devices.
218
-
219
- ---
220
-
221
- ## Capacitor Plugin Baseline
222
-
223
- The custom Kotlin shell and both Capacitor shells ship the same baseline plugin set. Container authors can rely on all Tier 1 plugins on every native host.
224
-
225
- ### Tier 1 — always available on every native host
226
-
227
- | Plugin | Surfaced via |
228
- |--------|-------------|
229
- | `@capacitor/haptics` | `host.ui.haptic()` |
230
- | `@capacitor/network` | `host.network.isOnline()` |
231
- | `@capacitor/device` | `host.device.info()` |
232
- | `@capacitor/share` | `host.actions.share()` |
233
- | `@capacitor/clipboard` | `host.actions.clipboard.*` |
234
- | `@capacitor/preferences` | `host.storage.*` *(planned — see note below)* |
235
- | `@capacitor/app` | host-managed (back button, deep links) |
236
- | `@capacitor/status-bar` | host-managed |
237
- | `@capacitor/keyboard` | host-managed |
238
- | `@capacitor/toast` | wired into `host.ui.toast()` |
239
-
240
- > **`host.storage` — planned shape.** Once released, the surface will wrap `@capacitor/preferences` directly:
241
- > ```ts
242
- > host.storage: {
243
- > get(key: string): Promise<string | null>
244
- > set(key: string, value: string): Promise<void>
245
- > remove(key: string): Promise<void>
246
- > keys(): Promise<string[]>
247
- > }
248
- > ```
249
- > Until then: `localStorage` works on web hosts; use `@capacitor/preferences` directly (bundle it in) on native.
250
-
251
- ### Tier 2 — capability-gated (declare in manifest)
252
-
253
- | Plugin | Capability flag |
254
- |--------|----------------|
255
- | `@capacitor/camera` | `"camera"` |
256
- | `@capacitor-mlkit/barcode-scanning` | `"qr"` |
257
- | `@capgo/capacitor-nfc` | `"nfc"` |
258
- | `@capacitor/geolocation` | `"geolocation"` |
259
- | `@capacitor/push-notifications` | `"push"` |
260
- | `@capacitor/filesystem` | *(used when `offline: true`; bundle it in)* |
261
-
262
- ### Tier 3 — custom-android only (not Capacitor)
263
-
264
- Proprietary hardware SDKs (UHF RFID, NTAG 21x/424 advanced programming, USB uFR reader feedback). These are wrapped behind `host.actions.*` — never access `window.SmartlinksScanner` directly.
265
-
266
- ---
267
-
268
- ## Manifest Declaration
269
-
270
- Declare the bundle under the top-level `mobileAdmin` key in `app.manifest.json`. This is separate from `containers` — the mobile launcher reads `mobileAdmin`; the public portal never loads it.
271
-
272
- ```json
273
- {
274
- "meta": { "appId": "my-app", "name": "My App", "version": "1.0.0" },
275
-
276
- "containers": {
277
- "files": { "js": { "umd": "dist/containers.umd.js", "esm": "dist/containers.esm.js" }, "css": "dist/containers.css" },
278
- "components": [
279
- { "name": "PublicContainer", "description": "Default consumer experience" }
280
- ]
281
- },
282
-
283
- "mobileAdmin": {
284
- "files": {
285
- "js": {
286
- "umd": "dist/mobile-admin.umd.js",
287
- "esm": "dist/mobile-admin.esm.js"
288
- },
289
- "css": null
290
- },
291
- "components": [
292
- {
293
- "name": "WarehousePickContainer",
294
- "description": "Pick orders by scanning NFC tags",
295
- "capabilities": ["nfc", "qr"],
296
- "offline": true
297
- }
298
- ]
299
- }
300
- }
301
- ```
302
-
303
- A `mobileAdmin` bundle can export multiple components targeting different operator workflows — each with its own `capabilities` declaration.
304
-
305
- **Component fields:**
306
-
307
- | Field | Type | Description |
308
- |-------|------|-------------|
309
- | `name` | string | Exported component name (must match the UMD bundle export) |
310
- | `description` | string | Shown in the mobile launcher's app picker |
311
- | `capabilities` | string[] | Hardware capabilities this component needs or can use. See table above. |
312
- | `offline` | boolean | Set to `true` if this component queues writes locally and needs offline sync support. |
313
-
314
- ---
315
-
316
- ## Launcher Discovery
317
-
318
- The SmartLinks Mobile launcher loads your `mobileAdmin` bundle through the platform's app registry — you do not reference the manifest URL directly.
319
-
320
- **How it works:**
321
-
322
- 1. A collection admin enables the app for a collection in the SmartLinks admin console.
323
- 2. On startup (and periodically), the launcher fetches `app.manifest.json` for every enabled app in that collection via the SmartLinks platform API. These requests are authenticated with the launcher's operator session.
324
- 3. The launcher reads `mobileAdmin.components[]`, evaluates each component's `capabilities` against the current device's hardware flags, and shows matching components in the app picker.
325
- 4. When the operator opens a component, the launcher resolves `mobileAdmin.files.js.umd` against the app's CDN base, fetches the bundle, and mounts the component with its `host` prop.
326
-
327
- **File URL resolution:** `files.js.umd` / `files.js.esm` are paths relative to your app's CDN root (set when the app version is published). Provide relative paths — the launcher resolves them; do not hardcode absolute URLs.
328
-
329
- **Auth:** Manifest and bundle fetches use the launcher's session token. Your container is already authenticated via `host.user` and `host.SL` — do not add additional auth headers.
330
-
331
- **On load failure:** If the bundle returns a non-2xx response, the launcher shows a user-visible error and logs it — it does not crash the full launcher. If `app.manifest.json` itself cannot be fetched, the app is silently excluded from the picker for that session.
332
-
333
- > To debug a missing or stale manifest, confirm in the SmartLinks admin console that the app version is published and that the `mobileAdmin` key is present in the uploaded manifest.
334
-
335
- ---
336
-
337
- ## Scanning: listening vs asking
338
-
339
- Every scan reaches a container in one of two ways. Pick per screen.
340
-
341
- | | Listening — `host.events` | Asking — `host.actions.request*` |
342
- |---|---|---|
343
- | Use for | "Tap or scan anything, any time" — a stock take, a scan-to-open list | "This step needs a scan" — tag this item, scan the shelf code |
344
- | What the user sees | Nothing changes | NFC: a small non-blocking hint with Cancel. QR / photo: the host's camera opens |
345
- | What you get | An event per tap / read / key | A promise for one result |
346
-
347
- ### NFC: two modes
348
-
349
- - **Listening** — subscribe to `nfc-tap`. Fires for every tap while no request is waiting.
350
- - **Asking** — `await host.actions.requestNfcTap({ prompt: 'Tap the bottle tag', signal })`. The next tap
351
- **made after the call** resolves it, and that tap is **not** also sent as an `nfc-tap` event, so
352
- nothing handles it twice. The request is non-blocking: the screen stays usable while it waits — show
353
- your own "or type the code" path and abort the wait with `signal` if the user takes it. One request at
354
- a time: a new call cancels the previous one.
355
-
356
- ```typescript
357
- const controller = new AbortController()
358
- try {
359
- const { uid } = await host.actions.requestNfcTap({ prompt: 'Tap the bottle tag', signal: controller.signal })
360
- await attachTag(uid)
361
- } catch (err) {
362
- if (err instanceof HostCancelledError) return // they pressed Cancel, or we aborted
363
- throw err
364
- }
365
- // elsewhere — the user typed the code instead:
366
- controller.abort()
367
- ```
368
-
369
- ### QR and photos
370
-
371
- `requestQrScan()` opens the host's camera scanner (full screen, or the bottom `heightPercent` of it) and
372
- resolves with the code; `requestCameraPhoto()` opens the camera and resolves with the image. Both reject
373
- with `HostCancelledError` when the user backs out.
374
-
375
- ### RFID
376
-
377
- `host.rfid` gives a container the same reader abilities the host's own scanner uses — so an app can be
378
- its own scanner. It's present only when the device has a UHF reader (`hardware.rfid`); check for it.
379
- There's one reader, so starting any of the three below ends the one before, and everything stops when
380
- the container unmounts.
381
-
382
- **Keep reading** — a stock take, an intake. De-duplicated and batched, so you get each tag once instead
383
- of hundreds of raw reads a second:
384
-
385
- ```typescript
386
- const session = host.rfid?.read({
387
- filter: { prefix: '3034' }, // optional: only EPCs starting with this (or { epcs: [...] })
388
- dedupe: 'session', // default — each tag once; { windowMs: 5000 } or 'none' for every read
389
- batchMs: 250, // default — reads arrive in batches; 0 = one at a time
390
- mode: 'trigger', // default — reads while the operator holds the trigger; 'continuous' = now until stop()
391
- })
392
- const off = session?.onRead((reads) => { // [{ epc, tid?, rssi?, timestamp, count }]
393
- for (const r of reads) addToCount(r.epc)
394
- })
395
- // later
396
- session?.stop()
397
- ```
398
-
399
- **One tag for this step** — tag an item. Resolves with the strongest tag read in the first moment of
400
- reading, then stops; the RFID counterpart of `requestNfcTap` (non-blocking, abortable, `prompt` hint):
401
-
402
- ```typescript
403
- const { epc } = await host.rfid.readOne({ prompt: 'Pull the trigger over the item', signal })
404
- ```
405
-
406
- **Find a tag** — a Geiger counter. `strength` runs 0 (not in range) to 100 (right here); by default the
407
- host plays faster beeps and haptics as you close in (`feedback: false` to do your own):
408
-
409
- ```typescript
410
- const hunt = host.rfid?.locate(item.epcs) // one EPC, or every tag on the item
411
- hunt?.onUpdate(({ strength, rssi, hitsPerSecond }) => setStrength(strength))
412
- // hunt.stop() when found
413
- ```
414
-
415
- `status()` / `onStatus(cb)` report whether a reader is available and connected, which one (`built-in`,
416
- `zebra`, `tsl`), whether it's reading, and its power range; `read`/`locate` take a `power` level for the
417
- session.
418
-
419
- Raw reads still arrive as `rfid-burst` events whenever the reader runs, for containers that want them.
420
-
421
- ---
422
-
423
- ## Event Stream
424
-
425
- For raw scan events (rather than the action-driven `host.actions.requestNfcTap`), subscribe to the unified event stream. Events flow identically on every host — the launcher normalises bridge messages, Capacitor callbacks, and Web API events into the same shape.
426
-
427
- ```typescript
428
- useEffect(() => {
429
- const unsubscribe = host.events.subscribe((event) => {
430
- switch (event.type) {
431
- case 'nfc-tap': handleNfc(event.uid, event.ndef); break
432
- case 'rfid-burst': handleEpcs(event.epcs); break
433
- case 'qr-scan': handleQr(event.code); break
434
- case 'key-press': if (event.keyCode === 293) startScan(); break
435
- case 'lifecycle': handleLifecycle(event.phase); break
436
- }
437
- })
438
- return unsubscribe
439
- }, [host.events])
440
- ```
441
-
442
- Event details:
443
-
444
- - Every event may carry `timestamp` (ms since epoch).
445
- - `nfc-tap` — `uid` is uppercase hex without separators (`04A1B2C3D4E5F6`); `ndef` is the tag's NDEF text (usually its URL), `""` when it had none.
446
- - `rfid-burst` — reads arrive as they happen, typically **one EPC per event, many per second** while the trigger is held. Collect and de-duplicate them yourself. `rssi` (dBm; closer = higher) when the reader reports it.
447
- - `key-press` — hosts that report both edges send `action: 'down'` then `'up'` for one press; act on `'down'` (or on events without `action`). `293` is the scan trigger.
448
-
449
- Lifecycle events (`event.type === 'lifecycle'`) carry a `phase` field: `'pause' | 'resume' | 'offline' | 'online'`. Use these instead of `window` event listeners so your container works identically on all hosts.
450
-
451
- ---
452
-
453
- ## Error Handling
454
-
455
- Action methods reject with structured errors — wrap every `host.actions.*` call even on hosts where the capability "should" be available (the user can deny permission at runtime):
456
-
457
- ```typescript
458
- class HostCapabilityUnavailableError extends Error {
459
- capability: 'nfc' | 'rfid' | 'qr' | 'camera'
460
- host: string // host ID
461
- }
462
-
463
- class HostPermissionDeniedError extends Error {
464
- capability: 'nfc' | 'rfid' | 'qr' | 'camera'
465
- }
466
-
467
- class HostTimeoutError extends Error {
468
- capability: 'nfc' | 'qr'
469
- timeoutMs: number
470
- }
471
-
472
- class HostCancelledError extends Error {
473
- capability: 'nfc' | 'qr' | 'camera'
474
- by: 'user' | 'app' // closed the scanner / pressed Cancel, or aborted by the container
475
- }
476
- ```
477
-
478
- All four are exported from `@proveanything/smartlinks`; check with `instanceof` or `err.name`.
479
-
480
- ```typescript
481
- try {
482
- const code = await host.actions.requestQrScan()
483
- host.ui.haptic('success')
484
- } catch (err) {
485
- if (err instanceof HostPermissionDeniedError) {
486
- host.ui.toast({ title: 'Camera access required', variant: 'destructive' })
487
- } else if (err instanceof HostTimeoutError) {
488
- host.ui.toast({ title: 'No QR code detected' })
489
- } else {
490
- throw err
491
- }
492
- }
493
- ```
494
-
495
- ---
496
-
497
- ## Lifecycle
498
-
499
- | Event | When | What to do |
500
- |-------|------|------------|
501
- | mount | User opens your container | Subscribe to events, start readers |
502
- | unmount | User backs out / app backgrounded > 30s | Unsubscribe; persist in-flight state |
503
- | `lifecycle: 'offline'` | Network lost | Switch to offline mode; queue writes locally |
504
- | `lifecycle: 'online'` | Network restored | Flush queued writes |
505
- | `lifecycle: 'pause'` | App backgrounded | Pause readers to save battery |
506
- | `lifecycle: 'resume'` | App foregrounded | Resubscribe; refresh stale data |
507
-
508
- Use `host.events.subscribe` for all lifecycle events — all five host types (`custom-android`, `capacitor-ios`, `capacitor-android`, `pwa`, `browser`) are guaranteed to emit every `'pause'`/`'resume'`/`'offline'`/`'online'` phase. No `window.addEventListener('online')` fallback is needed.
509
-
510
- > **Planned** — `phase: 'mount' | 'unmount'` events are on the roadmap. These will fire when the container becomes visible / is removed from the host view stack, enabling deferred reader start-up without a `useEffect` dependency.
511
-
512
- ---
513
-
514
- ## Build & Bundle Requirements
515
-
516
- The mobile admin bundle has its own Vite config: `vite.config.mobile-admin.ts`.
517
-
518
- ### Build output
519
-
520
- ```
521
- dist/mobile-admin.umd.js
522
- dist/mobile-admin.esm.js
523
- dist/mobile-admin.css the screen's own scoped stylesheet — declare it as mobileAdmin.files.css
524
- ```
525
-
526
- ### Styling
527
-
528
- The component renders **inside Sidekick's page**, not an iframe. Sidekick already has a CSS reset and
529
- its own styles, and loads your `mobileAdmin.files.css` alongside the bundle. Don't rely on Sidekick's
530
- classes: they only cover what Sidekick itself uses. Ship your own stylesheet, and keep it to your screen:
531
-
532
- - **No reset.** Build Tailwind's theme + utilities only (no preflight); Sidekick's reset is already there.
533
- - **Scoped.** Prefix every rule with a wrapper class your component renders (the example uses
534
- `.sl-mobile-admin`), and turn `:root` / `html` / `body` into that wrapper, so theme variables and
535
- rules can't touch Sidekick's UI.
536
- - **No cascade layers.** Tailwind 4 emits `@layer`; any unlayered rule on the page beats every layered
537
- one, so unwrap the layers or Sidekick's own utilities win clashes inside your screen.
538
-
539
- The example app does all three with a small PostCSS step in `vite.config.mobile-admin.ts`
540
- (`scripts/scope-css.mjs`) over `src/mobile-admin/styles.css`, and shares its theme with the rest of the
541
- app through `src/tokens.css`. Forge's preview loads the same file, so the screen looks the same there as
542
- on a phone.
543
-
544
- ### Example `vite.config.mobile-admin.ts`
545
-
546
- ```typescript
547
- import { defineConfig } from 'vite'
548
- import react from '@vitejs/plugin-react'
549
- import { resolve } from 'path'
550
-
551
- const EXTERNALS: Record<string, string> = {
552
- 'react': 'React',
553
- 'react-dom': 'ReactDOM',
554
- 'react/jsx-runtime': 'jsxRuntime',
555
- '@proveanything/smartlinks': 'SL',
556
- // Add all Radix, ReactQuery, ReactRouterDOM etc — same contract as containers
557
- }
558
-
559
- export default defineConfig({
560
- plugins: [react()],
561
- define: {
562
- __APP_VERSION__: JSON.stringify(process.env.npm_package_version),
563
- __BUILD_DATE__: JSON.stringify(new Date().toISOString()),
564
- },
565
- build: {
566
- lib: {
567
- entry: resolve(__dirname, 'src/mobile-admin/index.ts'),
568
- name: 'SmartLinksMobileAdmin',
569
- formats: ['umd', 'es'],
570
- fileName: (fmt) => `mobile-admin.${fmt === 'es' ? 'es' : 'umd'}.js`,
571
- },
572
- rollupOptions: {
573
- external: Object.keys(EXTERNALS),
574
- output: { globals: EXTERNALS },
575
- },
576
- },
577
- })
578
- ```
579
-
580
- **Key points:**
581
- - Externalise the same shared deps as `containers` (React, SL, Radix, ReactQuery, etc.) — the launcher provides them.
582
- - Capacitor plugins (Tier 2) should be **bundled in**, not externalised — the browser/PWA fallback must work even when the native plugin is absent.
583
- - Enable/disable the build with `VITE_ENABLE_MOBILE_ADMIN=true` in `.env`.
584
-
585
- ### Build command
586
-
587
- ```bash
588
- # Full pipeline
589
- vite build && \
590
- vite build --config vite.config.widget.ts && \
591
- vite build --config vite.config.container.ts && \
592
- vite build --config vite.config.mobile-admin.ts
593
-
594
- # Mobile admin only
595
- vite build --config vite.config.mobile-admin.ts
596
- ```
597
-
598
- ---
599
-
600
- ## Example: Minimal Mobile Admin Container
601
-
602
- ```typescript
603
- // src/mobile-admin/WarehousePickContainer.tsx
604
- import { useEffect, useState } from 'react'
605
- import type { AdminMobileHostContext } from '@proveanything/smartlinks'
606
-
607
- interface Props {
608
- host: AdminMobileHostContext
609
- }
610
-
611
- export function WarehousePickContainer({ host }: Props) {
612
- const [lastScan, setLastScan] = useState<string | null>(null)
613
-
614
- // Auth guard — host may already enforce this, but be explicit
615
- if (!host.user?.isAdmin) {
616
- return <p>Admin access required.</p>
617
- }
618
-
619
- async function handleScan() {
620
- try {
621
- const code = await host.actions.requestQrScan()
622
- setLastScan(code)
623
- host.ui.haptic('success')
624
- } catch (err) {
625
- host.ui.toast({ title: 'Scan failed', variant: 'destructive' })
626
- }
627
- }
628
-
629
- useEffect(() => {
630
- host.ui.setHeaderTitle('Warehouse Pick')
631
- return () => host.ui.setHeaderTitle(null)
632
- }, [])
633
-
634
- return (
635
- <div style={{ padding: 16 }}>
636
- {host.hardware.qr ? (
637
- <button onClick={handleScan}>Scan Barcode</button>
638
- ) : (
639
- <p>Camera not available on this device</p>
640
- )}
641
- {lastScan && <p>Last scan: {lastScan}</p>}
642
- </div>
643
- )
644
- }
645
- ```
646
-
647
- ```typescript
648
- // src/mobile-admin/index.ts
649
- export { WarehousePickContainer } from './WarehousePickContainer'
650
-
651
- export const MOBILE_ADMIN_MANIFEST = {
652
- name: 'WarehousePickContainer',
653
- version: __APP_VERSION__,
654
- buildDate: __BUILD_DATE__,
655
- }
656
- ```
657
-
658
- ---
659
-
660
- ## Best Practices
661
-
662
- - **Always check `host.hardware.X` before calling `host.actions.X`** — never assume a capability is available.
663
- - **Always wrap action calls in try/catch** — handle `HostPermissionDeniedError`, `HostTimeoutError`, and `HostCapabilityUnavailableError`.
664
- - **All four `host.ui` methods are optional** (`toast`, `haptic`, `setHeaderTitle`, `navigateBack`) — guard every call with `?.`. See the `host.ui` section above.
665
- - **`host.ui.setHeaderTitle` and `host.ui.navigateBack`** integrate with the host shell and have no in-container equivalent; call with `?.`.
666
- - **Use `host.events.subscribe` for lifecycle events** — `'offline'`/`'online'`/`'pause'`/`'resume'` fire consistently on every host.
667
- - **Never call `initializeApi`, never use top-level SDK imports for API calls** — `host.SL` is already configured. `SL.method()` instead of `host.SL.method()` silently uses the wrong baseURL.
668
- - **Bundle Capacitor plugins in** (do not externalise) — so the component degrades gracefully on PWA/browser without crashing.
669
- - **Declare `offline: true`** on a component if it queues writes locally — this signals the launcher to provision offline sync support.
670
- - **Use `'methodName' in host.actions`** to feature-detect new host capabilities rather than comparing `host._version`. The version is informational only.
671
-
672
- ---
673
-
674
- ## Native Capability Facade
675
-
676
- `host.native` gives containers access to a broader set of device capabilities — share sheet, clipboard, full haptics API, storage, QR, NFC, RFID (Kotlin only), auth, and cross-shell events — through a single interface that falls back gracefully across all host environments.
677
-
678
- ```typescript
679
- // Check host.hardware.* for physical availability, then call via host.native
680
- if (host.hardware.nfc && host.native?.nfc) {
681
- const { uid } = await host.native.nfc.read({ timeoutMs: 10_000 })
682
- }
683
-
684
- // Storage always available (Preferences → localStorage → in-memory Map)
685
- await host.native?.storage.set('lastScan', uid)
686
-
687
- // Share sheet with web fallback
688
- await host.native?.share.share({ title: 'Found tag', url: `https://app.example/tags/${uid}` })
689
- ```
690
-
691
- `host.native` is optional on `AdminMobileHostContext` — host stubs (Storybook, unit tests) need not implement it. `native.rfid` is additionally optional within `NativeFacade` itself, as it only exists on `custom-android`.
692
-
693
- For the full sub-facade table, fallback chains, and what's intentionally not wrapped, see **[native-facade.md](native-facade.md)**.
1
+ # Mobile Admin Container SDK
2
+
3
+ > **Version:** 1.0 · **Platform:** SmartLinks R5 · **Last updated:** 2026-09-21
4
+
5
+ This document describes how to build a **Mobile Admin Container** — a SmartLinks microapp that provides an in-the-field operator/admin surface optimised for mobile devices. These containers ship as a **separate `mobileAdmin` bundle** (not inside the `containers` bundle) so that Capacitor plugins, offline helpers, and operator-only code never reach the public consumer bundle.
6
+
7
+ > **See also:** [containers.md](containers.md) covers the public consumer container. The [Multiple Consumer Components](containers.md#multiple-consumer-components) section explains the consumer vs. admin bundle split. For the full `host.native` facade contract (share, clipboard, haptics, NFC, RFID, storage, etc.) see [native-facade.md](native-facade.md).
8
+
9
+ ---
10
+
11
+ ## Table of Contents
12
+
13
+ 1. [When to Build a Mobile Admin Container](#when-to-build-a-mobile-admin-container)
14
+ 2. [Host Environment](#host-environment)
15
+ 3. [The `host` Prop](#the-host-prop)
16
+ 4. [Hardware Capabilities & the Capability Matrix](#hardware-capabilities--the-capability-matrix)
17
+ 5. [Capacitor Plugin Baseline](#capacitor-plugin-baseline)
18
+ 6. [Manifest Declaration](#manifest-declaration)
19
+ 7. [Launcher Discovery](#launcher-discovery)
20
+ 8. [Event Stream](#event-stream)
21
+ 9. [Error Handling](#error-handling)
22
+ 10. [Lifecycle](#lifecycle)
23
+ 11. [Build & Bundle Requirements](#build--bundle-requirements)
24
+ 12. [Example: Minimal Mobile Admin Container](#example-minimal-mobile-admin-container)
25
+ 13. [Best Practices](#best-practices)
26
+ 14. [Native Capability Facade](#native-capability-facade)
27
+
28
+ ---
29
+
30
+ ## When to Build a Mobile Admin Container
31
+
32
+ Build a Mobile Admin Container when the surface is intended for **field operators or admins** rather than consumers — especially when:
33
+
34
+ - You need native hardware: NFC, RFID, camera/barcode, haptics, geolocation
35
+ - The surface must work offline or in flaky network conditions
36
+ - You want the bundle to version independently from the public consumer app
37
+
38
+ All admin-mobile containers ship in the `mobileAdmin` bundle and are never loaded by the public portal. The mobile launcher loads them via the `mobileAdmin` manifest key.
39
+
40
+ ---
41
+
42
+ ## Host Environment
43
+
44
+ The SmartLinks Mobile launcher runs on five host environments:
45
+
46
+ | Host ID | Description | Hardware bridge |
47
+ |---------|-------------|-----------------|
48
+ | `custom-android` | Original Kotlin WebView app — full RFID + NTAG-advanced | `window.SmartlinksScanner` |
49
+ | `capacitor-ios` | iOS app built via Capacitor | Capacitor plugins |
50
+ | `capacitor-android` | Generic Android Capacitor build (no RFID) | Capacitor plugins |
51
+ | `pwa` | Installed Progressive Web App | Web APIs only |
52
+ | `browser` | Regular browser tab | Web APIs only |
53
+
54
+ Your container **never** detects the host directly. It receives a `host` prop from the launcher and reads `host.hardware.*` capability flags. The launcher handles the rest.
55
+
56
+ ---
57
+
58
+ ## The `host` Prop
59
+
60
+ Every container mounted by the SmartLinks Mobile launcher receives a single `host` prop — `AdminMobileHostContext`. Do not reach for `window.SmartlinksScanner` or `window.Capacitor` directly; both are wrapped here.
61
+
62
+ > **SDK export** — `AdminMobileHostContext`, `AdminMobileCapability`, `ActionableCapability`, `AdminMobileHostId`, `AdminMobileEvent`, `AdminMobileEventCallback`, `AdminMobileEventSubscriber`, `AdminMobileComponentManifest`, `AdminMobileBundleManifest`, and `NativeFacade` (plus all sub-facade interfaces) are exported from `@proveanything/smartlinks`. Import via `import type { AdminMobileHostContext } from '@proveanything/smartlinks'` — no local mirror needed. The old names `ScannerEventSubscriber`, `MobileAdminComponentManifest` and `MobileAdminBundleManifest` were removed in SDK 3: use `AdminMobileEventCallback`, `AdminMobileComponentManifest` and `AdminMobileBundleManifest`.
63
+
64
+ ```typescript
65
+ interface AdminMobileHostContext {
66
+ // Identity
67
+ collectionId: string
68
+ appId: string
69
+ user: { uid?: string; email?: string; displayName?: string; isAdmin: boolean } | null
70
+
71
+ // SDK — already initialised. Do NOT call initializeApi again.
72
+ SL: typeof import('@proveanything/smartlinks')
73
+
74
+ // Capabilities declared by this container in its manifest
75
+ capabilities: AdminMobileCapability[]
76
+
77
+ // Live capability flags for the current device
78
+ hardware: {
79
+ nfc: boolean
80
+ rfid: boolean
81
+ qr: boolean
82
+ camera: boolean
83
+ keyboard: boolean
84
+ }
85
+
86
+ // Unified hardware event stream — callback type: AdminMobileEventCallback
87
+ events: { subscribe: (cb: AdminMobileEventCallback) => () => void }
88
+
89
+ // Promise-based hardware actions — reject with a structured error when unavailable or cancelled
90
+ actions: {
91
+ requestQrScan: (opts?: { signal?: AbortSignal; heightPercent?: number; prompt?: string }) => Promise<string>
92
+ requestNfcTap: (opts?: { timeoutMs?: number; signal?: AbortSignal; prompt?: string } | number) => Promise<{ uid: string; ndef?: string }>
93
+ requestCameraPhoto: (opts?: { signal?: AbortSignal }) => Promise<Blob>
94
+ share: (payload: { title: string; url: string; text?: string }) => Promise<void>
95
+ clipboard: {
96
+ read: () => Promise<string>
97
+ write: (text: string) => Promise<void>
98
+ }
99
+ }
100
+
101
+ // Host-provided UI helpers — all optional, see §3 note
102
+ ui: {
103
+ toast?: (opts: { title: string; description?: string; variant?: 'default' | 'destructive' }) => void
104
+ haptic?: (style?: 'light' | 'success' | 'error') => void
105
+ setHeaderTitle?: (title: string | null) => void
106
+ navigateBack?: () => void
107
+ }
108
+
109
+ // UHF RFID reader — only on hosts with one (feature-detect). See "RFID" below.
110
+ rfid?: AdminMobileRfid
111
+
112
+ // Network & device info
113
+ network: { isOnline: () => boolean }
114
+ device: { info: () => Promise<{ model: string; platform: string }> }
115
+
116
+ // Informational host version — use for logging/diagnostics, not feature detection.
117
+ // For feature detection prefer existence checks: 'requestNfcTap' in host.actions
118
+ _version: number
119
+
120
+ // Full native capability facade — share, clipboard, haptics, NFC, RFID, storage, etc.
121
+ // Optional: not every host stub populates it. See native-facade.md.
122
+ native?: NativeFacade
123
+ }
124
+ ```
125
+
126
+ ### Contract rules
127
+
128
+ 1. **Check `host.hardware.X` before calling `host.actions.X`.** Calls to unavailable capabilities reject with `HostCapabilityUnavailableError`.
129
+ 2. **Do not call `initializeApi`, and do not use top-level SDK imports for API calls.** `host.SL` is already configured with the right `baseURL`, auth, and logger. Code that does `import * as SL from "@proveanything/smartlinks"` and calls `SL.attestation.create(...)` will silently hit the wrong base URL — the top-level import is uninitialised in the launcher's runtime and produces no loud error. Always go through `host.SL`:
130
+ ```typescript
131
+ // ❌ Silent footgun — uninitialised SDK, wrong baseURL
132
+ import * as SL from '@proveanything/smartlinks'
133
+ await SL.attestation.create(...)
134
+
135
+ // ✅ Correct
136
+ await host.SL.attestation.create(...)
137
+ ```
138
+ 3. **Do not access `window.SmartlinksScanner` or `window.Capacitor` directly.** The host wraps both; direct access produces containers that only work on one shell.
139
+ 4. **Externalise all shared deps** (React, ReactDOM, SL, Radix, etc.) — the launcher provides them as globals. See [Build & Bundle Requirements](#build--bundle-requirements).
140
+
141
+ ```typescript
142
+ // Example — always check hardware flags first
143
+ const { host } = props
144
+
145
+ if (host.hardware.nfc) {
146
+ host.ui.setHeaderTitle('Scan NFC tag')
147
+ const { uid } = await host.actions.requestNfcTap(5000)
148
+ // ...
149
+ }
150
+ ```
151
+
152
+ ### `host.ui` — native helpers vs. your own components
153
+
154
+ All four `host.ui` methods are **optional by design**. A container may run in the Sidekick mobile shell, a standalone PWA or browser tab, Storybook, or a screenshot harness — none of those environments is guaranteed to have a native toast system, a managed header, or a back stack. Forcing every host implementer to provide them would exclude the web and desktop use-cases the rest of the contract explicitly supports. Always guard with `?.`:
155
+
156
+ - `host.ui.toast?.({...})` / `host.ui.haptic?.('success')` — optional native feedback. Fall back to your own `<Toaster />` when absent.
157
+ - `host.ui.setHeaderTitle?.('Scanning…')` / `host.ui.navigateBack?.()` — host-shell integrations with no in-container equivalent. Silently no-op when the host doesn't implement them.
158
+
159
+ **Stub pattern for testing and Storybook:**
160
+
161
+ ```typescript
162
+ const stubHost: Partial<AdminMobileHostContext> = {
163
+ hardware: { nfc: false, rfid: false, qr: true, camera: true, keyboard: false },
164
+ actions: {
165
+ requestQrScan: async () => 'STUB_QR_CODE',
166
+ requestNfcTap: async () => ({ uid: 'STUB_UID' }),
167
+ requestCameraPhoto: async () => new Blob(),
168
+ share: async () => {},
169
+ clipboard: { read: async () => '', write: async () => {} },
170
+ },
171
+ ui: {
172
+ toast: (opts) => console.log('[stub toast]', opts.title),
173
+ haptic: () => {},
174
+ setHeaderTitle: (t) => { if (t) document.title = t },
175
+ navigateBack: () => history.back(),
176
+ },
177
+ network: { isOnline: () => true },
178
+ user: { isAdmin: true, displayName: 'Test User', email: 'test@example.com' },
179
+ SL: undefined as any, // replace with your test SL instance
180
+ }
181
+ ```
182
+
183
+ ---
184
+
185
+ ## Hardware Capabilities & the Capability Matrix
186
+
187
+ Containers declare which capabilities they need (or can use) in the manifest `capabilities` array. The launcher uses this list to:
188
+
189
+ 1. **Filter availability** — hide containers whose required hardware is not on this device
190
+ 2. **Pre-warm** — start the right reader as soon as the container mounts
191
+ 3. **Permission prompts** — request only the permissions the container actually needs
192
+
193
+ | Capability | Description |
194
+ |------------|-------------|
195
+ | `"nfc"` | NFC tap — UID + NDEF read |
196
+ | `"nfc-advanced"` | NTAG 21x mirror config, NTAG 424 SUN, key rotation (`custom-android` only) |
197
+ | `"rfid"` | UHF RFID mass scan (`custom-android` only) |
198
+ | `"qr"` | QR / barcode scanning (camera-based) |
199
+ | `"camera"` | Photo capture, gallery picker |
200
+ | `"keyboard"` | Physical hardware trigger/action buttons |
201
+ | `"geolocation"` | GPS coordinates |
202
+ | `"push"` | Remote push notifications (FCM/APNs) |
203
+
204
+ The full hardware capability matrix by host:
205
+
206
+ | Capability | custom-android | capacitor-ios | capacitor-android | pwa | browser |
207
+ |------------|:-:|:-:|:-:|:-:|:-:|
208
+ | NFC tap (UID + NDEF read) | ✅ | ✅ | ✅ | ⚠️ Chrome Android | ⚠️ |
209
+ | NFC NDEF write | ✅ | ❌ | ✅ | ⚠️ | ⚠️ |
210
+ | NFC advanced (NTAG 21x / 424) | ✅ | ❌ | ❌ | ❌ | ❌ |
211
+ | RFID mass scan | ✅ | ❌ | ❌ | ❌ | ❌ |
212
+ | QR / barcode scan | ✅ | ✅ | ✅ | ✅ | ✅ |
213
+ | Camera photo | ✅ | ✅ | ✅ | ✅ | ✅ |
214
+ | Hardware key events | ✅ | ❌ | ❌ | ❌ | ❌ |
215
+ | Haptics | ✅ | ✅ | ✅ | ⚠️ visual only | ⚠️ |
216
+
217
+ > Containers that declare `"rfid"` or `"nfc-advanced"` are only offered on `custom-android`. All others are assumed to run on all five hosts — design for the lowest common denominator and use `host.hardware.*` flags to unlock richer UI on capable devices.
218
+
219
+ ---
220
+
221
+ ## Capacitor Plugin Baseline
222
+
223
+ The custom Kotlin shell and both Capacitor shells ship the same baseline plugin set. Container authors can rely on all Tier 1 plugins on every native host.
224
+
225
+ ### Tier 1 — always available on every native host
226
+
227
+ | Plugin | Surfaced via |
228
+ |--------|-------------|
229
+ | `@capacitor/haptics` | `host.ui.haptic()` |
230
+ | `@capacitor/network` | `host.network.isOnline()` |
231
+ | `@capacitor/device` | `host.device.info()` |
232
+ | `@capacitor/share` | `host.actions.share()` |
233
+ | `@capacitor/clipboard` | `host.actions.clipboard.*` |
234
+ | `@capacitor/preferences` | `host.storage.*` *(planned — see note below)* |
235
+ | `@capacitor/app` | host-managed (back button, deep links) |
236
+ | `@capacitor/status-bar` | host-managed |
237
+ | `@capacitor/keyboard` | host-managed |
238
+ | `@capacitor/toast` | wired into `host.ui.toast()` |
239
+
240
+ > **`host.storage` — planned shape.** Once released, the surface will wrap `@capacitor/preferences` directly:
241
+ > ```ts
242
+ > host.storage: {
243
+ > get(key: string): Promise<string | null>
244
+ > set(key: string, value: string): Promise<void>
245
+ > remove(key: string): Promise<void>
246
+ > keys(): Promise<string[]>
247
+ > }
248
+ > ```
249
+ > Until then: `localStorage` works on web hosts; use `@capacitor/preferences` directly (bundle it in) on native.
250
+
251
+ ### Tier 2 — capability-gated (declare in manifest)
252
+
253
+ | Plugin | Capability flag |
254
+ |--------|----------------|
255
+ | `@capacitor/camera` | `"camera"` |
256
+ | `@capacitor-mlkit/barcode-scanning` | `"qr"` |
257
+ | `@capgo/capacitor-nfc` | `"nfc"` |
258
+ | `@capacitor/geolocation` | `"geolocation"` |
259
+ | `@capacitor/push-notifications` | `"push"` |
260
+ | `@capacitor/filesystem` | *(used when `offline: true`; bundle it in)* |
261
+
262
+ ### Tier 3 — custom-android only (not Capacitor)
263
+
264
+ Proprietary hardware SDKs (UHF RFID, NTAG 21x/424 advanced programming, USB uFR reader feedback). These are wrapped behind `host.actions.*` — never access `window.SmartlinksScanner` directly.
265
+
266
+ ---
267
+
268
+ ## Manifest Declaration
269
+
270
+ Declare the bundle under the top-level `mobileAdmin` key in `app.manifest.json`. This is separate from `containers` — the mobile launcher reads `mobileAdmin`; the public portal never loads it.
271
+
272
+ ```json
273
+ {
274
+ "meta": { "appId": "my-app", "name": "My App", "version": "1.0.0" },
275
+
276
+ "containers": {
277
+ "files": { "js": { "umd": "dist/containers.umd.js", "esm": "dist/containers.esm.js" }, "css": "dist/containers.css" },
278
+ "components": [
279
+ { "name": "PublicContainer", "description": "Default consumer experience" }
280
+ ]
281
+ },
282
+
283
+ "mobileAdmin": {
284
+ "files": {
285
+ "js": {
286
+ "umd": "dist/mobile-admin.umd.js",
287
+ "esm": "dist/mobile-admin.esm.js"
288
+ },
289
+ "css": null
290
+ },
291
+ "components": [
292
+ {
293
+ "name": "WarehousePickContainer",
294
+ "description": "Pick orders by scanning NFC tags",
295
+ "capabilities": ["nfc", "qr"],
296
+ "offline": true
297
+ }
298
+ ]
299
+ }
300
+ }
301
+ ```
302
+
303
+ A `mobileAdmin` bundle can export multiple components targeting different operator workflows — each with its own `capabilities` declaration.
304
+
305
+ **Component fields:**
306
+
307
+ | Field | Type | Description |
308
+ |-------|------|-------------|
309
+ | `name` | string | Exported component name (must match the UMD bundle export) |
310
+ | `description` | string | Shown in the mobile launcher's app picker |
311
+ | `capabilities` | string[] | Hardware capabilities this component needs or can use. See table above. |
312
+ | `offline` | boolean | Set to `true` if this component queues writes locally and needs offline sync support. |
313
+
314
+ ---
315
+
316
+ ## Launcher Discovery
317
+
318
+ The SmartLinks Mobile launcher loads your `mobileAdmin` bundle through the platform's app registry — you do not reference the manifest URL directly.
319
+
320
+ **How it works:**
321
+
322
+ 1. A collection admin enables the app for a collection in the SmartLinks admin console.
323
+ 2. On startup (and periodically), the launcher fetches `app.manifest.json` for every enabled app in that collection via the SmartLinks platform API. These requests are authenticated with the launcher's operator session.
324
+ 3. The launcher reads `mobileAdmin.components[]`, evaluates each component's `capabilities` against the current device's hardware flags, and shows matching components in the app picker.
325
+ 4. When the operator opens a component, the launcher resolves `mobileAdmin.files.js.umd` against the app's CDN base, fetches the bundle, and mounts the component with its `host` prop.
326
+
327
+ **File URL resolution:** `files.js.umd` / `files.js.esm` are paths relative to your app's CDN root (set when the app version is published). Provide relative paths — the launcher resolves them; do not hardcode absolute URLs.
328
+
329
+ **Auth:** Manifest and bundle fetches use the launcher's session token. Your container is already authenticated via `host.user` and `host.SL` — do not add additional auth headers.
330
+
331
+ **On load failure:** If the bundle returns a non-2xx response, the launcher shows a user-visible error and logs it — it does not crash the full launcher. If `app.manifest.json` itself cannot be fetched, the app is silently excluded from the picker for that session.
332
+
333
+ > To debug a missing or stale manifest, confirm in the SmartLinks admin console that the app version is published and that the `mobileAdmin` key is present in the uploaded manifest.
334
+
335
+ ---
336
+
337
+ ## Scanning: listening vs asking
338
+
339
+ Every scan reaches a container in one of two ways. Pick per screen.
340
+
341
+ | | Listening — `host.events` | Asking — `host.actions.request*` |
342
+ |---|---|---|
343
+ | Use for | "Tap or scan anything, any time" — a stock take, a scan-to-open list | "This step needs a scan" — tag this item, scan the shelf code |
344
+ | What the user sees | Nothing changes | NFC: a small non-blocking hint with Cancel. QR / photo: the host's camera opens |
345
+ | What you get | An event per tap / read / key | A promise for one result |
346
+
347
+ ### NFC: two modes
348
+
349
+ - **Listening** — subscribe to `nfc-tap`. Fires for every tap while no request is waiting.
350
+ - **Asking** — `await host.actions.requestNfcTap({ prompt: 'Tap the bottle tag', signal })`. The next tap
351
+ **made after the call** resolves it, and that tap is **not** also sent as an `nfc-tap` event, so
352
+ nothing handles it twice. The request is non-blocking: the screen stays usable while it waits — show
353
+ your own "or type the code" path and abort the wait with `signal` if the user takes it. One request at
354
+ a time: a new call cancels the previous one.
355
+
356
+ ```typescript
357
+ const controller = new AbortController()
358
+ try {
359
+ const { uid } = await host.actions.requestNfcTap({ prompt: 'Tap the bottle tag', signal: controller.signal })
360
+ await attachTag(uid)
361
+ } catch (err) {
362
+ if (err instanceof HostCancelledError) return // they pressed Cancel, or we aborted
363
+ throw err
364
+ }
365
+ // elsewhere — the user typed the code instead:
366
+ controller.abort()
367
+ ```
368
+
369
+ ### QR and photos
370
+
371
+ `requestQrScan()` opens the host's camera scanner (full screen, or the bottom `heightPercent` of it) and
372
+ resolves with the code; `requestCameraPhoto()` opens the camera and resolves with the image. Both reject
373
+ with `HostCancelledError` when the user backs out.
374
+
375
+ ### RFID
376
+
377
+ `host.rfid` gives a container the same reader abilities the host's own scanner uses — so an app can be
378
+ its own scanner. It's present only when the device has a UHF reader (`hardware.rfid`); check for it.
379
+ There's one reader, so starting any of the three below ends the one before, and everything stops when
380
+ the container unmounts.
381
+
382
+ **Keep reading** — a stock take, an intake. De-duplicated and batched, so you get each tag once instead
383
+ of hundreds of raw reads a second:
384
+
385
+ ```typescript
386
+ const session = host.rfid?.read({
387
+ filter: { prefix: '3034' }, // optional: only EPCs starting with this (or { epcs: [...] })
388
+ dedupe: 'session', // default — each tag once; { windowMs: 5000 } or 'none' for every read
389
+ batchMs: 250, // default — reads arrive in batches; 0 = one at a time
390
+ mode: 'trigger', // default — reads while the operator holds the trigger; 'continuous' = now until stop()
391
+ })
392
+ const off = session?.onRead((reads) => { // [{ epc, tid?, rssi?, timestamp, count }]
393
+ for (const r of reads) addToCount(r.epc)
394
+ })
395
+ // later
396
+ session?.stop()
397
+ ```
398
+
399
+ **One tag for this step** — tag an item. Resolves with the strongest tag read in the first moment of
400
+ reading, then stops; the RFID counterpart of `requestNfcTap` (non-blocking, abortable, `prompt` hint):
401
+
402
+ ```typescript
403
+ const { epc } = await host.rfid.readOne({ prompt: 'Pull the trigger over the item', signal })
404
+ ```
405
+
406
+ **Find a tag** — a Geiger counter. `strength` runs 0 (not in range) to 100 (right here); by default the
407
+ host plays faster beeps and haptics as you close in (`feedback: false` to do your own):
408
+
409
+ ```typescript
410
+ const hunt = host.rfid?.locate(item.epcs) // one EPC, or every tag on the item
411
+ hunt?.onUpdate(({ strength, rssi, hitsPerSecond }) => setStrength(strength))
412
+ // hunt.stop() when found
413
+ ```
414
+
415
+ `status()` / `onStatus(cb)` report whether a reader is available and connected, which one (`built-in`,
416
+ `zebra`, `tsl`), whether it's reading, and its power range; `read`/`locate` take a `power` level for the
417
+ session.
418
+
419
+ Raw reads still arrive as `rfid-burst` events whenever the reader runs, for containers that want them.
420
+
421
+ ---
422
+
423
+ ## Event Stream
424
+
425
+ For raw scan events (rather than the action-driven `host.actions.requestNfcTap`), subscribe to the unified event stream. Events flow identically on every host — the launcher normalises bridge messages, Capacitor callbacks, and Web API events into the same shape.
426
+
427
+ ```typescript
428
+ useEffect(() => {
429
+ const unsubscribe = host.events.subscribe((event) => {
430
+ switch (event.type) {
431
+ case 'nfc-tap': handleNfc(event.uid, event.ndef); break
432
+ case 'rfid-burst': handleEpcs(event.epcs); break
433
+ case 'qr-scan': handleQr(event.code); break
434
+ case 'key-press': if (event.keyCode === 293) startScan(); break
435
+ case 'lifecycle': handleLifecycle(event.phase); break
436
+ }
437
+ })
438
+ return unsubscribe
439
+ }, [host.events])
440
+ ```
441
+
442
+ Event details:
443
+
444
+ - Every event may carry `timestamp` (ms since epoch).
445
+ - `nfc-tap` — `uid` is uppercase hex without separators (`04A1B2C3D4E5F6`); `ndef` is the tag's NDEF text (usually its URL), `""` when it had none.
446
+ - `rfid-burst` — reads arrive as they happen, typically **one EPC per event, many per second** while the trigger is held. Collect and de-duplicate them yourself. `rssi` (dBm; closer = higher) when the reader reports it.
447
+ - `key-press` — hosts that report both edges send `action: 'down'` then `'up'` for one press; act on `'down'` (or on events without `action`). `293` is the scan trigger.
448
+
449
+ Lifecycle events (`event.type === 'lifecycle'`) carry a `phase` field: `'pause' | 'resume' | 'offline' | 'online'`. Use these instead of `window` event listeners so your container works identically on all hosts.
450
+
451
+ ---
452
+
453
+ ## Error Handling
454
+
455
+ Action methods reject with structured errors — wrap every `host.actions.*` call even on hosts where the capability "should" be available (the user can deny permission at runtime):
456
+
457
+ ```typescript
458
+ class HostCapabilityUnavailableError extends Error {
459
+ capability: 'nfc' | 'rfid' | 'qr' | 'camera'
460
+ host: string // host ID
461
+ }
462
+
463
+ class HostPermissionDeniedError extends Error {
464
+ capability: 'nfc' | 'rfid' | 'qr' | 'camera'
465
+ }
466
+
467
+ class HostTimeoutError extends Error {
468
+ capability: 'nfc' | 'qr'
469
+ timeoutMs: number
470
+ }
471
+
472
+ class HostCancelledError extends Error {
473
+ capability: 'nfc' | 'qr' | 'camera'
474
+ by: 'user' | 'app' // closed the scanner / pressed Cancel, or aborted by the container
475
+ }
476
+ ```
477
+
478
+ All four are exported from `@proveanything/smartlinks`; check with `instanceof` or `err.name`.
479
+
480
+ ```typescript
481
+ try {
482
+ const code = await host.actions.requestQrScan()
483
+ host.ui.haptic('success')
484
+ } catch (err) {
485
+ if (err instanceof HostPermissionDeniedError) {
486
+ host.ui.toast({ title: 'Camera access required', variant: 'destructive' })
487
+ } else if (err instanceof HostTimeoutError) {
488
+ host.ui.toast({ title: 'No QR code detected' })
489
+ } else {
490
+ throw err
491
+ }
492
+ }
493
+ ```
494
+
495
+ ---
496
+
497
+ ## Lifecycle
498
+
499
+ | Event | When | What to do |
500
+ |-------|------|------------|
501
+ | mount | User opens your container | Subscribe to events, start readers |
502
+ | unmount | User backs out / app backgrounded > 30s | Unsubscribe; persist in-flight state |
503
+ | `lifecycle: 'offline'` | Network lost | Switch to offline mode; queue writes locally |
504
+ | `lifecycle: 'online'` | Network restored | Flush queued writes |
505
+ | `lifecycle: 'pause'` | App backgrounded | Pause readers to save battery |
506
+ | `lifecycle: 'resume'` | App foregrounded | Resubscribe; refresh stale data |
507
+
508
+ Use `host.events.subscribe` for all lifecycle events — all five host types (`custom-android`, `capacitor-ios`, `capacitor-android`, `pwa`, `browser`) are guaranteed to emit every `'pause'`/`'resume'`/`'offline'`/`'online'` phase. No `window.addEventListener('online')` fallback is needed.
509
+
510
+ > **Planned** — `phase: 'mount' | 'unmount'` events are on the roadmap. These will fire when the container becomes visible / is removed from the host view stack, enabling deferred reader start-up without a `useEffect` dependency.
511
+
512
+ ---
513
+
514
+ ## Build & Bundle Requirements
515
+
516
+ The mobile admin bundle has its own Vite config: `vite.config.mobile-admin.ts`.
517
+
518
+ ### Build output
519
+
520
+ ```
521
+ dist/mobile-admin.umd.js
522
+ dist/mobile-admin.esm.js
523
+ dist/mobile-admin.css the screen's own scoped stylesheet — declare it as mobileAdmin.files.css
524
+ ```
525
+
526
+ ### Styling
527
+
528
+ The component renders **inside Sidekick's page**, not an iframe. Sidekick already has a CSS reset and
529
+ its own styles, and loads your `mobileAdmin.files.css` alongside the bundle. Don't rely on Sidekick's
530
+ classes: they only cover what Sidekick itself uses. Ship your own stylesheet, and keep it to your screen:
531
+
532
+ - **No reset.** Build Tailwind's theme + utilities only (no preflight); Sidekick's reset is already there.
533
+ - **Scoped.** Prefix every rule with a wrapper class your component renders (the example uses
534
+ `.sl-mobile-admin`), and turn `:root` / `html` / `body` into that wrapper, so theme variables and
535
+ rules can't touch Sidekick's UI.
536
+ - **No cascade layers.** Tailwind 4 emits `@layer`; any unlayered rule on the page beats every layered
537
+ one, so unwrap the layers or Sidekick's own utilities win clashes inside your screen.
538
+
539
+ The example app does all three with a small PostCSS step in `vite.config.mobile-admin.ts`
540
+ (`scripts/scope-css.mjs`) over `src/mobile-admin/styles.css`, and shares its theme with the rest of the
541
+ app through `src/tokens.css`. Forge's preview loads the same file, so the screen looks the same there as
542
+ on a phone.
543
+
544
+ ### Example `vite.config.mobile-admin.ts`
545
+
546
+ ```typescript
547
+ import { defineConfig } from 'vite'
548
+ import react from '@vitejs/plugin-react'
549
+ import { resolve } from 'path'
550
+
551
+ const EXTERNALS: Record<string, string> = {
552
+ 'react': 'React',
553
+ 'react-dom': 'ReactDOM',
554
+ 'react/jsx-runtime': 'jsxRuntime',
555
+ '@proveanything/smartlinks': 'SL',
556
+ // Add all Radix, ReactQuery, ReactRouterDOM etc — same contract as containers
557
+ }
558
+
559
+ export default defineConfig({
560
+ plugins: [react()],
561
+ define: {
562
+ __APP_VERSION__: JSON.stringify(process.env.npm_package_version),
563
+ __BUILD_DATE__: JSON.stringify(new Date().toISOString()),
564
+ },
565
+ build: {
566
+ lib: {
567
+ entry: resolve(__dirname, 'src/mobile-admin/index.ts'),
568
+ name: 'SmartLinksMobileAdmin',
569
+ formats: ['umd', 'es'],
570
+ fileName: (fmt) => `mobile-admin.${fmt === 'es' ? 'es' : 'umd'}.js`,
571
+ },
572
+ rollupOptions: {
573
+ external: Object.keys(EXTERNALS),
574
+ output: { globals: EXTERNALS },
575
+ },
576
+ },
577
+ })
578
+ ```
579
+
580
+ **Key points:**
581
+ - Externalise the same shared deps as `containers` (React, SL, Radix, ReactQuery, etc.) — the launcher provides them.
582
+ - Capacitor plugins (Tier 2) should be **bundled in**, not externalised — the browser/PWA fallback must work even when the native plugin is absent.
583
+ - Enable/disable the build with `VITE_ENABLE_MOBILE_ADMIN=true` in `.env`.
584
+
585
+ ### Build command
586
+
587
+ ```bash
588
+ # Full pipeline
589
+ vite build && \
590
+ vite build --config vite.config.widget.ts && \
591
+ vite build --config vite.config.container.ts && \
592
+ vite build --config vite.config.mobile-admin.ts
593
+
594
+ # Mobile admin only
595
+ vite build --config vite.config.mobile-admin.ts
596
+ ```
597
+
598
+ ---
599
+
600
+ ## Example: Minimal Mobile Admin Container
601
+
602
+ ```typescript
603
+ // src/mobile-admin/WarehousePickContainer.tsx
604
+ import { useEffect, useState } from 'react'
605
+ import type { AdminMobileHostContext } from '@proveanything/smartlinks'
606
+
607
+ interface Props {
608
+ host: AdminMobileHostContext
609
+ }
610
+
611
+ export function WarehousePickContainer({ host }: Props) {
612
+ const [lastScan, setLastScan] = useState<string | null>(null)
613
+
614
+ // Auth guard — host may already enforce this, but be explicit
615
+ if (!host.user?.isAdmin) {
616
+ return <p>Admin access required.</p>
617
+ }
618
+
619
+ async function handleScan() {
620
+ try {
621
+ const code = await host.actions.requestQrScan()
622
+ setLastScan(code)
623
+ host.ui.haptic('success')
624
+ } catch (err) {
625
+ host.ui.toast({ title: 'Scan failed', variant: 'destructive' })
626
+ }
627
+ }
628
+
629
+ useEffect(() => {
630
+ host.ui.setHeaderTitle('Warehouse Pick')
631
+ return () => host.ui.setHeaderTitle(null)
632
+ }, [])
633
+
634
+ return (
635
+ <div style={{ padding: 16 }}>
636
+ {host.hardware.qr ? (
637
+ <button onClick={handleScan}>Scan Barcode</button>
638
+ ) : (
639
+ <p>Camera not available on this device</p>
640
+ )}
641
+ {lastScan && <p>Last scan: {lastScan}</p>}
642
+ </div>
643
+ )
644
+ }
645
+ ```
646
+
647
+ ```typescript
648
+ // src/mobile-admin/index.ts
649
+ export { WarehousePickContainer } from './WarehousePickContainer'
650
+
651
+ export const MOBILE_ADMIN_MANIFEST = {
652
+ name: 'WarehousePickContainer',
653
+ version: __APP_VERSION__,
654
+ buildDate: __BUILD_DATE__,
655
+ }
656
+ ```
657
+
658
+ ---
659
+
660
+ ## Best Practices
661
+
662
+ - **Always check `host.hardware.X` before calling `host.actions.X`** — never assume a capability is available.
663
+ - **Always wrap action calls in try/catch** — handle `HostPermissionDeniedError`, `HostTimeoutError`, and `HostCapabilityUnavailableError`.
664
+ - **All four `host.ui` methods are optional** (`toast`, `haptic`, `setHeaderTitle`, `navigateBack`) — guard every call with `?.`. See the `host.ui` section above.
665
+ - **`host.ui.setHeaderTitle` and `host.ui.navigateBack`** integrate with the host shell and have no in-container equivalent; call with `?.`.
666
+ - **Use `host.events.subscribe` for lifecycle events** — `'offline'`/`'online'`/`'pause'`/`'resume'` fire consistently on every host.
667
+ - **Never call `initializeApi`, never use top-level SDK imports for API calls** — `host.SL` is already configured. `SL.method()` instead of `host.SL.method()` silently uses the wrong baseURL.
668
+ - **Bundle Capacitor plugins in** (do not externalise) — so the component degrades gracefully on PWA/browser without crashing.
669
+ - **Declare `offline: true`** on a component if it queues writes locally — this signals the launcher to provision offline sync support.
670
+ - **Use `'methodName' in host.actions`** to feature-detect new host capabilities rather than comparing `host._version`. The version is informational only.
671
+
672
+ ---
673
+
674
+ ## Native Capability Facade
675
+
676
+ `host.native` gives containers access to a broader set of device capabilities — share sheet, clipboard, full haptics API, storage, QR, NFC, RFID (Kotlin only), auth, and cross-shell events — through a single interface that falls back gracefully across all host environments.
677
+
678
+ ```typescript
679
+ // Check host.hardware.* for physical availability, then call via host.native
680
+ if (host.hardware.nfc && host.native?.nfc) {
681
+ const { uid } = await host.native.nfc.read({ timeoutMs: 10_000 })
682
+ }
683
+
684
+ // Storage always available (Preferences → localStorage → in-memory Map)
685
+ await host.native?.storage.set('lastScan', uid)
686
+
687
+ // Share sheet with web fallback
688
+ await host.native?.share.share({ title: 'Found tag', url: `https://app.example/tags/${uid}` })
689
+ ```
690
+
691
+ `host.native` is optional on `AdminMobileHostContext` — host stubs (Storybook, unit tests) need not implement it. `native.rfid` is additionally optional within `NativeFacade` itself, as it only exists on `custom-android`.
692
+
693
+ For the full sub-facade table, fallback chains, and what's intentionally not wrapped, see **[native-facade.md](native-facade.md)**.