@tearleads/client-sdk 0.1.197 → 0.1.199

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 (30) hide show
  1. package/data/persistence/identity/trustedUserIdentityPinModel.d.ts +4 -0
  2. package/data/persistence/identity/trustedUserIdentityPinModel.js +113 -0
  3. package/data/persistence/identity/trustedUserIdentityPinModel.js.map +1 -1
  4. package/data/persistence/identity/trustedUserIdentityPinRepository.js +196 -0
  5. package/data/persistence/identity/trustedUserIdentityPinRepository.js.map +1 -0
  6. package/data/trustedUserIdentity/pinnedIdentity.d.ts +1 -1
  7. package/data/trustedUserIdentity/pinnedIdentity.js +2 -2
  8. package/data/trustedUserIdentity/pinnedIdentity.js.map +1 -1
  9. package/data/trustedUserIdentity/pinnedResolution.js +4 -5
  10. package/data/trustedUserIdentity/pinnedResolution.js.map +1 -1
  11. package/data/trustedUserIdentity/service.js +12 -13
  12. package/data/trustedUserIdentity/service.js.map +1 -1
  13. package/internal/loro/changeTimestamps.d.ts +26 -0
  14. package/internal/loro/changeTimestamps.js +29 -0
  15. package/internal/loro/changeTimestamps.js.map +1 -0
  16. package/internal/loro/document.js +2 -0
  17. package/internal/loro/document.js.map +1 -1
  18. package/internal/loro/index.d.ts +1 -0
  19. package/internal/loro/index.js +1 -0
  20. package/internal/loro/index.js.map +1 -1
  21. package/package.json +1 -1
  22. package/data/persistence/identity/trustedUserIdentityPinBatch.js +0 -36
  23. package/data/persistence/identity/trustedUserIdentityPinBatch.js.map +0 -1
  24. package/data/persistence/identity/trustedUserIdentitySigningKeyBinding.js +0 -18
  25. package/data/persistence/identity/trustedUserIdentitySigningKeyBinding.js.map +0 -1
  26. package/data/persistence/trustedUserIdentityPinPersistence.d.ts +0 -37
  27. package/data/persistence/trustedUserIdentityPinPersistence.js +0 -258
  28. package/data/persistence/trustedUserIdentityPinPersistence.js.map +0 -1
  29. /package/data/persistence/{trustedUserIdentityPinTransaction.js → identity/trustedUserIdentityPinTransaction.js} +0 -0
  30. /package/data/persistence/{trustedUserIdentityPinTransaction.js.map → identity/trustedUserIdentityPinTransaction.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kCAAkC,EAClC,mCAAmC,GACpC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,8BAA8B,EAAE,MAAM,8DAA8D,CAAC;AAC9G,OAAO,EACL,sCAAsC,GAEvC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AAEzG,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EACL,wBAAwB,EACxB,yCAAyC,EACzC,oCAAoC,EACpC,mCAAmC,GAKpC,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,cAAc,CAAC;AAEtB,SAAS,kBAAkB,CACzB,YAAoD;IAEpD,0EAA0E;IAC1E,IAAI,CAAC,YAAY,CAAC,mBAAmB,EAAE,CAAC;QACtC,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,qEAAqE,CACtE,CAAC;IACJ,CAAC;IACD,OAAO,YAAY,CAA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,CAAC;QACH,CAAC,EACD;YACE,aAAa,EAAE,CAAC,MAAM,EAAE,mBAAmB,EAAE,EAAE,CAC7C,mBAAmB,CAAC,YAAY,EAAE,MAAM,EAAE,mBAAmB,CAAC;YAChE,WAAW,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE,CAClD,sBAAsB,CAAC;gBACrB,aAAa;gBACb,OAAO;gBACP,WAAW,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE;gBAC/D,UAAU;gBACV,UAAU,EAAE,UAAU;aACvB,CAAC;SACL,EACD,OAAO,CACR;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { loadTrustedUserIdForSigningKey } from \"../persistence/identity/trustedUserIdentitySigningKeyBinding\";\nimport {\n compareOrInsertTrustedUserIdentityPins,\n type TrustedUserIdentityPinProvenance,\n} from \"../persistence/trustedUserIdentityPinPersistence\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/trustedUserIdentityPinTransaction\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../sync/databaseUnavailable\";\nimport { UnverifiedUserIdentityError } from \"./admission\";\nimport {\n assertIdentityLinkMatches,\n createIdentityLink,\n parseIdentityLink,\n} from \"./identityLink\";\nimport { loadPin, loadPinnedUserIdentity } from \"./pinnedIdentity\";\nimport { withPinnedIdentityResolution } from \"./pinnedResolution\";\nimport { withStagedIdentityHandoff } from \"./stagedIdentityHandoff\";\nimport {\n brandTrustedUserIdentity,\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type TrustedUserIdentity,\n type TrustedUserIdentityService,\n type TrustedUserIdentityServiceDependencies,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateLocalUserIdentity,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\nfunction requireTrustDomain(\n dependencies: TrustedUserIdentityServiceDependencies,\n): string {\n // A missing trust domain is a static misconfiguration and must stay loud.\n if (!dependencies.identityTrustDomain) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n }\n return dependencies.identityTrustDomain;\n}\n\nfunction requireTrustStore(\n dependencies: TrustedUserIdentityServiceDependencies,\n) {\n const identityTrustDomain = requireTrustDomain(dependencies);\n // An absent trust store is not: getExecSql() returns null exactly while the\n // database is not ready, which happens routinely when the runtime is swapped\n // under in-flight sync work. Callers that tolerate a vanishing database\n // discriminate on the error type, so this must not share the code above.\n const execSql = dependencies.getExecSql();\n if (!execSql) {\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n }\n return { execSql, identityTrustDomain };\n}\n\nfunction durablePin(\n identity: ValidatedUserIdentityCandidate,\n provenance: TrustedUserIdentityPinProvenance,\n firstSeenAt: string,\n) {\n return {\n encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),\n encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n firstSeenAt,\n provenance,\n formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n identityTrustDomain: identity.identityTrustDomain,\n signingKeyFingerprint: identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(identity.signingPublicKey),\n signingSuite: TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n userId: identity.userId,\n };\n}\n\n/** Compare-or-insert every identity in one transaction: all pin, or none. */\nasync function compareWithDurablePins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly firstSeenAt: string;\n readonly identities: readonly ValidatedUserIdentityCandidate[];\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<void> {\n const userIds = input.identities.map((identity) => identity.userId);\n try {\n await compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n pins: input.identities.map((identity) =>\n durablePin(identity, input.provenance, input.firstSeenAt),\n ),\n });\n } catch (error) {\n if (error instanceof TrustedUserIdentityPinMismatchError) {\n throw new KeyingVerificationError(\n \"equivocation\",\n error.existing.userId !== error.candidate.userId\n ? `Signing key for ${error.candidate.userId} is already bound to ${error.existing.userId}`\n : `Trusted user identity changed for ${error.candidate.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinCorruptError) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Trusted user identity pin is corrupt for ${error.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinContentionError) {\n // Lock contention says nothing about the identity; the caller retries\n // once the trust store is free, so this must not be recordable evidence.\n throw new DatabaseUnavailableError(\n `Trusted user identity pin store is busy for ${userIds.join(\", \")}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * The candidate for `userId` and where it came from: this device's own keys\n * (`self`) or the identity endpoint (`observed`). Provenance follows the\n * source, never the account that happens to be active once a lookup returns.\n */\nasync function resolveCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<{\n readonly identity: ValidatedUserIdentityCandidate;\n readonly source: \"self\" | \"observed\";\n} | null> {\n const localUserId = dependencies.getLocalUserId();\n if (userId === localUserId) {\n const localIdentity = dependencies.getLocalIdentity(userId);\n if (!localIdentity) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Authoritative local identity keys are unavailable\",\n );\n }\n return {\n identity: await validateLocalUserIdentity({\n candidate: localIdentity,\n identityTrustDomain,\n userId,\n }),\n source: \"self\",\n };\n }\n\n const identity = await loadRemoteCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n return identity ? { identity, source: \"observed\" } : null;\n}\n\nasync function loadRemoteCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<ValidatedUserIdentityCandidate | null> {\n const remoteIdentity = await dependencies.remoteSource.load(userId);\n return remoteIdentity\n ? validateRemoteUserIdentity({\n candidate: remoteIdentity,\n identityTrustDomain,\n requestedUserId: userId,\n })\n : null;\n}\n\n/** The trust store and account a lookup started under must still be active. */\nfunction assertResolutionScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n scope: { readonly execSql: ExecSql; readonly localUserId: string | null },\n message: string,\n): void {\n if (\n dependencies.getExecSql() !== scope.execSql ||\n dependencies.getLocalUserId() !== scope.localUserId\n ) {\n throw new DatabaseUnavailableError(message);\n }\n}\n\nasync function pinIdentity(input: {\n /** Checked inside the pin's write transaction, before it commits. */\n readonly assertCurrent?: (() => void) | undefined;\n readonly dependencies: TrustedUserIdentityServiceDependencies;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identity: ValidatedUserIdentityCandidate;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<TrustedUserIdentity> {\n await compareWithDurablePins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),\n identities: [input.identity],\n provenance: input.provenance,\n });\n return brandTrustedUserIdentity(input.identity);\n}\n\n/** Compares an independently received link before pinning it as `link`. */\nasync function verifyIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n link: string,\n): Promise<TrustedUserIdentity> {\n const expectation = parseIdentityLink(link);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (expectation.identityTrustDomain !== identityTrustDomain) {\n throw new Error(\n \"This identity link belongs to a different Tearleads service.\",\n );\n }\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n expectation.userId,\n identityTrustDomain,\n );\n if (!candidate)\n throw new Error(\"The identity in this link is unavailable.\");\n await assertIdentityLinkMatches(expectation, candidate.identity);\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed. Open the identity link again.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source === \"self\" ? \"self\" : \"link\",\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(expectation.userId);\n throw error;\n }\n}\n\nfunction admissionScopeChanged(): DatabaseUnavailableError {\n return new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n}\n\n/** Reads that admit a user: only `self` and `link` pins qualify. */\nfunction verifiedPinReaders(\n dependencies: TrustedUserIdentityServiceDependencies,\n): Pick<\n TrustedUserIdentityService,\n \"loadAdmissionPin\" | \"resolveVerified\" | \"requireVerified\"\n> {\n const resolveVerified = async (userId: string) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin && pin.provenance !== \"observed\" ? pin.identity : null;\n };\n // The pin in the trust store of the database the admission captured.\n const loadAdmittingPin = async (\n userId: string,\n admittingExecSql: ExecSql | null,\n ) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (execSql !== admittingExecSql) throw admissionScopeChanged();\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin;\n };\n return {\n resolveVerified,\n async requireVerified(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n if (!pin || pin.provenance === \"observed\") {\n throw new UnverifiedUserIdentityError(userId);\n }\n return pin.identity;\n },\n async loadAdmissionPin(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n return pin\n ? { identity: pin.identity, verified: pin.provenance !== \"observed\" }\n : null;\n },\n };\n}\n\n/** This user's own link, derived exclusively from this device's local keys. */\nasync function createLocalIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n appUrl: string,\n): Promise<string> {\n const identityTrustDomain = requireTrustDomain(dependencies);\n const userId = dependencies.getLocalUserId();\n const candidate = userId ? dependencies.getLocalIdentity(userId) : null;\n if (!userId || !candidate) {\n throw new Error(\"Sign in before sharing your identity link.\");\n }\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return createIdentityLink(identity, appUrl);\n}\n\nexport function createTrustedUserIdentityService(\n input: TrustedUserIdentityServiceDependencies,\n): TrustedUserIdentityService {\n const { dependencies, handoff } = withStagedIdentityHandoff(input);\n const verifiedReaders = verifiedPinReaders(dependencies);\n return {\n async resolvePinned(userId) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });\n },\n ...verifiedReaders,\n createLink: (appUrl) => createLocalIdentityLink(dependencies, appUrl),\n async createLinkFor(userId, appUrl) {\n if (\n userId === dependencies.getLocalUserId() &&\n dependencies.getLocalIdentity(userId)\n ) {\n return createLocalIdentityLink(dependencies, appUrl);\n }\n // Only a `link` or `self` pin: re-sharing an observed (TOFU) key as a\n // link would let its recipient pin an unverified key as `link`.\n const identity = await verifiedReaders.resolveVerified(userId);\n return identity ? createIdentityLink(identity, appUrl) : null;\n },\n verifyLink: (link) => verifyIdentityLink(dependencies, link),\n async boundUserId(signingKeyFingerprint) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadTrustedUserIdForSigningKey({\n execSql,\n identityTrustDomain,\n signingKeyFingerprint,\n });\n },\n async pinLocal(userId, candidate) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return pinIdentity({\n dependencies,\n execSql,\n identity,\n provenance: \"self\",\n });\n },\n resolve: withPinnedIdentityResolution(\n dependencies,\n async (userId) => {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } =\n requireTrustStore(dependencies);\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n if (!candidate) {\n return null;\n }\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed while resolving this user.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source,\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(userId);\n throw error;\n }\n },\n {\n loadCandidate: (userId, identityTrustDomain) =>\n loadRemoteCandidate(dependencies, userId, identityTrustDomain),\n pinObserved: (execSql, identities, assertCurrent) =>\n compareWithDurablePins({\n assertCurrent,\n execSql,\n firstSeenAt: (dependencies.now?.() ?? new Date()).toISOString(),\n identities,\n provenance: \"observed\",\n }),\n },\n handoff,\n ),\n };\n}\n"]}
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kCAAkC,EAClC,mCAAmC,GAEpC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,gCAAgC,EAAE,MAAM,0DAA0D,CAAC;AAC5G,OAAO,EAAE,qCAAqC,EAAE,MAAM,2DAA2D,CAAC;AAElH,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,iB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ToBase64 } from \"@tearleads/encoding\";\nimport {\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n type TrustedUserIdentityPinProvenance,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../sync/databaseUnavailable\";\nimport { UnverifiedUserIdentityError } from \"./admission\";\nimport {\n assertIdentityLinkMatches,\n createIdentityLink,\n parseIdentityLink,\n} from \"./identityLink\";\nimport { loadPin, loadPinnedUserIdentity } from \"./pinnedIdentity\";\nimport { withPinnedIdentityResolution } from \"./pinnedResolution\";\nimport { withStagedIdentityHandoff } from \"./stagedIdentityHandoff\";\nimport {\n brandTrustedUserIdentity,\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type TrustedUserIdentity,\n type TrustedUserIdentityService,\n type TrustedUserIdentityServiceDependencies,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateLocalUserIdentity,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\nfunction requireTrustDomain(\n dependencies: TrustedUserIdentityServiceDependencies,\n): string {\n // A missing trust domain is a static misconfiguration and must stay loud.\n if (!dependencies.identityTrustDomain) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n }\n return dependencies.identityTrustDomain;\n}\n\nfunction requireTrustStore(\n dependencies: TrustedUserIdentityServiceDependencies,\n) {\n const identityTrustDomain = requireTrustDomain(dependencies);\n // An absent trust store is not: getExecSql() returns null exactly while the\n // database is not ready, which happens routinely when the runtime is swapped\n // under in-flight sync work. Callers that tolerate a vanishing database\n // discriminate on the error type, so this must not share the code above.\n const execSql = dependencies.getExecSql();\n if (!execSql) {\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n }\n return { execSql, identityTrustDomain };\n}\n\nfunction durablePin(\n identity: ValidatedUserIdentityCandidate,\n provenance: TrustedUserIdentityPinProvenance,\n firstSeenAt: string,\n) {\n return {\n encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),\n encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n firstSeenAt,\n provenance,\n formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n identityTrustDomain: identity.identityTrustDomain,\n signingKeyFingerprint: identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(identity.signingPublicKey),\n signingSuite: TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n userId: identity.userId,\n };\n}\n\n/** Compare-or-insert every identity in one transaction: all pin, or none. */\nasync function compareWithDurablePins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly firstSeenAt: string;\n readonly identities: readonly ValidatedUserIdentityCandidate[];\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<void> {\n const userIds = input.identities.map((identity) => identity.userId);\n try {\n await new TrustedUserIdentityPinRepository(\n input.execSql,\n ).compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n pins: input.identities.map((identity) =>\n durablePin(identity, input.provenance, input.firstSeenAt),\n ),\n });\n } catch (error) {\n if (error instanceof TrustedUserIdentityPinMismatchError) {\n throw new KeyingVerificationError(\n \"equivocation\",\n error.existing.userId !== error.candidate.userId\n ? `Signing key for ${error.candidate.userId} is already bound to ${error.existing.userId}`\n : `Trusted user identity changed for ${error.candidate.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinCorruptError) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Trusted user identity pin is corrupt for ${error.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinContentionError) {\n // Lock contention says nothing about the identity; the caller retries\n // once the trust store is free, so this must not be recordable evidence.\n throw new DatabaseUnavailableError(\n `Trusted user identity pin store is busy for ${userIds.join(\", \")}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * The candidate for `userId` and where it came from: this device's own keys\n * (`self`) or the identity endpoint (`observed`). Provenance follows the\n * source, never the account that happens to be active once a lookup returns.\n */\nasync function resolveCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<{\n readonly identity: ValidatedUserIdentityCandidate;\n readonly source: \"self\" | \"observed\";\n} | null> {\n const localUserId = dependencies.getLocalUserId();\n if (userId === localUserId) {\n const localIdentity = dependencies.getLocalIdentity(userId);\n if (!localIdentity) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Authoritative local identity keys are unavailable\",\n );\n }\n return {\n identity: await validateLocalUserIdentity({\n candidate: localIdentity,\n identityTrustDomain,\n userId,\n }),\n source: \"self\",\n };\n }\n\n const identity = await loadRemoteCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n return identity ? { identity, source: \"observed\" } : null;\n}\n\nasync function loadRemoteCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<ValidatedUserIdentityCandidate | null> {\n const remoteIdentity = await dependencies.remoteSource.load(userId);\n return remoteIdentity\n ? validateRemoteUserIdentity({\n candidate: remoteIdentity,\n identityTrustDomain,\n requestedUserId: userId,\n })\n : null;\n}\n\n/** The trust store and account a lookup started under must still be active. */\nfunction assertResolutionScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n scope: { readonly execSql: ExecSql; readonly localUserId: string | null },\n message: string,\n): void {\n if (\n dependencies.getExecSql() !== scope.execSql ||\n dependencies.getLocalUserId() !== scope.localUserId\n ) {\n throw new DatabaseUnavailableError(message);\n }\n}\n\nasync function pinIdentity(input: {\n /** Checked inside the pin's write transaction, before it commits. */\n readonly assertCurrent?: (() => void) | undefined;\n readonly dependencies: TrustedUserIdentityServiceDependencies;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identity: ValidatedUserIdentityCandidate;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<TrustedUserIdentity> {\n await compareWithDurablePins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),\n identities: [input.identity],\n provenance: input.provenance,\n });\n return brandTrustedUserIdentity(input.identity);\n}\n\n/** The user this trust store already binds to a signing key, if any. */\nasync function boundUserId(\n dependencies: TrustedUserIdentityServiceDependencies,\n signingKeyFingerprint: string,\n): Promise<string | null> {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return new TrustedUserIdentityPinRepository(\n execSql,\n ).loadTrustedUserIdForSigningKey({\n identityTrustDomain,\n signingKeyFingerprint,\n });\n}\n\n/** Compares an independently received link before pinning it as `link`. */\nasync function verifyIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n link: string,\n): Promise<TrustedUserIdentity> {\n const expectation = parseIdentityLink(link);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (expectation.identityTrustDomain !== identityTrustDomain) {\n throw new Error(\n \"This identity link belongs to a different Tearleads service.\",\n );\n }\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n expectation.userId,\n identityTrustDomain,\n );\n if (!candidate)\n throw new Error(\"The identity in this link is unavailable.\");\n await assertIdentityLinkMatches(expectation, candidate.identity);\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed. Open the identity link again.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source === \"self\" ? \"self\" : \"link\",\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(expectation.userId);\n throw error;\n }\n}\n\nfunction admissionScopeChanged(): DatabaseUnavailableError {\n return new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n}\n\n/** Reads that admit a user: only `self` and `link` pins qualify. */\nfunction verifiedPinReaders(\n dependencies: TrustedUserIdentityServiceDependencies,\n): Pick<\n TrustedUserIdentityService,\n \"loadAdmissionPin\" | \"resolveVerified\" | \"requireVerified\"\n> {\n const resolveVerified = async (userId: string) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin && pin.provenance !== \"observed\" ? pin.identity : null;\n };\n // The pin in the trust store of the database the admission captured.\n const loadAdmittingPin = async (\n userId: string,\n admittingExecSql: ExecSql | null,\n ) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (execSql !== admittingExecSql) throw admissionScopeChanged();\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin;\n };\n return {\n resolveVerified,\n async requireVerified(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n if (!pin || pin.provenance === \"observed\") {\n throw new UnverifiedUserIdentityError(userId);\n }\n return pin.identity;\n },\n async loadAdmissionPin(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n return pin\n ? { identity: pin.identity, verified: pin.provenance !== \"observed\" }\n : null;\n },\n };\n}\n\n/** This user's own link, derived exclusively from this device's local keys. */\nasync function createLocalIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n appUrl: string,\n): Promise<string> {\n const identityTrustDomain = requireTrustDomain(dependencies);\n const userId = dependencies.getLocalUserId();\n const candidate = userId ? dependencies.getLocalIdentity(userId) : null;\n if (!userId || !candidate) {\n throw new Error(\"Sign in before sharing your identity link.\");\n }\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return createIdentityLink(identity, appUrl);\n}\n\nexport function createTrustedUserIdentityService(\n input: TrustedUserIdentityServiceDependencies,\n): TrustedUserIdentityService {\n const { dependencies, handoff } = withStagedIdentityHandoff(input);\n const verifiedReaders = verifiedPinReaders(dependencies);\n return {\n async resolvePinned(userId) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });\n },\n ...verifiedReaders,\n createLink: (appUrl) => createLocalIdentityLink(dependencies, appUrl),\n async createLinkFor(userId, appUrl) {\n if (\n userId === dependencies.getLocalUserId() &&\n dependencies.getLocalIdentity(userId)\n ) {\n return createLocalIdentityLink(dependencies, appUrl);\n }\n // Only a `link` or `self` pin: re-sharing an observed (TOFU) key as a\n // link would let its recipient pin an unverified key as `link`.\n const identity = await verifiedReaders.resolveVerified(userId);\n return identity ? createIdentityLink(identity, appUrl) : null;\n },\n verifyLink: (link) => verifyIdentityLink(dependencies, link),\n boundUserId: (signingKeyFingerprint) =>\n boundUserId(dependencies, signingKeyFingerprint),\n async pinLocal(userId, candidate) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return pinIdentity({\n dependencies,\n execSql,\n identity,\n provenance: \"self\",\n });\n },\n resolve: withPinnedIdentityResolution(\n dependencies,\n async (userId) => {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } =\n requireTrustStore(dependencies);\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n if (!candidate) {\n return null;\n }\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed while resolving this user.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source,\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(userId);\n throw error;\n }\n },\n {\n loadCandidate: (userId, identityTrustDomain) =>\n loadRemoteCandidate(dependencies, userId, identityTrustDomain),\n pinObserved: (execSql, identities, assertCurrent) =>\n compareWithDurablePins({\n assertCurrent,\n execSql,\n firstSeenAt: (dependencies.now?.() ?? new Date()).toISOString(),\n identities,\n provenance: \"observed\",\n }),\n },\n handoff,\n ),\n };\n}\n"]}
@@ -0,0 +1,26 @@
1
+ import type { LoroDoc } from "loro-crdt";
2
+ /**
3
+ * The longest span, in seconds, that one change may cover after its own
4
+ * timestamp. Loro folds a peer's consecutive commits into one change while
5
+ * they fall inside this window, and a change carries exactly one timestamp,
6
+ * so this is the time resolution of a document's history: an operation was
7
+ * committed no later than this many seconds after its change's timestamp.
8
+ *
9
+ * A wider window stores fewer changes and coarser times. One second costs at
10
+ * most one change per second of activity, which measured as roughly a fifth
11
+ * more snapshot bytes for the slowest possible typist (one character every
12
+ * one to three seconds) and far less for ordinary bursts.
13
+ */
14
+ export declare const DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS = 1;
15
+ /**
16
+ * Make every change this document authors carry the Unix time of its commit,
17
+ * rounded to the nearest second. History is the only durable record of when
18
+ * an edit happened: uploads coalesce local writes, and local tail rows fold
19
+ * into checkpoints.
20
+ *
21
+ * The setting belongs to the document instance, not to its exported bytes, so
22
+ * it must be applied to every document that can author. A document without it
23
+ * stamps the largest timestamp it has imported instead of the current time,
24
+ * which silently back-dates its edits. `fork()` copies the setting.
25
+ */
26
+ export declare function recordChangeTimestamps(doc: LoroDoc): void;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The longest span, in seconds, that one change may cover after its own
3
+ * timestamp. Loro folds a peer's consecutive commits into one change while
4
+ * they fall inside this window, and a change carries exactly one timestamp,
5
+ * so this is the time resolution of a document's history: an operation was
6
+ * committed no later than this many seconds after its change's timestamp.
7
+ *
8
+ * A wider window stores fewer changes and coarser times. One second costs at
9
+ * most one change per second of activity, which measured as roughly a fifth
10
+ * more snapshot bytes for the slowest possible typist (one character every
11
+ * one to three seconds) and far less for ordinary bursts.
12
+ */
13
+ export const DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS = 1;
14
+ /**
15
+ * Make every change this document authors carry the Unix time of its commit,
16
+ * rounded to the nearest second. History is the only durable record of when
17
+ * an edit happened: uploads coalesce local writes, and local tail rows fold
18
+ * into checkpoints.
19
+ *
20
+ * The setting belongs to the document instance, not to its exported bytes, so
21
+ * it must be applied to every document that can author. A document without it
22
+ * stamps the largest timestamp it has imported instead of the current time,
23
+ * which silently back-dates its edits. `fork()` copies the setting.
24
+ */
25
+ export function recordChangeTimestamps(doc) {
26
+ doc.setRecordTimestamp(true);
27
+ doc.setChangeMergeInterval(DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS);
28
+ }
29
+ //# sourceMappingURL=changeTimestamps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"changeTimestamps.js","sourceRoot":"","sources":["changeTimestamps.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,sCAAsC,GAAG,CAAC,CAAC;AAExD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,sBAAsB,CAAC,GAAY;IACjD,GAAG,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IAC7B,GAAG,CAAC,sBAAsB,CAAC,sCAAsC,CAAC,CAAC;AACrE,CAAC","sourcesContent":["import type { LoroDoc } from \"loro-crdt\";\n\n/**\n * The longest span, in seconds, that one change may cover after its own\n * timestamp. Loro folds a peer's consecutive commits into one change while\n * they fall inside this window, and a change carries exactly one timestamp,\n * so this is the time resolution of a document's history: an operation was\n * committed no later than this many seconds after its change's timestamp.\n *\n * A wider window stores fewer changes and coarser times. One second costs at\n * most one change per second of activity, which measured as roughly a fifth\n * more snapshot bytes for the slowest possible typist (one character every\n * one to three seconds) and far less for ordinary bursts.\n */\nexport const DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS = 1;\n\n/**\n * Make every change this document authors carry the Unix time of its commit,\n * rounded to the nearest second. History is the only durable record of when\n * an edit happened: uploads coalesce local writes, and local tail rows fold\n * into checkpoints.\n *\n * The setting belongs to the document instance, not to its exported bytes, so\n * it must be applied to every document that can author. A document without it\n * stamps the largest timestamp it has imported instead of the current time,\n * which silently back-dates its edits. `fork()` copies the setting.\n */\nexport function recordChangeTimestamps(doc: LoroDoc): void {\n doc.setRecordTimestamp(true);\n doc.setChangeMergeInterval(DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS);\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { base64ToBytes, bytesToBase64 } from "../encoding/index.js";
2
2
  import { LoroDoc, VersionVector } from "loro-crdt";
