foldkit-sync 0.12.3 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -24
- package/dist/diagnostics.d.ts +71 -0
- package/dist/diagnostics.d.ts.map +1 -0
- package/dist/diagnostics.js +67 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/{do.d.mts → do.d.ts} +12 -2
- package/dist/do.d.ts.map +1 -0
- package/dist/{do.mjs → do.js} +15 -9
- package/dist/do.js.map +1 -0
- package/dist/{entity.d.mts → entity.d.ts} +1 -1
- package/dist/entity.d.ts.map +1 -0
- package/dist/{entity.mjs → entity.js} +1 -1
- package/dist/entity.js.map +1 -0
- package/dist/errors.d.ts +91 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +75 -0
- package/dist/errors.js.map +1 -0
- package/dist/ids.d.ts +30 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +28 -0
- package/dist/ids.js.map +1 -0
- package/dist/index.d.ts +106 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +77 -0
- package/dist/index.js.map +1 -0
- package/dist/indexedDb.d.ts +62 -0
- package/dist/indexedDb.d.ts.map +1 -0
- package/dist/indexedDb.js +128 -0
- package/dist/indexedDb.js.map +1 -0
- package/dist/{journal.d.mts → journal.d.ts} +29 -5
- package/dist/journal.d.ts.map +1 -0
- package/dist/{journal-D5h-jqXE.mjs → journal.js} +43 -32
- package/dist/journal.js.map +1 -0
- package/dist/lww.d.ts +76 -0
- package/dist/lww.d.ts.map +1 -0
- package/dist/lww.js +121 -0
- package/dist/lww.js.map +1 -0
- package/dist/make.d.ts +162 -0
- package/dist/make.d.ts.map +1 -0
- package/dist/make.js +153 -0
- package/dist/make.js.map +1 -0
- package/dist/mount.d.ts +138 -0
- package/dist/mount.d.ts.map +1 -0
- package/dist/mount.js +344 -0
- package/dist/mount.js.map +1 -0
- package/dist/presence.d.ts +116 -0
- package/dist/presence.d.ts.map +1 -0
- package/dist/presence.js +277 -0
- package/dist/presence.js.map +1 -0
- package/dist/{remote.d.mts → remote.d.ts} +2 -2
- package/dist/remote.d.ts.map +1 -0
- package/dist/{remote.mjs → remote.js} +1 -1
- package/dist/remote.js.map +1 -0
- package/dist/revalidate.d.ts +6 -0
- package/dist/revalidate.d.ts.map +1 -0
- package/dist/revalidate.js +10 -0
- package/dist/revalidate.js.map +1 -0
- package/dist/sync.d.ts +276 -0
- package/dist/sync.d.ts.map +1 -0
- package/dist/sync.js +512 -0
- package/dist/sync.js.map +1 -0
- package/dist/transport.d.ts +151 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/{transport-BZ6utYmB.mjs → transport.js} +20 -30
- package/dist/transport.js.map +1 -0
- package/package.json +24 -24
- package/dist/do.d.mts.map +0 -1
- package/dist/do.mjs.map +0 -1
- package/dist/entity.d.mts.map +0 -1
- package/dist/entity.mjs.map +0 -1
- package/dist/index.d.mts +0 -397
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -1613
- package/dist/index.mjs.map +0 -1
- package/dist/journal-D5h-jqXE.mjs.map +0 -1
- package/dist/journal.d.mts.map +0 -1
- package/dist/journal.mjs +0 -1
- package/dist/make-DJ0Q1SSc.d.mts +0 -702
- package/dist/make-DJ0Q1SSc.d.mts.map +0 -1
- package/dist/remote.d.mts.map +0 -1
- package/dist/remote.mjs.map +0 -1
- package/dist/transport-BZ6utYmB.mjs.map +0 -1
package/dist/errors.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
// src/errors.ts
|
|
3
|
+
/** The persisted storage could not be read or written. */
|
|
4
|
+
var StorageError = class extends Schema.TaggedError()("StorageError", {
|
|
5
|
+
message: Schema.String,
|
|
6
|
+
cause: Schema.optional(Schema.Unknown)
|
|
7
|
+
}) {};
|
|
8
|
+
/** The stored clock state targets a schema version this build does not support. */
|
|
9
|
+
var UnsupportedClockVersionError = class extends Schema.TaggedError()("UnsupportedClockVersionError", {
|
|
10
|
+
schemaVersion: Schema.NullOr(Schema.Number),
|
|
11
|
+
message: Schema.String
|
|
12
|
+
}) {};
|
|
13
|
+
/** The storage holds a different replica's state. */
|
|
14
|
+
var WrongReplicaStorageError = class extends Schema.TaggedError()("WrongReplicaStorageError", {
|
|
15
|
+
documentId: Schema.String,
|
|
16
|
+
replicaId: Schema.String,
|
|
17
|
+
message: Schema.String
|
|
18
|
+
}) {};
|
|
19
|
+
/** The persisted replica history is internally inconsistent. */
|
|
20
|
+
var InvalidReplicaHistoryError = class extends Schema.TaggedError()("InvalidReplicaHistoryError", {
|
|
21
|
+
message: Schema.String,
|
|
22
|
+
cause: Schema.optional(Schema.Unknown)
|
|
23
|
+
}) {};
|
|
24
|
+
/** The server's exchange response did not match the protocol schema. */
|
|
25
|
+
var InvalidExchangeError = class extends Schema.TaggedError()("InvalidExchangeError", {
|
|
26
|
+
message: Schema.String,
|
|
27
|
+
cause: Schema.optional(Schema.Unknown)
|
|
28
|
+
}) {};
|
|
29
|
+
/** A persisted pending operation could not have been produced by this replica. */
|
|
30
|
+
var InvalidOutboxError = class extends Schema.TaggedError()("InvalidOutboxError", { message: Schema.String }) {};
|
|
31
|
+
/** The server sent a checkpoint older than the replica's cursor. */
|
|
32
|
+
var CheckpointRegressionError = class extends Schema.TaggedError()("CheckpointRegressionError", {
|
|
33
|
+
cursor: Schema.Number,
|
|
34
|
+
checkpointCursor: Schema.Number,
|
|
35
|
+
message: Schema.String
|
|
36
|
+
}) {};
|
|
37
|
+
/** Committed operations were not contiguous from the replica's cursor. */
|
|
38
|
+
var CommittedOrderError = class extends Schema.TaggedError()("CommittedOrderError", {
|
|
39
|
+
expected: Schema.Number,
|
|
40
|
+
actual: Schema.Number,
|
|
41
|
+
message: Schema.String
|
|
42
|
+
}) {};
|
|
43
|
+
/** The server rejected an operation the replica never sent. */
|
|
44
|
+
var ForeignRejectionError = class extends Schema.TaggedError()("ForeignRejectionError", {
|
|
45
|
+
opId: Schema.String,
|
|
46
|
+
message: Schema.String
|
|
47
|
+
}) {};
|
|
48
|
+
/**
|
|
49
|
+
* The server answered an operation this request never sent, or both
|
|
50
|
+
* acknowledged and rejected it. Acting on either would let a faulty or hostile
|
|
51
|
+
* server delete local work.
|
|
52
|
+
*/
|
|
53
|
+
var ForeignAcknowledgementError = class extends Schema.TaggedError()("ForeignAcknowledgementError", {
|
|
54
|
+
opId: Schema.String,
|
|
55
|
+
message: Schema.String
|
|
56
|
+
}) {};
|
|
57
|
+
/** The replica was closed while work was still being submitted. */
|
|
58
|
+
var ReplicaClosedError = class extends Schema.TaggedError()("ReplicaClosedError", { message: Schema.String }) {};
|
|
59
|
+
/** The stored replica state targets a protocol or schema version this build does not support. */
|
|
60
|
+
var UnsupportedReplicaVersionError = class extends Schema.TaggedError()("UnsupportedReplicaVersionError", {
|
|
61
|
+
protocolVersion: Schema.NullOr(Schema.Number),
|
|
62
|
+
schemaVersion: Schema.NullOr(Schema.Number),
|
|
63
|
+
message: Schema.String
|
|
64
|
+
}) {};
|
|
65
|
+
/**
|
|
66
|
+
* `replay` threw for a submitted Message, so it could never be applied here or
|
|
67
|
+
* on any other replica; nothing was written.
|
|
68
|
+
*/
|
|
69
|
+
var ReplayError = class extends Schema.TaggedError()("ReplayError", {
|
|
70
|
+
message: Schema.String,
|
|
71
|
+
cause: Schema.optional(Schema.Unknown)
|
|
72
|
+
}) {};
|
|
73
|
+
export { CheckpointRegressionError, CommittedOrderError, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, ReplayError, ReplicaClosedError, StorageError, UnsupportedClockVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError };
|
|
74
|
+
|
|
75
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** The persisted storage could not be read or written. */\nexport class StorageError extends Schema.TaggedError<StorageError>()('StorageError', {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n}) {}\n\n/** The stored clock state targets a schema version this build does not support. */\nexport class UnsupportedClockVersionError extends Schema.TaggedError<UnsupportedClockVersionError>()(\n 'UnsupportedClockVersionError',\n {\n schemaVersion: Schema.NullOr(Schema.Number),\n message: Schema.String,\n },\n) {}\n\n/** The storage holds a different replica's state. */\nexport class WrongReplicaStorageError extends Schema.TaggedError<WrongReplicaStorageError>()(\n 'WrongReplicaStorageError',\n {\n documentId: Schema.String,\n replicaId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** The persisted replica history is internally inconsistent. */\nexport class InvalidReplicaHistoryError extends Schema.TaggedError<InvalidReplicaHistoryError>()(\n 'InvalidReplicaHistoryError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/** The server's exchange response did not match the protocol schema. */\nexport class InvalidExchangeError extends Schema.TaggedError<InvalidExchangeError>()(\n 'InvalidExchangeError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/** A persisted pending operation could not have been produced by this replica. */\nexport class InvalidOutboxError extends Schema.TaggedError<InvalidOutboxError>()(\n 'InvalidOutboxError',\n {\n message: Schema.String,\n },\n) {}\n\n/** The server sent a checkpoint older than the replica's cursor. */\nexport class CheckpointRegressionError extends Schema.TaggedError<CheckpointRegressionError>()(\n 'CheckpointRegressionError',\n {\n cursor: Schema.Number,\n checkpointCursor: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/** Committed operations were not contiguous from the replica's cursor. */\nexport class CommittedOrderError extends Schema.TaggedError<CommittedOrderError>()(\n 'CommittedOrderError',\n {\n expected: Schema.Number,\n actual: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/** The server rejected an operation the replica never sent. */\nexport class ForeignRejectionError extends Schema.TaggedError<ForeignRejectionError>()(\n 'ForeignRejectionError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * The server answered an operation this request never sent, or both\n * acknowledged and rejected it. Acting on either would let a faulty or hostile\n * server delete local work.\n */\nexport class ForeignAcknowledgementError extends Schema.TaggedError<ForeignAcknowledgementError>()(\n 'ForeignAcknowledgementError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** The replica was closed while work was still being submitted. */\nexport class ReplicaClosedError extends Schema.TaggedError<ReplicaClosedError>()(\n 'ReplicaClosedError',\n {\n message: Schema.String,\n },\n) {}\n\n/** The stored replica state targets a protocol or schema version this build does not support. */\nexport class UnsupportedReplicaVersionError extends Schema.TaggedError<UnsupportedReplicaVersionError>()(\n 'UnsupportedReplicaVersionError',\n {\n protocolVersion: Schema.NullOr(Schema.Number),\n schemaVersion: Schema.NullOr(Schema.Number),\n message: Schema.String,\n },\n) {}\n\n/**\n * `replay` threw for a submitted Message, so it could never be applied here or\n * on any other replica; nothing was written.\n */\nexport class ReplayError extends Schema.TaggedError<ReplayError>()('ReplayError', {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n}) {}\n\nexport type ReplicaError =\n | StorageError\n | ReplayError\n | WrongReplicaStorageError\n | InvalidReplicaHistoryError\n | InvalidExchangeError\n | UnsupportedReplicaVersionError\n | InvalidOutboxError\n | CheckpointRegressionError\n | CommittedOrderError\n | ForeignRejectionError\n | ForeignAcknowledgementError\n | ReplicaClosedError\n"],"mappings":";;;AAGA,IAAa,eAAb,cAAkC,OAAO,YAA0B,CAAC,CAAC,gBAAgB;CACnF,SAAS,OAAO;CAChB,OAAO,OAAO,SAAS,OAAO,OAAO;AACvC,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,+BAAb,cAAkD,OAAO,YAA0C,CAAC,CAClG,gCACA;CACE,eAAe,OAAO,OAAO,OAAO,MAAM;CAC1C,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,2BAAb,cAA8C,OAAO,YAAsC,CAAC,CAC1F,4BACA;CACE,YAAY,OAAO;CAC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AAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;;;;AAMH,IAAa,cAAb,cAAiC,OAAO,YAAyB,CAAC,CAAC,eAAe;CAChF,SAAS,OAAO;CAChB,OAAO,OAAO,SAAS,OAAO,OAAO;AACvC,CAAC,CAAC,CAAC,CAAC"}
|
package/dist/ids.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
/** Identifies the replicated document a replica or operation belongs to. */
|
|
3
|
+
export declare const DocumentId: Schema.brand<Schema.NonEmptyString, "@foldkit-sync/DocumentId">;
|
|
4
|
+
export type DocumentId = typeof DocumentId.Type;
|
|
5
|
+
/** Identifies one replica (writer identity) within a document. */
|
|
6
|
+
export declare const ReplicaId: Schema.brand<Schema.NonEmptyString, "@foldkit-sync/ReplicaId">;
|
|
7
|
+
export type ReplicaId = typeof ReplicaId.Type;
|
|
8
|
+
/** The stable identity of one operation within a document. */
|
|
9
|
+
export declare const OpId: Schema.brand<Schema.NonEmptyString, "@foldkit-sync/OpId">;
|
|
10
|
+
export type OpId = typeof OpId.Type;
|
|
11
|
+
/**
|
|
12
|
+
* A position in the committed document order. `0` is the start; a committed
|
|
13
|
+
* operation's `serverSequence` and a replica's `cursor` are the same family.
|
|
14
|
+
*/
|
|
15
|
+
export declare const Sequence: Schema.brand<Schema.Number, "@foldkit-sync/Sequence">;
|
|
16
|
+
export type Sequence = typeof Sequence.Type;
|
|
17
|
+
/** A replica's own operation counter within a document; 1-based. */
|
|
18
|
+
export declare const LocalSequence: Schema.brand<Schema.Number, "@foldkit-sync/LocalSequence">;
|
|
19
|
+
export type LocalSequence = typeof LocalSequence.Type;
|
|
20
|
+
/**
|
|
21
|
+
* Decode-and-brand helpers. A branded schema constructs the same value with
|
|
22
|
+
* `DocumentId.make('todos')`, which is the spelling to lead with; these stay
|
|
23
|
+
* for callers that already have them.
|
|
24
|
+
*/
|
|
25
|
+
export declare const documentId: (value: string) => DocumentId;
|
|
26
|
+
export declare const replicaId: (value: string) => ReplicaId;
|
|
27
|
+
export declare const opId: (value: string) => OpId;
|
|
28
|
+
export declare const sequence: (value: number) => Sequence;
|
|
29
|
+
export declare const localSequence: (value: number) => LocalSequence;
|
|
30
|
+
//# sourceMappingURL=ids.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ids.d.ts","names":[],"sources":["../src/ids.ts"],"mappings":";;qBAGa,YAAU,OAAA,MAAA,OAAA;YACX,oBAAoB,WAAW;;qBAG9B,WAAS,OAAA,MAAA,OAAA;YACV,mBAAmB,UAAU;;qBAG5B,MAAI,OAAA,MAAA,OAAA;YACL,cAAc,KAAK;;;;;qBAMlB,UAAQ,OAAA,MAAA,OAAA;YAKT,kBAAkB,SAAS;;qBAG1B,eAAa,OAAA,MAAA,OAAA;YAKd,uBAAuB,cAAc;;;;;;qBAOpC,aAAU,kBAAoB;qBAC9B,YAAS,kBAAoB;qBAC7B,OAAI,kBAAoB;qBACxB,WAAQ,kBAAoB;qBAC5B,gBAAa,kBAAoB"}
|
package/dist/ids.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
// src/ids.ts
|
|
3
|
+
/** Identifies the replicated document a replica or operation belongs to. */
|
|
4
|
+
const DocumentId = Schema.NonEmptyString.pipe(Schema.brand("@foldkit-sync/DocumentId"));
|
|
5
|
+
/** Identifies one replica (writer identity) within a document. */
|
|
6
|
+
const ReplicaId = Schema.NonEmptyString.pipe(Schema.brand("@foldkit-sync/ReplicaId"));
|
|
7
|
+
/** The stable identity of one operation within a document. */
|
|
8
|
+
const OpId = Schema.NonEmptyString.pipe(Schema.brand("@foldkit-sync/OpId"));
|
|
9
|
+
/**
|
|
10
|
+
* A position in the committed document order. `0` is the start; a committed
|
|
11
|
+
* operation's `serverSequence` and a replica's `cursor` are the same family.
|
|
12
|
+
*/
|
|
13
|
+
const Sequence = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)).pipe(Schema.brand("@foldkit-sync/Sequence"));
|
|
14
|
+
/** A replica's own operation counter within a document; 1-based. */
|
|
15
|
+
const LocalSequence = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)).pipe(Schema.brand("@foldkit-sync/LocalSequence"));
|
|
16
|
+
/**
|
|
17
|
+
* Decode-and-brand helpers. A branded schema constructs the same value with
|
|
18
|
+
* `DocumentId.make('todos')`, which is the spelling to lead with; these stay
|
|
19
|
+
* for callers that already have them.
|
|
20
|
+
*/
|
|
21
|
+
const documentId = (value) => Schema.decodeUnknownSync(DocumentId)(value);
|
|
22
|
+
const replicaId = (value) => Schema.decodeUnknownSync(ReplicaId)(value);
|
|
23
|
+
const opId = (value) => Schema.decodeUnknownSync(OpId)(value);
|
|
24
|
+
const sequence = (value) => Schema.decodeUnknownSync(Sequence)(value);
|
|
25
|
+
const localSequence = (value) => Schema.decodeUnknownSync(LocalSequence)(value);
|
|
26
|
+
export { DocumentId, LocalSequence, OpId, ReplicaId, Sequence, documentId, localSequence, opId, replicaId, sequence };
|
|
27
|
+
|
|
28
|
+
//# sourceMappingURL=ids.js.map
|
package/dist/ids.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ids.js","names":[],"sources":["../src/ids.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** Identifies the replicated document a replica or operation belongs to. */\nexport const DocumentId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/DocumentId'))\nexport type DocumentId = typeof DocumentId.Type\n\n/** Identifies one replica (writer identity) within a document. */\nexport const ReplicaId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/ReplicaId'))\nexport type ReplicaId = typeof ReplicaId.Type\n\n/** The stable identity of one operation within a document. */\nexport const OpId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/OpId'))\nexport type OpId = typeof OpId.Type\n\n/**\n * A position in the committed document order. `0` is the start; a committed\n * operation's `serverSequence` and a replica's `cursor` are the same family.\n */\nexport const Sequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/Sequence'))\nexport type Sequence = typeof Sequence.Type\n\n/** A replica's own operation counter within a document; 1-based. */\nexport const LocalSequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(1),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/LocalSequence'))\nexport type LocalSequence = typeof LocalSequence.Type\n\n/**\n * Decode-and-brand helpers. A branded schema constructs the same value with\n * `DocumentId.make('todos')`, which is the spelling to lead with; these stay\n * for callers that already have them.\n */\nexport const documentId = (value: string): DocumentId => Schema.decodeUnknownSync(DocumentId)(value)\nexport const replicaId = (value: string): ReplicaId => Schema.decodeUnknownSync(ReplicaId)(value)\nexport const opId = (value: string): OpId => Schema.decodeUnknownSync(OpId)(value)\nexport const sequence = (value: number): Sequence => Schema.decodeUnknownSync(Sequence)(value)\nexport const localSequence = (value: number): LocalSequence =>\n Schema.decodeUnknownSync(LocalSequence)(value)\n"],"mappings":";;;AAGA,MAAa,aAAa,OAAO,eAAe,KAAK,OAAO,MAAM,0BAA0B,CAAC;;AAI7F,MAAa,YAAY,OAAO,eAAe,KAAK,OAAO,MAAM,yBAAyB,CAAC;;AAI3F,MAAa,OAAO,OAAO,eAAe,KAAK,OAAO,MAAM,oBAAoB,CAAC;;;;;AAOjF,MAAa,WAAW,OAAO,OAAO,MACpC,OAAO,MAAM,GACb,OAAO,uBAAuB,CAAC,GAC/B,OAAO,oBAAoB,OAAO,gBAAgB,CACpD,CAAC,CAAC,KAAK,OAAO,MAAM,wBAAwB,CAAC;;AAI7C,MAAa,gBAAgB,OAAO,OAAO,MACzC,OAAO,MAAM,GACb,OAAO,uBAAuB,CAAC,GAC/B,OAAO,oBAAoB,OAAO,gBAAgB,CACpD,CAAC,CAAC,KAAK,OAAO,MAAM,6BAA6B,CAAC;;;;;;AAQlD,MAAa,cAAc,UAA8B,OAAO,kBAAkB,UAAU,CAAC,CAAC,KAAK;AACnG,MAAa,aAAa,UAA6B,OAAO,kBAAkB,SAAS,CAAC,CAAC,KAAK;AAChG,MAAa,QAAQ,UAAwB,OAAO,kBAAkB,IAAI,CAAC,CAAC,KAAK;AACjF,MAAa,YAAY,UAA4B,OAAO,kBAAkB,QAAQ,CAAC,CAAC,KAAK;AAC7F,MAAa,iBAAiB,UAC5B,OAAO,kBAAkB,aAAa,CAAC,CAAC,KAAK"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { ExchangeFailed, HistoryRebuilt, HostDefect, HostStage, ListenerFailed, ListenerSite, SyncDiagnostic } from "./diagnostics.js";
|
|
2
|
+
import { ExchangeFrame, ExchangeReply, NotifyFrame, SocketLike, SocketOptions, Transport, TransportError, TransportShape, TransportSocket, layerFromPromise, layerFromPromise as layerFromPromise$1, layerLoopback, layerLoopback as layerLoopback$1, layerSocket, layerSocket as layerSocket$1, nativeSocket, nativeSocket as nativeSocket$1, portSocket, portSocket as portSocket$1, serveSocket, serveSocket as serveSocket$1, toPromise, toPromise as toPromise$1, workerSocket, workerSocket as workerSocket$1 } from "./transport.js";
|
|
3
|
+
import { OutboxEntry, Storage, TabStorageOptions, indexedDb, tabStorage } from "./indexedDb.js";
|
|
4
|
+
import { LwwClock, LwwClockState, lwwRegister, lwwRegister as lwwRegister$1, openLwwClock } from "./lww.js";
|
|
5
|
+
import { ApplicationSync, AuthorizeDecision, AuthorizePolicy, AuthorizeRequest, DefinedSync, FragmentMessages, MakeOptions, MsgOf, PolicyJournalContract, StampPolicy, SyncFragment, forApplication, forApplication as forApplication$1 } from "./make.js";
|
|
6
|
+
import { CommittedView, MountOptions, MountUrl, Mounted, Reinstall, fact, fact as fact$1, mount, mount as mount$1 } from "./mount.js";
|
|
7
|
+
import { Presence, PresenceChannel, PresenceHub, PresenceOptions, PresencePeer, PresenceUpdate, createPresence, createPresenceHub, createPresenceHub as createPresenceHub$1, loopbackPresenceChannel, servePresence, servePresence as servePresence$1, socketPresenceChannel, socketPresenceChannel as socketPresenceChannel$1 } from "./presence.js";
|
|
8
|
+
import { Checkpoint, CommitStamp, CommittedOperation, Exchange, JournalContract, OpenReplicaOptions, Operation, Rejection, Replica, ReplicaSnapshot, ReplicaState, ReplicaStatus, Sync as Sync$1, SyncDefinition, TransportClient, defineSync, defineSync as defineSync$1, syncMetrics } from "./sync.js";
|
|
9
|
+
import { DocumentId, LocalSequence, OpId, ReplicaId, Sequence, documentId, localSequence, opId, replicaId, sequence } from "./ids.js";
|
|
10
|
+
import { CheckpointRegressionError, CommittedOrderError, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, ReplayError, ReplicaClosedError, ReplicaError, StorageError, UnsupportedClockVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError } from "./errors.js";
|
|
11
|
+
/**
|
|
12
|
+
* The contract `Sync.define` and `Sync.forApplication(App).make` produce: the
|
|
13
|
+
* wire codecs, the server journal's contract, and `openReplica`.
|
|
14
|
+
*
|
|
15
|
+
* This is the type; `Sync` is also the value namespace below, the way
|
|
16
|
+
* `Effect.Effect` is both.
|
|
17
|
+
*/
|
|
18
|
+
export type Sync<Message, Shared, Durable = Message> = Sync$1<Message, Shared, Durable>;
|
|
19
|
+
/** The package's public surface, grouped. Each entry is the exported function itself. */
|
|
20
|
+
export declare const Sync: {
|
|
21
|
+
/** Derives a sync contract from a Foldkit application: `Sync.forApplication(App).make({…})`. */
|
|
22
|
+
forApplication: typeof forApplication$1;
|
|
23
|
+
/** The protocol primitive, for a client with no Foldkit application to derive from. */
|
|
24
|
+
define: typeof defineSync$1;
|
|
25
|
+
/** Runs a Foldkit application over an open replica with one reducer. */
|
|
26
|
+
mount: typeof mount$1;
|
|
27
|
+
/** A Command whose Message the mount applies within the transition that returned it. */
|
|
28
|
+
fact: typeof fact$1;
|
|
29
|
+
/** Counters and a histogram an application can scrape. */
|
|
30
|
+
metrics: {
|
|
31
|
+
exchanges: import("effect/Metric").Counter<number>;
|
|
32
|
+
applied: import("effect/Metric").Counter<number>;
|
|
33
|
+
checkpoints: import("effect/Metric").Counter<number>;
|
|
34
|
+
exchangePending: import("effect/Metric").Histogram<number>;
|
|
35
|
+
};
|
|
36
|
+
/** The storage adapter: one IndexedDB database per replica, named by the caller. */
|
|
37
|
+
indexedDb: (name: string | import("effect/Config").Config<string>, factory?: IDBFactory | undefined) => import("effect/Effect").Effect<Required<import("./indexedDb.js").Storage>, import("./errors.js").StorageError, import("effect/Scope").Scope>;
|
|
38
|
+
/** This tab's IndexedDB store, kept across reloads: what a browser opens a replica on. */
|
|
39
|
+
tabStorage: (name: string, options?: import("./indexedDb.js").TabStorageOptions | undefined) => import("effect/Effect").Effect<Required<import("./indexedDb.js").Storage>, import("./errors.js").StorageError, import("effect/Scope").Scope>;
|
|
40
|
+
/** The `Transport` service's layers, and the bridges to and from a promise client. */
|
|
41
|
+
transport: {
|
|
42
|
+
/** A reconnecting WebSocket client layer. */
|
|
43
|
+
socket: typeof layerSocket$1;
|
|
44
|
+
/** An in-process layer, for tests and single-process demos. */
|
|
45
|
+
loopback: typeof layerLoopback$1;
|
|
46
|
+
/** Wraps the promise-based client the replica already speaks. */
|
|
47
|
+
fromPromise: typeof layerFromPromise$1;
|
|
48
|
+
/** Bridges the service back to that promise client. */
|
|
49
|
+
toPromise: typeof toPromise$1;
|
|
50
|
+
/** The server side of one accepted socket connection. */
|
|
51
|
+
serve: typeof serveSocket$1;
|
|
52
|
+
/** The accepted end of a Cloudflare `WebSocketPair`, for `serve`. */
|
|
53
|
+
workerSocket: typeof workerSocket$1;
|
|
54
|
+
/** The default socket factory: the platform `WebSocket`. */
|
|
55
|
+
nativeSocket: typeof nativeSocket$1;
|
|
56
|
+
/** A socket over a `MessagePort`, closed by `close()` or an abort signal. */
|
|
57
|
+
portSocket: typeof portSocket$1;
|
|
58
|
+
};
|
|
59
|
+
/** An ephemeral, TTL'd peer registry, deliberately outside the durable log. */
|
|
60
|
+
presence: {
|
|
61
|
+
make: <Update>(options: import("./presence.js").PresenceOptions<Update>) => import("effect/Effect").Effect<{
|
|
62
|
+
set: (value: Update) => import("effect/Effect").Effect<void, never, never>;
|
|
63
|
+
leave: import("effect/Effect").Effect<void, never, never>;
|
|
64
|
+
peers: import("effect/Effect").Effect<{
|
|
65
|
+
id: string;
|
|
66
|
+
value: Update;
|
|
67
|
+
updatedAt: number;
|
|
68
|
+
}[], never, never>;
|
|
69
|
+
prune: import("effect/Effect").Effect<void, never, never>;
|
|
70
|
+
subscribe: (listener: () => void) => () => boolean;
|
|
71
|
+
changes: import("effect/Stream").Stream<{
|
|
72
|
+
id: string;
|
|
73
|
+
value: Update;
|
|
74
|
+
updatedAt: number;
|
|
75
|
+
}[], never, never>;
|
|
76
|
+
close: import("effect/Effect").Effect<void, never, never>;
|
|
77
|
+
}, never, import("effect/Scope").Scope>;
|
|
78
|
+
/** Broadcasts presence updates among connected peers, on the server. */
|
|
79
|
+
hub: typeof createPresenceHub$1;
|
|
80
|
+
/** Serves presence frames on an accepted socket, stamping the connection's identity. */
|
|
81
|
+
serve: typeof servePresence$1;
|
|
82
|
+
socketChannel: typeof socketPresenceChannel$1;
|
|
83
|
+
loopbackChannel: <Update>() => import("effect/Effect").Effect<{
|
|
84
|
+
updates: import("effect/PubSub").PubSub<import("./presence.js").PresenceUpdate<Update>>;
|
|
85
|
+
publish: (update: import("./presence.js").PresenceUpdate<Update>) => import("effect/Effect").Effect<boolean, never, never>;
|
|
86
|
+
}, never, never>;
|
|
87
|
+
};
|
|
88
|
+
/** Last-writer-wins registers (experimental): a per-field merge on logical time. */
|
|
89
|
+
lww: {
|
|
90
|
+
register: typeof lwwRegister$1;
|
|
91
|
+
/** The durable counter a stamp is allocated from, before dispatch. */
|
|
92
|
+
openClock: (options: {
|
|
93
|
+
readonly documentId: import("./ids.js").DocumentId;
|
|
94
|
+
readonly replicaId: import("./ids.js").ReplicaId;
|
|
95
|
+
readonly storage: import("./indexedDb.js").Storage;
|
|
96
|
+
}) => import("effect/Effect").Effect<{
|
|
97
|
+
next: (observedCounter?: any) => import("effect/Effect").Effect<{
|
|
98
|
+
readonly counter: number;
|
|
99
|
+
readonly replicaId: string & import("effect/Brand").Brand<"@foldkit-sync/ReplicaId">;
|
|
100
|
+
}, import("./errors.js").StorageError, never>;
|
|
101
|
+
close: import("effect/Effect").Effect<void, never, never>;
|
|
102
|
+
}, import("./errors.js").StorageError | import("./errors.js").UnsupportedClockVersionError, never>;
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
export { type ApplicationSync, type AuthorizeDecision, type AuthorizePolicy, type AuthorizeRequest, type Checkpoint, CheckpointRegressionError, type CommitStamp, type CommittedOperation, CommittedOrderError, type CommittedView, type DefinedSync, DocumentId, type Exchange, type ExchangeFailed, type ExchangeFrame, type ExchangeReply, ForeignAcknowledgementError, ForeignRejectionError, type FragmentMessages, type HistoryRebuilt, type HostDefect, type HostStage, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, type JournalContract, type ListenerFailed, type ListenerSite, LocalSequence, type LwwClock, type LwwClockState, type MakeOptions, type MountOptions, type MountUrl, type Mounted, type MsgOf, type NotifyFrame, OpId, type OpenReplicaOptions, type Operation, type OutboxEntry, type PolicyJournalContract, type Presence, type PresenceChannel, type PresenceHub, type PresenceOptions, type PresencePeer, type PresenceUpdate, type Reinstall, type Rejection, ReplayError, type Replica, ReplicaClosedError, type ReplicaError, ReplicaId, type ReplicaSnapshot, type ReplicaState, type ReplicaStatus, Sequence, type SocketLike, type SocketOptions, type StampPolicy, type Storage, StorageError, type SyncDefinition, type SyncDiagnostic, type SyncFragment, type TabStorageOptions, Transport, type TransportClient, TransportError, type TransportShape, TransportSocket, UnsupportedClockVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError, createPresence, createPresenceHub, defineSync, documentId, fact, forApplication, indexedDb, layerFromPromise, layerLoopback, layerSocket, localSequence, loopbackPresenceChannel, lwwRegister, mount, nativeSocket, opId, openLwwClock, portSocket, replicaId, sequence, servePresence, serveSocket, socketPresenceChannel, syncMetrics, tabStorage, toPromise, workerSocket };
|
|
106
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["SyncContract","forApplication","defineSync","mount","fact","layerSocket","layerLoopback","layerFromPromise","toPromise","serveSocket","workerSocket","nativeSocket","portSocket","createPresenceHub","servePresence","socketPresenceChannel","lwwRegister"],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;YA0CY,KAAK,SAAS,QAAQ,UAAU,WAAWA,OAAa,SAAS,QAAQ;;qBAGxE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAsCT,OAAI,QAAA,iCAAA,gBAAA,oCAAA;;;;;;;;;;;;;;;;;;IAEJ,YAAGa;;IAEH,cAAKC;IACL,sBAAaC;IACb,kBAAe,qCAAA;;;;;;;IAKf,iBAAQC;;IAER,YAAS"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { Transport, TransportError, TransportSocket, layerFromPromise, layerFromPromise as layerFromPromise$1, layerLoopback, layerLoopback as layerLoopback$1, layerSocket, layerSocket as layerSocket$1, nativeSocket, nativeSocket as nativeSocket$1, portSocket, portSocket as portSocket$1, serveSocket, serveSocket as serveSocket$1, toPromise, toPromise as toPromise$1, workerSocket, workerSocket as workerSocket$1 } from "./transport.js";
|
|
2
|
+
import { indexedDb, indexedDb as indexedDb$1, tabStorage, tabStorage as tabStorage$1 } from "./indexedDb.js";
|
|
3
|
+
import { lwwRegister, lwwRegister as lwwRegister$1, openLwwClock, openLwwClock as openLwwClock$1 } from "./lww.js";
|
|
4
|
+
import { forApplication, forApplication as forApplication$1 } from "./make.js";
|
|
5
|
+
import { fact, fact as fact$1, mount, mount as mount$1 } from "./mount.js";
|
|
6
|
+
import { createPresence, createPresence as createPresence$1, createPresenceHub, createPresenceHub as createPresenceHub$1, loopbackPresenceChannel, loopbackPresenceChannel as loopbackPresenceChannel$1, servePresence, servePresence as servePresence$1, socketPresenceChannel, socketPresenceChannel as socketPresenceChannel$1 } from "./presence.js";
|
|
7
|
+
import { defineSync, defineSync as defineSync$1, syncMetrics, syncMetrics as syncMetrics$1 } from "./sync.js";
|
|
8
|
+
import { DocumentId, LocalSequence, OpId, ReplicaId, Sequence, documentId, localSequence, opId, replicaId, sequence } from "./ids.js";
|
|
9
|
+
import { CheckpointRegressionError, CommittedOrderError, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, ReplayError, ReplicaClosedError, StorageError, UnsupportedClockVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError } from "./errors.js";
|
|
10
|
+
// src/index.ts
|
|
11
|
+
/**
|
|
12
|
+
* `foldkit-sync` — a local-first replica of a shared Foldkit projection.
|
|
13
|
+
*
|
|
14
|
+
* The application's Message union and update function stay authoritative: sync
|
|
15
|
+
* wraps them rather than introducing a second reducer. The replica owns the
|
|
16
|
+
* local outbox, optimistic projection, and reconciliation; a durable server
|
|
17
|
+
* journal provides authoritative order.
|
|
18
|
+
*
|
|
19
|
+
* `Sync` is the namespace: `Sync.forApplication`, `Sync.mount`,
|
|
20
|
+
* `Sync.transport.socket`. Ids are branded schemas, so they construct through
|
|
21
|
+
* `DocumentId.make('todos')`. Every name is also exported on its own.
|
|
22
|
+
*/
|
|
23
|
+
/** The package's public surface, grouped. Each entry is the exported function itself. */
|
|
24
|
+
const Sync = {
|
|
25
|
+
/** Derives a sync contract from a Foldkit application: `Sync.forApplication(App).make({…})`. */
|
|
26
|
+
forApplication: forApplication$1,
|
|
27
|
+
/** The protocol primitive, for a client with no Foldkit application to derive from. */
|
|
28
|
+
define: defineSync$1,
|
|
29
|
+
/** Runs a Foldkit application over an open replica with one reducer. */
|
|
30
|
+
mount: mount$1,
|
|
31
|
+
/** A Command whose Message the mount applies within the transition that returned it. */
|
|
32
|
+
fact: fact$1,
|
|
33
|
+
/** Counters and a histogram an application can scrape. */
|
|
34
|
+
metrics: syncMetrics$1,
|
|
35
|
+
/** The storage adapter: one IndexedDB database per replica, named by the caller. */
|
|
36
|
+
indexedDb: indexedDb$1,
|
|
37
|
+
/** This tab's IndexedDB store, kept across reloads: what a browser opens a replica on. */
|
|
38
|
+
tabStorage: tabStorage$1,
|
|
39
|
+
/** The `Transport` service's layers, and the bridges to and from a promise client. */
|
|
40
|
+
transport: {
|
|
41
|
+
/** A reconnecting WebSocket client layer. */
|
|
42
|
+
socket: layerSocket$1,
|
|
43
|
+
/** An in-process layer, for tests and single-process demos. */
|
|
44
|
+
loopback: layerLoopback$1,
|
|
45
|
+
/** Wraps the promise-based client the replica already speaks. */
|
|
46
|
+
fromPromise: layerFromPromise$1,
|
|
47
|
+
/** Bridges the service back to that promise client. */
|
|
48
|
+
toPromise: toPromise$1,
|
|
49
|
+
/** The server side of one accepted socket connection. */
|
|
50
|
+
serve: serveSocket$1,
|
|
51
|
+
/** The accepted end of a Cloudflare `WebSocketPair`, for `serve`. */
|
|
52
|
+
workerSocket: workerSocket$1,
|
|
53
|
+
/** The default socket factory: the platform `WebSocket`. */
|
|
54
|
+
nativeSocket: nativeSocket$1,
|
|
55
|
+
/** A socket over a `MessagePort`, closed by `close()` or an abort signal. */
|
|
56
|
+
portSocket: portSocket$1
|
|
57
|
+
},
|
|
58
|
+
/** An ephemeral, TTL'd peer registry, deliberately outside the durable log. */
|
|
59
|
+
presence: {
|
|
60
|
+
make: createPresence$1,
|
|
61
|
+
/** Broadcasts presence updates among connected peers, on the server. */
|
|
62
|
+
hub: createPresenceHub$1,
|
|
63
|
+
/** Serves presence frames on an accepted socket, stamping the connection's identity. */
|
|
64
|
+
serve: servePresence$1,
|
|
65
|
+
socketChannel: socketPresenceChannel$1,
|
|
66
|
+
loopbackChannel: loopbackPresenceChannel$1
|
|
67
|
+
},
|
|
68
|
+
/** Last-writer-wins registers (experimental): a per-field merge on logical time. */
|
|
69
|
+
lww: {
|
|
70
|
+
register: lwwRegister$1,
|
|
71
|
+
/** The durable counter a stamp is allocated from, before dispatch. */
|
|
72
|
+
openClock: openLwwClock$1
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
export { CheckpointRegressionError, CommittedOrderError, DocumentId, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, LocalSequence, OpId, ReplayError, ReplicaClosedError, ReplicaId, Sequence, StorageError, Sync, Transport, TransportError, TransportSocket, UnsupportedClockVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError, createPresence, createPresenceHub, defineSync, documentId, fact, forApplication, indexedDb, layerFromPromise, layerLoopback, layerSocket, localSequence, loopbackPresenceChannel, lwwRegister, mount, nativeSocket, opId, openLwwClock, portSocket, replicaId, sequence, servePresence, serveSocket, socketPresenceChannel, syncMetrics, tabStorage, toPromise, workerSocket };
|
|
76
|
+
|
|
77
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["defineSync","syncMetrics","layerSocket","layerLoopback","layerFromPromise","serveSocket","createPresence","createPresenceHub","servePresence","socketPresenceChannel","loopbackPresenceChannel","lwwRegister","openLwwClock"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-sync` — a local-first replica of a shared Foldkit projection.\n *\n * The application's Message union and update function stay authoritative: sync\n * wraps them rather than introducing a second reducer. The replica owns the\n * local outbox, optimistic projection, and reconciliation; a durable server\n * journal provides authoritative order.\n *\n * `Sync` is the namespace: `Sync.forApplication`, `Sync.mount`,\n * `Sync.transport.socket`. Ids are branded schemas, so they construct through\n * `DocumentId.make('todos')`. Every name is also exported on its own.\n */\nimport { indexedDb, tabStorage } from './indexedDb.js'\nimport { lwwRegister, openLwwClock } from './lww.js'\nimport { forApplication } from './make.js'\nimport { fact, mount } from './mount.js'\nimport {\n createPresence,\n createPresenceHub,\n loopbackPresenceChannel,\n servePresence,\n socketPresenceChannel,\n} from './presence.js'\nimport { defineSync, syncMetrics, type Sync as SyncContract } from './sync.js'\nimport {\n layerFromPromise,\n layerLoopback,\n layerSocket,\n nativeSocket,\n portSocket,\n serveSocket,\n toPromise,\n workerSocket,\n} from './transport.js'\n\n/**\n * The contract `Sync.define` and `Sync.forApplication(App).make` produce: the\n * wire codecs, the server journal's contract, and `openReplica`.\n *\n * This is the type; `Sync` is also the value namespace below, the way\n * `Effect.Effect` is both.\n */\nexport type Sync<Message, Shared, Durable = Message> = SyncContract<Message, Shared, Durable>\n\n/** The package's public surface, grouped. Each entry is the exported function itself. */\nexport const Sync = {\n /** Derives a sync contract from a Foldkit application: `Sync.forApplication(App).make({…})`. */\n forApplication,\n /** The protocol primitive, for a client with no Foldkit application to derive from. */\n define: defineSync,\n /** Runs a Foldkit application over an open replica with one reducer. */\n mount,\n /** A Command whose Message the mount applies within the transition that returned it. */\n fact,\n /** Counters and a histogram an application can scrape. */\n metrics: syncMetrics,\n /** The storage adapter: one IndexedDB database per replica, named by the caller. */\n indexedDb,\n /** This tab's IndexedDB store, kept across reloads: what a browser opens a replica on. */\n tabStorage,\n\n /** The `Transport` service's layers, and the bridges to and from a promise client. */\n transport: {\n /** A reconnecting WebSocket client layer. */\n socket: layerSocket,\n /** An in-process layer, for tests and single-process demos. */\n loopback: layerLoopback,\n /** Wraps the promise-based client the replica already speaks. */\n fromPromise: layerFromPromise,\n /** Bridges the service back to that promise client. */\n toPromise,\n /** The server side of one accepted socket connection. */\n serve: serveSocket,\n /** The accepted end of a Cloudflare `WebSocketPair`, for `serve`. */\n workerSocket,\n /** The default socket factory: the platform `WebSocket`. */\n nativeSocket,\n /** A socket over a `MessagePort`, closed by `close()` or an abort signal. */\n portSocket,\n },\n\n /** An ephemeral, TTL'd peer registry, deliberately outside the durable log. */\n presence: {\n make: createPresence,\n /** Broadcasts presence updates among connected peers, on the server. */\n hub: createPresenceHub,\n /** Serves presence frames on an accepted socket, stamping the connection's identity. */\n serve: servePresence,\n socketChannel: socketPresenceChannel,\n loopbackChannel: loopbackPresenceChannel,\n },\n\n /** Last-writer-wins registers (experimental): a per-field merge on logical time. */\n lww: {\n register: lwwRegister,\n /** The durable counter a stamp is allocated from, before dispatch. */\n openClock: openLwwClock,\n },\n}\n\nexport type {\n ExchangeFailed,\n HistoryRebuilt,\n HostDefect,\n HostStage,\n ListenerFailed,\n ListenerSite,\n SyncDiagnostic,\n} from './diagnostics.js'\nexport {\n indexedDb,\n tabStorage,\n type OutboxEntry,\n type Storage,\n type TabStorageOptions,\n} from './indexedDb.js'\nexport {\n fact,\n mount,\n type CommittedView,\n type MountOptions,\n type Reinstall,\n type MountUrl,\n type Mounted,\n} from './mount.js'\nexport {\n forApplication,\n type ApplicationSync,\n type AuthorizeDecision,\n type AuthorizePolicy,\n type AuthorizeRequest,\n type DefinedSync,\n type FragmentMessages,\n type MakeOptions,\n type MsgOf,\n type PolicyJournalContract,\n type StampPolicy,\n type SyncFragment,\n} from './make.js'\nexport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n documentId,\n localSequence,\n opId,\n replicaId,\n sequence,\n} from './ids.js'\nexport {\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n StorageError,\n UnsupportedClockVersionError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nexport { lwwRegister, openLwwClock, type LwwClock, type LwwClockState } from './lww.js'\nexport {\n createPresence,\n createPresenceHub,\n loopbackPresenceChannel,\n servePresence,\n socketPresenceChannel,\n type Presence,\n type PresenceChannel,\n type PresenceHub,\n type PresenceOptions,\n type PresencePeer,\n type PresenceUpdate,\n} from './presence.js'\nexport {\n layerFromPromise,\n layerLoopback,\n layerSocket,\n nativeSocket,\n portSocket,\n serveSocket,\n toPromise,\n workerSocket,\n Transport,\n TransportSocket,\n TransportError,\n type ExchangeFrame,\n type ExchangeReply,\n type NotifyFrame,\n type SocketLike,\n type SocketOptions,\n type TransportShape,\n} from './transport.js'\nexport {\n defineSync,\n syncMetrics,\n type Checkpoint,\n type CommitStamp,\n type CommittedOperation,\n type Exchange,\n type JournalContract,\n type OpenReplicaOptions,\n type Operation,\n type Rejection,\n type Replica,\n type ReplicaSnapshot,\n type ReplicaState,\n type ReplicaStatus,\n type SyncDefinition,\n type TransportClient,\n} from './sync.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAa,OAAO;;CAElB,gBAAA;;CAEA,QAAQA;;CAER,OAAA;;CAEA,MAAA;;CAEA,SAASC;;CAET,WAAA;;CAEA,YAAA;;CAGA,WAAW;;EAET,QAAQC;;EAER,UAAUC;;EAEV,aAAaC;;EAEb,WAAA;;EAEA,OAAOC;;EAEP,cAAA;;EAEA,cAAA;;EAEA,YAAA;CACF;;CAGA,UAAU;EACR,MAAMC;;EAEN,KAAKC;;EAEL,OAAOC;EACP,eAAeC;EACf,iBAAiBC;CACnB;;CAGA,KAAK;EACH,UAAUC;;EAEV,WAAWC;CACb;AACF"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { Config, Effect } from "effect";
|
|
2
|
+
import { StorageError } from "./errors.js";
|
|
3
|
+
/** One submitted operation, as `Storage.append` records it. */
|
|
4
|
+
export interface OutboxEntry {
|
|
5
|
+
/** The replica's revision once this operation is in its outbox. */
|
|
6
|
+
readonly revision: number;
|
|
7
|
+
readonly nextLocalSequence: number;
|
|
8
|
+
/**
|
|
9
|
+
* The operation's local sequence. An entry with the sequence of one already in the
|
|
10
|
+
* outbox replaces it: a coalesced submit rewrites the last operation.
|
|
11
|
+
*/
|
|
12
|
+
readonly localSequence: number;
|
|
13
|
+
/** The operation, encoded. */
|
|
14
|
+
readonly operation: unknown;
|
|
15
|
+
}
|
|
16
|
+
/** Persists a replica's state with compare-and-swap on its revision. */
|
|
17
|
+
export interface Storage {
|
|
18
|
+
/**
|
|
19
|
+
* The saved state, with every operation appended since in its `pending` (replacing the
|
|
20
|
+
* one of the same local sequence), and the last one's `revision` and `nextLocalSequence`.
|
|
21
|
+
*/
|
|
22
|
+
load: () => Effect.Effect<unknown, StorageError>;
|
|
23
|
+
/** Replaces the whole state, and with it every appended operation. */
|
|
24
|
+
save: (state: unknown, expectedRevision: number | null) => Effect.Effect<void, StorageError>;
|
|
25
|
+
/**
|
|
26
|
+
* Optional. Records one submitted operation without rewriting the rest of the state, so
|
|
27
|
+
* a submit costs the operation's size rather than the document's. Without it, a submit
|
|
28
|
+
* saves the whole state.
|
|
29
|
+
*/
|
|
30
|
+
append?: (entry: OutboxEntry, expectedRevision: number) => Effect.Effect<void, StorageError>;
|
|
31
|
+
/** Idempotent; the caller closes the connection explicitly. */
|
|
32
|
+
close: Effect.Effect<void>;
|
|
33
|
+
}
|
|
34
|
+
/** One database per document/replica; CAS prevents two tabs from sharing a writer identity. */
|
|
35
|
+
export declare const indexedDb: (name: string | Config.Config<string>, factory?: IDBFactory | undefined) => Effect.Effect<Required<Storage>, StorageError, import("effect/Scope").Scope>;
|
|
36
|
+
/** What `tabStorage` reads of the page, given in a test. */
|
|
37
|
+
export interface TabStorageOptions {
|
|
38
|
+
/** Where the tab's key lives; it survives a reload and is copied to a duplicated tab. */
|
|
39
|
+
readonly sessionStorage?: {
|
|
40
|
+
getItem(key: string): string | null;
|
|
41
|
+
setItem(key: string, value: string): void;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Claims the key while the tab is open, so a duplicated tab takes another;
|
|
45
|
+
* `undefined` where the page has no Web Locks.
|
|
46
|
+
*/
|
|
47
|
+
readonly locks?: {
|
|
48
|
+
request(name: string, options: {
|
|
49
|
+
readonly ifAvailable: true;
|
|
50
|
+
}, callback: (lock: unknown) => Promise<void> | undefined): Promise<unknown>;
|
|
51
|
+
} | undefined;
|
|
52
|
+
readonly indexedDB?: IDBFactory;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* This tab's store: IndexedDB `${name}/${key}`, where the key is read from
|
|
56
|
+
* `sessionStorage` under `name`, or minted. A reload reopens the store, unsent
|
|
57
|
+
* operations included; a duplicated tab, whose copied key another tab holds,
|
|
58
|
+
* mints its own. Pass it to `openReplica`, which takes the replica's id from
|
|
59
|
+
* the store.
|
|
60
|
+
*/
|
|
61
|
+
export declare const tabStorage: (name: string, options?: TabStorageOptions | undefined) => Effect.Effect<Required<Storage>, StorageError, import("effect/Scope").Scope>;
|
|
62
|
+
//# sourceMappingURL=indexedDb.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"indexedDb.d.ts","names":[],"sources":["../src/indexedDb.ts"],"mappings":";;;iBAIiB;;WAEN;WACA;;;;;WAKA;;WAEA;;;iBAIM;;;;;EAKf,YAAY,OAAO,gBAAgB;;EAEnC,OAAO,gBAAgB,oCAAoC,OAAO,aAAa;;;;;;EAM/E,UAAU,OAAO,aAAa,6BAA6B,OAAO,aAAa;;EAE/E,OAAO,OAAO;;;qBAwCH,YAAS,eAAA,OAAA,gBAAA,UAAA,2BAAA,OAAA,OAAA,SAAA,UAAA,qCAAA;;iBAsHL;;WAEN;IACP,QAAQ;IACR,QAAQ,aAAa;;;;;;WAMd;IAEH,QACE,cACA;eAAoB;OACpB,WAAW,kBAAkB,4BAC5B;;WAGA,YAAY;;;;;;;;;qBA8BV,aAAU,cAAA,UAAA,kCAAA,OAAA,OAAA,SAAA,UAAA,qCAAA"}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { Effect, Option } from "effect";
|
|
2
|
+
import { StorageError } from "./errors.js";
|
|
3
|
+
// src/indexedDb.ts
|
|
4
|
+
const storageError = (message, cause) => new StorageError({
|
|
5
|
+
message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
6
|
+
cause
|
|
7
|
+
});
|
|
8
|
+
const openDatabase = (name, factory) => Effect.tryPromise({
|
|
9
|
+
try: () => new Promise((resolve, reject) => {
|
|
10
|
+
const request = factory.open(name, 2);
|
|
11
|
+
request.onupgradeneeded = (event) => {
|
|
12
|
+
const database = request.result;
|
|
13
|
+
if (event.oldVersion < 1) database.createObjectStore("replica");
|
|
14
|
+
if (event.oldVersion < 2) database.createObjectStore("outbox");
|
|
15
|
+
};
|
|
16
|
+
let blocked = false;
|
|
17
|
+
request.onsuccess = () => blocked ? request.result.close() : resolve(request.result);
|
|
18
|
+
request.onerror = () => reject(request.error);
|
|
19
|
+
request.onblocked = () => {
|
|
20
|
+
blocked = true;
|
|
21
|
+
reject(/* @__PURE__ */ new Error("IndexedDB upgrade is blocked by another connection"));
|
|
22
|
+
};
|
|
23
|
+
}),
|
|
24
|
+
catch: (cause) => storageError("Could not open the storage", cause)
|
|
25
|
+
});
|
|
26
|
+
/** One database per document/replica; CAS prevents two tabs from sharing a writer identity. */
|
|
27
|
+
const indexedDb = Effect.fn("Storage.indexedDb")(function* (name, factory = globalThis.indexedDB) {
|
|
28
|
+
const databaseName = typeof name === "string" ? name : yield* name.pipe(Effect.catchTag("ConfigError", (cause) => Effect.fail(storageError("Could not read the storage name", cause))));
|
|
29
|
+
const database = yield* Effect.acquireRelease(openDatabase(databaseName, factory), (database) => Effect.sync(() => database.close()));
|
|
30
|
+
database.onversionchange = () => database.close();
|
|
31
|
+
/**
|
|
32
|
+
* Writes under compare-and-swap: `write` runs only if the stored revision is the one
|
|
33
|
+
* expected. The revision is its own key, so an append need not read the state; a database
|
|
34
|
+
* written before it existed has it inside the state.
|
|
35
|
+
*/
|
|
36
|
+
const write = (expectedRevision, writing) => new Promise((resolve, reject) => {
|
|
37
|
+
const transaction = database.transaction(["replica", "outbox"], "readwrite", { durability: "strict" });
|
|
38
|
+
const replica = transaction.objectStore("replica");
|
|
39
|
+
let conflict = false;
|
|
40
|
+
const check = (revision) => {
|
|
41
|
+
if (revision !== expectedRevision) {
|
|
42
|
+
conflict = true;
|
|
43
|
+
transaction.abort();
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
writing(replica, transaction.objectStore("outbox"));
|
|
47
|
+
};
|
|
48
|
+
const stored = replica.get("revision");
|
|
49
|
+
stored.onsuccess = () => {
|
|
50
|
+
if (stored.result !== void 0) return check(stored.result);
|
|
51
|
+
const state = replica.get("state");
|
|
52
|
+
state.onsuccess = () => check(state.result?.revision ?? null);
|
|
53
|
+
};
|
|
54
|
+
transaction.oncomplete = () => resolve();
|
|
55
|
+
transaction.onabort = () => reject(conflict ? /* @__PURE__ */ new Error("Replica was changed by another writer") : transaction.error ?? /* @__PURE__ */ new Error("IndexedDB write aborted"));
|
|
56
|
+
});
|
|
57
|
+
return {
|
|
58
|
+
load: () => Effect.tryPromise({
|
|
59
|
+
try: () => new Promise((resolve, reject) => {
|
|
60
|
+
const transaction = database.transaction(["replica", "outbox"], "readonly");
|
|
61
|
+
const state = transaction.objectStore("replica").get("state");
|
|
62
|
+
const appended = transaction.objectStore("outbox").getAll();
|
|
63
|
+
transaction.oncomplete = () => {
|
|
64
|
+
const saved = state.result;
|
|
65
|
+
const entries = appended.result;
|
|
66
|
+
const latest = entries[entries.length - 1];
|
|
67
|
+
const replaced = new Set(entries.map((entry) => entry.localSequence));
|
|
68
|
+
resolve(saved === void 0 || latest === void 0 ? saved : {
|
|
69
|
+
...saved,
|
|
70
|
+
revision: latest.revision,
|
|
71
|
+
nextLocalSequence: latest.nextLocalSequence,
|
|
72
|
+
pending: [...saved.pending.filter((operation) => !replaced.has(operation.localSequence)), ...entries.map((entry) => entry.operation)]
|
|
73
|
+
});
|
|
74
|
+
};
|
|
75
|
+
transaction.onabort = () => reject(transaction.error ?? /* @__PURE__ */ new Error("IndexedDB read aborted"));
|
|
76
|
+
}),
|
|
77
|
+
catch: (cause) => storageError("Could not read the replica", cause)
|
|
78
|
+
}),
|
|
79
|
+
save: (state, expectedRevision) => Effect.tryPromise({
|
|
80
|
+
try: () => write(expectedRevision, (replica, outbox) => {
|
|
81
|
+
replica.put(state, "state");
|
|
82
|
+
replica.put(state.revision, "revision");
|
|
83
|
+
outbox.clear();
|
|
84
|
+
}),
|
|
85
|
+
catch: (cause) => storageError("Could not save the replica", cause)
|
|
86
|
+
}),
|
|
87
|
+
append: (entry, expectedRevision) => Effect.tryPromise({
|
|
88
|
+
try: () => write(expectedRevision, (replica, outbox) => {
|
|
89
|
+
outbox.put(entry, entry.localSequence);
|
|
90
|
+
replica.put(entry.revision, "revision");
|
|
91
|
+
}),
|
|
92
|
+
catch: (cause) => storageError("Could not save the replica", cause)
|
|
93
|
+
}),
|
|
94
|
+
close: Effect.sync(() => database.close())
|
|
95
|
+
};
|
|
96
|
+
});
|
|
97
|
+
/** Holds a Web Lock for the scope; false when another tab holds it. */
|
|
98
|
+
const claim = (locks, name) => Effect.acquireRelease(Effect.callback((resume) => {
|
|
99
|
+
locks.request(name, { ifAvailable: true }, (lock) => {
|
|
100
|
+
if (lock === null) {
|
|
101
|
+
resume(Effect.succeed(Option.none()));
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
return new Promise((release) => resume(Effect.succeed(Option.some(release))));
|
|
105
|
+
}).catch(() => resume(Effect.succeed(Option.some(() => {}))));
|
|
106
|
+
}), (held) => Effect.sync(() => Option.map(held, (release) => release()))).pipe(Effect.map(Option.isSome));
|
|
107
|
+
/**
|
|
108
|
+
* This tab's store: IndexedDB `${name}/${key}`, where the key is read from
|
|
109
|
+
* `sessionStorage` under `name`, or minted. A reload reopens the store, unsent
|
|
110
|
+
* operations included; a duplicated tab, whose copied key another tab holds,
|
|
111
|
+
* mints its own. Pass it to `openReplica`, which takes the replica's id from
|
|
112
|
+
* the store.
|
|
113
|
+
*/
|
|
114
|
+
const tabStorage = Effect.fn("Storage.tabStorage")(function* (name, options = {}) {
|
|
115
|
+
const session = options.sessionStorage ?? globalThis.sessionStorage;
|
|
116
|
+
const locks = "locks" in options ? options.locks : globalThis.navigator?.locks;
|
|
117
|
+
const held = (key) => locks === void 0 ? Effect.succeed(true) : claim(locks, `foldkit-sync:${name}/${key}`);
|
|
118
|
+
const kept = session.getItem(name);
|
|
119
|
+
const key = kept !== null && (yield* held(kept)) ? kept : crypto.randomUUID();
|
|
120
|
+
if (key !== kept) {
|
|
121
|
+
yield* held(key);
|
|
122
|
+
session.setItem(name, key);
|
|
123
|
+
}
|
|
124
|
+
return yield* indexedDb(`${name}/${key}`, options.indexedDB);
|
|
125
|
+
});
|
|
126
|
+
export { indexedDb, tabStorage };
|
|
127
|
+
|
|
128
|
+
//# sourceMappingURL=indexedDb.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"indexedDb.js","names":[],"sources":["../src/indexedDb.ts"],"sourcesContent":["import { Config, Effect, Option } from 'effect'\nimport { StorageError } from './errors.js'\n\n/** One submitted operation, as `Storage.append` records it. */\nexport interface OutboxEntry {\n /** The replica's revision once this operation is in its outbox. */\n readonly revision: number\n readonly nextLocalSequence: number\n /**\n * The operation's local sequence. An entry with the sequence of one already in the\n * outbox replaces it: a coalesced submit rewrites the last operation.\n */\n readonly localSequence: number\n /** The operation, encoded. */\n readonly operation: unknown\n}\n\n/** Persists a replica's state with compare-and-swap on its revision. */\nexport interface Storage {\n /**\n * The saved state, with every operation appended since in its `pending` (replacing the\n * one of the same local sequence), and the last one's `revision` and `nextLocalSequence`.\n */\n load: () => Effect.Effect<unknown, StorageError>\n /** Replaces the whole state, and with it every appended operation. */\n save: (state: unknown, expectedRevision: number | null) => Effect.Effect<void, StorageError>\n /**\n * Optional. Records one submitted operation without rewriting the rest of the state, so\n * a submit costs the operation's size rather than the document's. Without it, a submit\n * saves the whole state.\n */\n append?: (entry: OutboxEntry, expectedRevision: number) => Effect.Effect<void, StorageError>\n /** Idempotent; the caller closes the connection explicitly. */\n close: Effect.Effect<void>\n}\n\nconst storageError = (message: string, cause: unknown): StorageError =>\n new StorageError({\n message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,\n cause,\n })\n\nconst openDatabase = (\n name: string,\n factory: IDBFactory,\n): Effect.Effect<IDBDatabase, StorageError> =>\n Effect.tryPromise({\n try: () =>\n new Promise<IDBDatabase>((resolve, reject) => {\n const request = factory.open(name, 2)\n // Version 2 adds the outbox that `append` writes; a version 1 database keeps its\n // state, and its revision is read from that state until the next write.\n request.onupgradeneeded = event => {\n const database = request.result\n if (event.oldVersion < 1) database.createObjectStore('replica')\n if (event.oldVersion < 2) database.createObjectStore('outbox')\n }\n let blocked = false\n // A blocked open still succeeds once the other connection closes, after the\n // effect has failed; nothing else would ever close that connection.\n request.onsuccess = () => (blocked ? request.result.close() : resolve(request.result))\n request.onerror = () => reject(request.error)\n // Without this, a version upgrade blocked by another open connection\n // never settles and the effect hangs.\n request.onblocked = () => {\n blocked = true\n reject(new Error('IndexedDB upgrade is blocked by another connection'))\n }\n }),\n catch: cause => storageError('Could not open the storage', cause),\n })\n\n/** One database per document/replica; CAS prevents two tabs from sharing a writer identity. */\nexport const indexedDb = Effect.fn('Storage.indexedDb')(function* (\n name: Config.Config<string> | string,\n factory: IDBFactory = globalThis.indexedDB,\n) {\n const databaseName =\n typeof name === 'string'\n ? name\n : yield* name.pipe(\n Effect.catchTag('ConfigError', cause =>\n Effect.fail(storageError('Could not read the storage name', cause)),\n ),\n )\n const database = yield* Effect.acquireRelease(openDatabase(databaseName, factory), database =>\n Effect.sync(() => database.close()),\n )\n database.onversionchange = () => database.close()\n /**\n * Writes under compare-and-swap: `write` runs only if the stored revision is the one\n * expected. The revision is its own key, so an append need not read the state; a database\n * written before it existed has it inside the state.\n */\n const write = (\n expectedRevision: number | null,\n writing: (replica: IDBObjectStore, outbox: IDBObjectStore) => void,\n ): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n const transaction = database.transaction(['replica', 'outbox'], 'readwrite', {\n durability: 'strict',\n })\n const replica = transaction.objectStore('replica')\n let conflict = false\n const check = (revision: number | null): void => {\n if (revision !== expectedRevision) {\n conflict = true\n transaction.abort()\n return\n }\n writing(replica, transaction.objectStore('outbox'))\n }\n const stored = replica.get('revision')\n stored.onsuccess = () => {\n if (stored.result !== undefined) return check(stored.result as number)\n const state = replica.get('state')\n state.onsuccess = () =>\n check((state.result as { revision: number } | undefined)?.revision ?? null)\n }\n transaction.oncomplete = () => resolve()\n transaction.onabort = () =>\n reject(\n conflict\n ? new Error('Replica was changed by another writer')\n : (transaction.error ?? new Error('IndexedDB write aborted')),\n )\n })\n // Every member, `append` included, so a caller need not check for it.\n const storage: Required<Storage> = {\n load: () =>\n Effect.tryPromise({\n try: () =>\n new Promise((resolve, reject) => {\n const transaction = database.transaction(['replica', 'outbox'], 'readonly')\n const state = transaction.objectStore('replica').get('state')\n // In key order, which is local-sequence order.\n const appended = transaction.objectStore('outbox').getAll()\n transaction.oncomplete = () => {\n const saved = state.result as\n | { pending: ReadonlyArray<{ readonly localSequence?: unknown }> }\n | undefined\n const entries = appended.result as ReadonlyArray<OutboxEntry>\n // Only the last operation is ever rewritten, so the last row is the latest.\n const latest = entries[entries.length - 1]\n const replaced = new Set(entries.map(entry => entry.localSequence))\n resolve(\n saved === undefined || latest === undefined\n ? saved\n : {\n ...saved,\n revision: latest.revision,\n nextLocalSequence: latest.nextLocalSequence,\n pending: [\n ...saved.pending.filter(\n operation => !replaced.has(operation.localSequence as number),\n ),\n ...entries.map(entry => entry.operation),\n ],\n },\n )\n }\n transaction.onabort = () =>\n reject(transaction.error ?? new Error('IndexedDB read aborted'))\n }),\n catch: cause => storageError('Could not read the replica', cause),\n }),\n save: (state, expectedRevision) =>\n Effect.tryPromise({\n try: () =>\n write(expectedRevision, (replica, outbox) => {\n replica.put(state, 'state')\n replica.put((state as { revision: number }).revision, 'revision')\n outbox.clear()\n }),\n catch: cause => storageError('Could not save the replica', cause),\n }),\n append: (entry, expectedRevision) =>\n Effect.tryPromise({\n try: () =>\n write(expectedRevision, (replica, outbox) => {\n outbox.put(entry, entry.localSequence)\n replica.put(entry.revision, 'revision')\n }),\n catch: cause => storageError('Could not save the replica', cause),\n }),\n close: Effect.sync(() => database.close()),\n }\n return storage\n})\n\n/** What `tabStorage` reads of the page, given in a test. */\nexport interface TabStorageOptions {\n /** Where the tab's key lives; it survives a reload and is copied to a duplicated tab. */\n readonly sessionStorage?: {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n }\n /**\n * Claims the key while the tab is open, so a duplicated tab takes another;\n * `undefined` where the page has no Web Locks.\n */\n readonly locks?:\n | {\n request(\n name: string,\n options: { readonly ifAvailable: true },\n callback: (lock: unknown) => Promise<void> | undefined,\n ): Promise<unknown>\n }\n | undefined\n readonly indexedDB?: IDBFactory\n}\n\n/** Holds a Web Lock for the scope; false when another tab holds it. */\nconst claim = (locks: NonNullable<TabStorageOptions['locks']>, name: string) =>\n Effect.acquireRelease(\n Effect.callback<Option.Option<() => void>>(resume => {\n locks\n .request(name, { ifAvailable: true }, lock => {\n if (lock === null) {\n resume(Effect.succeed(Option.none()))\n return undefined\n }\n // The lock is held until this promise settles, which the scope's close does.\n return new Promise<void>(release => resume(Effect.succeed(Option.some(release))))\n })\n // A page that may not use locks (an opaque origin) is refused before any\n // callback: it keeps its key as a page without locks does.\n .catch(() => resume(Effect.succeed(Option.some(() => {}))))\n }),\n held => Effect.sync(() => Option.map(held, release => release())),\n ).pipe(Effect.map(Option.isSome))\n\n/**\n * This tab's store: IndexedDB `${name}/${key}`, where the key is read from\n * `sessionStorage` under `name`, or minted. A reload reopens the store, unsent\n * operations included; a duplicated tab, whose copied key another tab holds,\n * mints its own. Pass it to `openReplica`, which takes the replica's id from\n * the store.\n */\nexport const tabStorage = Effect.fn('Storage.tabStorage')(function* (\n name: string,\n options: TabStorageOptions = {},\n) {\n const session = options.sessionStorage ?? globalThis.sessionStorage\n const locks =\n 'locks' in options\n ? options.locks\n : (globalThis.navigator as { locks?: TabStorageOptions['locks'] } | undefined)?.locks\n const held = (key: string) =>\n locks === undefined ? Effect.succeed(true) : claim(locks, `foldkit-sync:${name}/${key}`)\n const kept = session.getItem(name)\n const key = kept !== null && (yield* held(kept)) ? kept : crypto.randomUUID()\n if (key !== kept) {\n yield* held(key)\n session.setItem(name, key)\n }\n return yield* indexedDb(`${name}/${key}`, options.indexedDB)\n})\n"],"mappings":";;;AAoCA,MAAM,gBAAgB,SAAiB,UACrC,IAAI,aAAa;CACf,SAAS,GAAG,QAAQ,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAC7E;AACF,CAAC;AAEH,MAAM,gBACJ,MACA,YAEA,OAAO,WAAW;CAChB,WACE,IAAI,SAAsB,SAAS,WAAW;EAC5C,MAAM,UAAU,QAAQ,KAAK,MAAM,CAAC;EAGpC,QAAQ,mBAAkB,UAAS;GACjC,MAAM,WAAW,QAAQ;GACzB,IAAI,MAAM,aAAa,GAAG,SAAS,kBAAkB,SAAS;GAC9D,IAAI,MAAM,aAAa,GAAG,SAAS,kBAAkB,QAAQ;EAC/D;EACA,IAAI,UAAU;EAGd,QAAQ,kBAAmB,UAAU,QAAQ,OAAO,MAAM,IAAI,QAAQ,QAAQ,MAAM;EACpF,QAAQ,gBAAgB,OAAO,QAAQ,KAAK;EAG5C,QAAQ,kBAAkB;GACxB,UAAU;GACV,uBAAO,IAAI,MAAM,oDAAoD,CAAC;EACxE;CACF,CAAC;CACH,QAAO,UAAS,aAAa,8BAA8B,KAAK;AAClE,CAAC;;AAGH,MAAa,YAAY,OAAO,GAAG,mBAAmB,CAAC,CAAC,WACtD,MACA,UAAsB,WAAW,WACjC;CACA,MAAM,eACJ,OAAO,SAAS,WACZ,OACA,OAAO,KAAK,KACV,OAAO,SAAS,gBAAe,UAC7B,OAAO,KAAK,aAAa,mCAAmC,KAAK,CAAC,CACpE,CACF;CACN,MAAM,WAAW,OAAO,OAAO,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