组织本地数据与同步
v0.1 鼓励 local-first:store 是应用权威本地状态;identity 只决定平台同步是否可用;net 只在应用确实有自有服务时引入。
1. 先读本地状态
const entry = await host.store.get('documents/current');
const document = entry ? decodeDocument(entry.value) : createDocument();
render(document);
应用不应等网络或登录才显示本地内容。
2. 使用版本避免覆盖
async function save(document, expectedVersion) {
try {
return await host.store.put('documents/current', encodeDocument(document), expectedVersion);
} catch (error) {
if (error.code !== 'conflict') throw error;
return resolveConflict(document, await host.store.get('documents/current'));
}
}
3. 可选登录
let account = await host.identity.status();
if (!account.authenticated && userWantsSync) {
await host.identity.login();
account = await host.identity.status();
}
应用只知道布尔状态,不得用全局用户 ID 做数据库主键。
4. 自有服务的明确边界
只有应用确实需要访问 manifest 声明的第三方 API 时才使用 net.fetch():
const response = await host.net.fetch({
url: 'https://sync.example.com/v1/changes',
method: 'POST',
body: encodeEncryptedChanges(document.pendingChanges),
});
平台持有的身份不会自动成为任意第三方 API 的身份。凭据作用域必须由独立契约定义。
5. 哪些东西留在 guest
数据库页、索引、查询、CRDT、同步日志、冲突解决与端到端加密协议都是 L2/L3。宿主 API 只提供持久化资源、受控身份流程和经代理网络。