diff --git a/public/examples/sandbox-quickstart.mjs b/public/examples/sandbox-quickstart.mjs index f186ef4..0fb24c9 100644 --- a/public/examples/sandbox-quickstart.mjs +++ b/public/examples/sandbox-quickstart.mjs @@ -1,50 +1,55 @@ -import { unwrapOperation } from "@mdbase/connect"; -import { createSandbox } from "@mdbase/connect-dev"; +import { createSandbox } from "@mdbase-dev/connect-dev"; const { client, transport } = createSandbox({ - records: [ - { - path: "tasks/first.md", - types: ["task"], - frontmatter: { - type: "task", - title: "Read the collection", - completed: false - } + records: [{ + path: "tasks/first.md", + types: ["task"], + frontmatter: { + type: "task", + title: "Read the collection", + completed: false } - ] + }] }); -const first = unwrapOperation(await client.read({ path: "tasks/first.md" })); +// Every operation returns a ConnectOutcome: check ok, then use value or problem. +function required(outcome) { + if (!outcome.ok) throw new Error(`${outcome.problem.code}: ${outcome.problem.message}`); + return outcome.value; +} -const created = unwrapOperation( - await client.create({ +const first = required(await client.read({ path: "tasks/first.md" })); + +const created = required(await client.create({ + type: "task", + path: "tasks/second.md", + frontmatter: { type: "task", - path: "tasks/second.md", - frontmatter: { - type: "task", - title: "Update one record", - completed: false - } - }) -); - -const updated = unwrapOperation( - await client.update({ - path: created.path, - patch: { completed: true }, - if_revision: created.revision - }) -); - -const tasks = unwrapOperation( - await client.query({ - types: ["task"], - limit: 20 - }) -); + title: "Update one record", + completed: false + } +})); + +const updated = required(await client.update({ + path: created.path, + patch: { completed: true }, + ifRevision: created.revision +})); + +// Reusing the old revision is refused instead of overwriting the update. +const stale = await client.update({ + path: created.path, + patch: { completed: false }, + ifRevision: created.revision +}); + +const tasks = required(await client.query({ + types: ["task"], + limit: 20 +})); console.log(`Read: ${first.frontmatter.title}`); console.log(`Updated: ${updated.path} (completed: ${updated.frontmatter.completed})`); +console.log(`Stale revision: ${stale.ok ? "accepted" : stale.problem.code}`); console.log(`Task records: ${tasks.results.length}`); console.log(`Markdown paths: ${transport.snapshot().map((record) => record.path).join(", ")}`); diff --git a/src/pages/sdk/api/index.astro b/src/pages/sdk/api/index.astro index a5f8e09..c1c755a 100644 --- a/src/pages/sdk/api/index.astro +++ b/src/pages/sdk/api/index.astro @@ -3,48 +3,57 @@ import DocsLayout from "../../../components/DocsLayout.astro"; import CodeBlock from "../../../components/CodeBlock.astro"; const constructor = `new MdbaseConnect({ - serverUrl: string, - manifest?: MdbaseAppManifest | string, - redirectUri?: string, + serverUrl: string | URL, + manifest?: MdbaseAppManifest | string | URL, + redirectUri?: string | URL, storage?: Storage, relayEncryption?: "required" | "disabled", keyStore?: GrantKeyStore, + identityStore?: ApplicationIdentityStore, directAccess?: "auto" | "disabled", - loopbackUrl?: string, - navigate?: (url: string) => void | Promise + loopbackUrl?: string | URL, + navigate?: (url: string) => void | Promise, + timeouts?: { + requestMs?: number | null, + watchStartMs?: number | null, + fileIndexMs?: number | null, + uploadMs?: number | null, + syncMs?: number | null + } })`; -const browserLocation = `const collectionLocation = - new MdbaseBrowserLocation(manager, { +const session = `const session = mdbase.application({ + selection: new MdbaseBrowserSelection({ collectionParameter: "collection", fallbackPath: "/" - });`; + }) +});`; -const error = `try { - const result = unwrapOperation(await connection.update(input)); -} catch (error) { - if (error instanceof MdbaseOperationValidationError) { - renderDiagnostics(error.diagnostics); - } else if (error instanceof MdbaseConnectError) { - renderTransportError(error.code, error.recovery); +const error = `const updated = await connection.update(input); +if (!updated.ok) { + if (updated.problem.code === "operation_invalid") { + renderDiagnostics(updated.problem.details.diagnostics); + } else { + renderProblem(updated.problem.code, updated.problem.recovery); } }`; ---

MdbaseConnect constructor

@@ -103,6 +112,16 @@ const error = `try { location.assign Open authorization, including in a native system browser + + identityStore + IndexedDB + Persist the application's signing identity + + + timeouts + Per workload + Default budgets for requests, watch start-up, file indexing, uploads and sync; null disables one deliberately + @@ -115,7 +134,12 @@ const error = `try { storage or key adapter reports custom.

-

Registration and authorization

+

MdbaseConnect methods

+

+ Every asynchronous method accepts a final{" "} + ConnectRequestOptions argument, with signal and + {" "}timeoutMs, and resolves to a ConnectOutcome. +

@@ -125,46 +149,23 @@ const error = `try { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + +
register()Promise<Application>Load, canonicalize, and register the bundled manifest
authorize(options?)Promise<MdbaseAuthorizationResult>Navigate for web/native, or resolve after short-code approval for portable files
completeAuthorization(callbackUrl?)MdbaseAuthorizationResultComplete a web or native callback and return its bound connection
connections()MdbaseConnectionInfo[]List every saved collection authorization for this application
connection(collectionId)MdbaseConnection | nullResolve one permanently collection-bound client
onConnectionsChange(listener)Unsubscribe functionObserve additions, removal, refresh, and cross-tab storage changes
forgetAll()voidForget every locally retained connection for this application
application(options)MdbaseApplicationSessionThe ordinary application lifecycle entry point
register(options?)ConnectOutcome<Application>Load, canonicalize, and register the bundled manifest
manifest(options?)ConnectOutcome<MdbaseApplicationManifest>The loaded, validated manifest
authorize(options?)ConnectOutcome<MdbaseAuthorizationOutcome>Registry-level authorization; applications normally use the session
completeAuthorization(callbackUrl?, options?)ConnectOutcome<MdbaseAuthorizationResult>Complete a web or native callback
connections()MdbaseConnectionInfo[]Every saved collection authorization for this application
connection(collectionId)MdbaseConnection | nullOne permanently collection-bound client
unavailableReason(collectionId)MdbaseUnavailableReason | nullWhy a saved collection cannot be used
onConnectionsChange(listener)Unsubscribe functionObserve additions, removal, refresh, and cross-tab storage changes
environment()MdbaseConnectEnvironmentDistribution, origin, and credential storage in effect
forgetAll()voidForget every locally retained connection for this application

Portable authorization options

- authorize() accepts onDeviceCode to report + authorize() on the manager or session accepts + {" "}onDeviceCode to report {" "}userCode, verificationUri, {" "}verificationUriComplete, expiresAt, and {" "}intervalSeconds. Supply openVerification to own @@ -172,27 +173,28 @@ const error = `try { discard the unapproved key.

-

MdbaseBrowserLocation

- +

MdbaseApplicationSession

+

- Keep one location helper beside the application's stable - {" "}MdbaseConnect manager. It treats the explicit URL - identity as authoritative and selects a saved fallback only when exactly - one connection exists. + One session owns collection selection, authorization, setup checks, and a + snapshot. MdbaseBrowserSelection keeps the selected + collection in the URL and follows back and forward navigation; native + shells supply their own selection adapter.

- - - - - - - - + + + + + + + + +
MethodPurpose
selectedCollectionId()Read the explicit bookmark identity, including one that is not currently authorized
activeConnection()Resolve the bookmarked connection or the sole saved fallback
selectConnection(id, options?)Push or replace a cleaned bookmark URL
authorizationReturnTo()Return the current app-local path after removing temporary OAuth parameters
completeAuthorization(callbackUrl?)Complete PKCE and restore a safe same-origin URL for the approved collection
isAuthorizationCallback(url)Recognize browser and native callback URLs with an authorization result
clearAuthorizationCallback(returnTo?)Remove callback parameters after denial or failure
onChange(listener)Observe saved-connection changes plus browser back and forward navigation
start(options?)Load the manifest and restore the selected collection; concurrent callers share the work
subscribe(listener), getSnapshot()External-store state: unselected, authorization_required, checking_setup, setup_review_required, ready, unavailable, blocked, and start-up states
connection()The ready collection's MdbaseConnection, or null
authorize(target, options?)Authorize "choose", "selected", or {`{ collectionId }`}
completeAuthorization(callbackUrl?, options?)Complete the callback; the snapshot becomes ready
ensureCapabilities(capabilities, options?)Request declared optional capabilities; unchanged when already granted
applyCollectionSetup(options?)Apply reviewed collection setup
select(collectionId), clearSelection(), forget(collectionId)Change or forget the selection
destroy()End the session
@@ -214,27 +216,27 @@ const error = `try { Method - Required operation + Capability Notes - describe()describeTypes, contracts, schemas, settings, and supported operations - changes(input?)changesOne resumable cursor page - watch(options?)changesAsync iterator with retry and reset status - read({ path })readEffective and raw frontmatter plus revision - query(input?)queryOne query page - queryPages(input?, options?)querySnapshot-consistent async pages - queryAll(input?, options?)queryLoad every page into one result - create(input)createTyped frontmatter and optional body - update(input)updateCanonical patch and optional revision - preflightRename(input)renameRead-only reference impact - rename(input)renameMove with optional reference updates - renameWithProgress(input, options)renamePreflight reuse, cancellation, and outcome recovery - preflightDelete(input)deleteRead-only backlink impact - delete(input)deleteDelete with optional backlink check - deleteWithProgress(input, options)deletePreflight reuse, cancellation, and outcome recovery - validate(input?)validateCanonical collection validation envelope + describe()collection.readTypes, contracts, schemas, settings, and supported operations + changes(input?)collection.readOne resumable cursor page + watch(options?)collection.readBounded start-up, then a subscription with retry, status, and close() + read({ path })collection.readEffective and raw frontmatter plus revision; file_not_found when missing + query(input?)collection.readOne query page + queryPages(input?, options?)collection.readSnapshot-consistent pages, one outcome each + queryAll(input?, options?)collection.readLoad every page into one result + create(input)records.createTyped frontmatter and optional body + update(input)records.editCanonical patch, optional body, and ifRevision; concurrent_modification when stale + preflightRename(input)records.editRead-only reference impact + rename(input)records.editMove with optional reference updates + renameWithProgress(input, options)records.editPreflight reuse, cancellation, and outcome recovery + preflightDelete(input)records.deleteRead-only backlink impact + delete(input)records.deleteDelete with optional backlink check + deleteWithProgress(input, options)records.deletePreflight reuse, cancellation, and outcome recovery + validate(input?)collection.readCanonical collection validation result @@ -248,6 +250,19 @@ const error = `try { updateType(). Updates require the source revision.

+

Record sessions

+

+ connection.records.open(path, options?) returns a lease on + the one shared MdbaseRecordSession for that record; + {" "}connection.records.follow(watch) keeps open sessions + current. Sessions provide setBody(), + {" "}patchFrontmatter(), save(), + {" "}flush(), refresh(), resolve(), + {" "}discard(), subscribe() and + {" "}getSnapshot(). See Editing + records. +

+

Notifications and timers

@@ -272,38 +287,45 @@ const error = `try { - - - + + - - + + +
info()Read collection ID, display name, operations, scope, route, and direct status
authorizationCapabilities(required)Compare required and granted operations for this collection
hasOperations(required)Check an operation subset
requestOperations(required, options?)Request the least-privilege union for this same collection
authorizationCapabilities(required)Compare required and granted operations (legacy v1 grants)
requestCapabilities(capabilities, options?)Request more declared capabilities for this same collection
forget()Forget only this locally retained connection
onConnectionChange(listener)Subscribe and receive an unsubscribe function
checkDirectAccess()Read same-computer availability silently
requestDirectAccess()Prompt from a user gesture where required
disableDirectAccess()Persist a relay-only preference for this app
sync()Return one credential-hiding sync transport for a remote, direct, or relayed authority, or null
pendingMutation()Inspect an interrupted encrypted mutation
resumePendingMutation()Recover its exact durable connector receipt
pendingMutations(), pendingMutation(requestId)Durable handles for writes whose outcome is unknown, including after a reload
pending.recover(options?)Resend the exact original request; never a new write
filesUpload, list, download, move, and delete collection files

MdbaseCollectionClient

- Construct with any MdbaseCollectionTransport. It exposes the + Import from @mdbase-dev/connect/advanced and construct with + any MdbaseCollectionTransport. It exposes the record, query, view, type, validation, and timer methods above. Its surface is limited to collection behavior. Domain packages should prefer this dependency when they use collection operations alone.

-

Errors and helpers

- +

Outcomes and helpers

+

+ Expected failures are ConnectOutcome data: + {" "}{`{ ok: false, problem }`} with a stable + {" "}code, a category, a suggested + {" "}recovery, and code-specific details. +

+ - - - + + + diff --git a/src/pages/sdk/authorization/index.astro b/src/pages/sdk/authorization/index.astro index c982c0d..680b7c7 100644 --- a/src/pages/sdk/authorization/index.astro +++ b/src/pages/sdk/authorization/index.astro @@ -2,68 +2,60 @@ import DocsLayout from "../../../components/DocsLayout.astro"; import CodeBlock from "../../../components/CodeBlock.astro"; -const stepUp = `const required = ["read", "query", "update"] as const; -const capability = connection.authorizationCapabilities([...required]); +const stepUp = `const granted = await session.ensureCapabilities(["records.create"]); +if (!granted.ok) renderProblem(granted.problem);`; -if (!capability.sufficient) { - await connection.requestOperations([...required], { - returnTo: collectionLocation.authorizationReturnTo() - }); -}`; - -const listen = `const stop = collectionLocation.onChange(({ connection }) => { - if (!connection) { - renderDisconnected(); - return; +const listen = `const stop = session.subscribe(() => { + const snapshot = session.getSnapshot(); + switch (snapshot.status) { + case "ready": + renderConnection({ collectionId: snapshot.collectionId, route: snapshot.info.route }); + break; + case "authorization_required": + renderReconnect(); + break; + case "unavailable": + renderUnavailable(snapshot.reason); + break; + default: + renderStatus(snapshot.status); } - - const info = connection.info(); - renderConnection({ - collectionId: info.collectionId, - route: info.route, - operations: info.operations - }); }); - // Call stop() when the owning UI is destroyed.`; -const recover = `try { - await connection.update(input); -} catch (error) { - if (error instanceof MdbaseConnectError) { - switch (error.recovery) { - case "reauthorize": - await connection.requestOperations(["update"]); - break; - case "refresh": - await refreshVisibleState(); - break; - case "resolve_outcome": - await connection.resumePendingMutation(input); - break; - } - } - throw error; +const recover = `const updated = await connection.update(input); +if (updated.ok) return; +switch (updated.problem.recovery) { + case "reauthorize": + await session.authorize("selected"); + break; + case "refresh": + await refreshVisibleState(); + break; + case "resolve_outcome": + for (const pending of connection.pendingMutations()) await pending.recover(); + break; + default: + renderProblem(updated.problem); }`; const portableAuthorize = `const controller = new AbortController(); - -const { connection } = await connect.authorize({ - operations: ["describe", "read", "query"], +const authorized = await session.authorize("choose", { onDeviceCode: ({ userCode, verificationUriComplete }) => { renderApprovalCode(userCode, verificationUriComplete); }, signal: controller.signal -});`; +}); +if (!authorized.ok) renderProblem(authorized.problem);`; --- Use the flow selected by the manifest

Web and native-shell manifests use an authorization-code redirect with - PKCE. authorize() navigates away, and the callback route calls - {" "}completeAuthorization(). + PKCE. session.authorize() navigates away, and the callback + route calls session.completeAuthorization().

A distribution: "portable" manifest uses short-code device authorization with PKCE and a P-256 application key. - authorize() opens the approval page, polls at the server - interval, and resolves with the collection-bound connection after approval. + session.authorize() opens the approval page, polls at the + server interval, and resolves after approval.

@@ -101,79 +93,66 @@ const { connection } = await connect.authorize({ for the complete downloaded-file boundary.

-

Choose operations by feature

+

Declare capabilities by feature

+

+ The manifest's requirements.capabilities lists what the + application may do. required groups are always requested; + {" "}optional groups are requested when a feature needs them. + An application never requests a capability its manifest does not declare. +

ExportPurpose
unwrapOperation()Return a valid result or throw validation diagnostics
MdbaseConnectErrorTransport, authorization, routing, and request errors with recovery metadata
MdbaseOperationValidationErrorInvalid canonical operation envelope
ConnectOutcomeThe result type of every asynchronous operation
externalStore()Adapt a session to useSyncExternalStore
MdbaseConnectErrorCarries a problem through custom transports and adapters
isRetryableConnectError()Classify transient Connect failures
parseMdbasePushPayload()Validate a browser push envelope
parseMdbaseNativeNotificationData()Validate string-valued FCM/APNs data
- - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + +
FeatureTypical operationsCapabilityAllows
Browse recordsdescribe, read, query
Live refreshchanges
Edit recordscreate, update
Move or remove recordsrename, delete
Use saved viewslist_views, execute_view
Administer saved view sourceread_view_source, create_view_source, update_view_source, delete_view_source
Administer collection typesread_type, create_type, update_type
Authority timerslist_timers, put_timer, cancel_timer, reconcile_timers
collection.readDescribe the collection, read, query and watch records, use saved views, read types, validate
records.createCreate records
records.editUpdate and rename records
records.deleteDelete records
views.manageCreate, update and delete saved view sources
definitions.manageCreate and update types, assess and apply type packs
background.scheduleAuthority timers
offline.replicaOffline sync
-

Request additional operations at the point of use

+

Request optional capabilities at the point of use

- Begin with the operations used by the current feature. Inspect the current - gap when a user opens an editing or administration feature. + Begin with the required capabilities. When a user opens a feature that + needs an optional one, ensure it then.

- requestOperations() is a no-op when the current grant is - already sufficient. Otherwise it asks for the least-privilege union of the - existing operations and the new requirements. + ensureCapabilities() returns unchanged when the + current grant already covers the request. Otherwise it asks for the + existing grant plus the new capabilities, and refuses capabilities the + manifest does not declare.

Render current connection state

- The route is direct, relay, or - {" "}hosted. Display it as status information. The SDK selects - the route. The browser location subscription also reports back and forward - selection changes. A null connection means the bookmarked - collection has no usable authorization. + The session snapshot names its state: unselected, + {" "}authorization_required, checking_setup, + {" "}setup_review_required, ready, + {" "}unavailable, blocked, and the start-up + states. The route is direct, relay, or + {" "}hosted; display it as status information, as the SDK + selects it. Browser back and forward selection changes also notify + subscribers.

Use structured recovery actions

- MdbaseConnectError includes a machine-readable code, current - grant information where relevant, and a recovery action: - retry, reauthorize, refresh, - resolve_outcome, fix_request, or{" "} - none. + A failed outcome's problem has a machine-readable + {" "}code, a category, and a suggested + {" "}recovery, such as retry, + {" "}reauthorize, refresh, + {" "}resolve_outcome, resolve_conflict, + {" "}fix_request, or contact_support.

@@ -188,7 +167,7 @@ const { connection } = await connect.authorize({

Disconnecting an application

connection.forget() clears only that collection's local - authorization state. manager.forgetAll() clears the saved set. + authorization state. mdbase.forgetAll() clears the saved set. Neither replaces user-controlled revocation at the collection authority. Provide a clear path to the Connect controller when a user needs to review, narrow, pause, or revoke a grant. diff --git a/src/pages/sdk/connect-quickstart/index.astro b/src/pages/sdk/connect-quickstart/index.astro index c4a20df..68074b5 100644 --- a/src/pages/sdk/connect-quickstart/index.astro +++ b/src/pages/sdk/connect-quickstart/index.astro @@ -11,29 +11,41 @@ const manifest = `{ "http://localhost:5173/auth/mdbase/callback" ], "requirements": { + "access": "full_collection", "contracts": [ - { "id": "workout.record", "version": "1.0.0" } - ] + { + "id": "workout.record", + "version": "1.0.0", + "digest": "sha256:1b55e89c59ddeb7d6676af6fdc2792aa07cc78b89ea09f8f95001fad8455a180" + } + ], + "capabilities": { + "contract_version": 2, + "required": [ + "collection.read", + "records.edit" + ] + } }, "provisions": { "type_packs": [ { - "provides": [ - { "id": "workout.record", "version": "1.0.0" } - ], "manifest": { "kind": "mdbase.type-pack", "id": "example.workouts", "version": "1.0.0", + "name": "Workouts", "resources": [ { "kind": "contract", + "mode": "managed", "source": "contracts/workout.record.md", "target": "_contracts/workout.record.md", - "digest": "sha256:e0c2f77dd7158ca7e6b52b13da8c306f0a7e1b97582a1024f00ec0cf7fe5f259" + "digest": "sha256:0446184b7f36dd77e244cbe3c4ac97871cf9b78e7ff46a1e3686f542cecb32c2" }, { "kind": "type", + "mode": "seed", "source": "types/workout.md", "target": "_types/workout.md", "digest": "sha256:ff35309cd4598182d2021f698ee85cad4d320d965cd5f7c1bd608ee2eb16505b" @@ -43,12 +55,19 @@ const manifest = `{ "resources": [ { "source": "contracts/workout.record.md", - "document": "---\\nkind: mdbase.contract\\ncontract_type: record\\nid: workout.record\\nversion: 1.0.0\\nrecord_schema:\\n dialect: json-schema-2020-12\\n value:\\n $schema: https://json-schema.org/draft/2020-12/schema\\n type: object\\n additionalProperties: false\\n properties:\\n title: { type: string }\\n completed: { type: boolean, default: false }\\n required: [title]\\n---\\n" + "document": "---\\nkind: mdbase.contract\\ncontract_type: record\\nid: workout.record\\nversion: 1.0.0\\nrecord_schema:\\n dialect: json-schema-2020-12\\n value:\\n type: object\\n additionalProperties: false\\n properties:\\n title: { type: string }\\n completed: { type: boolean, default: false }\\n required: [title]\\n---\\n" }, { "source": "types/workout.md", "document": "---\\nkind: mdbase.type\\nname: workout\\nversion: 1\\nschema:\\n dialect: json-schema-2020-12\\n value:\\n type: object\\n additionalProperties: true\\n properties:\\n title: { type: string }\\n completed: { type: boolean }\\n required: [title]\\nimplements:\\n - contract: workout.record\\n version: 1.0.0\\n fields:\\n title: title\\n completed: completed\\n---\\n" } + ], + "provides": [ + { + "id": "workout.record", + "version": "1.0.0", + "digest": "sha256:1b55e89c59ddeb7d6676af6fdc2792aa07cc78b89ea09f8f95001fad8455a180" + } ] } ] @@ -75,7 +94,7 @@ const validate = `mdbase-connect-dev validate-manifest \\ --allow-local`; const client = `import { - MdbaseBrowserLocation, + MdbaseBrowserSelection, MdbaseConnect, type JsonObject } from "@mdbase-dev/connect"; @@ -85,97 +104,152 @@ export interface Workout extends JsonObject { completed?: boolean; } -const loopback = new Set([ - "localhost", - "127.0.0.1", - "::1" -]).has(location.hostname); +const loopback = new Set(["localhost", "127.0.0.1", "::1"]).has(location.hostname); export const mdbase = new MdbaseConnect({ - serverUrl: loopback - ? "http://127.0.0.1:8787" - : "https://connect.mdbase.dev", - manifest: new URL( - "/.well-known/mdbase-app.json", - location.origin - ).href, - redirectUri: new URL( - "/auth/mdbase/callback", - location.origin - ).href + serverUrl: loopback ? "http://127.0.0.1:8787" : "https://connect.mdbase.dev", + manifest: new URL("/.well-known/mdbase-app.json", location.origin).href, + redirectUri: new URL("/auth/mdbase/callback", location.origin).href }); -export const collectionLocation = - new MdbaseBrowserLocation(mdbase);`; +// One session owns collection selection, authorization and a reactive snapshot. +export const session = mdbase.application({ + selection: new MdbaseBrowserSelection() +});`; -const connectButton = `import { collectionLocation, mdbase } from "./connect"; +const connectButton = `import { session } from "./connect"; -export async function connectCollection() { - await mdbase.authorize({ - operations: ["describe", "read", "query", "create", "update"], - collectionId: - collectionLocation.selectedCollectionId() ?? undefined, - returnTo: collectionLocation.authorizationReturnTo() - }); - // authorize() navigates to Connect and does not return. +export async function connectCollection(): Promise { + // Opens Connect to choose a collection; the manifest declares what is requested. + const authorized = await session.authorize("choose"); + if (!authorized.ok) renderProblem(authorized.problem); }`; -const callback = `import { collectionLocation } from "./connect"; +const buildManifest = `import { writeFile } from "node:fs/promises"; +import { defineTypePack } from "@mdbase-dev/connect-dev"; + +const origin = "http://localhost:5173"; + +const contract = \`--- +kind: mdbase.contract +contract_type: record +id: workout.record +version: 1.0.0 +record_schema: + dialect: json-schema-2020-12 + value: + type: object + additionalProperties: false + properties: + title: { type: string } + completed: { type: boolean, default: false } + required: [title] +--- +\`; + +const type = \`--- +kind: mdbase.type +name: workout +version: 1 +schema: + dialect: json-schema-2020-12 + value: + type: object + additionalProperties: true + properties: + title: { type: string } + completed: { type: boolean } + required: [title] +implements: + - contract: workout.record + version: 1.0.0 + fields: + title: title + completed: completed +--- +\`; + +// Digests are computed from the documents, so the manifest stays reviewable. +const workouts = defineTypePack({ + id: "example.workouts", + version: "1.0.0", + name: "Workouts", + resources: [ + { kind: "contract", mode: "managed", source: "contracts/workout.record.md", target: "_contracts/workout.record.md", document: contract }, + { kind: "type", mode: "seed", source: "types/workout.md", target: "_types/workout.md", document: type } + ] +}); + +const manifest = { + manifest_version: 1, + id: "dev.example.workouts", + name: "Example Workouts", + homepage: origin, + redirect_uris: [\`\${origin}/auth/mdbase/callback\`], + requirements: { + access: "full_collection", + contracts: workouts.provides, + capabilities: { + contract_version: 2, + required: ["collection.read", "records.edit"] + } + }, + provisions: { type_packs: [workouts] } +}; -export async function completeMdbaseCallback() { - const connection = - await collectionLocation.completeAuthorization(); +await writeFile("public/.well-known/mdbase-app.json", \`\${JSON.stringify(manifest, null, 2)}\\n\`);`; - console.log( - "Connected collection:", - connection.collectionId - ); +const wiring = `import { connectCollection } from "./connect-button"; +import { session } from "./connect"; - return connection; -}`; +declare function renderProblem(problem: { message: string }): void; -const wiring = `import { - completeMdbaseCallback -} from "./mdbase-callback"; -import { connectCollection } from "./connect-button"; +session.subscribe(() => render(session.getSnapshot())); + +const started = await session.start({ timeoutMs: 20_000 }); +if (!started.ok) renderProblem(started.problem); + +if (location.pathname === "/auth/mdbase/callback") { + const completed = await session.completeAuthorization(location.href, { timeoutMs: 15_000 }); + if (!completed.ok) renderProblem(completed.problem); +} document .querySelector("[data-connect-mdbase]") - ?.addEventListener("click", () => connectCollection()); + ?.addEventListener("click", () => void connectCollection());`; -if (location.pathname === "/auth/mdbase/callback") { - await completeMdbaseCallback(); -}`; +const operate = `import { session } from "./connect"; -const operate = `import { unwrapOperation } from "@mdbase-dev/connect"; -import { collectionLocation } from "./connect"; +const workout = { id: "workout.record", version: "1.0.0" }; -const collection = collectionLocation.activeConnection(); -if (!collection) throw new Error("Choose a collection."); +export async function completeNextWorkout(): Promise { + const connection = session.connection(); + if (!connection) return; -const page = unwrapOperation(await collection.query({ - contract: { - id: "workout.record", - version: "1.0.0" - }, - limit: 50 -})); - -const first = page.results - .filter((row) => row.completed !== true) - .sort((left, right) => - left.title.localeCompare(right.title) - )[0]; -if (first) { - unwrapOperation(await collection.update({ - path: first.path, + const page = await connection.query({ contract: workout, limit: 50 }); + if (!page.ok) return renderProblem(page.problem); + + const next = page.value.results + .filter((row) => row.effectiveFrontmatter?.completed !== true) + .sort((left, right) => + String(left.effectiveFrontmatter?.title).localeCompare(String(right.effectiveFrontmatter?.title)) + )[0]; + if (!next) return; + + // Read the record to learn its current revision, then update against it. + const current = await connection.read({ path: next.path, contract: workout }); + if (!current.ok) return renderProblem(current.problem); + + const updated = await connection.update({ + path: current.value.path, + contract: workout, patch: { completed: true }, - contract: { - id: "workout.record", - version: "1.0.0" - }, - if_revision: first.revision - })); + ifRevision: current.value.revision + }); + if (!updated.ok && updated.problem.code === "concurrent_modification") { + return completeNextWorkout(); // It changed elsewhere: start again from the current record. + } + if (!updated.ok) renderProblem(updated.problem); }`; --- @@ -189,7 +263,7 @@ if (first) { { href: "#install", label: "2. Add packages" }, { href: "#client", label: "3. Create the client" }, { href: "#authorize", label: "4. Authorize" }, - { href: "#callback", label: "5. Complete callback" }, + { href: "#callback", label: "5. Start and complete" }, { href: "#operate", label: "6. Use operations" }, { href: "#production", label: "Production HTTPS" }, { href: "#success", label: "Expected result" } @@ -233,16 +307,24 @@ if (first) {

1. Add a bundled application manifest

- Save this file at - {" "}public/.well-known/mdbase-app.json. These loopback URLs are - accepted by the local Connect stack. Pass --allow-local to the - validator when checking this development manifest. + Generate the manifest from readable contract and type documents. + {" "}defineTypePack() computes every digest, so nothing is + copied by hand. Run it with Node after adding the packages in step 2. +

+ +

+ It writes public/.well-known/mdbase-app.json. These loopback + URLs are accepted by the local Connect stack; pass + {" "}--allow-local to the validator when checking this + development manifest.

- The contract requirement limits compatible collections. The type pack makes - a collection safely provisionable during approval and does not give the - application general type-management access. + requirements.capabilities declares what the application may + do: read the collection and edit records. The contract requirement limits + compatible collections. The type pack makes a collection safely + provisionable during approval and does not give the application general + type-management access.

2. Add the SDK and validator

@@ -263,37 +345,43 @@ if (first) {

-

3. Create one stable Connect client

+

3. Create one client and one application session

- The manager owns saved authorizations. The location helper owns the - bookmarkable collection ID, browser history changes, and authorization - return cleanup. + MdbaseConnect owns saved authorizations. The application + session owns the selected collection (kept in the URL by + {" "}MdbaseBrowserSelection), authorization, and one snapshot + your interface subscribes to.

4. Start authorization from a user action

Connect presents ready and provisionable collections, then asks the user - to approve the listed operations. Collection records remain private until - approval succeeds. + to approve the capabilities the manifest declares. Collection records + remain private until approval succeeds.

-

5. Complete the exact callback route

- +

5. Start the session and complete the callback

+

- Call this once at the manifest's callback path. PKCE is mandatory. A - successful callback stores the grant-bound authorization and returns a - collection-bound connection. + Start the session once per page. At the manifest's callback path, complete + the authorization with the exact callback URL; PKCE is mandatory. Success + stores the grant-bound authorization and the snapshot becomes + {" "}ready, with a collection-bound connection. Every call + returns a ConnectOutcome: expected failures are data you + render, not exceptions.

- -

6. Query and update with a revision

+

6. Query, then update against a revision

- Query results carry an opaque revision. Passing it as - {" "}if_revision prevents one application from silently - overwriting a newer change. + A record read carries an opaque revision. Passing it as + {" "}ifRevision prevents one application from silently + overwriting a newer change: the update fails with + {" "}concurrent_modification instead. For a record people + type into, use a record session, which handles + revisions, autosave and conflicts for you.

Contract-scoped queries expose normalized mapped fields only. They union @@ -320,15 +408,15 @@ if (first) {

  1. The Connect approval screen names Example Workouts.
  2. The collection chooser marks a matching collection as ready or provisionable.
  3. -
  4. The approval screen lists the five requested operations.
  5. +
  6. The approval screen lists reading the collection and editing records.
  7. The browser returns to /auth/mdbase/callback.
  8. -
  9. The console prints the stable ID of the approved collection.
  10. +
  11. The session snapshot becomes ready for the approved collection.
  12. The first incomplete workout receives completed: true.
Keep the collection ID in application URLs.

- MdbaseBrowserLocation writes + MdbaseBrowserSelection writes {" "}?collection=<id> and follows browser back and forward navigation. Collection IDs are opaque locators and can appear in browser history and logs. They are not credentials. diff --git a/src/pages/sdk/editing/index.astro b/src/pages/sdk/editing/index.astro new file mode 100644 index 0000000..32f1c4c --- /dev/null +++ b/src/pages/sdk/editing/index.astro @@ -0,0 +1,146 @@ +--- +import DocsLayout from "../../../components/DocsLayout.astro"; +import CodeBlock from "../../../components/CodeBlock.astro"; + +const open = `const opened = await connection.records.open("Notes/today.md", { + autosave: { idleMs: 1_000 }, + timeoutMs: 8_000 +}); +if (!opened.ok) return renderProblem(opened.problem); +const { session, release } = opened.value; + +const unsubscribe = session.subscribe(() => render(session.getSnapshot())); +editor.onChange((text) => session.setBody(text)); +properties.onChange((patch) => session.patchFrontmatter(patch));`; + +const follow = `const watch = await connection.watch({}, { timeoutMs: 20_000 }); +if (watch.ok) { + const stopFollowing = connection.records.follow(watch.value); + // On sign-out: stopFollowing(); watch.value.close(); +}`; + +const leave = `const flushed = await session.flush({ timeoutMs: 8_000 }); +if (!flushed.ok) { + if (flushed.problem.code === "concurrent_modification") { + showConflict(session.getSnapshot()); // local body and snapshot.remote + } else { + renderProblem(flushed.problem); + } +} +unsubscribe(); +release();`; + +const resolve = `session.resolve({ keep: "mine" }); // write local changes over the newer record +session.resolve({ keep: "theirs" }); // take the newer record +session.resolve({ body: merged }); // save text the user merged`; + +const react = `const store = externalStore(session); + +function useRecord() { + return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot); +}`; + +const adapter = `import { MdbaseRecordSession } from "@mdbase-dev/connect"; +import type { MdbaseRecordSessionAdapter } from "@mdbase-dev/connect/advanced"; + +const adapter: MdbaseRecordSessionAdapter = { + revision: (note) => note.revision, + body: (note) => note.body, + frontmatter: (note) => note.frontmatter, + write: (base, change, options) => notes.write(base, change, options), // ConnectOutcome + read: (base, options) => notes.read(base.id, options), + recover: (requestId, options) => notes.recover(requestId, options), + isPending: (requestId) => notes.isPending(requestId) +}; +const session = new MdbaseRecordSession(note, adapter, { autosave: { idleMs: 650 } });`; +--- + + +

+ An application that lets people type into a record should not call{" "} + update() on every change. Open the record as a session + instead. The session saves after a pause in typing, never runs two writes + for the same record, and tells your interface what state the record is in. +

+ +

Open a record

+ +

+ open() reads the record and returns a lease: the session and a{" "} + release() function for this view. Every view that opens the + same path shares one session, so an application never has two competing + writers for a record. Each save sends only the body and the frontmatter + keys that changed, checked against the revision they were based on. +

+ +

Stay current while it is open

+ +

+ follow() routes collection changes to open sessions. A record + changed elsewhere is re-read, a renamed record keeps its session at the new + path, and a deleted record keeps its local text. After a change gap every + open record is re-read. The session recognizes its own saves, including + when the saved text comes back normalized before the save has finished, + so they are never mistaken for someone else's edit. +

+ +

States

+
    +
  • saved: the text is the saved record.
  • +
  • unsaved: local changes wait for autosave or flush().
  • +
  • saving: a write is in flight. Typing continues; newer text is saved next.
  • +
  • conflict: the record changed elsewhere in a part edited locally.
  • +
  • recovery: a save's response was lost. The same save is recovered exactly; nothing new is written until it is. This includes a save interrupted by a reload: open() resumes it.
  • +
  • error: the last save failed. Local text is kept, and nothing retries in the background.
  • +
  • deleted: the record no longer exists. Local text is kept.
  • +
+

+ snapshot.problem holds the typed problem behind{" "} + error and recovery. +

+ +

Resolve conflicts

+ +

+ A change made elsewhere is a conflict only when it touched something edited + locally: the body, or a frontmatter key the user changed. Otherwise the + session builds on the newer record without asking. If the other change + produced exactly the local text, the record is simply saved. +

+ +

Leave safely

+ +

+ flush() saves until nothing is left, or returns why it cannot. + Releasing the last view never cancels a save in progress; the session is + dropped once it has nothing left to save. +

+ +

Use it from React

+ + +

Records behind your own storage

+ +

+ Applications that reach records through their own repository or a test + double construct the session with an adapter from{" "} + @mdbase-dev/connect/advanced. Adapters report failures as{" "} + ConnectOutcome values. A file_not_found problem + from read marks the record deleted, and recover{" "} + must continue the original write through its pending mutation, never send + a new one. +

+ diff --git a/src/pages/sdk/index.astro b/src/pages/sdk/index.astro index 204124e..cf14a70 100644 --- a/src/pages/sdk/index.astro +++ b/src/pages/sdk/index.astro @@ -2,13 +2,13 @@ import DocsLayout from "../../components/DocsLayout.astro"; import CodeBlock from "../../components/CodeBlock.astro"; -const seam = `import type { MdbaseCollectionClient } from "@mdbase-dev/connect"; +const seam = `import type { MdbaseCollectionClient } from "@mdbase-dev/connect/advanced"; export async function listOpenTasks(client: MdbaseCollectionClient) { return client.queryAll({ types: ["task"], where: 'status == "open"', - order_by: [{ field: "due", direction: "asc" }] + orderBy: [{ field: "due", direction: "asc" }] }); }`; --- @@ -27,8 +27,9 @@ export async function listOpenTasks(client: MdbaseCollectionClient) {

@mdbase-dev/connect is the browser and native-shell SDK for applications that operate on one user-approved local or hosted mdbase - collection. The application asks for exact operations. Connect selects the - route and the collection authority checks the current grant. + collection. The application declares the capabilities it needs in its + manifest. Connect selects the route and the collection authority checks + the current grant.

Starting points

@@ -97,12 +98,17 @@ export async function listOpenTasks(client: MdbaseCollectionClient) { Browser APIs or adapters supplied by a native shell - MdbaseBrowserLocation - Bookmarkable collection selection, authorization return URLs, and browser navigation - A stable MdbaseConnect manager and browser history APIs + MdbaseApplicationSession + One application's collection selection, authorization, setup checks, and reactive snapshot + An MdbaseConnect manager and a selection adapter such as MdbaseBrowserSelection - MdbaseCollectionClient + connection.records + Records people type into: autosave, conflicts, exact recovery, live updates + An MdbaseConnection + + + MdbaseCollectionClient (/advanced) Domain and feature logic that should be independent of OAuth and hosting A small MdbaseCollectionTransport @@ -121,11 +127,10 @@ export async function listOpenTasks(client: MdbaseCollectionClient) {

Application structure

- Create one MdbaseConnect manager at the application boundary. - Pair it with one MdbaseBrowserLocation at the browser - application boundary. Resolve its active connection, then pass that - {" "}MdbaseConnection into feature code. The location helper owns - bookmark selection and OAuth return cleanup; the manager owns saved + Create one MdbaseConnect manager and one application session + at the application boundary. Read the session's active connection, then + pass that MdbaseConnection into feature code. The session owns + collection selection and authorization; the manager owns saved authorizations. A bound connection never changes collections underneath a repository, and feature code written against {" "}MdbaseCollectionClient can also run against the developer @@ -139,12 +144,13 @@ export async function listOpenTasks(client: MdbaseCollectionClient) {

- Operation envelopes + Typed outcomes

- Record operations return {`{ valid, result, diagnostics }`}. - Use unwrapOperation() when exceptions suit the calling code, - or inspect the envelope when the interface should present validation - diagnostics inline. + Every operation returns a ConnectOutcome: + {" "}{`{ ok: true, value, diagnostics }`} or + {" "}{`{ ok: false, problem }`}. Expected failures are data + with a stable code and a suggested recovery; exceptions mean a + programming error.

diff --git a/src/pages/sdk/operations/index.astro b/src/pages/sdk/operations/index.astro index 4f6e6fa..39c722c 100644 --- a/src/pages/sdk/operations/index.astro +++ b/src/pages/sdk/operations/index.astro @@ -2,104 +2,111 @@ import DocsLayout from "../../../components/DocsLayout.astro"; import CodeBlock from "../../../components/CodeBlock.astro"; -const readQuery = `const record = unwrapOperation(await connection.read({ - path: "tasks/release.md" -})); +const readQuery = `const record = await connection.read({ path: "tasks/release.md" }); +if (!record.ok) return renderProblem(record.problem); -const open = unwrapOperation(await connection.query({ +const open = await connection.query({ types: ["task"], where: 'status == "open" && due != null', - order_by: [ - { field: "due", direction: "asc" } - ], + orderBy: [{ field: "due", direction: "asc" }], limit: 100 -}));`; +}); +if (!open.ok) return renderProblem(open.problem);`; -const pageQuery = `for await (const page of connection.queryPages( +const pageQuery = `let loaded = 0; +for await (const page of connection.queryPages( { types: ["task"], where: 'status != "done"' }, - { - firstPageSize: 100, - pageSize: 1000, - signal: abortController.signal, - onProgress: ({ loaded }) => renderProgress(loaded) - } + { firstPageSize: 100, pageSize: 1000, signal: abortController.signal } )) { - appendRows(page.results); + if (!page.ok) return renderProblem(page.problem); + appendRows(page.value.results); + renderProgress(loaded += page.value.results.length); }`; -const createUpdate = `const created = unwrapOperation(await connection.create({ +const createUpdate = `const created = await connection.create({ path: "tasks/release.md", type: "task", - frontmatter: { - type: "task", - title: "Prepare release", - status: "open" - }, + frontmatter: { type: "task", title: "Prepare release", status: "open" }, body: "Release checklist." -})); +}); +if (!created.ok) return renderProblem(created.problem); -unwrapOperation(await connection.update({ - path: created.path, +const updated = await connection.update({ + path: created.value.path, patch: { status: "done" }, - if_revision: created.revision -}));`; - -const watch = `const controller = new AbortController(); - -for await (const change of connection.watch({ - signal: controller.signal, - onStatus: (status) => renderWatchStatus(status) -})) { - applyChange(change); + ifRevision: created.value.revision +}); +if (!updated.ok && updated.problem.code === "concurrent_modification") { + // Changed since it was read: refresh, then let the user or domain logic decide. }`; -const preflight = `const preview = unwrapOperation(await connection.preflightRename({ +const watch = `const lifetime = new AbortController(); +const opened = await connection.watch({ lifetimeSignal: lifetime.signal }, { timeoutMs: 20_000 }); +if (!opened.ok) return renderProblem(opened.problem); +const unsubscribe = opened.value.subscribe( + (change) => applyChange(change.type, change.payload.path), + renderWatchStatus, + renderProblem +); +// Leaving: unsubscribe(); opened.value.close(); +void unsubscribe;`; + +const preflight = `const preview = await connection.preflightRename({ from: "tasks/release.md", to: "archive/release.md", - update_refs: true, - if_revision: current.revision -})); - -showImpact(preview.references_affected, preview.warnings); - -await connection.renameWithProgress({ - from: preview.from, - to: preview.to, - update_refs: true, - if_revision: current.revision + updateRefs: true, + ifRevision: current.revision +}); +if (!preview.ok) return renderProblem(preview.problem); +showImpact(preview.value.referencesAffected, preview.value.warnings); + +const renamed = await connection.renameWithProgress({ + from: preview.value.from, + to: preview.value.to, + updateRefs: true, + ifRevision: current.revision }, { - preflight: preview, - signal: controller.signal, + preflight: preview.value, + signal: abortController.signal, onProgress: renderMutationProgress -});`; +}); +if (!renamed.ok) renderProblem(renamed.problem);`; + +const recover = `for (const pending of connection.pendingMutations()) { + const recovered = await pending.recover({ timeoutMs: 30_000 }); + if (!recovered.ok) renderProblem(recovered.problem); +}`; --- -

Operation envelopes

+

Typed outcomes

- Record-facing operations return{" "} - {`MdbaseOperationEnvelope`}. A successful envelope - contains valid: true, the typed result, and any non-fatal - diagnostics. Validation failures return diagnostics in the same envelope. - Transport failures use exceptions. + Every operation returns a ConnectOutcome. Check{" "} + ok: a success has the typed value and any + non-fatal diagnostics; a failure has a problem{" "} + with a stable code, a category, a suggested{" "} + recovery, and, for mutations, whether the write was sent, + rejected or has an unknown outcome. Expected failures are data, not + exceptions; exceptions mean a programming error.

- unwrapOperation(envelope) returns the result or throws{" "} - MdbaseOperationValidationError. Use it when the calling layer - uses exceptions. Keep the raw envelope when diagnostics are part of the - interface. + Record conditions have one code whichever authority holds the collection: + a stale revision is concurrent_modification, a missing record + is file_not_found, and invalid input is{" "} + operation_invalid with the mdbase diagnostics in its details.

Read one path or query a collection

@@ -114,8 +121,9 @@ await connection.renameWithProgress({

Page large result sets against one snapshot

- queryPages() preserves the snapshot token returned by the - first page and rejects a changed token. queryAll() provides the + queryPages() yields one outcome per page. It preserves the + snapshot token returned by the first page and reports a changed token as + {" "}query_snapshot_changed. queryAll() provides the same behavior when holding the complete result set in memory is acceptable.

@@ -123,18 +131,27 @@ await connection.renameWithProgress({

patch is the canonical v0.3 partial-frontmatter update. A - mismatched if_revision produces{" "} + mismatched ifRevision produces{" "} concurrent_modification. Refresh the record and ask the user or domain logic to resolve the conflict before submitting another write.

+

+ For a record people are typing into, use a{" "} + record session instead of issuing updates + yourself. +

+

Resume changes by cursor

- watch() uses the collection authority's resumable change - cursor. The local change feed remains at the collection authority. The - iterator reconnects transient routes by default and reports{" "} - reset_required when the consumer must refresh a complete view. + watch() starts within a bounded budget and returns a + subscription that lasts until close() or its lifetime signal. + It resumes from the collection authority's change cursor, reconnects + transient routes by default, and reports a reset_required{" "} + status when the consumer must refresh a complete view. To keep open + records current, pass the subscription to{" "} + connection.records.follow().

Show authoritative impact before destructive work

@@ -145,13 +162,14 @@ await connection.renameWithProgress({ renameWithProgress() or deleteWithProgress() so the confirmation shown to the user matches the operation that will run.

-
- Encrypted local mutations have durable outcomes. -

- If the caller stops waiting after dispatch, inspect{" "} - pendingMutation() and recover the exact connector receipt - with resumePendingMutation(). Wait for that outcome before - submitting a different mutation. -

-
+

Recover interrupted writes exactly

+ +

+ The SDK stores each mutation's exact encrypted request before sending it. + If the response is lost, the write fails with{" "} + operation_outcome_unknown and a durable handle appears in{" "} + pendingMutations(), including after a reload.{" "} + recover() resends the original request identity; never repeat + the write as a new mutation. Record sessions do this for you. +

diff --git a/src/pages/sdk/quickstart/index.astro b/src/pages/sdk/quickstart/index.astro index 816718d..8b8e058 100644 --- a/src/pages/sdk/quickstart/index.astro +++ b/src/pages/sdk/quickstart/index.astro @@ -13,8 +13,7 @@ const download = `curl -fsSLo packages/devkit/sandbox-quickstart.mjs \\ node packages/devkit/sandbox-quickstart.mjs`; -const example = `import { unwrapOperation } from "@mdbase-dev/connect"; -import { createSandbox } from "@mdbase-dev/connect-dev"; +const example = `import { createSandbox } from "@mdbase-dev/connect-dev"; const { client, transport } = createSandbox({ records: [{ @@ -28,11 +27,15 @@ const { client, transport } = createSandbox({ }] }); -const first = unwrapOperation( - await client.read({ path: "tasks/first.md" }) -); +// Every operation returns a ConnectOutcome: check ok, then use value or problem. +function required(outcome) { + if (!outcome.ok) throw new Error(\`\${outcome.problem.code}: \${outcome.problem.message}\`); + return outcome.value; +} -const created = unwrapOperation(await client.create({ +const first = required(await client.read({ path: "tasks/first.md" })); + +const created = required(await client.create({ type: "task", path: "tasks/second.md", frontmatter: { @@ -42,30 +45,33 @@ const created = unwrapOperation(await client.create({ } })); -const updated = unwrapOperation(await client.update({ +const updated = required(await client.update({ path: created.path, patch: { completed: true }, - if_revision: created.revision + ifRevision: created.revision })); -const tasks = unwrapOperation(await client.query({ +// Reusing the old revision is refused instead of overwriting the update. +const stale = await client.update({ + path: created.path, + patch: { completed: false }, + ifRevision: created.revision +}); + +const tasks = required(await client.query({ types: ["task"], limit: 20 })); console.log(\`Read: \${first.frontmatter.title}\`); -console.log( - \`Updated: \${updated.path} (completed: \${updated.frontmatter.completed})\` -); +console.log(\`Updated: \${updated.path} (completed: \${updated.frontmatter.completed})\`); +console.log(\`Stale revision: \${stale.ok ? "accepted" : stale.problem.code}\`); console.log(\`Task records: \${tasks.results.length}\`); -console.log( - \`Markdown paths: \${transport.snapshot() - .map((record) => record.path) - .join(", ")}\` -);`; +console.log(\`Markdown paths: \${transport.snapshot().map((record) => record.path).join(", ")}\`);`; const output = `Read: Read the collection Updated: tasks/second.md (completed: true) +Stale revision: concurrent_modification Task records: 2 Markdown paths: tasks/first.md, tasks/second.md`; --- @@ -125,14 +131,19 @@ Markdown paths: tasks/first.md, tasks/second.md`; createSandbox() returns the same {" "}MdbaseCollectionClient boundary used by a connected collection. The example reads one seed record, creates a second record, - updates it with its revision token, and queries both task records. + updates it with its revision token, shows that a stale revision is + refused, and queries both task records. Every operation returns a{" "} + ConnectOutcome: check ok, then use{" "} + value or problem. Expected failures are data, + not exceptions.

4. Check the expected result

- A stale revision fails with a - {" "}concurrent_modification diagnostic. The sandbox also supports + A stale revision fails with the + {" "}concurrent_modification problem, the same code a real + collection returns. The sandbox also supports typed CRUD, pagination, read defaults, and change cursors. CEL expressions, authorization, routing, and filesystem behavior belong in real-stack integration tests. diff --git a/src/pages/sdk/testing/index.astro b/src/pages/sdk/testing/index.astro index dbd8c99..4ec0372 100644 --- a/src/pages/sdk/testing/index.astro +++ b/src/pages/sdk/testing/index.astro @@ -4,6 +4,7 @@ import CodeBlock from "../../../components/CodeBlock.astro"; const sandbox = `import { createSandbox } from "@mdbase-dev/connect-dev"; import type { JsonObject } from "@mdbase-dev/connect"; +import type { MdbaseCollectionClient } from "@mdbase-dev/connect/advanced"; interface Task extends JsonObject { type: "task"; @@ -11,21 +12,41 @@ interface Task extends JsonObject { status: "open" | "done"; } -const { client, transport } = createSandbox({ - records: [{ - path: "tasks/first.md", - types: ["task"], - frontmatter: { - type: "task", - title: "First", - status: "open" - } - }] +// Feature logic under test: depends only on the collection client. +async function openTasks(client: MdbaseCollectionClient) { + const tasks = await client.queryAll({ types: ["task"] }); + if (!tasks.ok) return tasks; + return { + ...tasks, + value: tasks.value.results.filter((task) => task.effectiveFrontmatter?.status === "open") + }; +} + +const { client } = createSandbox({ + records: [ + { path: "tasks/first.md", types: ["task"], frontmatter: { type: "task", title: "First", status: "open" } }, + { path: "tasks/done.md", types: ["task"], frontmatter: { type: "task", title: "Done", status: "done" } } + ] }); -const result = await listOpenTasks(client); -expect(result.results).toHaveLength(1); -expect(transport.snapshot()[0].path).toBe("tasks/first.md");`; +const result = await openTasks(client); +if (!result.ok) throw new Error(result.problem.message); +expect(result.value.map((task) => task.path)).toEqual(["tasks/first.md"]);`; + +const editing = `import { createRecordTestAuthority } from "@mdbase-dev/connect-testing"; + +const authority = createRecordTestAuthority(); +authority.seed("Notes/one.md", { body: "Original" }); +authority.records.follow(authority.watch); + +// Mount the editor with authority.records where it expects connection.records. +const opened = await authority.records.open("Notes/one.md"); +if (!opened.ok) throw new Error(opened.problem.message); +opened.value.session.setBody("Mine"); + +authority.editElsewhere("Notes/one.md", { body: "Theirs" }); +await vi.runAllTimersAsync(); +expect(opened.value.session.getSnapshot().state).toBe("conflict");`; const ci = `pnpm exec mdbase-connect-dev validate-manifest \\ public/.well-known/mdbase-app.json @@ -43,6 +64,7 @@ pnpm e2e`; headings={[ { href: "#sandbox", label: "Sandbox tests" }, { href: "#coverage", label: "Sandbox coverage" }, + { href: "#editing", label: "Editing features" }, { href: "#real", label: "Real connector tests" }, { href: "#ci", label: "CI sequence" } ]} @@ -66,7 +88,7 @@ pnpm e2e`; - Typed CRUD and operation envelopes + Typed CRUD and outcomes CEL expression semantics @@ -88,10 +110,24 @@ pnpm e2e`;

- The sandbox rejects where and order_by. Run CEL + The sandbox rejects where and orderBy with sandbox_unsupported. Run CEL expression and ordering tests against a conforming collection authority.

+

Test editing features

+ +

+ createRecordTestAuthority() from + {" "}@mdbase-dev/connect-testing is an in-memory authority + with revision checks and a change watch; its records is the + real connection.records implementation. Controls reproduce + what other clients and the network do: editElsewhere(), + {" "}renameElsewhere(), deleteElsewhere(), + {" "}loseNextResponse(), failNextWrite() and + {" "}resetWatch(), with writes recording what + reached the authority. +

+

Use the real stack at system boundaries

Run integration tests against the local Connect stack for:

    diff --git a/src/pages/security/index.astro b/src/pages/security/index.astro index 158202e..aacb71c 100644 --- a/src/pages/security/index.astro +++ b/src/pages/security/index.astro @@ -105,8 +105,8 @@ import BaseLayout from "../../layouts/BaseLayout.astro";

    Revision preconditions

    - Preserve the revision returned by reads and queries, then pass{" "} - if_revision to update, rename, and delete operations. + Preserve the revision returned by a read or write, then pass{" "} + ifRevision to update, rename, and delete operations. Resolve conflicts explicitly.