3
+ import { recordChangeTimestamps } from "./changeTimestamps.js";
3
4
  import { serializeCanonicalHistory } from "./historyCanonicalization.js";
4
5
  import { getImportBlobMetadata } from "./importMetadata.js";
5
6
  export { getImportBlobMetadata } from "./importMetadata.js";
@@ -47,6 +48,7 @@ export async function derivePeerId(seed) {
47
48
  export async function createDocument(peerSeed) {
48
49
  const doc = new LoroDoc();
49
50
  doc.setPeerId(await derivePeerId(peerSeed));
51
+ recordChangeTimestamps(doc);
50
52
  return doc;
51
53
  }
52
54
  export function exportAllUpdates(doc) {
@@ -1 +1 @@
1
- {"version":3,"file":"document.js","sourceRoot":"","sources":["document.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAuB,MAAM,kBAAkB,CAAC;A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Q,CAAC,CAAC;QAC9B,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC/B,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YAC9B,GAAG;YACH,MAAM,EAAE,GAAG,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,IAAI;SACvC,CAAC,CAAC,CAAC;IACN,CAAC;YAAS,CAAC;QACT,GAAG,CAAC,IAAI,EAAE,CAAC;IACb,CAAC;AACH,CAAC","sourcesContent":["import { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { LoroDoc, VersionVector } from \"loro-crdt\";\nimport { serializeCanonicalHistory } from \"./historyCanonicalization\";\nimport { getImportBlobMetadata } from \"./importMetadata\";\n\nexport { getImportBlobMetadata, type ImportBlobMode } from \"./importMetadata\";\n\nfunction isPeerIdString(value: string): value is `${number}` {\n return /^\\d+$/.test(value);\n}\n\nconst MAX_POSTGRES_INTEGER = 2_147_483_647;\n\nexport class LoroImportUnresolvedDependenciesError extends Error {\n readonly importKind: \"snapshot\" | \"updates\";\n\n constructor(importKind: \"snapshot\" | \"updates\") {\n super(\n `import${importKind === \"snapshot\" ? \"Snapshot\" : \"Updates\"} received ${\n importKind === \"snapshot\" ? \"a snapshot\" : \"updates\"\n } with unresolved pending dependencies`,\n );\n this.name = \"LoroImportUnresolvedDependenciesError\";\n this.importKind = importKind;\n }\n}\n\nexport interface VersionVectorSpan {\n peerId: `${number}`;\n startCounter: number;\n endCounter: number;\n}\n\nfunction assertSupportedVersionVectorCounter(counter: number): void {\n if (\n !Number.isInteger(counter) ||\n counter < 0 ||\n counter > MAX_POSTGRES_INTEGER\n ) {\n throw new Error(\n \"Version vector counter is outside the supported integer range.\",\n );\n }\n}\n\nfunction normalizeVersionVectorEntries(\n versionVector: VersionVector,\n): Map<`${number}`, number> {\n const entries = new Map<`${number}`, number>();\n\n for (const [peerId, counter] of versionVector.toJSON()) {\n const normalizedPeerId = String(peerId);\n if (!isPeerIdString(normalizedPeerId)) {\n throw new Error(\"Version vector contains a non-numeric peer ID.\");\n }\n assertSupportedVersionVectorCounter(counter);\n entries.set(normalizedPeerId, counter);\n }\n\n return entries;\n}\n\nexport async function derivePeerId(\n seed: string | Uint8Array,\n): Promise<`${number}`> {\n const bytes =\n typeof seed === \"string\" ? new TextEncoder().encode(seed) : seed;\n const digest = new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", bytes.slice()),\n );\n const view = new DataView(\n digest.buffer,\n digest.byteOffset,\n digest.byteLength,\n );\n const peerId = (view.getBigUint64(0, false) || 1n).toString();\n\n if (!isPeerIdString(peerId)) {\n throw new Error(\"Failed to derive a numeric peer ID.\");\n }\n\n return peerId;\n}\n\nexport async function createDocument(peerSeed: string | Uint8Array) {\n const doc = new LoroDoc();\n doc.setPeerId(await derivePeerId(peerSeed));\n return doc;\n}\n\nexport function exportAllUpdates(doc: LoroDoc): Uint8Array {\n return doc.export({ mode: \"update\" });\n}\n\n/** Deterministic, peer-uncompressed identity for an operation-log prefix. */\nexport function exportFullHistoryIdentity(\n doc: LoroDoc,\n endVersion?: string,\n): string {\n return serializeCanonicalHistory(\n doc.exportJsonUpdates(\n undefined,\n endVersion === undefined ? undefined : decodeVersionVector(endVersion),\n false,\n ),\n );\n}\n\n/**\n * Export a mergeable, full-history snapshot — the only snapshot form this\n * codebase produces. Every document is born with full durable history and\n * restored from it, so a partial (gc'd) export here is an invariant\n * violation, not a state to accommodate; fail loudly instead of publishing a\n * blob that could not safely merge concurrent frontiers.\n */\nexport function exportFullHistorySnapshot(doc: LoroDoc): Uint8Array {\n const snapshot = doc.export({ mode: \"snapshot\" });\n const metadata = getImportBlobMetadata(snapshot);\n if (\n metadata.mode !== \"snapshot\" ||\n !versionVectorsEqual(\n metadata.partialStartVersionVector,\n emptyVersionVector(),\n )\n ) {\n throw new Error(\n \"Document export lost full history; this document was restored from an incomplete source\",\n );\n }\n return snapshot;\n}\n\nexport function exportUpdatesSince(\n doc: LoroDoc,\n encodedVersionVector?: string | null,\n): Uint8Array {\n if (!encodedVersionVector) {\n return exportAllUpdates(doc);\n }\n\n return doc.export({\n mode: \"update\",\n from: VersionVector.decode(base64ToBytes(encodedVersionVector)),\n });\n}\n\nexport function encodeEncodedVersionVector(\n versionVector: VersionVector,\n): string {\n return bytesToBase64(versionVector.encode());\n}\n\nexport function encodeVersionVector(doc: LoroDoc): string {\n return encodeEncodedVersionVector(doc.oplogVersion());\n}\n\nexport function emptyVersionVector(): string {\n return encodeEncodedVersionVector(new VersionVector(undefined));\n}\n\nexport function decodeVersionVector(\n encodedVersionVector: string | null | undefined,\n): VersionVector {\n if (!encodedVersionVector) {\n return new VersionVector(undefined);\n }\n\n return VersionVector.decode(base64ToBytes(encodedVersionVector));\n}\n\nexport function getUpdateVersionVectors(update: Uint8Array): {\n partialStartVersionVector: string;\n partialEndVersionVector: string;\n} {\n const metadata = getImportBlobMetadata(update);\n\n return {\n partialStartVersionVector: metadata.partialStartVersionVector,\n partialEndVersionVector: metadata.partialEndVersionVector,\n };\n}\n\nexport function satisfiesVersionVector(\n encodedVersionVector: string | null | undefined,\n partialVersionVector: string,\n): boolean {\n const versionVector = decodeVersionVector(encodedVersionVector);\n const requiredVersionVector = decodeVersionVector(partialVersionVector);\n\n for (const [peerId, counter] of requiredVersionVector.toJSON()) {\n if ((versionVector.get(peerId) ?? 0) < counter) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function mergeVersionVectors(\n encodedVersionVectors: ReadonlyArray<string>,\n): string {\n const merged = new Map<`${number}`, number>();\n\n for (const encodedVersionVector of encodedVersionVectors) {\n for (const [normalizedPeerId, counter] of normalizeVersionVectorEntries(\n decodeVersionVector(encodedVersionVector),\n )) {\n merged.set(\n normalizedPeerId,\n Math.max(merged.get(normalizedPeerId) ?? 0, counter),\n );\n }\n }\n\n return encodeEncodedVersionVector(VersionVector.parseJSON(merged));\n}\n\nexport function listVersionVectorSpans(input: {\n partialStartVersionVector: string;\n partialEndVersionVector: string;\n}): VersionVectorSpan[] {\n const startEntries = normalizeVersionVectorEntries(\n decodeVersionVector(input.partialStartVersionVector),\n );\n const endEntries = normalizeVersionVectorEntries(\n decodeVersionVector(input.partialEndVersionVector),\n );\n const spans: VersionVectorSpan[] = [];\n\n for (const [peerId, startCounter] of startEntries) {\n const endCounter = endEntries.get(peerId) ?? 0;\n if (startCounter > endCounter) {\n throw new Error(\"Version vector end must cover start.\");\n }\n }\n\n for (const [peerId, endCounter] of endEntries) {\n const startCounter = startEntries.get(peerId) ?? 0;\n if (endCounter <= startCounter) {\n continue;\n }\n\n spans.push({ peerId, startCounter, endCounter });\n }\n\n return spans.sort((left, right) => left.peerId.localeCompare(right.peerId));\n}\n\nexport function versionVectorsEqual(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n const leftEntries = decodeVersionVector(left).toJSON();\n const rightEntries = decodeVersionVector(right).toJSON();\n\n if (leftEntries.size !== rightEntries.size) {\n return false;\n }\n\n for (const [peerId, leftCounter] of leftEntries) {\n if (rightEntries.get(peerId) !== leftCounter) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function importUpdates(doc: LoroDoc, updates: Uint8Array[]): void {\n // Reject an obsolete member before importBatch can mutate the document.\n for (const update of updates) getImportBlobMetadata(update);\n const status = doc.importBatch(updates);\n if (status.pending != null && status.pending.size > 0) {\n // importBatch applies out-of-order batches correctly but can still report\n // the intermediate pending set it saw mid-batch. Trust the document, not\n // the report: the import only genuinely failed when the document's final\n // version does not cover some batched update's end version.\n const documentVersion = encodeVersionVector(doc);\n const covered = updates.every((update) =>\n satisfiesVersionVector(\n documentVersion,\n getImportBlobMetadata(update).partialEndVersionVector,\n ),\n );\n if (!covered) {\n throw new LoroImportUnresolvedDependenciesError(\"updates\");\n }\n }\n}\n\n/**\n * Load a snapshot blob into a document. Snapshots MUST go through a single\n * `import()`, never `importBatch()`. A non-empty `pending` means the import\n * target is incompatible or dependencies are missing, so fail loudly instead\n * of silently loading a short document.\n */\nexport function importSnapshot(doc: LoroDoc, snapshot: Uint8Array): void {\n getImportBlobMetadata(snapshot);\n const status = doc.import(snapshot);\n // Reject only a genuinely incomplete import: `pending` can be an empty\n // VersionVector (size 0) rather than null when everything resolved, so test\n // for at least one unresolved dependency instead of mere presence.\n if (status.pending != null && status.pending.size > 0) {\n throw new LoroImportUnresolvedDependenciesError(\"snapshot\");\n }\n}\n\nexport function getTextValue(doc: LoroDoc, key = \"text\"): string {\n return doc.getText(key).toString();\n}\n\nexport interface TextCharOpId {\n /** Peer of the op that inserted this character. */\n peerId: `${number}`;\n /** Counter of that op — identifies the character within the peer's stream. */\n counter: number;\n}\n\nexport interface TextCharBlameSource {\n /** One entry per Unicode code point of the prose, in document order. */\n codePoints: string[];\n /** The op id that inserted each code point — same length and order as `codePoints`. */\n opIds: TextCharOpId[];\n}\n\n/**\n * Walk a LoroText's prose once, collecting each Unicode code point alongside the\n * op id `(peerId, counter)` of the op that inserted it. The two arrays share an\n * index, so callers can both blame and re-render the prose (the per-range view)\n * from a single pass.\n *\n * One Loro op (one counter) is one code point, but an astral character spans\n * two UTF-16 units. Loro cursors address UTF-16 positions; an interior\n * low-surrogate position has no op id. Iterate code points and advance by their\n * UTF-16 length so attribution neither splits nor double-counts a character.\n */\nfunction collectTextCharBlame(doc: LoroDoc, key: string): TextCharBlameSource {\n const text = doc.getText(key);\n const codePoints: string[] = [];\n const opIds: TextCharOpId[] = [];\n let utf16Start = 0;\n for (const char of text.toString()) {\n // getCursor mints a WASM-backed Cursor each call; free it immediately after\n // reading its op id so a long document does not pile up cursors on the heap.\n const cursor = text.getCursor(utf16Start, 1);\n const opId = cursor?.pos();\n cursor?.free();\n if (opId === undefined) {\n throw new Error(\n `LoroText \"${key}\" code point starting at UTF-16 index ${utf16Start} has no op id.`,\n );\n }\n codePoints.push(char);\n opIds.push({ peerId: opId.peer, counter: opId.counter });\n utf16Start += char.length;\n }\n return { codePoints, opIds };\n}\n\n/**\n * Per-character op-id attribution for a LoroText container's prose. Returns one\n * `(peerId, counter)` per Unicode code point — the op that inserted that\n * character — in document order; the array length equals the code-point count\n * (`[...text].length`). This is the client-side primitive for character-level\n * \"blame\": each op id resolves to a writer by intersecting it against the\n * document's edit-attribution segments.\n */\nexport function listTextCharOpIds(doc: LoroDoc, key = \"text\"): TextCharOpId[] {\n return collectTextCharBlame(doc, key).opIds;\n}\n\n/**\n * {@link listTextCharOpIds} for a persisted snapshot blob, without opening an\n * editor: rebuilds a throwaway read-only `LoroDoc` from the snapshot and reads\n * each character's op id, so blame is exact. The doc is only read, never\n * edited, so no peer id is set.\n *\n * Extraction is linear: `getCursor()` is an O(log n) b-tree lookup per code\n * point (measured ~1.8µs/char — ~90ms for a 50k-char snapshot, flat per char and\n * unaffected by tombstones). `maxCharacters` (UTF-16 length) is therefore a soft\n * guard against pathologically large prose, not a quadratic cliff: over it we\n * return `null` (\"skipped, too large\", distinct from `[]` for an empty document)\n * rather than do unbounded synchronous work on the render thread.\n */\nexport function listSnapshotCharOpIds(\n snapshot: Uint8Array,\n maxCharacters: number,\n key = \"text\",\n): TextCharOpId[] | null {\n const source = listSnapshotCharBlameSource(snapshot, maxCharacters, key);\n return source === null ? null : source.opIds;\n}\n\n/**\n * {@link listSnapshotCharBlameSource} is {@link listSnapshotCharOpIds} that also\n * returns each code point's text, so a caller can render the prose tinted by\n * writer (the per-range \"blame\" view) without a second snapshot reconstruction.\n * Same linear cost and `maxCharacters` guard.\n */\nexport function listSnapshotCharBlameSource(\n snapshot: Uint8Array,\n maxCharacters: number,\n key = \"text\",\n): TextCharBlameSource | null {\n const doc = new LoroDoc();\n try {\n importSnapshot(doc, snapshot);\n if (doc.getText(key).length > maxCharacters) {\n return null;\n }\n return collectTextCharBlame(doc, key);\n } finally {\n // The throwaway doc is WASM-backed and never returned — free it immediately\n // rather than waiting for GC, since blame rebuilds one per Info-panel load.\n doc.free();\n }\n}\n\nexport interface FieldEditor {\n /** The map key (e.g. `firstName`, `cardNumber`) of a structured document field. */\n key: string;\n /** Peer of the op that last set this field, or null if none is recorded. */\n peerId: `${number}` | null;\n}\n\n/**\n * The structured-document counterpart to {@link listSnapshotCharBlameSource}:\n * for a persisted snapshot, name the peer that last wrote each key of a LoroMap\n * (the document's `fields` map). Structured documents (contacts, cards, licenses)\n * store each field as a `LoroMap` entry — a last-writer-wins register that keeps\n * the setting op's peer, which `getLastEditor` reads. That peer resolves to a\n * writer via the same attribution segments,\n * giving per-field \"blame\". Fields carry only the peer (no op counter), so\n * resolution is peer-level. A note (or any document without this map) yields an\n * empty array. Reconstructing the small map is cheap, so there is no size cap.\n */\nexport function listSnapshotFieldEditors(\n snapshot: Uint8Array,\n mapKey: string,\n): FieldEditor[] {\n const doc = new LoroDoc();\n try {\n importSnapshot(doc, snapshot);\n const map = doc.getMap(mapKey);\n return map.keys().map((key) => ({\n key,\n peerId: map.getLastEditor(key) ?? null,\n }));\n } finally {\n doc.free();\n }\n}\n"]}
1
+ {"version":3,"file":"document.js","sourceRoot":"","sources":["document.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAuB,MAAM,kBAAkB,CAAC;AAE9E,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC7B,CAAC;AAED,MAAM,oBAAoB,GAAG,aAAa,CAAC;AAE3C,MAAM,OAAO,qCAAsC,SAAQ,KAAK;IACrD,UAAU,CAAyB;IAE5C,YAAY,UAAkC;QAC5C,KAAK,CACH,SA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M,EAAE,GAAG,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,IAAI;SACvC,CAAC,CAAC,CAAC;IACN,CAAC;YAAS,CAAC;QACT,GAAG,CAAC,IAAI,EAAE,CAAC;IACb,CAAC;AACH,CAAC","sourcesContent":["import { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { LoroDoc, VersionVector } from \"loro-crdt\";\nimport { recordChangeTimestamps } from \"./changeTimestamps\";\nimport { serializeCanonicalHistory } from \"./historyCanonicalization\";\nimport { getImportBlobMetadata } from \"./importMetadata\";\n\nexport { getImportBlobMetadata, type ImportBlobMode } from \"./importMetadata\";\n\nfunction isPeerIdString(value: string): value is `${number}` {\n return /^\\d+$/.test(value);\n}\n\nconst MAX_POSTGRES_INTEGER = 2_147_483_647;\n\nexport class LoroImportUnresolvedDependenciesError extends Error {\n readonly importKind: \"snapshot\" | \"updates\";\n\n constructor(importKind: \"snapshot\" | \"updates\") {\n super(\n `import${importKind === \"snapshot\" ? \"Snapshot\" : \"Updates\"} received ${\n importKind === \"snapshot\" ? \"a snapshot\" : \"updates\"\n } with unresolved pending dependencies`,\n );\n this.name = \"LoroImportUnresolvedDependenciesError\";\n this.importKind = importKind;\n }\n}\n\nexport interface VersionVectorSpan {\n peerId: `${number}`;\n startCounter: number;\n endCounter: number;\n}\n\nfunction assertSupportedVersionVectorCounter(counter: number): void {\n if (\n !Number.isInteger(counter) ||\n counter < 0 ||\n counter > MAX_POSTGRES_INTEGER\n ) {\n throw new Error(\n \"Version vector counter is outside the supported integer range.\",\n );\n }\n}\n\nfunction normalizeVersionVectorEntries(\n versionVector: VersionVector,\n): Map<`${number}`, number> {\n const entries = new Map<`${number}`, number>();\n\n for (const [peerId, counter] of versionVector.toJSON()) {\n const normalizedPeerId = String(peerId);\n if (!isPeerIdString(normalizedPeerId)) {\n throw new Error(\"Version vector contains a non-numeric peer ID.\");\n }\n assertSupportedVersionVectorCounter(counter);\n entries.set(normalizedPeerId, counter);\n }\n\n return entries;\n}\n\nexport async function derivePeerId(\n seed: string | Uint8Array,\n): Promise<`${number}`> {\n const bytes =\n typeof seed === \"string\" ? new TextEncoder().encode(seed) : seed;\n const digest = new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", bytes.slice()),\n );\n const view = new DataView(\n digest.buffer,\n digest.byteOffset,\n digest.byteLength,\n );\n const peerId = (view.getBigUint64(0, false) || 1n).toString();\n\n if (!isPeerIdString(peerId)) {\n throw new Error(\"Failed to derive a numeric peer ID.\");\n }\n\n return peerId;\n}\n\nexport async function createDocument(peerSeed: string | Uint8Array) {\n const doc = new LoroDoc();\n doc.setPeerId(await derivePeerId(peerSeed));\n recordChangeTimestamps(doc);\n return doc;\n}\n\nexport function exportAllUpdates(doc: LoroDoc): Uint8Array {\n return doc.export({ mode: \"update\" });\n}\n\n/** Deterministic, peer-uncompressed identity for an operation-log prefix. */\nexport function exportFullHistoryIdentity(\n doc: LoroDoc,\n endVersion?: string,\n): string {\n return serializeCanonicalHistory(\n doc.exportJsonUpdates(\n undefined,\n endVersion === undefined ? undefined : decodeVersionVector(endVersion),\n false,\n ),\n );\n}\n\n/**\n * Export a mergeable, full-history snapshot — the only snapshot form this\n * codebase produces. Every document is born with full durable history and\n * restored from it, so a partial (gc'd) export here is an invariant\n * violation, not a state to accommodate; fail loudly instead of publishing a\n * blob that could not safely merge concurrent frontiers.\n */\nexport function exportFullHistorySnapshot(doc: LoroDoc): Uint8Array {\n const snapshot = doc.export({ mode: \"snapshot\" });\n const metadata = getImportBlobMetadata(snapshot);\n if (\n metadata.mode !== \"snapshot\" ||\n !versionVectorsEqual(\n metadata.partialStartVersionVector,\n emptyVersionVector(),\n )\n ) {\n throw new Error(\n \"Document export lost full history; this document was restored from an incomplete source\",\n );\n }\n return snapshot;\n}\n\nexport function exportUpdatesSince(\n doc: LoroDoc,\n encodedVersionVector?: string | null,\n): Uint8Array {\n if (!encodedVersionVector) {\n return exportAllUpdates(doc);\n }\n\n return doc.export({\n mode: \"update\",\n from: VersionVector.decode(base64ToBytes(encodedVersionVector)),\n });\n}\n\nexport function encodeEncodedVersionVector(\n versionVector: VersionVector,\n): string {\n return bytesToBase64(versionVector.encode());\n}\n\nexport function encodeVersionVector(doc: LoroDoc): string {\n return encodeEncodedVersionVector(doc.oplogVersion());\n}\n\nexport function emptyVersionVector(): string {\n return encodeEncodedVersionVector(new VersionVector(undefined));\n}\n\nexport function decodeVersionVector(\n encodedVersionVector: string | null | undefined,\n): VersionVector {\n if (!encodedVersionVector) {\n return new VersionVector(undefined);\n }\n\n return VersionVector.decode(base64ToBytes(encodedVersionVector));\n}\n\nexport function getUpdateVersionVectors(update: Uint8Array): {\n partialStartVersionVector: string;\n partialEndVersionVector: string;\n} {\n const metadata = getImportBlobMetadata(update);\n\n return {\n partialStartVersionVector: metadata.partialStartVersionVector,\n partialEndVersionVector: metadata.partialEndVersionVector,\n };\n}\n\nexport function satisfiesVersionVector(\n encodedVersionVector: string | null | undefined,\n partialVersionVector: string,\n): boolean {\n const versionVector = decodeVersionVector(encodedVersionVector);\n const requiredVersionVector = decodeVersionVector(partialVersionVector);\n\n for (const [peerId, counter] of requiredVersionVector.toJSON()) {\n if ((versionVector.get(peerId) ?? 0) < counter) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function mergeVersionVectors(\n encodedVersionVectors: ReadonlyArray<string>,\n): string {\n const merged = new Map<`${number}`, number>();\n\n for (const encodedVersionVector of encodedVersionVectors) {\n for (const [normalizedPeerId, counter] of normalizeVersionVectorEntries(\n decodeVersionVector(encodedVersionVector),\n )) {\n merged.set(\n normalizedPeerId,\n Math.max(merged.get(normalizedPeerId) ?? 0, counter),\n );\n }\n }\n\n return encodeEncodedVersionVector(VersionVector.parseJSON(merged));\n}\n\nexport function listVersionVectorSpans(input: {\n partialStartVersionVector: string;\n partialEndVersionVector: string;\n}): VersionVectorSpan[] {\n const startEntries = normalizeVersionVectorEntries(\n decodeVersionVector(input.partialStartVersionVector),\n );\n const endEntries = normalizeVersionVectorEntries(\n decodeVersionVector(input.partialEndVersionVector),\n );\n const spans: VersionVectorSpan[] = [];\n\n for (const [peerId, startCounter] of startEntries) {\n const endCounter = endEntries.get(peerId) ?? 0;\n if (startCounter > endCounter) {\n throw new Error(\"Version vector end must cover start.\");\n }\n }\n\n for (const [peerId, endCounter] of endEntries) {\n const startCounter = startEntries.get(peerId) ?? 0;\n if (endCounter <= startCounter) {\n continue;\n }\n\n spans.push({ peerId, startCounter, endCounter });\n }\n\n return spans.sort((left, right) => left.peerId.localeCompare(right.peerId));\n}\n\nexport function versionVectorsEqual(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n const leftEntries = decodeVersionVector(left).toJSON();\n const rightEntries = decodeVersionVector(right).toJSON();\n\n if (leftEntries.size !== rightEntries.size) {\n return false;\n }\n\n for (const [peerId, leftCounter] of leftEntries) {\n if (rightEntries.get(peerId) !== leftCounter) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function importUpdates(doc: LoroDoc, updates: Uint8Array[]): void {\n // Reject an obsolete member before importBatch can mutate the document.\n for (const update of updates) getImportBlobMetadata(update);\n const status = doc.importBatch(updates);\n if (status.pending != null && status.pending.size > 0) {\n // importBatch applies out-of-order batches correctly but can still report\n // the intermediate pending set it saw mid-batch. Trust the document, not\n // the report: the import only genuinely failed when the document's final\n // version does not cover some batched update's end version.\n const documentVersion = encodeVersionVector(doc);\n const covered = updates.every((update) =>\n satisfiesVersionVector(\n documentVersion,\n getImportBlobMetadata(update).partialEndVersionVector,\n ),\n );\n if (!covered) {\n throw new LoroImportUnresolvedDependenciesError(\"updates\");\n }\n }\n}\n\n/**\n * Load a snapshot blob into a document. Snapshots MUST go through a single\n * `import()`, never `importBatch()`. A non-empty `pending` means the import\n * target is incompatible or dependencies are missing, so fail loudly instead\n * of silently loading a short document.\n */\nexport function importSnapshot(doc: LoroDoc, snapshot: Uint8Array): void {\n getImportBlobMetadata(snapshot);\n const status = doc.import(snapshot);\n // Reject only a genuinely incomplete import: `pending` can be an empty\n // VersionVector (size 0) rather than null when everything resolved, so test\n // for at least one unresolved dependency instead of mere presence.\n if (status.pending != null && status.pending.size > 0) {\n throw new LoroImportUnresolvedDependenciesError(\"snapshot\");\n }\n}\n\nexport function getTextValue(doc: LoroDoc, key = \"text\"): string {\n return doc.getText(key).toString();\n}\n\nexport interface TextCharOpId {\n /** Peer of the op that inserted this character. */\n peerId: `${number}`;\n /** Counter of that op — identifies the character within the peer's stream. */\n counter: number;\n}\n\nexport interface TextCharBlameSource {\n /** One entry per Unicode code point of the prose, in document order. */\n codePoints: string[];\n /** The op id that inserted each code point — same length and order as `codePoints`. */\n opIds: TextCharOpId[];\n}\n\n/**\n * Walk a LoroText's prose once, collecting each Unicode code point alongside the\n * op id `(peerId, counter)` of the op that inserted it. The two arrays share an\n * index, so callers can both blame and re-render the prose (the per-range view)\n * from a single pass.\n *\n * One Loro op (one counter) is one code point, but an astral character spans\n * two UTF-16 units. Loro cursors address UTF-16 positions; an interior\n * low-surrogate position has no op id. Iterate code points and advance by their\n * UTF-16 length so attribution neither splits nor double-counts a character.\n */\nfunction collectTextCharBlame(doc: LoroDoc, key: string): TextCharBlameSource {\n const text = doc.getText(key);\n const codePoints: string[] = [];\n const opIds: TextCharOpId[] = [];\n let utf16Start = 0;\n for (const char of text.toString()) {\n // getCursor mints a WASM-backed Cursor each call; free it immediately after\n // reading its op id so a long document does not pile up cursors on the heap.\n const cursor = text.getCursor(utf16Start, 1);\n const opId = cursor?.pos();\n cursor?.free();\n if (opId === undefined) {\n throw new Error(\n `LoroText \"${key}\" code point starting at UTF-16 index ${utf16Start} has no op id.`,\n );\n }\n codePoints.push(char);\n opIds.push({ peerId: opId.peer, counter: opId.counter });\n utf16Start += char.length;\n }\n return { codePoints, opIds };\n}\n\n/**\n * Per-character op-id attribution for a LoroText container's prose. Returns one\n * `(peerId, counter)` per Unicode code point — the op that inserted that\n * character — in document order; the array length equals the code-point count\n * (`[...text].length`). This is the client-side primitive for character-level\n * \"blame\": each op id resolves to a writer by intersecting it against the\n * document's edit-attribution segments.\n */\nexport function listTextCharOpIds(doc: LoroDoc, key = \"text\"): TextCharOpId[] {\n return collectTextCharBlame(doc, key).opIds;\n}\n\n/**\n * {@link listTextCharOpIds} for a persisted snapshot blob, without opening an\n * editor: rebuilds a throwaway read-only `LoroDoc` from the snapshot and reads\n * each character's op id, so blame is exact. The doc is only read, never\n * edited, so no peer id is set.\n *\n * Extraction is linear: `getCursor()` is an O(log n) b-tree lookup per code\n * point (measured ~1.8µs/char — ~90ms for a 50k-char snapshot, flat per char and\n * unaffected by tombstones). `maxCharacters` (UTF-16 length) is therefore a soft\n * guard against pathologically large prose, not a quadratic cliff: over it we\n * return `null` (\"skipped, too large\", distinct from `[]` for an empty document)\n * rather than do unbounded synchronous work on the render thread.\n */\nexport function listSnapshotCharOpIds(\n snapshot: Uint8Array,\n maxCharacters: number,\n key = \"text\",\n): TextCharOpId[] | null {\n const source = listSnapshotCharBlameSource(snapshot, maxCharacters, key);\n return source === null ? null : source.opIds;\n}\n\n/**\n * {@link listSnapshotCharBlameSource} is {@link listSnapshotCharOpIds} that also\n * returns each code point's text, so a caller can render the prose tinted by\n * writer (the per-range \"blame\" view) without a second snapshot reconstruction.\n * Same linear cost and `maxCharacters` guard.\n */\nexport function listSnapshotCharBlameSource(\n snapshot: Uint8Array,\n maxCharacters: number,\n key = \"text\",\n): TextCharBlameSource | null {\n const doc = new LoroDoc();\n try {\n importSnapshot(doc, snapshot);\n if (doc.getText(key).length > maxCharacters) {\n return null;\n }\n return collectTextCharBlame(doc, key);\n } finally {\n // The throwaway doc is WASM-backed and never returned — free it immediately\n // rather than waiting for GC, since blame rebuilds one per Info-panel load.\n doc.free();\n }\n}\n\nexport interface FieldEditor {\n /** The map key (e.g. `firstName`, `cardNumber`) of a structured document field. */\n key: string;\n /** Peer of the op that last set this field, or null if none is recorded. */\n peerId: `${number}` | null;\n}\n\n/**\n * The structured-document counterpart to {@link listSnapshotCharBlameSource}:\n * for a persisted snapshot, name the peer that last wrote each key of a LoroMap\n * (the document's `fields` map). Structured documents (contacts, cards, licenses)\n * store each field as a `LoroMap` entry — a last-writer-wins register that keeps\n * the setting op's peer, which `getLastEditor` reads. That peer resolves to a\n * writer via the same attribution segments,\n * giving per-field \"blame\". Fields carry only the peer (no op counter), so\n * resolution is peer-level. A note (or any document without this map) yields an\n * empty array. Reconstructing the small map is cheap, so there is no size cap.\n */\nexport function listSnapshotFieldEditors(\n snapshot: Uint8Array,\n mapKey: string,\n): FieldEditor[] {\n const doc = new LoroDoc();\n try {\n importSnapshot(doc, snapshot);\n const map = doc.getMap(mapKey);\n return map.keys().map((key) => ({\n key,\n peerId: map.getLastEditor(key) ?? null,\n }));\n } finally {\n doc.free();\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  export { LoroList, LoroMap } from "loro-crdt";
2
+ export { DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS } from "./changeTimestamps.js";
2
3
  export { createDocument, decodeVersionVector, derivePeerId, emptyVersionVector, encodeEncodedVersionVector, encodeVersionVector, exportAllUpdates, exportFullHistoryIdentity, exportFullHistorySnapshot, exportUpdatesSince, type FieldEditor, getImportBlobMetadata, getTextValue, getUpdateVersionVectors, type ImportBlobMode, importSnapshot, importUpdates, LoroImportUnresolvedDependenciesError, listSnapshotCharBlameSource, listSnapshotCharOpIds, listSnapshotFieldEditors, listTextCharOpIds, listVersionVectorSpans, mergeVersionVectors, satisfiesVersionVector, type TextCharBlameSource, type TextCharOpId, type VersionVectorSpan, versionVectorsEqual, } from "./document.js";
3
4
  export * from "./shared/index.js";
4
5
  export { updateMatchesDocumentHistory } from "./updateIdentity.js";
@@ -1,4 +1,5 @@
1
1
  export { LoroList, LoroMap } from "loro-crdt";
2
+ export { DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS } from "./changeTimestamps.js";
2
3
  export { createDocument, decodeVersionVector, derivePeerId, emptyVersionVector, encodeEncodedVersionVector, encodeVersionVector, exportAllUpdates, exportFullHistoryIdentity, exportFullHistorySnapshot, exportUpdatesSince, getImportBlobMetadata, getTextValue, getUpdateVersionVectors, importSnapshot, importUpdates, LoroImportUnresolvedDependenciesError, listSnapshotCharBlameSource, listSnapshotCharOpIds, listSnapshotFieldEditors, listTextCharOpIds, listVersionVectorSpans, mergeVersionVectors, satisfiesVersionVector, versionVectorsEqual, } from "./document.js";
3
4
  export * from "./shared/index.js";
4
5
  export { updateMatchesDocumentHistory } from "./updateIdentity.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,kBAAkB,EAClB,0BAA0B,EAC1B,mBAAmB,EACnB,gBAAgB,EAChB,yBAAyB,EACzB,yBAAyB,EACzB,kBAAkB,EAElB,qBAAqB,EACrB,YAAY,EACZ,uBAAuB,EAEvB,cAAc,EACd,aAAa,EACb,qCAAqC,EACrC,2BAA2B,EAC3B,qBAAqB,EACrB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,EAItB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,4BAA4B,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,gBAAgB,CAAC","sourcesContent":["export { LoroList, LoroMap } from \"loro-crdt\";\nexport {\n createDocument,\n decodeVersionVector,\n derivePeerId,\n emptyVersionVector,\n encodeEncodedVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistoryIdentity,\n exportFullHistorySnapshot,\n exportUpdatesSince,\n type FieldEditor,\n getImportBlobMetadata,\n getTextValue,\n getUpdateVersionVectors,\n type ImportBlobMode,\n importSnapshot,\n importUpdates,\n LoroImportUnresolvedDependenciesError,\n listSnapshotCharBlameSource,\n listSnapshotCharOpIds,\n listSnapshotFieldEditors,\n listTextCharOpIds,\n listVersionVectorSpans,\n mergeVersionVectors,\n satisfiesVersionVector,\n type TextCharBlameSource,\n type TextCharOpId,\n type VersionVectorSpan,\n versionVectorsEqual,\n} from \"./document\";\nexport * from \"./shared\";\nexport { updateMatchesDocumentHistory } from \"./updateIdentity\";\nexport {\n exportUpdatesInVersionRange,\n minimumVersionVectors,\n} from \"./versionRange\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,sCAAsC,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,kBAAkB,EAClB,0BAA0B,EAC1B,mBAAmB,EACnB,gBAAgB,EAChB,yBAAyB,EACzB,yBAAyB,EACzB,kBAAkB,EAElB,qBAAqB,EACrB,YAAY,EACZ,uBAAuB,EAEvB,cAAc,EACd,aAAa,EACb,qCAAqC,EACrC,2BAA2B,EAC3B,qBAAqB,EACrB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,EAItB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,4BAA4B,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,gBAAgB,CAAC","sourcesContent":["export { LoroList, LoroMap } from \"loro-crdt\";\nexport { DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS } from \"./changeTimestamps\";\nexport {\n createDocument,\n decodeVersionVector,\n derivePeerId,\n emptyVersionVector,\n encodeEncodedVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistoryIdentity,\n exportFullHistorySnapshot,\n exportUpdatesSince,\n type FieldEditor,\n getImportBlobMetadata,\n getTextValue,\n getUpdateVersionVectors,\n type ImportBlobMode,\n importSnapshot,\n importUpdates,\n LoroImportUnresolvedDependenciesError,\n listSnapshotCharBlameSource,\n listSnapshotCharOpIds,\n listSnapshotFieldEditors,\n listTextCharOpIds,\n listVersionVectorSpans,\n mergeVersionVectors,\n satisfiesVersionVector,\n type TextCharBlameSource,\n type TextCharOpId,\n type VersionVectorSpan,\n versionVectorsEqual,\n} from \"./document\";\nexport * from \"./shared\";\nexport { updateMatchesDocumentHistory } from \"./updateIdentity\";\nexport {\n exportUpdatesInVersionRange,\n minimumVersionVectors,\n} from \"./versionRange\";\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.197",
3
+ "version": "0.1.199",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1,36 +0,0 @@
1
- import { and, eq, inArray } from "drizzle-orm";
2
- import { trustedUserIdentityPins, trustedUserIdentityPinTables, } from "../../sqlite/schema/trustedUserIdentityPinSchema.js";
3
- import { sqliteRowsPerStatement } from "../../sqlite/sqliteBindBudget.js";
4
- import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
5
- import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
6
- import { parseStoredPin, } from "../trustedUserIdentityPinPersistence.js";
7
- import { runTrustedUserIdentityPinTransaction } from "../trustedUserIdentityPinTransaction.js";
8
- // Each member binds one ID; the trust domain binds once per statement.
9
- const PIN_READ_BATCH_SIZE = sqliteRowsPerStatement(1, 1);
10
- /** Read immutable pins together, never exposing another adapter's uncommitted rows. */
11
- export async function loadTrustedUserIdentityPins(input) {
12
- const userIds = [...new Set(input.userIds)];
13
- if (userIds.length === 0)
14
- return new Map();
15
- await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);
16
- const runtime = getClientSQLitePersistenceRuntime(input.execSql);
17
- return runTrustedUserIdentityPinTransaction(() => runtime.transaction(async (tx) => {
18
- const pins = new Map();
19
- for (let start = 0; start < userIds.length; start += PIN_READ_BATCH_SIZE) {
20
- const batch = userIds.slice(start, start + PIN_READ_BATCH_SIZE);
21
- const rows = await tx
22
- .select()
23
- .from(trustedUserIdentityPins)
24
- .where(and(eq(trustedUserIdentityPins.identityTrustDomain, input.identityTrustDomain), inArray(trustedUserIdentityPins.userId, batch)));
25
- for (const row of rows) {
26
- const pin = parseStoredPin(row, {
27
- identityTrustDomain: input.identityTrustDomain,
28
- userId: row.userId,
29
- });
30
- pins.set(pin.userId, pin);
31
- }
32
- }
33
- return pins;
34
- }));
35
- }
36
- //# sourceMappingURL=trustedUserIdentityPinBatch.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"trustedUserIdentityPinBatch.js","sourceRoot":"","sources":["trustedUserIdentityPinBatch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EACL,cAAc,GAEf,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,oCAAoC,EAAE,MAAM,sCAAsC,CAAC;AAE5F,uEAAuE;AACvE,MAAM,mBAAmB,GAAG,sBAAsB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAEzD,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,KAIjD;IACC,MAAM,OAAO,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,OAAO,CAA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le-orm\";\nimport {\n trustedUserIdentityPins,\n trustedUserIdentityPinTables,\n} from \"../../sqlite/schema/trustedUserIdentityPinSchema\";\nimport { sqliteRowsPerStatement } from \"../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n parseStoredPin,\n type TrustedUserIdentityPin,\n} from \"../trustedUserIdentityPinPersistence\";\nimport { runTrustedUserIdentityPinTransaction } from \"../trustedUserIdentityPinTransaction\";\n\n// Each member binds one ID; the trust domain binds once per statement.\nconst PIN_READ_BATCH_SIZE = sqliteRowsPerStatement(1, 1);\n\n/** Read immutable pins together, never exposing another adapter's uncommitted rows. */\nexport async function loadTrustedUserIdentityPins(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userIds: readonly string[];\n}): Promise<ReadonlyMap<string, TrustedUserIdentityPin>> {\n const userIds = [...new Set(input.userIds)];\n if (userIds.length === 0) return new Map();\n await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n return runTrustedUserIdentityPinTransaction(() =>\n runtime.transaction(async (tx) => {\n const pins = new Map<string, TrustedUserIdentityPin>();\n for (\n let start = 0;\n start < userIds.length;\n start += PIN_READ_BATCH_SIZE\n ) {\n const batch = userIds.slice(start, start + PIN_READ_BATCH_SIZE);\n const rows = await tx\n .select()\n .from(trustedUserIdentityPins)\n .where(\n and(\n eq(\n trustedUserIdentityPins.identityTrustDomain,\n input.identityTrustDomain,\n ),\n inArray(trustedUserIdentityPins.userId, batch),\n ),\n );\n for (const row of rows) {\n const pin = parseStoredPin(row, {\n identityTrustDomain: input.identityTrustDomain,\n userId: row.userId,\n });\n pins.set(pin.userId, pin);\n }\n }\n return pins;\n }),\n );\n}\n"]}
@@ -1,18 +0,0 @@
1
- import { and, eq } from "drizzle-orm";
2
- import { trustedUserIdentityPins, trustedUserIdentityPinTables, } from "../../sqlite/schema/trustedUserIdentityPinSchema.js";
3
- import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
4
- import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
5
- /**
6
- * The user a signing key is already bound to in this trust domain, if any.
7
- * Each key has at most one such user: the reverse binding is unique.
8
- */
9
- export async function loadTrustedUserIdForSigningKey(input) {
10
- await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);
11
- const rows = await getClientSQLitePersistenceRuntime(input.execSql)
12
- .db.select({ userId: trustedUserIdentityPins.userId })
13
- .from(trustedUserIdentityPins)
14
- .where(and(eq(trustedUserIdentityPins.identityTrustDomain, input.identityTrustDomain), eq(trustedUserIdentityPins.signingKeyFingerprint, input.signingKeyFingerprint)))
15
- .limit(1);
16
- return rows[0]?.userId ?? null;
17
- }
18
- //# sourceMappingURL=trustedUserIdentitySigningKeyBinding.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"trustedUserIdentitySigningKeyBinding.js","sourceRoot":"","sources":["trustedUserIdentitySigningKeyBinding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEvE;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,KAIpD;IACC,MAAM,eAAe,CAAC,KAAK,CAAC,OAAO,EAAE,4BAA4B,CAAC,CAAC;IACnE,MAAM,IAAI,GAAG,MAAM,iCAAiC,CAAC,KAAK,CAAC,OAAO,CAAC;SAChE,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,uBAAuB,CAAC,MAAM,EAAE,CAAC;SACrD,IAAI,CAAC,uBAAuB,CAAC;SAC7B,KAAK,CACJ,GAAG,CACD,EAAE,CACA,uBAAuB,CAAC,mBAAmB,EAC3C,KAAK,CAAC,mBAAmB,CAC1B,EACD,EAAE,CACA,uBAAuB,CAAC,qBAAqB,EAC7C,KAAK,CAAC,qBAAqB,CAC5B,CACF,CACF;SACA,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,MAAM,IAAI,IAAI,CAAC;AACjC,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport {\n trustedUserIdentityPins,\n trustedUserIdentityPinTables,\n} from \"../../sqlite/schema/trustedUserIdentityPinSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\n\n/**\n * The user a signing key is already bound to in this trust domain, if any.\n * Each key has at most one such user: the reverse binding is unique.\n */\nexport async function loadTrustedUserIdForSigningKey(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly signingKeyFingerprint: string;\n}): Promise<string | null> {\n await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);\n const rows = await getClientSQLitePersistenceRuntime(input.execSql)\n .db.select({ userId: trustedUserIdentityPins.userId })\n .from(trustedUserIdentityPins)\n .where(\n and(\n eq(\n trustedUserIdentityPins.identityTrustDomain,\n input.identityTrustDomain,\n ),\n eq(\n trustedUserIdentityPins.signingKeyFingerprint,\n input.signingKeyFingerprint,\n ),\n ),\n )\n .limit(1);\n return rows[0]?.userId ?? null;\n}\n"]}
@@ -1,37 +0,0 @@
1
- import { type ExecSql } from "../sqlite/sqlSchema.js";
2
- import { type PinScope, type TrustedUserIdentityPin } from "./identity/trustedUserIdentityPinModel.js";
3
- export type { TrustedUserIdentityPin, TrustedUserIdentityPinProvenance, } from "./identity/trustedUserIdentityPinModel.js";
4
- export declare function parseStoredPin(value: unknown, scope: PinScope): TrustedUserIdentityPin;
5
- export declare function loadTrustedUserIdentityPin(input: {
6
- readonly execSql: ExecSql;
7
- readonly identityTrustDomain: string;
8
- readonly userId: string;
9
- }): Promise<TrustedUserIdentityPin | null>;
10
- /**
11
- * Atomically establishes or verifies a durable identity pin.
12
- *
13
- * The immediate transaction serializes first contact across SDK instances that
14
- * share the SQLite database. Conflict handling never replaces the existing
15
- * keys: the winning pin is re-read and every identity field is compared before
16
- * this function returns. When the keys match and the candidate's provenance
17
- * ranks higher (an identity link confirming an observed pin), only the
18
- * provenance is raised; it is never lowered.
19
- *
20
- * `assertCurrent` is the caller's lifetime check. It guards the write
21
- * transaction's COMMIT, so an operation whose account or database changed
22
- * while it awaited SQLite rolls its pin back instead of committing it.
23
- */
24
- export declare function compareOrInsertTrustedUserIdentityPin(input: {
25
- readonly assertCurrent?: (() => void) | undefined;
26
- readonly execSql: ExecSql;
27
- readonly pin: TrustedUserIdentityPin;
28
- }): Promise<TrustedUserIdentityPin>;
29
- /**
30
- * Compare-or-insert a set of pins in one write transaction: a conflict on any
31
- * pin, or a failed `assertCurrent` at COMMIT, leaves none of them stored.
32
- */
33
- export declare function compareOrInsertTrustedUserIdentityPins(input: {
34
- readonly assertCurrent?: (() => void) | undefined;
35
- readonly execSql: ExecSql;
36
- readonly pins: readonly TrustedUserIdentityPin[];
37
- }): Promise<TrustedUserIdentityPin[]>;