@mdbase-dev/sdk 0.1.0-beta.187 → 0.1.0-beta.189

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 (155) hide show
  1. package/README.md +188 -953
  2. package/dist/app-grant/client.js +7 -3
  3. package/dist/app-grant/client.js.map +1 -1
  4. package/dist/app-grant/setup.js +2 -2
  5. package/dist/app-grant/setup.js.map +1 -1
  6. package/dist/app-host/cloud-copy-host.js +1 -1
  7. package/dist/app-host/cloud-copy-host.js.map +1 -1
  8. package/dist/app-host/collection-readiness.js +10 -12
  9. package/dist/app-host/collection-readiness.js.map +1 -1
  10. package/dist/app-host/handover.js +1 -1
  11. package/dist/app-host/handover.js.map +1 -1
  12. package/dist/app-host/initial-sync.js +4 -4
  13. package/dist/app-host/initial-sync.js.map +1 -1
  14. package/dist/application/browser-capabilities.d.ts +1 -1
  15. package/dist/application/browser-capabilities.js +3 -2
  16. package/dist/application/browser-capabilities.js.map +1 -1
  17. package/dist/application/configuration.js +12 -12
  18. package/dist/application/configuration.js.map +1 -1
  19. package/dist/application/entry.d.ts +51 -107
  20. package/dist/application/entry.js +139 -86
  21. package/dist/application/entry.js.map +1 -1
  22. package/dist/application/front-door.d.ts +30 -12
  23. package/dist/application/front-door.js +2 -89
  24. package/dist/application/front-door.js.map +1 -1
  25. package/dist/application/phase.d.ts +4 -1
  26. package/dist/application/phase.js +5 -4
  27. package/dist/application/phase.js.map +1 -1
  28. package/dist/application/private-collections.js +2 -1
  29. package/dist/application/private-collections.js.map +1 -1
  30. package/dist/application/registration-refusal.d.ts +1 -1
  31. package/dist/application/registration-refusal.js +1 -3
  32. package/dist/application/registration-refusal.js.map +1 -1
  33. package/dist/application/registration.js +1 -4
  34. package/dist/application/registration.js.map +1 -1
  35. package/dist/application/setup.d.ts +6 -9
  36. package/dist/application/setup.js +16 -0
  37. package/dist/application/setup.js.map +1 -1
  38. package/dist/application/tabs.d.ts +15 -2
  39. package/dist/application/tabs.js +35 -13
  40. package/dist/application/tabs.js.map +1 -1
  41. package/dist/application/unsynced-transfer.d.ts +1 -1
  42. package/dist/application/unsynced-transfer.js +3 -3
  43. package/dist/application/unsynced-transfer.js.map +1 -1
  44. package/dist/application/worker.js +928 -449
  45. package/dist/browser/mdbase-sdk.js +21271 -20750
  46. package/dist/browser/mdbase-sdk.min.js +65 -65
  47. package/dist/browser.d.ts +1 -0
  48. package/dist/browser.js +1 -0
  49. package/dist/browser.js.map +1 -1
  50. package/dist/client.d.ts +173 -84
  51. package/dist/client.js +236 -178
  52. package/dist/client.js.map +1 -1
  53. package/dist/codec.d.ts +15 -0
  54. package/dist/codec.js +44 -2
  55. package/dist/codec.js.map +1 -1
  56. package/dist/collection-api.d.ts +44 -0
  57. package/dist/collection-api.js +24 -0
  58. package/dist/collection-api.js.map +1 -0
  59. package/dist/collection-availability.js +1 -1
  60. package/dist/collection-availability.js.map +1 -1
  61. package/dist/contract-query.d.ts +22 -3
  62. package/dist/contract-query.js.map +1 -1
  63. package/dist/contract-records.d.ts +2 -1
  64. package/dist/contract-records.js.map +1 -1
  65. package/dist/describe-error.d.ts +1 -1
  66. package/dist/describe-error.js +7 -6
  67. package/dist/describe-error.js.map +1 -1
  68. package/dist/errors.d.ts +3 -5
  69. package/dist/errors.js +3 -8
  70. package/dist/errors.js.map +1 -1
  71. package/dist/files.d.ts +7 -5
  72. package/dist/files.js +16 -17
  73. package/dist/files.js.map +1 -1
  74. package/dist/holds.d.ts +2 -1
  75. package/dist/holds.js.map +1 -1
  76. package/dist/index.d.ts +7 -11
  77. package/dist/index.js +5 -7
  78. package/dist/index.js.map +1 -1
  79. package/dist/live.d.ts +2 -1
  80. package/dist/live.js.map +1 -1
  81. package/dist/manifest.d.ts +1 -1
  82. package/dist/manifest.js +1 -1
  83. package/dist/native/provenance.json +1 -1
  84. package/dist/people.js +3 -7
  85. package/dist/people.js.map +1 -1
  86. package/dist/plain.d.ts +102 -0
  87. package/dist/plain.js +62 -0
  88. package/dist/plain.js.map +1 -0
  89. package/dist/presence.d.ts +2 -1
  90. package/dist/presence.js +3 -3
  91. package/dist/presence.js.map +1 -1
  92. package/dist/read-helpers.d.ts +8 -6
  93. package/dist/read-helpers.js +20 -13
  94. package/dist/read-helpers.js.map +1 -1
  95. package/dist/record-set.d.ts +98 -0
  96. package/dist/record-set.js +347 -0
  97. package/dist/record-set.js.map +1 -0
  98. package/dist/records/session.d.ts +2 -1
  99. package/dist/records/session.js +22 -20
  100. package/dist/records/session.js.map +1 -1
  101. package/dist/records/types.d.ts +5 -3
  102. package/dist/records/witness.d.ts +7 -4
  103. package/dist/records/witness.js +13 -8
  104. package/dist/records/witness.js.map +1 -1
  105. package/dist/records.js +5 -2
  106. package/dist/records.js.map +1 -1
  107. package/dist/saved-views.d.ts +12 -4
  108. package/dist/saved-views.js +51 -43
  109. package/dist/saved-views.js.map +1 -1
  110. package/dist/settle.d.ts +62 -0
  111. package/dist/settle.js +119 -0
  112. package/dist/settle.js.map +1 -0
  113. package/dist/status.d.ts +84 -28
  114. package/dist/status.js +54 -48
  115. package/dist/status.js.map +1 -1
  116. package/dist/testing/application.d.ts +16 -9
  117. package/dist/testing/application.js +49 -45
  118. package/dist/testing/application.js.map +1 -1
  119. package/dist/testing/index.d.ts +2 -2
  120. package/dist/testing/memory-contracts.d.ts +5 -0
  121. package/dist/testing/memory-contracts.js.map +1 -1
  122. package/dist/testing/memory-replica.d.ts +60 -5
  123. package/dist/testing/memory-replica.js +127 -20
  124. package/dist/testing/memory-replica.js.map +1 -1
  125. package/dist/testing/test-app.d.ts +9 -10
  126. package/dist/testing/test-app.js +8 -17
  127. package/dist/testing/test-app.js.map +1 -1
  128. package/dist/thin-client.d.ts +15 -38
  129. package/dist/thin-client.js +11 -20
  130. package/dist/thin-client.js.map +1 -1
  131. package/dist/transport/control-route.js +1 -1
  132. package/dist/transport/control-route.js.map +1 -1
  133. package/dist/transport/relay-close.d.ts +0 -1
  134. package/dist/transport/relay-close.js +4 -2
  135. package/dist/transport/relay-close.js.map +1 -1
  136. package/dist/transport/relay-pipe.js +2 -2
  137. package/dist/transport/relay-pipe.js.map +1 -1
  138. package/dist/type-packs.js +4 -4
  139. package/dist/type-packs.js.map +1 -1
  140. package/dist/validation.d.ts +1 -1
  141. package/dist/validation.js +2 -2
  142. package/dist/validation.js.map +1 -1
  143. package/dist/values.d.ts +4 -20
  144. package/dist/values.js +3 -49
  145. package/dist/values.js.map +1 -1
  146. package/dist/view-sources.d.ts +2 -1
  147. package/dist/view-sources.js +1 -1
  148. package/dist/view-sources.js.map +1 -1
  149. package/dist/wire.d.ts +7 -3
  150. package/dist/wire.js +4 -4
  151. package/dist/wire.js.map +1 -1
  152. package/dist/write-ledger.d.ts +2 -1
  153. package/dist/write-ledger.js +3 -6
  154. package/dist/write-ledger.js.map +1 -1
  155. package/package.json +1 -1
package/README.md CHANGED
@@ -1,1013 +1,248 @@
1
1
  # @mdbase-dev/sdk
2
2
 
3
- `@mdbase-dev/sdk` on npmjs contains production trust only. Staging/LAB use
4
- separately attested, version-pinned GitHub prerelease assets, not npm packages
5
- published to a registry. Publication uses the exact production-verified release
6
- tag and version; see
7
- [`docs/sdk-publication.md`](../../../docs/sdk-publication.md).
8
-
9
- The TS SDK for mdbase-next replicas. It implements the client side of
10
- `docs/contracts/replica-client-api.md` and is what web apps, Obsidian plugins and
11
- scripts use instead of today's `@mdbase-dev/connect`.
12
-
13
- The SDK implements transport, session and typed client-API boundaries.
14
-
15
- ## Layout
16
-
17
- | Path | What |
18
- |---|---|
19
- | `src/index.ts` (`@mdbase-dev/sdk`) | The full entry: everything in the thin client, plus `MdbaseConnect` (which validates the app's declaration), people, timers, notifications, holds, `describeError`, `WasmRuntime` and `inProcessConnector` |
20
- | `src/thin-client.ts` (`@mdbase-dev/sdk/thin-client`) | The thin client for consumers that bring their own connection (an Obsidian-plugin-style integration): codec, client, records, files, presence, Noise and relay transports, keys, status, availability. Held to 64 KiB gzip and never bundles manifest validation |
21
- | `src/cbor.ts` | Strict `mdb-cbor/1` codec (00-overview §3.2): the TS twin of `crates/wire/src/cbor.rs` |
22
- | `src/codec.ts` | Typed struct/union/enum codecs, the TS twin of `crates/wire/src/schema.rs` |
23
- | `src/wire.ts` | Client API messages and operations, typed (mirrors `crates/wire/src/client.rs`, `intent.rs`) |
24
- | `src/errors.ts` | The 15 error codes and `MdbaseError` (§9) |
25
- | `src/transport/noise.ts` | `Noise_IK_25519_ChaChaPoly_SHA256` for local IPC and relay sessions (§12.2, §12.3) |
26
- | `src/session.ts`, `src/client.ts` | One session (frames, cancel, pushes); `MdbaseClient` (reads, live queries, writes, receipts, status, holds, conflicts, fence, reconnect) |
27
- | `src/files.ts`, `src/presence.ts` | Files (§10) and presence (§11) |
28
- | `src/view-sources.ts` | Shared saved-view source create/update helpers over ordinary record intents |
29
- | `src/records.ts`, `src/records/` | Shared record editor leases, bounded drafts and exact receipt recovery |
30
- | `src/timers.ts` | Opaque control-plane timers and push channel registration (`connection.timers`) |
31
- | `src/notifications.ts` (`@mdbase-dev/sdk/notifications`) | The push delivery envelope (`docs/contracts/push-envelope.md`) and service-worker helpers |
32
- | `src/manifest.ts` (`@mdbase-dev/sdk/manifest`) | Build-time `mdbase-app.json` validation (`validateAppManifest`, `parseAppManifest`, `formatManifestValidationIssues`) and `MDBASE_TIMER_FIRED_CONTRACT`, using the validator Connect runs. For build scripts and tests; never needed at runtime |
33
- | `src/describe-error.ts` (`@mdbase-dev/sdk/describe`) | `describeError()`: plain-language title, message and suggested action for any SDK error, sign-in/open problem (including `collection_migrating`, `account_suspended`, `update_required`) or readiness facet |
34
- | `src/collection-availability.ts` | `CollectionAvailability` (`available`, `opening`, `unavailable` + reason): Private collections served by one of the account's computers, and listed cloud copies (`AppInstallationCollection.availability`, absent meaning available) |
35
- | `src/app-grant/` (`@mdbase-dev/sdk/app-grant`) | `MdbaseAppGrants`: grants for Private collections (OAuth PKCE + an attested client Noise key), listing with availability, bounded waits, relay connector |
36
- | `src/private.ts` | Device approval and recovery key (private collections) |
37
- | `src/keys.ts` | Client static keys: non-extractable WebCrypto X25519 in IndexedDB where possible |
38
- | `src/transport/port.ts` | The transport seam: `FramePort`, `Connector`, `u32be` record framing |
39
- | `src/transport/inprocess.ts` | In-process connector to a shared runtime (§12.1) |
40
- | `src/transport/noise-session.ts` | Noise sessions over message carriers (WebSocket, `u16be`-framed streams) |
41
- | `src/transport/relay.ts` | Relay / hosted replica connector (§12.3) |
42
- | `src/node.ts` (`@mdbase-dev/sdk/node`) | Local IPC to the daemon (§12.2) |
43
- | `src/testing/` (`@mdbase-dev/sdk/testing`) | `MemoryReplica` (in-memory replica speaking the protocol) and `serveNoise` |
44
- | `test/golden.test.ts` | Runs every fixture in `conformance/wire/` from TS |
45
-
46
- ## Value model
47
-
48
- What the SDK hands to apps, following §12.1:
49
-
50
- | CBOR | TS |
51
- |---|---|
52
- | integer within ±(2^53−1) | `number` |
53
- | integer beyond that | `bigint` |
54
- | float with a fractional part | `number` |
55
- | integral float (`1.0`, `-0.0`) | `Float64` (so `1` and `1.0` stay distinct) |
56
- | byte string | `Uint8Array` |
57
- | data map (text keys, order is data) | `Map<string, …>` |
58
- | struct map | `Map<number, …>` at the raw level; named-field objects in the typed layer |
59
-
60
- In the typed layer, UUIDs are canonical lowercase strings, hashes are `sha256:<hex>`
61
- revision tokens, and enumerations are their snake_case names.
62
-
63
- ## Usage
3
+ The TypeScript SDK for apps that read and write mdbase collections. It signs
4
+ the person in, opens the collection they choose, keeps it open and in sync, and
5
+ gives the app one connection for its records, files and people.
64
6
 
65
7
  ```ts
66
- import { connect, relayConnector, loadOrCreateClientKey } from "@mdbase-dev/sdk";
8
+ import { createMdbase } from "@mdbase-dev/sdk";
67
9
 
68
- const key = await loadOrCreateClientKey("my-app"); // register key.publicKey with the grant
69
- const db = await connect({
70
- app: { name: "my-app", version: "1.0.0" },
71
- connector: relayConnector({ collection, grant, staticKey: key, resolveRoute }),
72
- waitForDevice: true, // private collections
73
- });
74
-
75
- const tasks = db.live({ types: ["task"], order_by: ["-due"], limit: 200 }); // windowed, no bodies
76
- tasks.subscribe((s) => render(s.records, { stale: s.stale, complete: s.complete }));
77
-
78
- const rec = await db.get(id, { body: true });
79
- const w = await db.update(rec, { patch: { status: "done" }, body: edited }); // base + body edits filled in
80
- w.records; // optimistic view now
81
- await w.confirmed; // at a log position, or throws MdbaseError (15 codes)
82
-
83
- db.onStatus((s) => show(`Synced through ${s.confirmedThrough}` + (s.pending ? `, ${s.pending} waiting` : "")));
10
+ const mdbase = createMdbase(declaration);
11
+ mdbase.subscribe(() => render(mdbase.getSnapshot().phase));
12
+ await mdbase.start();
84
13
  ```
85
14
 
86
- `await db.create(input)` returns a `RecordWrite`, the existing tracked `Write`
87
- with an added `recordId`. It is the submitted UUID, available even when the
88
- receipt has no optimistic records. Contract creates and retries with the same
89
- `intent` return that same identity. Confirmation/publication semantics are unchanged.
90
- Likewise, `files.upload()` returns `FileWrite.fileId`; concurrent uploads on one
91
- client run in FIFO order through the replica's single upload lane. An upload
92
- releases the queue after its commit receipt, without waiting for log confirmation.
15
+ ## Install
93
16
 
94
- ## Record editor leases
95
-
96
- ```ts
97
- const lease = await db.records.open({path: "notes/writing.md"}, {
98
- autosave: {idleMs: 500}, // omitted/false means explicit flush only
99
- signal,
100
- });
101
- const stop = lease.session.subscribe(() => render(lease.session.getSnapshot()));
102
- lease.session.setBody(editedBody);
103
- lease.session.patchFrontmatter({title: "New title"}); // undefined unsets a key
104
- const result = await lease.session.flush({timeoutMs: 30_000, signal});
105
- if (!result.ok) showProblem(result.problem);
106
- stop();
107
- lease.release();
108
- ```
109
-
110
- UUIDs and `{path}` selectors use ordinary native `get`/`update` operations. Full
111
- native document/body/revision and current protection gates are required; edits
112
- use the actual source's whole-document CAS, field observations and body base.
113
- There is no source reconstruction, replacement record UUID or new app database.
114
- `records.open` throws SDK errors; `flush` returns `{ok, record}` or `{ok, problem}`.
115
- Snapshots retain exact SDK value maps, native `record`/`remote`, draft `body`,
116
- `dirty`, `problem`, and the original `recovery` mutation identity/receipt/`Write`.
117
- Saved requires actual confirmed, unprotected, same-UUID full native readback;
118
- receipt confirmation alone (or optimistic/pending readback) is insufficient.
119
-
120
- Submission is serialized per UUID/client. A mutation ID is exposed through the
121
- snapshot **before** submission. Ambiguous submit/readback failures keep that ID;
122
- subsequent flush only awaits its actual receipt, never resubmits or substitutes
123
- another mutation. New edits made during capture remain drafts for a subsequent
124
- intent only after the first has genuinely settled. A unique pending operation
125
- from this client's native pending API can recover an editor session; foreign or
126
- ambiguous pending ownership refuses. Across client lifetime/reload, retain the
127
- snapshot's `RecordRecoveryRef` (`mutationId`, `recordId`, `baseRevision`) in the
128
- caller-owned recovery state and pass it as `open(..., {recovery})`, particularly
129
- when the receipt settled but readback failed. The helper adds no durable journal
130
- and does not infer ownership from a shared current pending record.
131
-
132
- Active leases share the UUID's draft/session and must agree on autosave/timeout
133
- policy. Releasing/aborting one lease unsubscribes it without closing the client
134
- or evicting another lease. Last release stops autosave/observation and aborts
135
- late delivery, retaining unsaved/recovering data for reopen on the same client.
136
- Client close suspends all leases. Retention is bounded to 64 sessions and 8 MiB
137
- of serialized retained-data accounting; budget refusal never evicts drafts.
138
- This accounting is not a measured peak-heap claim.
139
-
140
- For a settled CAS conflict, `resolve({keep: "mine" | "theirs"})` or
141
- `resolve({body})` explicitly rebases on a genuine confirmed/unprotected remote
142
- readback. Native held/unresolved records remain refused: the current native
143
- hold-resolution producer lacks caller-captured mutation identity and cancellation,
144
- so this helper cannot safely resolve a hold or retry its unknown outcome. It does
145
- not use a fresh `resolveHold` call as a workaround. Change notifications hydrate
146
- the same UUID; observer failure is exposed, not treated as a successful refresh.
147
-
148
- ### Writer lease mapping
149
-
150
- Writer's editor leases are local references to a shared draft/session, not
151
- server-issued exclusive editing locks. Its existing lease contract maps to the
152
- public SDK without a new lease RPC:
153
-
154
- | Writer use | Public SDK operation |
155
- | --- | --- |
156
- | Open/follow a manuscript or embedded record | `records.open(ref, {autosave, timeoutMs, signal})`, session `subscribe` / `getSnapshot` |
157
- | Edit body or staged frontmatter | Session `setBody` / `patchFrontmatter` |
158
- | Autosave or explicit bounded save | Session `flush`; actual revision CAS and original mutation/receipt recovery |
159
- | Show saved/conflict/recovery/deleted state | Genuine session snapshot; confirmed receipt plus full confirmed/unprotected same-UUID readback for saved |
160
- | Choose a settled CAS conflict result | Session `resolve`; native held/unresolved records remain refused |
161
- | Recover across client lifetimes (caller retains witness) | Retained `RecordRecoveryRef` passed to `records.open`; never a replacement mutation |
162
- | Close an editor | Unsubscribe and `lease.release`; local lifetime release, not a remote unlock or save acknowledgment |
163
-
164
- Sharing is per UUID/client, not across devices or independent clients. Revision
165
- CAS protects save attempts; it does not exclude another editor. Writer's lease
166
- flow does not need presence. The current native Replica presence RPCs return
167
- `not_yet("presence")`, even though its hello can admit the `presence` marker;
168
- negotiation alone is not a live presence implementation or write authority.
169
- This mapping does not qualify Writer's native UI/runtime integration.
170
-
171
- ## Classic-script browser bundle
172
-
173
- `npm run build` includes `dist/browser/mdbase-sdk.js` and
174
- `dist/browser/mdbase-sdk.min.js` in the SDK archive. Serve the exact qualified
175
- archive's asset from your app's origin; no CDN publication is implied.
176
-
177
- ```html
178
- <script src="./vendor/mdbase-sdk.min.js"></script>
179
- <script>
180
- const { connect, Client, AppHost } = window.MdbaseSDK;
181
- // Root exports match @mdbase-dev/sdk; Client groups client.ts exports.
182
- // AppHost matches @mdbase-dev/sdk/app-host.
183
- </script>
17
+ ```sh
18
+ npm install --save-exact @mdbase-dev/sdk
184
19
  ```
185
20
 
186
- Module consumers can import the same surface from `@mdbase-dev/sdk/browser`.
187
- There is no `MdbaseConnect` compatibility shim or app-specific adapter. Loading
188
- this bundle does not create a session, open storage, load a WASM runtime or grant
189
- access. App-host APIs still require explicit qualified app/environment trust,
190
- runtime, origin and custody inputs. This package does not supply a complete web
191
- Worker/session/runtime composition; use the shared SDK composition when available,
192
- not an app-specific substitute. Packaging tests are not sign-in, CRUD, custody,
193
- physical durability or release-qualification evidence.
194
-
195
- ## Application access and step-up
196
-
197
- `MdbaseConnect` replaces the Connect session's `authorize(target)`:
198
- `authorize()` (sign in or choose), `reauthorize()` (the open or requested
199
- collection, `authorize("selected")`), `approve(id)` (`{collectionId}`) and
200
- `chooseAnother()`. Call them from the user gesture; the SDK reserves the popup,
201
- and a `signal` replaces `timeoutMs`. There is no per-call capability list
202
- (`requestCapabilities`, `requestOperations`, `ensure*`): approval always asks for
203
- the declaration's groups.
204
-
205
- `effectiveCapabilities(declaration, connection)` compares the declaration's v2
206
- required and optional groups with the current session's negotiated hello grant,
207
- for step-up UI only, and returns `{values, requiredAvailable, missing}` (null
208
- without a v2 contract). It does not refresh permissions or authorize an
209
- operation; native operation checks remain authoritative. For write access after
210
- a read-only grant, show `missing` and call `reauthorize()`. Reauthorization still
211
- requires user approval and may return another restricted grant.
212
-
213
- ### Optional file actions at the moment of use
214
-
215
- Declare a file action the app needs only sometimes (adding an image, say) in
216
- `requirements.files.optional`, and ask for it the first time the person does
217
- that, from the same click:
21
+ Pin an exact version, not a range. The npm package trusts the production
22
+ service only. Staging and LAB builds use separate packages; see
23
+ [SDK publication](../../../docs/sdk-publication.md).
218
24
 
219
- ```ts
220
- const result = await app.requestAccess({files: ["add"]}, {reason: "Insert images into your notes"});
221
- if (result.status === "granted") await connection.files.upload(path, image);
222
- else if (result.status === "declined") show(describeError("access_declined"));
223
- // "cancelled": the window was closed, the request expired or `signal` aborted.
224
- ```
25
+ ## Quick start
225
26
 
226
- `requestAccess` resolves `granted` at once, with no window, when the action is
227
- already allowed (required, or allowed earlier). Otherwise it opens Connect for
228
- the open collection with the one-line `reason` (at most 140 characters). The
229
- connection stays open and the app keeps its state. An action the manifest does
230
- not declare rejects with `access_undeclared`. Until the person allows it,
231
- `files.upload` (and `replace`, `move`, `delete` when optional) rejects with a
232
- `forbidden` error whose reason is `access_required`; its `describeError` copy
233
- has an "Allow" action that should call `requestAccess`. `files.grant` leaves out
234
- writes not yet allowed.
235
-
236
- File-action consent is advisory on an installation device: Connect records the
237
- person's choice and the SDK enforces it, but the app's own replica is not
238
- narrowed by it.
239
-
240
- ## Cloud-copy first-open waits
241
-
242
- Initial opening keeps the same enrolled device, native host, SQL and keys while
243
- retrying a parsed CP HTTP 503 `busy` log-token refusal. There are at most three
244
- log-init attempts; retries must fit a 15-second scheduling window and respect
245
- Retry-After. Individual challenge/mint requests retain their 15-second deadlines.
246
- Unknown 401/403/409 responses, malformed responses and generic unavailable errors
247
- do not authorize a retry. Each failed mint retry obtains a fresh challenge/proof,
248
- not another enrollment or collection.
249
-
250
- For a previously synced local replica, the native verified-read gate keeps its
251
- 15-second deadline, including connect, pump and Query. For a cold replica (the
252
- SDK join ledger has never recorded a completed first sync), the same 15 seconds
253
- bounds **lack of progress**, not total catch-up time. The watchdog observes native
254
- accepted prefix, advancing data/control READ cursors and snapshot-install
255
- positions even while a multi-RPC pump is pending. Control READ cursors cover
256
- key scanning whose native `reading` incident does not expose intermediate
257
- positions. Only native-accepted replies to increasing cursors count; sending
258
- calls, rejected replies, head growth, heartbeats and repeated cursors do not
259
- reset it. Active, size/range-capped response bytes can defer a stall for the
260
- already in-flight calls under their existing per-request deadlines; they do not
261
- reset native progress or admit READ. Once those calls settle, successive retries
262
- cannot renew that deferral without accepted native progress. This also covers
263
- object downloads whose existing per-request budget exceeds 15 seconds.
264
- Cold catch-up must reach the complete known prefix,
265
- then pass an actual native Query; metadata never admits a data facade. A stall
266
- fails typed `AppCloudCopyHostError("sync_stalled")` (the existing public
267
- `unavailable` problem with a distinct diagnostic code).
268
-
269
- Both paths retain typed READ-unavailable pacing (250 ms, 500 ms, then at most
270
- one per second). Explicit server authority outcomes and typed HTTP 403
271
- `forbidden` are latched against concurrent success. An HTTP status alone is not
272
- terminal: stale-token 401 can invalidate/refresh through the existing authority,
273
- and opaque routing/timeouts keep the existing NoResponse path. Native Query
274
- `unauthenticated`/`forbidden` errors still refuse without retry. Cancellation stops the waits;
275
- failed keyring recovery and non-retryable native errors still refuse. This remains the existing opening
276
- state, with explicit retry after a terminal failure: no new migration state,
277
- write/setup replay, legacy fallback or application retry loop is needed.
278
-
279
- ## Reopening a cloud copy from this device
280
-
281
- A cloud copy whose join ledger records a completed first sync opens from the
282
- replica on this device before the log is reached. The log-token request starts
283
- in the background, a verified read is answered by the replica as it stands, and
284
- the collection is handed to the app. The first drive turn then binds the log,
285
- sends edits captured meanwhile and brings in what changed elsewhere. What the
286
- app shows first is therefore the collection as of this device's last sync, and
287
- it updates when the first turn lands. Saved views read in that window as well:
288
- the replica serves them while it re-derives its keys from the log.
289
-
290
- The ledger and the replica are stored separately. A replica that holds nothing
291
- from the log (`holdsLog()` is false: its storage was lost after that sync) is
292
- not opened this way. It binds the log first and catches up like a first open.
293
-
294
- A bind that fails is sorted once:
295
-
296
- - offline, unreachable, 5xx and 429 leave the collection open with `health`
297
- set, and the drive loop retries with its usual backoff and on foreground. A
298
- reply that is not Connect's, such as the sign-in page of a network the device
299
- has just joined, counts as unreachable;
300
- - a server outcome with its own copy (migrating, suspended, update required,
301
- not yet migrated) shows as the connection's `problem` and is retried slowly;
302
- - any other answer from Connect (401/403, other 4xx) sets the connection's
303
- `failure`. The sign-in session then blocks the collection with the same
304
- problem a failed open reports and closes it. It reads `failure` when the open
305
- returns as well as on later changes, so a refusal that arrived before the
306
- handoff never shows as ready.
307
-
308
- Once bound, the replica checks its stored policy against the log while it
309
- re-derives its keys. A replica that fails that check sets `failure` with
310
- `recovery_required`, which is what a waited open refuses it with.
311
-
312
- An edit made before the bind is an offline edit and is treated as one: kept
313
- pending and sent once the log is bound. Nothing here changes what the log does
314
- with an edit from a device whose access was removed while the app was closed.
315
- A log token is valid for up to 16 minutes, so such a device can still bind
316
- with a token it kept; refusing its entries is the log's job, as it was before.
317
-
318
- The local read has five seconds. If the replica cannot answer it, the open
319
- takes the ordinary path above. Private collections and cold replicas always
320
- take that path.
321
-
322
- A signed-in start likewise publishes the collection list this installation kept
323
- from its last listing, with no request. That list carries no file actions and a
324
- collection missing from it is not treated as removed. The Worker host then reads
325
- Connect's list: straight after a start that already holds a collection,
326
- otherwise after the page's next request, or after two seconds. A read that did
327
- not happen (the session was busy, or the request failed) is tried again two
328
- seconds later, three times in all; after that the next show or reconnect reads
329
- it. `collectionListCached()` on the session says which list is showing.
330
-
331
- ## Private collections from web apps
332
-
333
- `@mdbase-dev/sdk/app-grant` lets a signed-in web app open a Private collection
334
- through the relay to one of the account's online computers. It is a separate
335
- entry so apps that only use cloud copies don't load it.
336
-
337
- - `new MdbaseAppGrants({declaration, redirectUri})`; `authorize({popup})` from the
338
- user gesture asks for a grant (OAuth PKCE, popup, at most 30 minutes). The
339
- redirect page calls `deliverAppGrantCallback(location.href)`.
340
- - `collections()` lists granted Private collections with `availability`;
341
- `mergeCollectionEntries(cloud, privates)` merges them with cloud copies.
342
- - `waitForAvailable(id, {timeoutMs})` polls (default 60 s, at most 10 minutes)
343
- and returns the last availability; it never waits on `sync_required` or
344
- `access_removed`. `connector(id)` opens; an unavailable collection fails with
345
- `collectionUnavailableError(reason)`, and `describeError` gives the copy.
346
-
347
- Storage: the installation signing key and each grant's Noise static key are
348
- non-extractable WebCrypto keys structured-cloned into IndexedDB. The refresh
349
- token is stored only as AES-256-GCM ciphertext under a per-grant
350
- non-extractable key, and access tokens stay in memory. Script can use but not
351
- read these secrets, so it cannot copy them elsewhere; same-origin script running
352
- while the app is open can still use them, so apps still need a strict CSP.
353
- The default store belongs to the app's own manifest family (`bundle:<manifest
354
- id>` from its declaration), never the id Connect assigns: the database name,
355
- every record and the refresh ciphertext carry it, and records for another owner
356
- are refused. Grants stored before this labelling are not adopted; the app asks
357
- for access again and the old records are left in place.
358
-
359
- ### Listing and opening Private collections in an app
360
-
361
- Every launch app follows the same pattern (the Editor's `private-collections.ts`
362
- and `SdkEditorRoot.tsx` are the reference):
363
-
364
- 1. **Load it lazily.** Construct one `MdbaseAppGrants` per app, behind
365
- `import("@mdbase-dev/sdk/app-grant")` on first use, so the relay and grant code
366
- stay out of the initial bundle. `redirectUri` is the manifest redirect URI on
367
- the app's own origin.
368
- 2. **Handle the callback page.** When the app loads with `state` and `code` or
369
- `error` in its URL, call `deliverAppGrantCallback(location.href)`, then
370
- `window.close()`. Don't start the application SDK in that window.
371
- 3. **List.** Once signed in, merge `grants.collections()` into the chooser with
372
- `mergeCollectionEntries(snapshot.collections, privates)`. `collections()` is
373
- empty until this browser holds a grant, so always offer **Add a Private
374
- collection**. It calls `authorize({popup})`; reserve the popup with
375
- `window.open` inside the click, before any `await`.
376
- 4. **Show availability.** Every merged entry has one `availability` shape:
377
- cloud copies take theirs from `snapshot.collections` (absent there means
378
- available), Private ones from `collections()`.
379
- `describeError(entry.availability)` gives the title and message for each
380
- reason. Actions:
381
-
382
- | Availability | Action |
383
- |---|---|
384
- | `available` | Open |
385
- | `opening`, `device_offline`, `approval_required`, `desktop_update_required`, `old_connector_running`, `no_device_registered` | Open: `waitForAvailable(id, {onAvailability})` (bounded), then open when it reports `available` |
386
- | `sync_required` | **Give access again**: `authorize({popup, collection: id})` |
387
- | `access_removed` | No open. For a Private entry, offer `forget(id)` to remove it from this browser |
388
- | `collection_migrating` | Wait; the collection reopens when the upgrade is done |
389
- | `collection_deleted` | No open |
390
-
391
- 5. **Open.** `connect({connector: grants.connector(id), app})` returns an
392
- `MdbaseClient` that the app owns. Check `client.collection === id`, and close
393
- the client when the person leaves the collection. A failure carries its
394
- availability reason, so pass it to `describeError`.
395
-
396
- 6. **People.** `grants.people(id, client)` returns the same `MdbasePeopleClient`
397
- as cloud copies (`current()`, `members()`, `directory()`), reading Person
398
- records over `client` and identity and members from Connect with the grant.
399
- Until a computer approves the app, identity and members fail with
400
- availability `approval_required`; members also need the person's people
401
- approval (`people_permission_declined` otherwise). Needs a Connect server
402
- that serves people metadata for Private grants; older ones answer
403
- `people_unsupported` or refuse the token.
404
-
405
- 7. **Setup.** `grants.setup(client)` gives the same plan and review wording as
406
- a cloud copy's `setup`. `assess()` answers `ready`, `setup_required` or
407
- `incompatible`. `plan({adopt?, records?})` returns an `MdbaseSetupPlan`:
408
- show its `summary`, then each `changes[].message` (for example "Add the
409
- "task" record type."), and offer `adoptable` conflicts as a choice.
410
- `apply(plan)` writes everything in one guarded mutation that the person's
411
- computer checks. If anything changed since the review it refuses
412
- `setup_changed` and writes nothing, so plan again. The original Native session
413
- must negotiate `declared-collection-setup-v1`; Native verifies the signed
414
- declaration and plans the complete batch. This does not require or grant
415
- arbitrary `definitions.manage`. Starter notes independently need `records.create`.
416
- Before apply, the SDK durably retains an encrypted original mutation ID under
417
- existing grant custody. Lost/unknown outcomes reconcile that receipt only;
418
- they never replay setup or fall back to Hosted. Custom grant stores must
419
- implement the optional setup-attempt register to support setup.
420
-
421
- Not covered yet for Private collections:
422
-
423
- - The `MdbaseApplication` readiness flow (`configure`) doesn't apply; use
424
- `grants.setup(client)` and `grants.availability(id)`.
425
- - Merged entries carry `role` (`owner`, `editor`, `viewer` or `null`). Cloud
426
- copies always have one. A Private entry's is `null` when Connect doesn't
427
- report it: older servers, or an account whose access needs renewing. Gate
428
- owner actions on `role === "owner"`; Connect still checks each action.
429
-
430
- ## Private collections on the app's own replica
431
-
432
- An app that hosts its own replica through `MdbaseApplication` (`createMdbase`)
433
- can open an existing Private collection with that replica, as a device of the
434
- collection, instead of through the relay. The person unlocks it once with the
435
- account's encryption password or recovery key. Connect only offers this to
436
- apps it allows to hold a Private key.
437
-
438
- - **Ask for it.** List `offline.replica` in the declaration's capabilities,
439
- under `requirements.capabilities.optional` or `required`. Prefer `optional`:
440
- the app then still signs in and syncs cloud copies where device access is not
441
- offered, and consent for an app grant on a current account refuses an app
442
- that lists it as required. The sign-in request asks for device access
443
- (`requested_private_device`), and the person chooses which Private
444
- collections to share. A server that does not know the request is asked again
445
- without it, and one that does not offer device access to this app answers
446
- with no Private collections; both leave an ordinary cloud-copy sign-in. An
447
- installation paired before this needs to ask for access again.
448
- - **List.** Entries in `snapshot.collections` carry `mode: "private"`; absent
449
- means a cloud copy. A server from before this feature (after a rollback)
450
- answers the list without modes; the SDK then asks once more with the earlier
451
- request, so file actions are kept and no Private entry is listed.
452
- - **Open.** `select(id)` as usual. An approval that shares only Private
453
- collections names no selected collection, so the app arrives in its chooser;
454
- when exactly one collection is approved the application opens it by itself,
455
- as it does a sole cloud copy. A device that already holds the key goes
456
- straight to `ready`. One that doesn't reads
457
- `{kind: "needs_unlock", collectionId, displayName, mode, unlocking, problem}`.
458
- There is no `connection` while locked.
459
- - **Unlock.** For `mode: "password"`, call
460
- `mdbase.unlock(collectionId, {password})` or `{recoveryKey}` with what the
461
- person typed, and keep no copy. It resolves when the attempt has settled: the
462
- collection continues to `ready` (or `needs_setup`) without a reload, or the
463
- phase is still `needs_unlock` with `problem` set. `problem` is an
464
- `MdbaseProblem` with its copy already described; its `key` is one of
465
- `wrong_secret`, `invalid_recovery_key`, `rate_limited`, `unavailable`,
466
- `unlock_unavailable` or `unlock_failed`. `mode: "strict"`
467
- and `mode: "none"` cannot be unlocked here: explain that this collection has
468
- to be opened on a computer running the mdbase app.
469
- - **Retries.** Connect limits how often an account's sealed key can be fetched
470
- (10 an hour, shared by all of the account's devices; `rate_limited` carries
471
- the wait). A mistyped recovery key (`invalid_recovery_key`) and a password
472
- shorter than the 12-character minimum (`wrong_secret`) are refused in the
473
- Worker without any request. After a wrong secret the Worker keeps the sealed
474
- bundle in memory for the next attempt on the same locked collection, and
475
- uses it only while Connect's status still reports the same account key
476
- version; it is dropped when the collection unlocks or closes.
477
- - **Afterwards.** Once the unlock has applied, reopening needs no secret. A
478
- restart before it applied returns to `needs_unlock`.
479
-
480
- The password or recovery key is sent to the Worker as bytes that are wiped in
481
- the tab as soon as they are posted and in the Worker when the call settles. The
482
- key it unlocks is used once and wiped; neither is stored. One installation can
483
- be a device of one Private collection (`private_device_limit` for a second),
484
- and People is not available for these collections yet: `connection.people`
485
- is present, and its reads reject with `upgrade_required`
486
- (`people_unsupported`).
487
-
488
- To fetch the sealed account key, the app runtime signs one fixed request: the
489
- account-key fetch proof for its own connector and device, over the server's
490
- challenge and the signed-in account. It signs nothing else for the account key
491
- (no change, no strict approval, no caller-chosen digest), and the fetched
492
- bundle is still sealed under the person's password or recovery key, which both
493
- kinds of unlock need. An older app runtime without this signer answers
494
- `unlock_unavailable`, and the collection stays `needs_unlock`.
495
-
496
- ## Managed application build environments
497
-
498
- Application declarations support explicit `lab`, `staging` and `production`
499
- environments. Each SDK artifact must be packaged with the completed authenticated
500
- trust handoff for that exact environment; changing an app build variable cannot
501
- retarget a LAB archive. Staging packaging pins Connect to
502
- `https://connect-staging.mdbase.dev`, production to `https://connect.mdbase.dev`.
503
- CP/log origins and release trust still come only from the verified build context;
504
- missing, expired or crossed trust refuses without a fallback. Isolated `local`
505
- builds remain separate and refuse all managed environments.
506
-
507
- ### Developing on localhost
508
-
509
- In every managed environment the app's own `origin` may be a loopback HTTP
510
- origin (`http://localhost:<port>`, `http://127.0.0.1:<port>` or
511
- `http://[::1]:<port>`), so an app is developed against production with the
512
- published package:
27
+ An app declares itself with its manifest, the `mdbase-app.json` it serves at
28
+ `/.well-known/`. The manifest names the app and what it asks for: the
29
+ contracts it uses, what it may do with records, and which file actions.
30
+ `@mdbase-dev/sdk/manifest` validates it at build time.
513
31
 
514
32
  ```ts
515
- createMdbase({ id, name, origin: "http://localhost:5173", environment: "production", manifest: devManifest });
516
- ```
517
-
518
- The manifest's `homepage` and `redirect_uris` use that same origin. Connect
519
- registers it as its own application, apart from the one published at the HTTPS
520
- origin: approvals and device storage belong to the exact origin and are not
521
- shared between the two. The approval screen calls it "an app running on this
522
- computer" and says its identity is unverified, as it does for a native app.
523
- Connect's own origins (control plane, log) stay HTTPS outside LAB; no other
524
- plain-HTTP app origin is accepted.
525
-
526
- `vite dev` and `vite build` both work with Vite's default configuration: the
527
- SDK's worker and WebAssembly files are served from `node_modules` in
528
- development and emitted as assets in a build.
529
-
530
- The app manifest must declare the installation origin under
531
- `installation_origins.staging` for staging pairing, just as for other environments.
532
- Packaging support alone is not an application deployment or acceptance receipt.
533
-
534
- ## Native shells and browser extensions
535
-
536
- A Capacitor app declares its native origin (for example
537
- `capacitor://app.tasknotes.dev`) as `origin`, and lists it in the manifest under
538
- `installation_origins.<environment>.mobile`. Pairing then uses installation kind
539
- `mobile`. `capacitor://` origins default to that kind; an Android shell served
540
- from https sets `installationKind: "mobile"`. A Chrome extension uses its
541
- `chrome-extension://<id>` origin under `installation_origins.<environment>.app-runtime`.
542
- Firefox `moz-extension://` origins differ per profile and are not accepted by
543
- Connect.
544
-
545
- Where a popup is unavailable, pass a sign-in opener:
33
+ import { createMdbase, type MdbaseApplicationDeclaration } from "@mdbase-dev/sdk";
34
+ import manifest from "../public/.well-known/mdbase-app.json";
35
+
36
+ const declaration: MdbaseApplicationDeclaration = {
37
+ id: manifest.id,
38
+ name: manifest.name,
39
+ origin: location.origin,
40
+ environment: "production",
41
+ manifest,
42
+ };
43
+
44
+ export const mdbase = createMdbase(declaration);
45
+ ```
46
+
47
+ `mdbase.getSnapshot().phase` is the one state the app renders from. Switch on
48
+ `phase.kind`:
49
+
50
+ ```tsx
51
+ function App() {
52
+ const { phase, collections } = useSyncExternalStore(mdbase.subscribe, mdbase.getSnapshot);
53
+ switch (phase.kind) {
54
+ case "starting":
55
+ case "opening":
56
+ return <Loading />;
57
+ case "signed_out":
58
+ return <button onClick={() => mdbase.signIn()}>Sign in</button>;
59
+ case "authorizing":
60
+ return <p>Continue in the mdbase window.</p>;
61
+ case "choosing":
62
+ return <Chooser collections={collections} onOpen={(id) => mdbase.select(id)} onAdd={() => mdbase.addCollection()} />;
63
+ case "needs_approval":
64
+ return <button onClick={() => mdbase.approve(phase.collectionId)}>Allow access</button>;
65
+ case "needs_unlock":
66
+ return <Unlock onSubmit={(password) => mdbase.unlock(phase.collectionId, { password })} />;
67
+ case "needs_setup":
68
+ return <button onClick={() => mdbase.configure()}>Set up this collection</button>;
69
+ case "ready":
70
+ case "unsynced":
71
+ return <Notes db={phase.connection.records} />;
72
+ case "problem":
73
+ case "unavailable":
74
+ return <Problem problem={phase.problem} />;
75
+ case "closed":
76
+ return null;
77
+ }
78
+ }
546
79
 
547
- ```ts
548
- const connect = new MdbaseConnect(declaration, {
549
- signIn: {
550
- open: url => Browser.open({ url }), // or chrome.tabs.create({ url })
551
- close: () => Browser.close(),
552
- returnUrl: "dev.tasknotes.app://auth/mdbase/callback", // optional; see below
553
- },
554
- followVisibility: true, // re-poll as soon as the app returns to the foreground
555
- });
80
+ void mdbase.start();
556
81
  ```
557
82
 
558
- `returnUrl` must exactly equal one of the manifest's `redirect_uris`, or the
559
- constructor throws `application_sign_in_opener`. That is either an https URL on
560
- the homepage origin or, for a native app, a private-use scheme derived from the
561
- manifest ID (RFC 8252), such as `dev.tasknotes.app://auth/mdbase/callback` for
562
- ID `dev.tasknotes.app`. No prefix or wildcard matching. Connect applies the same
563
- exact match before it returns the user there. The URL carries no credential:
564
- sign-in still completes by the SDK's pairing poll.
565
-
566
- The SDK still binds the URL to the environment's Connect origin. The pending
567
- pairing request is persisted, so a context that closes during sign-in (an
568
- extension popup) resumes it on the next `start()`. Run extension sign-in from a
569
- side panel or tab page where possible. Without `followVisibility`, call
570
- `application().setForeground(active)` from the shell's resume/pause events.
83
+ `start` restores a signed-in device and opens the collection named in the URL
84
+ or the one last used. `signIn`, `addCollection` and `approve` open a Connect
85
+ window, so call them from a click.
571
86
 
572
- ### Running inside another app's document
87
+ ### Phases
573
88
 
574
- A host app that runs the SDK in a document without a URL of its own (a `blob:`
575
- iframe inside a mobile WebView, for example) passes two options:
89
+ | `phase.kind` | The app shows | What moves it on |
90
+ |---|---|---|
91
+ | `starting` | Its own loading screen | The SDK |
92
+ | `signed_out` | A sign-in button; `phase.notice` when sign-in just ended | `mdbase.signIn()` |
93
+ | `authorizing` | "Continue in the mdbase window" | The person, in Connect |
94
+ | `choosing` | `snapshot.collections` and an "add" button | `mdbase.select(id)`, `mdbase.addCollection()` |
95
+ | `opening` | A loading screen; `phase.slow` after 15 seconds | The SDK |
96
+ | `needs_approval` | A request to allow this app | `mdbase.approve(phase.collectionId)` |
97
+ | `needs_unlock` | A password field when `phase.mode` is `password` | `mdbase.unlock(id, { password })` |
98
+ | `needs_setup` | What the app will add to the collection | `mdbase.configure()`, or `mdbase.setup.plan()` then `setup.apply(plan)` |
99
+ | `ready` | The app, using `phase.connection` | |
100
+ | `unsynced` | The app, on work kept only in this browser (the `unsynced` option) | `mdbase.signIn()`; then `mdbase.unsynced.planTransfer()` and `transfer(plan)` copy the work into the collection the person opens |
101
+ | `problem` | `phase.problem`: a title, a message and an action | The action |
102
+ | `unavailable` | `phase.problem`: the SDK cannot run here | |
103
+ | `closed` | Nothing; `mdbase.close()` was called | |
104
+
105
+ The phase stays `ready` while the collection is checked again or meets a
106
+ problem that clears by itself; `phase.rechecking` and `phase.problem` say so.
107
+ Going offline does not change the phase. [Status](#status) reports it.
108
+
109
+ ## Records
110
+
111
+ `phase.connection.records` is the collection client. Values are plain JSON.
576
112
 
577
113
  ```ts
578
- const workerScript = await (await fetch(sdkWorkerUrl)).text(); // the SDK's own worker.js
579
- const workerBlob = URL.createObjectURL(new Blob([workerScript], { type: "text/javascript" }));
580
- const mdbase = createMdbase(declaration, {
581
- urlSelection: false, // select with select()/approve()
582
- worker: url => new Worker(workerBlob, { type: "module" }), // url: where worker.js is served
583
- });
584
- ```
114
+ const db = phase.connection.records;
585
115
 
586
- - `urlSelection: false`: the SDK never reads or writes the page URL. A link or
587
- Back/forward no longer selects a collection, and the app selects with
588
- `select`, `approve` and `clearSelection`. The last-used collection is still
589
- remembered on the device. Without it, a `blob:` document reports
590
- `application_selection_binding`.
591
- - `worker`: the SDK calls it with the URL it would load its module Worker from
592
- (`worker.js` beside the SDK's entry module). Return a module Worker running
593
- that script's exact bytes. The Worker loads `runtime.wasm`, `sqlite3.wasm`
594
- and `sqlite3.js` from `../native/` beside that URL, so serve the SDK's
595
- `dist/application` and `dist/native` files there; their bytes are still
596
- checked against the SDK's pins. A factory that throws or returns no Worker
597
- fails with `application_worker_unavailable`.
598
-
599
- Both default to the ordinary behaviour, and a bundler-built app needs neither.
600
-
601
- ## Multiple vaults on one origin
602
-
603
- Give each vault a stable, distinct `storage.applicationNamespace` (different
604
- from the application ID). The SDK scopes tab/Worker grouping, pre-account
605
- sign-in locks, protected installations and Private grants to that namespace.
606
- Each vault pairs independently and receives its own installation/device IDs;
607
- the existing device-key stores and OPFS replica pools then remain separate.
608
- Signing out erases only that namespace's installations, grants and replica data,
609
- and evicts log tokens matching its CP/connector/device, including unlisted
610
- collections. Other vaults stay signed in.
116
+ const note = await db.get({ path: "notes/hello.md" }, { include: { body: true } });
117
+ const { records } = await db.query({ types: ["note"], where: 'status == "open"', limit: 50 });
611
118
 
612
- ```ts
613
- const vault = createMdbase({
614
- ...declaration,
615
- storage: { applicationNamespace: "obsidian-vault-<stable-vault-id>" },
616
- });
119
+ const created = db.create({ type: "note", path: "notes/new.md", frontmatter: { title: "New" }, body: "" });
120
+ const updated = db.update(note, { patch: { status: "done" } });
617
121
  ```
618
122
 
619
- Omitted join/setup database names derive from the namespace. If you override
620
- `joinDatabaseName` or `setupDatabaseName`, keep those names distinct per vault
621
- as well: sign-out deletes those explicitly assigned journals. Namespace changes
622
- select fresh local storage; they do not migrate or adopt a previous installation
623
- or grant. Previously used overrides must pair and authorize afresh after this
624
- change. Keep the same namespace across reloads and builds.
625
-
626
- The no-override path keeps its existing names, owners, Worker grouping and
627
- legacy sign-in compatibility locks, including legacy whole-token-cache erasure.
628
- A default sign-out also clears all other vaults' cached log tokens on the origin;
629
- they re-mint them on next open.
630
- Public verified-asset and manifest-registration caches remain shared. Namespaces
631
- organize storage; they are not a security boundary against other JavaScript on
632
- the same origin. Consent and grant verification remain authoritative.
633
-
634
- ## Definition errors
635
-
636
- An error-level issue on a definition the app does not declare never affects
637
- readiness. An issue without a path always makes the collection
638
- `incompatible`. By default, an issue on one of the app's own declared types
639
- also makes it `incompatible`. To keep the rest of the collection usable, pass
640
- `readiness: {typeIssues: "degrade"}`. The collection then stays `ready`, and
641
- each affected type is listed in `readiness.assessment.unavailableTypes`
642
- (`{name, path, contract, problem}`). Treat that type as unavailable. Show
643
- `describeError(entry).message` for it. An error on a declared contract's own
644
- definition always blocks.
645
-
646
- ## Collection setup
647
-
648
- `application.setup` sets up the open collection from the app's declaration
649
- with one review screen. `plan(options)` changes no collection data: native Core plans the
650
- declared types into the collection's configured definition folders (an
651
- installed pack stays where it is) and the SDK words the result for a
652
- first-run user. Show `summary`, then `changes[].message` as a list,
653
- `conflicts[].message` and `refusal.message` as is. No message contains a code.
654
-
655
- Before planning, `plan` first settles any earlier setup still in progress
656
- (for example, records that an interrupted apply was confirmed or finally
657
- rejected), so it can write the SDK's own local setup journal. It never
658
- prepares, submits or retries a collection change.
123
+ A write resolves as soon as it is kept on the device. `settle` waits for the
124
+ answer the person cares about, and reads the record back:
659
125
 
660
126
  ```ts
661
- let plan = await app.setup.plan({ records: [{ path: "Welcome.md", document: welcome }] });
662
- if (Object.keys(plan.adoptable).length && userChoseAppVersions) {
663
- plan = await app.setup.plan({ adopt: plan.adoptable, records: [{ path: "Welcome.md", document: welcome }] });
127
+ const saved = await db.settle(updated, { read: { include: { body: true } } });
128
+ switch (saved.outcome) {
129
+ case "confirmed": // the sync service has it
130
+ case "saved_on_device": // kept here; it syncs when the service can be reached
131
+ case "conflicted": // confirmed, but a concurrent change won for some values
132
+ render(saved.record);
133
+ break;
134
+ case "rejected": // not saved
135
+ show(describeError(saved.problem));
136
+ break;
137
+ case "unknown": // it may have been saved; settle(saved.mutationId) asks again
138
+ remember(saved.mutationId);
664
139
  }
665
- if (plan.canApply) await app.setup.apply(plan);
666
140
  ```
667
141
 
668
- `status` is `current` (nothing to do), `setup` or `conflict`. A conflict that
669
- `adoptable` lists is an existing definition with different content, or a type
670
- the app seeded that was edited in a way no published version can be combined
671
- with: if the user chooses the app's version, plan again with `adopt` and that
672
- definition is replaced over exactly the reviewed revision. `staged` holds the definition
673
- documents setup would write, for a details view.
674
-
675
- Starter `records` (at most 32, 256 KiB in total) are created once, in the
676
- same mutation as the setup, and only if setup has something to do. A path
677
- that is already occupied is listed with action `skip` and left alone.
678
- Creating them needs `records.create`. After apply, each starter record is
679
- checked by its identity, path and confirmation, not by its exact bytes: Core
680
- may canonicalize frontmatter on create, and a later edit to that note does not
681
- make setup fail.
682
-
683
- `apply(plan)` takes a plan from `plan` unchanged and writes everything as one
684
- guarded mutation, all or nothing. If the collection changed since review,
685
- including a definition or starter path taken in the meantime, it refuses with
686
- `conflict`/`setup_changed`, nothing is applied, and the next `plan` starts
687
- afresh. If another Private setup plan only retired Native's review ticket,
688
- the SDK re-plans once and continues only when the fresh assessment and file
689
- impact match the original consent. Different changes return `setup_changed`
690
- (`mdbase.setup.apply` returns `outcome: "changed"`); show a fresh plan and ask
691
- for consent again. Lost or uncertain mutation outcomes are never retried.
692
- Refusal codes: `setup_forbidden` (no `definitions.manage`),
693
- `setup_conflict`, `setup_unresolved`, `installed_newer` (a newer app version
694
- set it up; `setup_downgrade` is its former name) and `setup_records_forbidden`.
695
- `setup_unresolved` means the collection still lacks what the app needs but
696
- setup has nothing it may write: a type the app seeded was removed. The person
697
- restores it in the collection; readiness re-checks and the next `plan` reflects it.
698
-
699
- `configure()` is plan and apply in one step, for collections with nothing to
700
- review. A conflict leaves the configuration facet `incompatible`; use
701
- `setup.plan()` to show it.
702
-
703
- ## Deleting a collection
704
-
705
- Owners can delete a collection for everyone with `application.deleteCollection(id, {confirmName})`.
706
- Show it only when the collection's `role` in `snapshot.collections` is `"owner"`, and only after a
707
- confirmation where the person types the collection's name. `confirmName` must equal the current name after trimming (`New collection` for an unnamed one);
708
- the control plane checks ownership and the name, and refuses while an account upgrade is in progress.
709
-
710
- Deletion revokes access on every device and app right away and cannot be undone. On success the
711
- collection leaves `collections` (and closes if it was open). A refusal rejects with a
712
- `collection_delete_*` code and changes nothing; pass the error to `describeError()` for the copy.
713
- `collection_delete_outcome_unknown` means the reply was lost: refresh the collections before retrying.
714
-
715
- ## Type packs
716
-
717
- `client.typePacks.plan(pack, options)` asks the replica's Core to plan a type
718
- pack against the local collection and writes nothing. The plan has `status`
719
- (`install`, `upgrade`, `downgrade`, `reconfigure`, `current`, `conflict`),
720
- `canApply`, a `summary` of targets by action for a diff, per-target
721
- `resources`, `conflicts` with display-ready messages, and `refusal` (`code`,
722
- `message`) when it cannot be applied. Show `refusal.message` as is.
142
+ For a list the app keeps on screen, a record set reads every record of the
143
+ chosen types once and then follows changes, from this device or another:
723
144
 
724
145
  ```ts
725
- let plan = await client.typePacks.plan(pack, { installedBy: "app.example.notes" });
726
- if (Object.keys(plan.adoptable).length) {
727
- // The user reviewed the existing types: let the pack manage them.
728
- plan = await client.typePacks.plan(pack, { installedBy: "app.example.notes", adopt: plan.adoptable });
729
- }
730
- if (plan.canApply) {
731
- const result = await client.typePacks.apply(plan);
732
- // "pending" is accepted locally; wait for the original mutation to confirm.
733
- if (result.outcome === "pending") await result.write!.confirmed;
734
- }
146
+ const notes = db.recordSet({ types: ["note"] });
147
+ notes.subscribe(() => render(notes.getSnapshot().records));
148
+ await notes.ready;
735
149
  ```
736
150
 
737
- `apply(plan)` re-plans against the reviewed `digest` and submits every write
738
- as one mutation, so the collection gets all of it or none. Each write,
739
- including the lock and every adopted unchanged target, is bound to the
740
- revision the plan reviewed. If anything changed since review, apply refuses
741
- with `conflict`/`concurrent_modification`; plan again. A pack that is already
742
- current returns `{ outcome: "already_current" }` and writes nothing.
743
- Otherwise the outcome is `applied` (confirmed) or `pending` (accepted; await
744
- `write.confirmed`, which rejects with the original mutation's problem). A
745
- mutation the replica rejects or cannot settle throws its problem with the
746
- original `mutationId` and is never reported as applied. `dryRun` returns
747
- `preview` and installs nothing. Upgrades
748
- use the pack's seed baselines. An older version is refused
749
- (`type_pack_downgrade`) unless `allowDowngrade` is set.
750
-
751
- Refusal codes: `forbidden` (no `definitions.manage`, reported by `plan`),
752
- `type_pack_conflict`, `type_pack_downgrade`, `invalid_type_pack`,
753
- `type_pack_contract_setups_unsupported`, and from apply
754
- `concurrent_modification`. Older replicas return
755
- `upgrade_required`/`type_packs_unsupported`.
756
-
757
- ## Saved-view sources
758
-
759
- `db.views.createSource({id, path, document, type?}, {mutationId, ...writeOptions})`
760
- creates the exact caller-supplied source. Capture and retain the record UUID and
761
- mutation UUID before submitting (the SDK exports `uuidv7`). No renderer, record
762
- type, filename extension or YAML is inferred or rewritten.
763
-
764
- `db.views.getSourceRecord(ref, {include?, signal?})` requests a complete native
765
- record with its document included. `db.views.updateSource(seen, document,
766
- {mutationId, ...writeOptions})` uses that genuine `RecordView`'s UUID, path, full
767
- source and revision for whole-document CAS. Pending revisions are valid; held,
768
- unresolved, metadata-only or inconsistent source witnesses refuse. A new edit
769
- needs its own captured mutation UUID, not a replacement for an unknown outcome.
770
-
771
- Both write helpers return the original SDK `Write`, force document-inclusive
772
- readback, and preserve receipt IDs, confirmation and publication separately.
773
- Neither performs an implicit refresh or prepares/resubmits on unknown outcomes.
774
- The ordinary client transport's same-mutation retry policy is unchanged.
775
-
776
- For **web app-host** saved-view discovery/execution/exact source reads, use
777
- `listAppBasesViews`, `executeAppBases` and `readAppBasesViewSource`, with the types
778
- from `@mdbase-dev/sdk/app-host`. Keep native UUID/SHA/original ordinal and actual
779
- source options. The generic `views.list/execute/readSource` RPC surface is not an
780
- app-host fallback; unavailable capabilities remain explicit refusals.
781
-
782
- To read a whole saved view in pages, iterate `executeAppBasesPages(request,
783
- {firstPageSize?, pageSize?, signal?})` (defaults 200 then 1000 rows; at most
784
- 65536). Each page is one independent windowed read with `page`, `offset`,
785
- `loaded` and `complete`. Native reads have no cross-request cursor or snapshot,
786
- so `changedSinceFirst` marks pages read after the collection revision or matched
787
- row count changed; rows may then be skipped or repeated, and callers that need a
788
- coherent set restart. A native refusal is yielded once and ends the iteration.
789
-
790
- ## Persisted-record validation
151
+ Guides: [writes](../../../docs/sdk-writes.md),
152
+ [record sets](../../../docs/sdk-record-sets.md),
153
+ [reading and queries](../../../docs/sdk-reading.md),
154
+ [values](../../../docs/sdk-values.md),
155
+ [editing one record](../../../docs/sdk-record-editing.md).
791
156
 
792
- ```ts
793
- const seen = await db.get(id, { document: true }, signal);
794
- const [validation] = await db.validate([seen], signal);
795
- // validation.id/path/revision identify the actual document validated.
796
- for (const issue of validation.issues) {
797
- console.log(issue.severity, issue.code, issue.location, issue.message);
798
- }
799
- ```
800
-
801
- `validate(refs?, originalSignal?)` returns typed `RecordValidation[]` with real
802
- Core `ValidationIssue`s, including optional location/type name and diagnostic
803
- tier. UUID/path selections validate current native records; a `RecordView`
804
- selection also requires the result to match that captured view's revision.
805
- Changed revisions refuse with `record_validation_stale`; the SDK never refreshes
806
- a witness or turns missing/refused/malformed/partial results into `[]`.
807
- Order and duplicate selections are preserved. The original signal fences both
808
- dispatch and final delivery, including an empty batch. Ordinary SDK read transport
809
- policy is unchanged; no validation-specific retry or fallback is added.
810
-
811
- This validates persisted/current local-native documents (including pending
812
- changes), **not an unsaved draft or permission to submit/CAS a write**. A returned
813
- revision records the version examined, not a promise that it remains current
814
- after delivery. No types/contracts are installed implicitly. Older producers
815
- without this operation remain real refusals, not empty success.
816
-
817
- Selection count is at most 1000; paths are nonempty and at most 4096 UTF-8 bytes.
818
- Native validation bounds examined documents/read work and refuses oversized
819
- results (1 MiB/4096 issues/65536 nodes/depth 32). Omitted refs request a bounded
820
- whole-collection inventory (at most 1000 records); some cross-record uniqueness
821
- checks require that inventory even for an explicit record. Over-bound work is
822
- `too_large`, never partial diagnostics. These are read/serialization bounds, not
823
- a native peak-heap/CPU, app-intake or UI acceptance certificate.
824
-
825
- ## Shared read helpers
826
-
827
- ```ts
828
- const records = await db.readMany(refs, { effective: true }, signal, {
829
- concurrency: 8,
830
- });
831
- for await (const page of db.queryPages(query, include, signal)) {
832
- displayPage(page); // retains complete/asOf/diagnostics, not only records
833
- }
834
- ```
157
+ ## Status
835
158
 
836
- `readMany(refs, include?, signal?, options?)` makes ordinary `get` calls and
837
- returns genuine `RecordView` values in input order. Duplicate selections retain
838
- separate calls and output slots. Up to 1000 selections are allowed; concurrency
839
- is an integer 1..16 (default 8). Path selectors must be nonempty and at most
840
- 4096 UTF-8 bytes. UUIDs (including a supplied view's UUID), paths, Include and
841
- concurrency are captured before the first await. A view's old path/revision is
842
- not asserted current and a partial input is never promoted to a native witness.
843
-
844
- Missing/refused/error reads fail the entire batch with the first observed error,
845
- not omitted rows or partial success. Scheduling stops; already-started reads
846
- settle before that error is delivered. The original signal fences dispatch and
847
- final delivery, including late backend replies. There is no helper-level retry,
848
- refresh, fallback, replacement identity or cancellation of the caller's signal;
849
- the ordinary SDK `get` transport policy is unchanged. Request/in-flight bounds
850
- are not a peak-heap or returned-byte budget. Use explicit Include and bounded
851
- selections when hydrating bodies/documents. Multiple gets are **not a single
852
- native snapshot**; callers still check identity/source-revision witnesses.
853
-
854
- `queryPages(query, include?, signal?, options?)` delegates **exactly** to `pages`
855
- and returns the same whole-page iterator. No records are flattened and no reset
856
- is added. Root exports `readMany(client, ...)`, `queryPages(client, ...)` and
857
- `ReadManyOptions` are also available.
858
-
859
- ## Feature negotiation and operation mapping
860
-
861
- Use the existing `connect({ features: [...] })` / `client.hello.features` surfaces.
862
- Keep the exact factory-owned request list, not a later-mutated options array:
159
+ `snapshot.sync` is the one status to show for the open collection: saved,
160
+ saving, offline, reconnecting, or needing the person. The app does not combine
161
+ network state and pending writes itself.
863
162
 
864
163
  ```ts
865
- const requestedFeatures = Object.freeze(["presence"]);
866
- const client = await connect({ connector, app, features: [...requestedFeatures], signal });
867
- function negotiatedMarker(name: string) {
868
- // Access the current hello; session errors propagate, never become false.
869
- const granted = client.hello.features;
870
- if (!requestedFeatures.includes(name)) return "not_requested";
871
- return granted.includes(name) ? "negotiated" : "not_negotiated";
872
- }
164
+ const { sync } = mdbase.getSnapshot();
165
+ if (sync?.state === "saved") allowClose();
873
166
  ```
874
167
 
875
- While the initial hello is pending, a requested marker is **requested / pending**,
876
- not unsupported. A successful hello grants only the requested-supported
877
- intersection, not a complete catalog. An absent *unrequested* marker is not
878
- negative evidence. Failed negotiation, no current session, connection/refusal
879
- errors or cancellation stay errors; do not substitute `false` or a stale hello
880
- from another session. No new probe or feature-discovery RPC is needed.
168
+ See [sync status](../../../docs/sdk-sync-status.md).
881
169
 
882
- The current native Replica source admits `presence`, bare `attachment-v1` codec
883
- support, and qualified `attachment-v1.read` / `attachment-v1.materialize`
884
- directions where that replica supports them. Bare codec support does not grant a
885
- direction; this producer does not grant `attachment-v1.write`. This is a source
886
- inventory, not deployed runtime/transport/app acceptance. A testing replica's
887
- advertised markers are not a native capability certificate.
170
+ ## Problems
888
171
 
889
- Legacy Connect labels are not native feature names or negotiation aliases:
890
-
891
- | Legacy probe | Public SDK mapping | What it does **not** prove |
892
- |---|---|---|
893
- | `query-metadata-v1` (Reader and Writer discovery) | `query` / `queryPages` with canonical Core `select` and explicit Include; typed `QueryResult` / `RecordView.values`, columns and page metadata | No legacy `output: metadata` mode, metadata-only SQL/performance guarantee or native feature marker |
894
- | `read-many-documents-v1` (Reader hydration) | `readMany(refs, include, originalSignal)`; ordinary bounded `get` calls | No native bulk opcode, transaction or same-snapshot / shared-`asOf` proof |
895
- | `query-record-revisions-v1` (legacy performance fixtures, not a Reader/Writer product probe) | Genuine mandatory `RecordView.id`, `.path` and `.revision` | No confirmed save, currentness after delivery, full edit base or draft/CAS authorization |
896
-
897
- Writer's legacy changed-path `readMany` call has no bulk-feature probe. The next
898
- Reader/Writer adapters do not require legacy feature probes: use their public
899
- SDK operations and preserve actual errors. These mappings do not add an
900
- app-specific engine, legacy protocol fallback, automatic query reset or new
901
- permissions.
902
-
903
- For discovery without bodies/documents, use explicit `{ body: false, document:
904
- false }` Include and the intended canonical query selection. Retain whole pages,
905
- `complete`, `asOf`, diagnostics and opaque cursors; unsupported semantics or
906
- insufficient native budgets refuse, not approximate or empty success. Discovery
907
- and hydration can observe different cuts: recheck actual ID, provider/source and
908
- revision witnesses rather than treating multiple gets as one snapshot.
909
-
910
- `client.hello.grant.capabilities` and role are hello-time permission snapshots,
911
- **not current authorization or feature support**. READ uses `collection.read`;
912
- ordinary native RPC reauthorization remains authoritative. `describe()` inspects
913
- catalog/types/contracts, not a feature catalog. Neither a successful grant nor a
914
- negotiated marker overrides a later native refusal. Keep the original signal and
915
- problem; do not turn errors into negative capabilities or fabricated diagnostics.
916
-
917
- ## People and canonical contract inspection
172
+ Every problem the SDK reports has a title, a message and an action to branch
173
+ on. `phase.problem` is already described. For an error the app catches:
918
174
 
919
175
  ```ts
920
- import { MdbasePeopleClient } from "@mdbase-dev/sdk";
921
- // Inside the trusted owned Worker, after collection adoption and CP transport pinning.
922
- // host is the existing AppWebCloudCopyHost; its session/credential stays private.
923
- const metadata = host.peopleAuthority();
924
- const people = new MdbasePeopleClient(db, metadata);
925
- const directory = await people.directory({ members: "if-approved", signal });
926
- directory.account; // public exact issuer/subject/name/account UUID
927
- directory.me; // linked, unlinked, ambiguous, or invalid; never name/email inference
928
- directory.people; // complete native mdbase.person 2.0.0 inventory
929
- // host.close() retires metadata before native/SQL shutdown.
930
- ```
931
-
932
- The host returns only a frozen read-only metadata view, not a session or bearer
933
- getter. Send only public directory projections over the Worker channel. Other
934
- trusted hosts owning a genuine registered-device session can construct
935
- `AppCpPeopleAuthority` internally; callers must never reconstruct it from receipts.
936
-
937
- `current()` and `members()` read fixed CP metadata endpoints; `directory()` uses
938
- Core's canonical resolved mappings, defaults and validation through
939
- `db.queryContract({ id, version }, { pageSize, cursor, signal })`. It does not
940
- recreate contract semantics from raw frontmatter. The directory checks CP/native
941
- collection binding and consumes every native continuation under one session,
942
- `asOf` and contract digest; stale/incomplete/oversized inventories fail as a whole.
943
- A full unindexed window refuses with `contract_query_cursor_required`, not a
944
- fabricated cursor or partial result. A fresh absent registered Person contract
945
- means unlinked; disappearance after any page is an error. Invalid claiming
946
- records take precedence over an otherwise linked match. Optional members are
947
- omitted only for explicit permission decline (or `members: "omit"`), never scope,
948
- revocation, integrity or network errors. Old producers refuse the additive
949
- version-one method, without an SDK projection fallback. No record path/payload
950
- or key is sent to the metadata authority.
951
-
952
- ## Query cursor resets
953
-
954
- `pages(query, include?, signal?, options?)` repeats the original query with the
955
- replica's opaque cursor. By default, typed `invalid_request/fix_request` reasons
956
- `cursor_expired` and `cursor_stale` are thrown unchanged. There is no offset
957
- fallback or automatic mixing of already-yielded pages with a fresh query.
958
-
959
- To opt in to **one restart per iterator**, clear your accumulated/displayed
960
- paging state in the awaited `onReset` callback:
176
+ import { describeError } from "@mdbase-dev/sdk";
961
177
 
962
- ```ts
963
- for await (const page of db.pages(query, include, signal, {
964
- onReset: async ({ reason, pagesYielded, signal }) => {
965
- await clearDisplayedPages(); // completes BEFORE the fresh first-page RPC
966
- },
967
- })) {
968
- displayPage(page);
178
+ try {
179
+ await db.get(id);
180
+ } catch (error) {
181
+ const problem = describeError(error); // null for a cancellation
182
+ if (problem) show(problem.title, problem.message);
969
183
  }
970
184
  ```
971
185
 
972
- Reset clears all earlier pages even if expiry keeps the same `asOf`. The SDK
973
- strips the cursor and preserves the captured original offset, limit, query and
974
- include on restart. Callback failure, cancellation, or a second cursor refusal
975
- stops the iterator. Malformed/foreign/conflicting cursors, READ denial and other
976
- errors never trigger this callback. Native cursor lifetime/clock/head guarantees
977
- remain the replica's responsibility; these SDK tests do not qualify that producer.
186
+ Pass `messages` to `createMdbase` and `describeError` to put the copy in the
187
+ person's language; see [problem copy](../../../docs/sdk-problem-copy.md).
978
188
 
979
- ## Static key custody
189
+ ## Testing
980
190
 
981
- Browser extensions should explicitly require non-extractable custody **before consent**:
191
+ `@mdbase-dev/sdk/testing` runs the app against an in-memory collection, with no
192
+ network, Worker or sign-in:
982
193
 
983
194
  ```ts
984
- const key = await loadOrCreateClientKey("reader", {
985
- storage: indexedDbKeyStorage("reader-keys"),
986
- requireNonExtractable: true,
195
+ import { createTestApp } from "@mdbase-dev/sdk/testing";
196
+
197
+ const app = await createTestApp({
198
+ phase: "ready",
199
+ collections: [{ name: "Notes", records: [{ path: "hello.md", body: "Hi" }] }],
987
200
  });
201
+ render(<App mdbase={app.mdbase} />);
988
202
  ```
989
203
 
990
- Import `indexedDbKeyStorage` from the SDK. Unsupported X25519 or an existing
991
- raw/extractable identity fails closed; existing identities are never silently
992
- replaced. Reauthorization must be explicit. Without this option, the legacy raw
993
- fallback remains available. Non-extractability does not prevent compromised
994
- extension code from using DH, and is not hardware-backed custody.
204
+ See [testing an app](../../../docs/sdk-testing.md).
995
205
 
996
- Built-in stores return only committed identities and atomically choose one
997
- first-creation winner. Custom persistent stores shared across contexts must
998
- implement `KeyStorage.putIfAbsent`; same-store in-process creation is coalesced.
999
- Keep the key in the extension origin, not a content script or unrestricted DH bridge.
206
+ ## Where the app runs
1000
207
 
1001
- `PLAYWRIGHT_MODULE=<module> CHROMIUM_EXECUTABLE=<browser> node scripts/keys-mv3-smoke.mjs`
1002
- runs the actual SDK in a fresh isolated MV3 profile: page/worker races, export
1003
- refusal, real DH, existing-key refusal, late IDB abort, worker wake and browser reopen.
208
+ | Environment | Guide |
209
+ |---|---|
210
+ | A web app | This page, then [opening a cloud copy](../../../docs/sdk-opening.md) and [build environments and localhost](../../../docs/sdk-environments.md) |
211
+ | A browser extension, or several bundles on one origin | [Shared session](../../../docs/sdk-shared-session.md) |
212
+ | A native shell | [Native shells](../../../docs/sdk-native-shells.md) |
213
+ | A document embedded in another app | [Running inside another app's document](../../../docs/sdk-native-shells.md#running-inside-another-apps-document) |
214
+ | A page without a bundler | [Classic-script bundle](../../../docs/sdk-browser-bundle.md) |
215
+ | A server, a CLI, or a plugin with its own connection | [Bringing your own connection](../../../docs/sdk-thin-client.md) |
1004
216
 
1005
- ## Checks
217
+ ## More
1006
218
 
1007
- ```sh
1008
- npm ci && npm run typecheck && npm test && npm run build && npm run bundle-boundaries # or: cargo xtask sdk
1009
- ```
219
+ | Topic | Page |
220
+ |---|---|
221
+ | Private collections | [sdk-private-collections.md](../../../docs/sdk-private-collections.md) |
222
+ | File access and asking for more | [sdk-access.md](../../../docs/sdk-access.md) |
223
+ | Collection setup, deletion and type packs | [sdk-collection-setup.md](../../../docs/sdk-collection-setup.md) |
224
+ | Several vaults on one origin | [sdk-multiple-vaults.md](../../../docs/sdk-multiple-vaults.md) |
225
+ | Validation and definition errors | [sdk-validation.md](../../../docs/sdk-validation.md) |
226
+ | Saved views | [sdk-saved-views.md](../../../docs/sdk-saved-views.md) |
227
+ | People and contracts | [sdk-people.md](../../../docs/sdk-people.md) |
228
+ | Read options | [sdk-read-options.md](../../../docs/sdk-read-options.md) |
229
+ | Feature negotiation | [sdk-features.md](../../../docs/sdk-features.md) |
230
+ | Which entry to import | [sdk-entries.md](../../../docs/sdk-entries.md) |
231
+
232
+ ## Entries
233
+
234
+ | Import | For |
235
+ |---|---|
236
+ | `@mdbase-dev/sdk` | An app: `createMdbase` and the collection API |
237
+ | `@mdbase-dev/sdk/thin-client` | Code that makes its own connection: `connect` and the transports |
238
+ | `@mdbase-dev/sdk/testing` | Tests: `createTestApp`, `MemoryReplica` |
239
+ | `@mdbase-dev/sdk/describe` | `describeError` alone, for a page that does not load the SDK |
240
+ | `@mdbase-dev/sdk/manifest` | Build scripts: validate `mdbase-app.json` |
241
+ | `@mdbase-dev/sdk/browser` | The classic-script bundle |
242
+
243
+ The package has other entries for hosts and build tools. The layout table in
244
+ [sdk-development.md](../../../docs/sdk-development.md) lists them.
245
+
246
+ ## Working on this package
1010
247
 
1011
- `npm run bundle-boundaries` fails when either entry bundles the Ajv compiler
1012
- (manifest validators are precompiled in connect-protocol), the thin client
1013
- bundles yaml, or either bundles `app-grant`.
248
+ Source layout and checks: [sdk-development.md](../../../docs/sdk-development.md).