foldkit-sync 0.12.4 → 0.14.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.
Files changed (82) hide show
  1. package/README.md +77 -25
  2. package/dist/diagnostics.d.ts +71 -0
  3. package/dist/diagnostics.d.ts.map +1 -0
  4. package/dist/diagnostics.js +67 -0
  5. package/dist/diagnostics.js.map +1 -0
  6. package/dist/{do.d.mts → do.d.ts} +12 -2
  7. package/dist/do.d.ts.map +1 -0
  8. package/dist/{do.mjs → do.js} +15 -9
  9. package/dist/do.js.map +1 -0
  10. package/dist/{entity.d.mts → entity.d.ts} +1 -1
  11. package/dist/entity.d.ts.map +1 -0
  12. package/dist/{entity.mjs → entity.js} +1 -1
  13. package/dist/entity.js.map +1 -0
  14. package/dist/errors.d.ts +91 -0
  15. package/dist/errors.d.ts.map +1 -0
  16. package/dist/errors.js +75 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/ids.d.ts +30 -0
  19. package/dist/ids.d.ts.map +1 -0
  20. package/dist/ids.js +28 -0
  21. package/dist/ids.js.map +1 -0
  22. package/dist/index.d.ts +106 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +77 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/indexedDb.d.ts +62 -0
  27. package/dist/indexedDb.d.ts.map +1 -0
  28. package/dist/indexedDb.js +128 -0
  29. package/dist/indexedDb.js.map +1 -0
  30. package/dist/{journal.d.mts → journal.d.ts} +29 -5
  31. package/dist/journal.d.ts.map +1 -0
  32. package/dist/{journal-D5h-jqXE.mjs → journal.js} +43 -32
  33. package/dist/journal.js.map +1 -0
  34. package/dist/lww.d.ts +76 -0
  35. package/dist/lww.d.ts.map +1 -0
  36. package/dist/lww.js +121 -0
  37. package/dist/lww.js.map +1 -0
  38. package/dist/make.d.ts +162 -0
  39. package/dist/make.d.ts.map +1 -0
  40. package/dist/make.js +153 -0
  41. package/dist/make.js.map +1 -0
  42. package/dist/mount.d.ts +138 -0
  43. package/dist/mount.d.ts.map +1 -0
  44. package/dist/mount.js +344 -0
  45. package/dist/mount.js.map +1 -0
  46. package/dist/presence.d.ts +116 -0
  47. package/dist/presence.d.ts.map +1 -0
  48. package/dist/presence.js +277 -0
  49. package/dist/presence.js.map +1 -0
  50. package/dist/{remote.d.mts → remote.d.ts} +4 -11
  51. package/dist/remote.d.ts.map +1 -0
  52. package/dist/{remote.mjs → remote.js} +8 -7
  53. package/dist/remote.js.map +1 -0
  54. package/dist/revalidate.d.ts +6 -0
  55. package/dist/revalidate.d.ts.map +1 -0
  56. package/dist/revalidate.js +10 -0
  57. package/dist/revalidate.js.map +1 -0
  58. package/dist/sync.d.ts +276 -0
  59. package/dist/sync.d.ts.map +1 -0
  60. package/dist/sync.js +512 -0
  61. package/dist/sync.js.map +1 -0
  62. package/dist/transport.d.ts +151 -0
  63. package/dist/transport.d.ts.map +1 -0
  64. package/dist/{transport-BZ6utYmB.mjs → transport.js} +20 -30
  65. package/dist/transport.js.map +1 -0
  66. package/package.json +25 -25
  67. package/dist/do.d.mts.map +0 -1
  68. package/dist/do.mjs.map +0 -1
  69. package/dist/entity.d.mts.map +0 -1
  70. package/dist/entity.mjs.map +0 -1
  71. package/dist/index.d.mts +0 -397
  72. package/dist/index.d.mts.map +0 -1
  73. package/dist/index.mjs +0 -1613
  74. package/dist/index.mjs.map +0 -1
  75. package/dist/journal-D5h-jqXE.mjs.map +0 -1
  76. package/dist/journal.d.mts.map +0 -1
  77. package/dist/journal.mjs +0 -1
  78. package/dist/make-DJ0Q1SSc.d.mts +0 -702
  79. package/dist/make-DJ0Q1SSc.d.mts.map +0 -1
  80. package/dist/remote.d.mts.map +0 -1
  81. package/dist/remote.mjs.map +0 -1
  82. package/dist/transport-BZ6utYmB.mjs.map +0 -1
package/dist/make.d.ts ADDED
@@ -0,0 +1,162 @@
1
+ import { Schema } from "effect";
2
+ import { AppScope, Contract, MergeConstructors, MergeFields, MessageSet, RunnableApplication, Surface, Wiring, WritableProjection } from "foldkit-surface";
3
+ import { CommitStamp, JournalContract, Operation, Sync } from "./sync.js";
4
+ import { DocumentId } from "./ids.js";
5
+ type MessageConstructor<Message> = (...args: never[]) => Message;
6
+ /** The Message union a tuple of constructors produces. */
7
+ export type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends ((...args: never[]) => infer M) ? M : never;
8
+ type AppMessage<AppModel, F extends Schema.Struct.Fields, Cases extends Record<string, Schema.Struct.Fields>> = Schema.Schema.Type<AppScope<AppModel, F, Cases>['Message']>;
9
+ /** The `_tag` literal of the Message a constructor produces. */
10
+ type TagOf<C> = C extends ((...args: never[]) => infer M) ? M extends {
11
+ readonly _tag: infer T extends string;
12
+ } ? T : never : never;
13
+ /**
14
+ * A journal contract that also carries the declared authorization policy, in
15
+ * the shape `makeJournal` takes, so `makeJournal({ ...contract })` applies it.
16
+ */
17
+ export interface PolicyJournalContract<Operation, Shared, Principal> extends JournalContract<Operation, Shared> {
18
+ readonly authorize?: (request: {
19
+ readonly principal: Principal;
20
+ readonly operation: Operation;
21
+ readonly snapshot: Shared;
22
+ }) => AuthorizeDecision;
23
+ }
24
+ /**
25
+ * What a rule decides: allowed, refused, or refused with a reason the server
26
+ * sends to the person whose edit it was. The shape of Durable's own decision.
27
+ */
28
+ export type AuthorizeDecision = boolean | {
29
+ readonly allowed: false;
30
+ readonly reason: string;
31
+ };
32
+ /** What a per-variant `authorize` rule sees before the journal commits. */
33
+ export interface AuthorizeRequest<Principal, Message, Shared> {
34
+ readonly principal: Principal;
35
+ readonly message: Message;
36
+ readonly shared: Shared;
37
+ }
38
+ /**
39
+ * Per-variant policy, keyed by durable tag: `message` is that variant exactly,
40
+ * `shared` the authoritative snapshot. A variant without a rule is allowed; the
41
+ * server may still refuse on its own grounds.
42
+ */
43
+ export type AuthorizePolicy<Principal, Fields extends Schema.Struct.Fields, Ms extends readonly unknown[]> = { readonly [K in TagOf<Ms[number]>]?: (request: AuthorizeRequest<Principal, Extract<MsgOf<Ms>, {
44
+ readonly _tag: K;
45
+ }>, Schema.Struct.Type<Fields>>) => AuthorizeDecision; };
46
+ /**
47
+ * Per-variant commit stamps, keyed by durable tag: each writes what the server's commit
48
+ * decided (its sequence, its actor) into that variant, and returns the same variant. A
49
+ * variant without one is committed as sent.
50
+ */
51
+ export type StampPolicy<Ms extends readonly unknown[]> = { readonly [K in TagOf<Ms[number]>]?: (message: Extract<MsgOf<Ms>, {
52
+ readonly _tag: K;
53
+ }>, commit: CommitStamp) => Extract<MsgOf<Ms>, {
54
+ readonly _tag: K;
55
+ }>; };
56
+ interface BaseOptions<Principal, Fields extends Schema.Struct.Fields, Ms extends readonly unknown[]> {
57
+ readonly documentId: DocumentId;
58
+ /** Name for the generated `surface`; defaults to the document id. */
59
+ readonly name?: string;
60
+ /**
61
+ * Replaces the replay derived from the application's `update`. It is a pure
62
+ * reducer over the shared subset; only durable Messages reach it, and it runs
63
+ * during admission, replay, and optimistic projection. It is not guarded: the
64
+ * author owns its agreement with `update`.
65
+ */
66
+ readonly replay?: (shared: Schema.Struct.Type<NoInfer<Fields>>, message: MsgOf<NoInfer<Ms>>) => Schema.Struct.Type<NoInfer<Fields>>;
67
+ /** Authorization the server journal applies before committing; see `AuthorizePolicy`. */
68
+ readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>;
69
+ /** What the server's commit writes into a durable Message; see `StampPolicy`. */
70
+ readonly stamp?: StampPolicy<NoInfer<Ms>>;
71
+ /**
72
+ * Merges a durable Message into the one submitted before it while that one is unsent,
73
+ * so a burst of edits is one operation. Replaying the result must equal replaying
74
+ * `last` then `next`; undefined keeps them apart.
75
+ */
76
+ readonly coalesce?: (last: MsgOf<NoInfer<Ms>>, next: MsgOf<NoInfer<Ms>>) => MsgOf<NoInfer<Ms>> | undefined;
77
+ }
78
+ export interface MakeOptions<AppModel, Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<any>[], Principal = unknown> extends BaseOptions<Principal, Fields, Ms> {
79
+ /** The writable projection of the shared fields. */
80
+ readonly shared: WritableProjection<AppModel, Fields>;
81
+ /** The Message subset the replica durably records and replays. */
82
+ readonly durable: MessageSet<AppModel, any, Subset, Ms>;
83
+ }
84
+ /**
85
+ * One feature's contribution to a document: the fields it shares and the
86
+ * Messages it records. `compose` merges fragments into one, to spread into
87
+ * `make`; a field declared twice with a different codec or a tag declared twice
88
+ * is rejected there.
89
+ */
90
+ export interface SyncFragment<AppModel, Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<any>[]> {
91
+ readonly shared: WritableProjection<AppModel, Fields>;
92
+ readonly durable: MessageSet<AppModel, any, Subset, Ms>;
93
+ }
94
+ type SharedOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = { readonly [K in keyof Fs]: Fs[K]['shared']; };
95
+ type DurableOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = { readonly [K in keyof Fs]: Fs[K]['durable']; };
96
+ /** The merged shared fields of several fragments. */
97
+ export type FragmentFields<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeFields<SharedOf<Fs>>;
98
+ /** The concatenated durable constructors of several fragments. */
99
+ export type FragmentConstructors<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeConstructors<DurableOf<Fs>>;
100
+ /** The union of Messages several fragments record. */
101
+ export type FragmentMessages<Fs extends readonly SyncFragment<any, any, any, any>[]> = Fs[number] extends SyncFragment<any, any, infer V, any> ? V : never;
102
+ /**
103
+ * The value `make` returns: the low-level `Sync` protocol plus the writable
104
+ * projection, the declared Messages, and a read-only Surface over the
105
+ * projection. Exported so a consumer can name the type.
106
+ */
107
+ export interface DefinedSync<AppModel, Fields extends Schema.Struct.Fields, Message, Ms extends readonly unknown[], Principal = unknown,
108
+ /** `true` when `make` was given `authorize`, so the contract's `authorize` is present. */
109
+ Authorized extends boolean = false> extends Sync<Message, Schema.Struct.Type<Fields>, MsgOf<Ms>> {
110
+ readonly surface: Surface<AppModel, Schema.Struct.Type<Fields>, MsgOf<Ms>, void>;
111
+ readonly projection: WritableProjection<AppModel, Fields>;
112
+ /** The reducer the replica replays durable Messages with: derived from `update`, or `make`'s `replay`. */
113
+ readonly replay: (shared: Schema.Struct.Type<Fields>, message: Message) => Schema.Struct.Type<Fields>;
114
+ readonly messages: Ms;
115
+ /** For `Module`: this contract owns the shared projection's paths and records the durable tags. */
116
+ readonly contract: Contract;
117
+ /**
118
+ * How this contract joins an assembly: contract-only, so the Module sees it.
119
+ * It routes nothing, runs nothing, and subscribes to nothing; Sync owns the
120
+ * runtime through `mount` rather than joining it.
121
+ */
122
+ readonly wiring: () => Wiring<AppModel, never>;
123
+ /** The durable journal's codecs, reducer, and, when declared, authorization. */
124
+ readonly journalContract: () => Authorized extends true ? PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal> & Required<Pick<PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>, 'authorize'>> : PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>;
125
+ }
126
+ /** The sync constructors specialized to one application. */
127
+ export interface ApplicationSync<AppModel, F extends Schema.Struct.Fields, Cases extends Record<string, Schema.Struct.Fields>, Principal = unknown> {
128
+ /**
129
+ * Fixes the `Principal` that `authorize` rules see. A `Principal` cannot be a
130
+ * positional type argument beside an inferred Model, so it is supplied here:
131
+ * `Sync.forApplication(App).withPrincipal<User>()`. Type-only.
132
+ */
133
+ readonly withPrincipal: <P>() => ApplicationSync<AppModel, F, Cases, P>;
134
+ /** One feature's shared fields and durable Messages, for `compose`. */
135
+ readonly fragment: <Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[]>(config: {
136
+ readonly shared: WritableProjection<AppModel, Fields>;
137
+ readonly durable: MessageSet<AppModel, any, Subset, Ms>;
138
+ }) => SyncFragment<AppModel, Fields, Subset, Ms>;
139
+ /**
140
+ * Merges fragments into one: `make({ documentId, ...compose(Todos, Members) })`.
141
+ * A field declared twice with a different codec, a tag declared twice, or a
142
+ * fragment from another application throws.
143
+ */
144
+ readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(...fragments: Fs) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>;
145
+ readonly make: {
146
+ <Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[]>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal> & {
147
+ readonly authorize: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>;
148
+ }): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, true>;
149
+ <Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[]>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal>): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal>;
150
+ };
151
+ }
152
+ /**
153
+ * Specializes the sync constructors to a `Surface.application`, so
154
+ * `Sync.forApplication(App).make({ documentId, shared, durable })` derives the
155
+ * shared codec, the initial snapshot, the durable predicate, and replay from
156
+ * the application, and refuses a subset that belongs to another application.
157
+ * `defineSync` remains the protocol primitive when there is no application to
158
+ * derive from.
159
+ */
160
+ export declare const forApplication: <AppModel, F extends Schema.Struct.Fields, Cases extends Record<string, Schema.Struct.Fields>>(app: RunnableApplication<AppModel, F, Cases, any>) => ApplicationSync<AppModel, F, Cases>;
161
+ export {};
162
+ //# sourceMappingURL=make.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"make.d.ts","names":[],"sources":["../src/make.ts"],"mappings":";;;;KA4BK,mBAAmB,eAAe,kBAAkB;;YAG7C,MAAM,iCAAiC,wBAAuB,wBAAwB,KAC9F;KAGC,WACH,UACA,UAAU,OAAO,OAAO,QACxB,cAAc,eAAe,OAAO,OAAO,WACzC,OAAO,OAAO,KAAK,SAAS,UAAU,GAAG;;KAgBxC,MAAM,KAAK,eAAc,wBAAwB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IAAI;KAEnE,eAAe,OAAO,OAAO,QAC7B,QACA,oBAAoB,mBAAmB,WAAW,UAAU,GAAG,WAE/D,SAAS,YAAY,UAAU,QAAQ,QAAQ,IAAI,aAClD,YAAY,UAAU,QAAQ,WAAW,UAAU,GAAG,QAAQ,IAAI;;;;;;;;;;;qBAqF5D,iBACX,UACA,UAAU,OAAO,OAAO,QACxB,cAAc,eAAe,OAAO,OAAO,SAAO,KAE7C,oBAAoB,UAAU,GAAG,gBACrC,gBAAgB,UAAU,GAAG"}
package/dist/make.js ADDED
@@ -0,0 +1,153 @@
1
+ import { Equal, Option, Predicate, Schema } from "effect";
2
+ import { MessageSet, Projection, Surface } from "foldkit-surface";
3
+ import { defineSync } from "./sync.js";
4
+ // src/make.ts
5
+ /**
6
+ * The Foldkit-facing sync layer: `Sync.forApplication(App).make(config)`
7
+ * compiles an application, a writable projection, and a durable Message subset
8
+ * into the low-level `defineSync` contract, and exposes a read-only Surface over
9
+ * the same projection.
10
+ */
11
+ /** Reads the tag off a Foldkit Message constructor without constructing one. */
12
+ const messageTag = (constructor) => {
13
+ const literal = constructor.fields?._tag?.ast?.literal;
14
+ return typeof literal === "string" ? literal : void 0;
15
+ };
16
+ /** A Message's tag. The application's union is generic here, so its `_tag` is read, not typed. */
17
+ const tagOf = (message) => Predicate.hasProperty(message, "_tag") && typeof message._tag === "string" ? Option.some(message._tag) : Option.none();
18
+ /**
19
+ * Replay derived from the application's own `update`: install the shared slice
20
+ * into the initial Model, apply the Message, and read the slice back.
21
+ *
22
+ * A durable Message must be a deterministic, state-only transition of the shared
23
+ * projection. Replay refuses one that returns a Command (a live effect cannot be
24
+ * replayed) or that changes a Model field outside the projection (the change
25
+ * would be silently lost), so a Message that needs either stays local and emits
26
+ * a durable fact once the effect settles.
27
+ */
28
+ const derivedReplay = (app, shared) => {
29
+ const { initial, update } = app;
30
+ const owned = new Set(shared.dependencies.filter((path) => path.length === 1).map((path) => path[0]));
31
+ const fields = Object.entries(app.Model.fields).filter(([key]) => !owned.has(key)).map(([key, field]) => [key, Schema.toEquivalence(field)]);
32
+ return (value, message) => {
33
+ const result = update(shared.set(initial, value), message);
34
+ if (result.commands !== void 0 && result.commands.length > 0) throw new Error(`Sync.forApplication: durable "${Option.getOrElse(tagOf(message), () => "untagged")}" returned ${result.commands.length} Command(s); a durable transition is state-only`);
35
+ const next = shared.get(result.model);
36
+ const written = shared.set(initial, next);
37
+ const actual = result.model;
38
+ const changed = fields.filter(([key, equal]) => !equal(actual[key], written[key]));
39
+ if (changed.length > 0) throw new Error(`Sync.forApplication: durable "${Option.getOrElse(tagOf(message), () => "untagged")}" changed Model fields outside the shared projection: ${changed.map(([key]) => key).join(", ")}`);
40
+ return next;
41
+ };
42
+ };
43
+ /**
44
+ * Merges fragments into one. The primitives reject a conflicting field, a
45
+ * duplicate tag, and a subset from another application.
46
+ */
47
+ const composeFragments = (fragments) => {
48
+ const compose = Projection.compose;
49
+ const union = MessageSet.union;
50
+ return {
51
+ shared: compose(...fragments.map((fragment) => fragment.shared)),
52
+ durable: union(...fragments.map((fragment) => fragment.durable))
53
+ };
54
+ };
55
+ /**
56
+ * Specializes the sync constructors to a `Surface.application`, so
57
+ * `Sync.forApplication(App).make({ documentId, shared, durable })` derives the
58
+ * shared codec, the initial snapshot, the durable predicate, and replay from
59
+ * the application, and refuses a subset that belongs to another application.
60
+ * `defineSync` remains the protocol primitive when there is no application to
61
+ * derive from.
62
+ */
63
+ const forApplication = (app) => build(app);
64
+ const build = (app) => {
65
+ const decodeMessage = Schema.decodeUnknownSync(app.Message);
66
+ const make = (options) => {
67
+ const { shared, durable } = options;
68
+ if (durable.owner !== app.owner) throw new Error("Sync.make: the durable subset belongs to a different application");
69
+ const replay = options.replay === void 0 ? derivedReplay(app, shared) : (value, message) => options.replay(value, message);
70
+ const durableTags = new Set(durable.constructors.map(messageTag).filter((tag) => tag !== void 0));
71
+ const sharedCodec = shared.schema;
72
+ const stamps = options.stamp;
73
+ const sync = defineSync({
74
+ documentId: options.documentId,
75
+ message: app.Message,
76
+ shared: sharedCodec,
77
+ empty: shared.get(app.initial),
78
+ durable: (message) => Option.exists(tagOf(message), (tag) => durableTags.has(tag)),
79
+ replay,
80
+ coalesce: options.coalesce,
81
+ ...stamps === void 0 ? {} : { stamp: (message, commit) => Option.match(Option.flatMapNullishOr(tagOf(message), (tag) => stamps[tag]), {
82
+ onNone: () => message,
83
+ onSome: (rule) => {
84
+ const stamped = rule(message, commit);
85
+ if (!Equal.equals(tagOf(stamped), tagOf(message))) throw new Error("A stamp must return the variant it was given");
86
+ return stamped;
87
+ }
88
+ }) }
89
+ });
90
+ const rules = options.authorize;
91
+ const journalContract = () => {
92
+ const base = sync.journalContract();
93
+ if (rules === void 0) return base;
94
+ return {
95
+ ...base,
96
+ authorize: ({ principal, operation, snapshot }) => {
97
+ const message = decodeMessage(operation.message);
98
+ return Option.match(Option.flatMapNullishOr(tagOf(message), (tag) => rules[tag]), {
99
+ onNone: () => true,
100
+ onSome: (rule) => rule({
101
+ principal,
102
+ message,
103
+ shared: snapshot
104
+ })
105
+ });
106
+ }
107
+ };
108
+ };
109
+ const readOnly = Projection.fromReader(sharedCodec, shared.get, { dependencies: shared.dependencies });
110
+ const surface = Surface.make(app, options.name ?? String(options.documentId), {
111
+ model: () => readOnly,
112
+ messages: durable.constructors
113
+ });
114
+ const contract = {
115
+ kind: "sync",
116
+ name: surface.name,
117
+ owner: app.owner,
118
+ owns: shared.dependencies,
119
+ observes: shared.dependencies,
120
+ messages: [...durable.tags],
121
+ metadata: []
122
+ };
123
+ return {
124
+ ...sync,
125
+ journalContract,
126
+ surface,
127
+ projection: shared,
128
+ replay,
129
+ messages: durable.constructors,
130
+ contract,
131
+ wiring: () => ({
132
+ key: `sync:${contract.name}`,
133
+ handles: [],
134
+ contract
135
+ })
136
+ };
137
+ };
138
+ return {
139
+ withPrincipal: () => build(app),
140
+ fragment: (config) => {
141
+ if (config.durable.owner !== app.owner) throw new Error("Sync.fragment: the durable subset belongs to a different application");
142
+ return {
143
+ shared: config.shared,
144
+ durable: config.durable
145
+ };
146
+ },
147
+ compose: ((...fragments) => composeFragments(fragments)),
148
+ make
149
+ };
150
+ };
151
+ export { forApplication };
152
+
153
+ //# sourceMappingURL=make.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"make.js","names":[],"sources":["../src/make.ts"],"sourcesContent":["/**\n * The Foldkit-facing sync layer: `Sync.forApplication(App).make(config)`\n * compiles an application, a writable projection, and a durable Message subset\n * into the low-level `defineSync` contract, and exposes a read-only Surface over\n * the same projection.\n */\nimport { Equal, Option, Predicate, Schema } from 'effect'\nimport {\n MessageSet,\n Projection,\n Surface,\n type AppScope,\n type Contract,\n type MergeConstructors,\n type MergeFields,\n type RunnableApplication,\n type Wiring,\n type WritableProjection,\n} from 'foldkit-surface'\nimport type { DocumentId } from './ids.js'\nimport {\n defineSync,\n type CommitStamp,\n type JournalContract,\n type Operation,\n type Sync,\n} from './sync.js'\n\ntype MessageConstructor<Message> = (...args: never[]) => Message\n\n/** The Message union a tuple of constructors produces. */\nexport type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends (...args: never[]) => infer M\n ? M\n : never\n\ntype AppMessage<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n> = Schema.Schema.Type<AppScope<AppModel, F, Cases>['Message']>\n\n/** Reads the tag off a Foldkit Message constructor without constructing one. */\nconst messageTag = (constructor: unknown): string | undefined => {\n const literal = (constructor as { fields?: { _tag?: { ast?: { literal?: unknown } } } }).fields\n ?._tag?.ast?.literal\n return typeof literal === 'string' ? literal : undefined\n}\n\n/** A Message's tag. The application's union is generic here, so its `_tag` is read, not typed. */\nconst tagOf = (message: unknown): Option.Option<string> =>\n Predicate.hasProperty(message, '_tag') && typeof message._tag === 'string'\n ? Option.some(message._tag)\n : Option.none()\n\n/** The `_tag` literal of the Message a constructor produces. */\ntype TagOf<C> = C extends (...args: never[]) => infer M\n ? M extends { readonly _tag: infer T extends string }\n ? T\n : never\n : never\n\n/**\n * A journal contract that also carries the declared authorization policy, in\n * the shape `makeJournal` takes, so `makeJournal({ ...contract })` applies it.\n */\nexport interface PolicyJournalContract<Operation, Shared, Principal> extends JournalContract<\n Operation,\n Shared\n> {\n readonly authorize?: (request: {\n readonly principal: Principal\n readonly operation: Operation\n readonly snapshot: Shared\n }) => AuthorizeDecision\n}\n\n/**\n * What a rule decides: allowed, refused, or refused with a reason the server\n * sends to the person whose edit it was. The shape of Durable's own decision.\n */\nexport type AuthorizeDecision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a per-variant `authorize` rule sees before the journal commits. */\nexport interface AuthorizeRequest<Principal, Message, Shared> {\n readonly principal: Principal\n readonly message: Message\n readonly shared: Shared\n}\n\n/**\n * Per-variant policy, keyed by durable tag: `message` is that variant exactly,\n * `shared` the authoritative snapshot. A variant without a rule is allowed; the\n * server may still refuse on its own grounds.\n */\nexport type AuthorizePolicy<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n> = {\n readonly [K in TagOf<Ms[number]>]?: (\n request: AuthorizeRequest<\n Principal,\n Extract<MsgOf<Ms>, { readonly _tag: K }>,\n Schema.Struct.Type<Fields>\n >,\n ) => AuthorizeDecision\n}\n\n/**\n * Per-variant commit stamps, keyed by durable tag: each writes what the server's commit\n * decided (its sequence, its actor) into that variant, and returns the same variant. A\n * variant without one is committed as sent.\n */\nexport type StampPolicy<Ms extends readonly unknown[]> = {\n readonly [K in TagOf<Ms[number]>]?: (\n message: Extract<MsgOf<Ms>, { readonly _tag: K }>,\n commit: CommitStamp,\n ) => Extract<MsgOf<Ms>, { readonly _tag: K }>\n}\n\ninterface BaseOptions<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n> {\n readonly documentId: DocumentId\n /** Name for the generated `surface`; defaults to the document id. */\n readonly name?: string\n /**\n * Replaces the replay derived from the application's `update`. It is a pure\n * reducer over the shared subset; only durable Messages reach it, and it runs\n * during admission, replay, and optimistic projection. It is not guarded: the\n * author owns its agreement with `update`.\n */\n readonly replay?: (\n shared: Schema.Struct.Type<NoInfer<Fields>>,\n message: MsgOf<NoInfer<Ms>>,\n ) => Schema.Struct.Type<NoInfer<Fields>>\n /** Authorization the server journal applies before committing; see `AuthorizePolicy`. */\n readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>\n /** What the server's commit writes into a durable Message; see `StampPolicy`. */\n readonly stamp?: StampPolicy<NoInfer<Ms>>\n /**\n * Merges a durable Message into the one submitted before it while that one is unsent,\n * so a burst of edits is one operation. Replaying the result must equal replaying\n * `last` then `next`; undefined keeps them apart.\n */\n readonly coalesce?: (\n last: MsgOf<NoInfer<Ms>>,\n next: MsgOf<NoInfer<Ms>>,\n ) => MsgOf<NoInfer<Ms>> | undefined\n}\n\nexport interface MakeOptions<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n Principal = unknown,\n> extends BaseOptions<Principal, Fields, Ms> {\n /** The writable projection of the shared fields. */\n readonly shared: WritableProjection<AppModel, Fields>\n /** The Message subset the replica durably records and replays. */\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n}\n\n/**\n * One feature's contribution to a document: the fields it shares and the\n * Messages it records. `compose` merges fragments into one, to spread into\n * `make`; a field declared twice with a different codec or a tag declared twice\n * is rejected there.\n */\nexport interface SyncFragment<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n> {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n}\n\ntype SharedOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['shared']\n}\ntype DurableOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['durable']\n}\n/** The merged shared fields of several fragments. */\nexport type FragmentFields<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeFields<\n SharedOf<Fs>\n>\n/** The concatenated durable constructors of several fragments. */\nexport type FragmentConstructors<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n MergeConstructors<DurableOf<Fs>>\n\n/** The union of Messages several fragments record. */\nexport type FragmentMessages<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n Fs[number] extends SyncFragment<any, any, infer V, any> ? V : never\n\n/**\n * The value `make` returns: the low-level `Sync` protocol plus the writable\n * projection, the declared Messages, and a read-only Surface over the\n * projection. Exported so a consumer can name the type.\n */\nexport interface DefinedSync<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n Principal = unknown,\n /** `true` when `make` was given `authorize`, so the contract's `authorize` is present. */\n Authorized extends boolean = false,\n> extends Sync<Message, Schema.Struct.Type<Fields>, MsgOf<Ms>> {\n readonly surface: Surface<AppModel, Schema.Struct.Type<Fields>, MsgOf<Ms>, void>\n readonly projection: WritableProjection<AppModel, Fields>\n /** The reducer the replica replays durable Messages with: derived from `update`, or `make`'s `replay`. */\n readonly replay: (\n shared: Schema.Struct.Type<Fields>,\n message: Message,\n ) => Schema.Struct.Type<Fields>\n readonly messages: Ms\n /** For `Module`: this contract owns the shared projection's paths and records the durable tags. */\n readonly contract: Contract\n /**\n * How this contract joins an assembly: contract-only, so the Module sees it.\n * It routes nothing, runs nothing, and subscribes to nothing; Sync owns the\n * runtime through `mount` rather than joining it.\n */\n readonly wiring: () => Wiring<AppModel, never>\n /** The durable journal's codecs, reducer, and, when declared, authorization. */\n readonly journalContract: () => Authorized extends true\n ? PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal> &\n Required<\n Pick<PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>, 'authorize'>\n >\n : PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>\n}\n\n/** The sync constructors specialized to one application. */\nexport interface ApplicationSync<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal = unknown,\n> {\n /**\n * Fixes the `Principal` that `authorize` rules see. A `Principal` cannot be a\n * positional type argument beside an inferred Model, so it is supplied here:\n * `Sync.forApplication(App).withPrincipal<User>()`. Type-only.\n */\n readonly withPrincipal: <P>() => ApplicationSync<AppModel, F, Cases, P>\n /** One feature's shared fields and durable Messages, for `compose`. */\n readonly fragment: <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(config: {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n }) => SyncFragment<AppModel, Fields, Subset, Ms>\n /**\n * Merges fragments into one: `make({ documentId, ...compose(Todos, Members) })`.\n * A field declared twice with a different codec, a tag declared twice, or a\n * fragment from another application throws.\n */\n readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(\n ...fragments: Fs\n ) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>\n readonly make: {\n <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal> & {\n readonly authorize: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>\n },\n ): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, true>\n <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal>,\n ): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal>\n }\n}\n\n/**\n * Replay derived from the application's own `update`: install the shared slice\n * into the initial Model, apply the Message, and read the slice back.\n *\n * A durable Message must be a deterministic, state-only transition of the shared\n * projection. Replay refuses one that returns a Command (a live effect cannot be\n * replayed) or that changes a Model field outside the projection (the change\n * would be silently lost), so a Message that needs either stays local and emits\n * a durable fact once the effect settles.\n */\nconst derivedReplay = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Fields extends Schema.Struct.Fields,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n shared: WritableProjection<AppModel, Fields>,\n): ((\n value: Schema.Struct.Type<Fields>,\n message: AppMessage<AppModel, F, Cases>,\n) => Schema.Struct.Type<Fields>) => {\n const { initial, update } = app\n // Per-field equivalences for the fields the projection does not own outright,\n // built once, so a violation names the fields and replay (which runs per\n // pending operation on every optimistic read) does not re-compare the shared\n // slice against itself. A partially shared field is still compared.\n const owned = new Set(shared.dependencies.filter(path => path.length === 1).map(path => path[0]))\n const fields = Object.entries(app.Model.fields)\n .filter(([key]) => !owned.has(key))\n .map(\n ([key, field]) =>\n [key, Schema.toEquivalence(field as unknown as Schema.Schema<unknown>)] as const,\n )\n return (value, message) => {\n const result = update(shared.set(initial, value), message)\n if (result.commands !== undefined && result.commands.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${Option.getOrElse(tagOf(message), () => 'untagged')}\" returned ${result.commands.length} Command(s); a durable transition is state-only`,\n )\n const next = shared.get(result.model)\n // Writing the projection back into the baseline reproduces `update`'s\n // result exactly when it touched only shared fields.\n const written = shared.set(initial, next) as Record<string, unknown>\n const actual = result.model as Record<string, unknown>\n const changed = fields.filter(([key, equal]) => !equal(actual[key], written[key]))\n if (changed.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${Option.getOrElse(tagOf(message), () => 'untagged')}\" changed Model fields outside the shared projection: ${changed.map(([key]) => key).join(', ')}`,\n )\n return next\n }\n}\n\n/**\n * Merges fragments into one. The primitives reject a conflicting field, a\n * duplicate tag, and a subset from another application.\n */\nconst composeFragments = (\n fragments: readonly SyncFragment<any, any, any, any>[],\n): SyncFragment<any, any, any, any> => {\n const compose = Projection.compose as (\n ...projections: readonly WritableProjection<any, any>[]\n ) => WritableProjection<any, any>\n const union = MessageSet.union as (\n ...subsets: readonly MessageSet<any, any, any, any>[]\n ) => MessageSet<any, any, any, any>\n return {\n shared: compose(...fragments.map(fragment => fragment.shared)),\n durable: union(...fragments.map(fragment => fragment.durable)),\n }\n}\n\n/**\n * Specializes the sync constructors to a `Surface.application`, so\n * `Sync.forApplication(App).make({ documentId, shared, durable })` derives the\n * shared codec, the initial snapshot, the durable predicate, and replay from\n * the application, and refuses a subset that belongs to another application.\n * `defineSync` remains the protocol primitive when there is no application to\n * derive from.\n */\nexport const forApplication = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases> => build(app)\n\nconst build = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases, Principal> => {\n type Message = AppMessage<AppModel, F, Cases>\n const decodeMessage = Schema.decodeUnknownSync(\n app.Message as unknown as Schema.Codec<Message, unknown>,\n )\n\n const make = (\n options: MakeOptions<AppModel, any, any, any, Principal>,\n ): DefinedSync<AppModel, any, Message, any, Principal, boolean> => {\n type Shared = Record<string, unknown>\n const { shared, durable } = options\n\n // Two applications can have structurally identical Message unions, so the\n // types cannot separate them; the owner token can.\n if (durable.owner !== app.owner)\n throw new Error('Sync.make: the durable subset belongs to a different application')\n\n const replay: (value: Shared, message: Message) => Shared =\n options.replay === undefined\n ? derivedReplay(app, shared)\n : // `durable` has already rejected anything outside the declared subset.\n (value, message) => options.replay!(value, message as never)\n const durableTags = new Set(\n (durable.constructors as readonly unknown[])\n .map(messageTag)\n .filter((tag): tag is string => tag !== undefined),\n )\n // `AppScope` does not constrain its schemas' services; a Foldkit Message union\n // and a Struct are pure, so the low-level contract's `never` is satisfied.\n const sharedCodec = shared.schema as unknown as Schema.Codec<Shared, unknown>\n const stamps = options.stamp as\n | Record<string, (message: Message, commit: CommitStamp) => Message>\n | undefined\n const sync = defineSync<Message, Shared, unknown, unknown>({\n documentId: options.documentId,\n message: app.Message as unknown as Schema.Codec<Message, unknown>,\n shared: sharedCodec,\n empty: shared.get(app.initial),\n durable: message => Option.exists(tagOf(message), tag => durableTags.has(tag)),\n replay,\n // `durable` has already rejected anything outside the declared subset.\n coalesce: options.coalesce as\n | ((last: Message, next: Message) => Message | undefined)\n | undefined,\n ...(stamps === undefined\n ? {}\n : {\n stamp: (message: Message, commit: CommitStamp): Message =>\n Option.match(\n Option.flatMapNullishOr(tagOf(message), tag => stamps[tag]),\n {\n onNone: () => message,\n onSome: rule => {\n const stamped = rule(message, commit)\n if (!Equal.equals(tagOf(stamped), tagOf(message)))\n throw new Error('A stamp must return the variant it was given')\n return stamped\n },\n },\n ),\n }),\n })\n\n const rules = options.authorize as\n | Record<string, (request: AuthorizeRequest<Principal, Message, Shared>) => AuthorizeDecision>\n | undefined\n const journalContract = (): PolicyJournalContract<Operation, Shared, Principal> => {\n const base = sync.journalContract()\n if (rules === undefined) return base\n return {\n ...base,\n authorize: ({ principal, operation, snapshot }) => {\n const message = decodeMessage(operation.message)\n return Option.match(\n Option.flatMapNullishOr(tagOf(message), tag => rules[tag]),\n {\n onNone: () => true,\n onSome: rule => rule({ principal, message, shared: snapshot }),\n },\n )\n },\n }\n }\n\n const readOnly: Projection<AppModel, Shared> = Projection.fromReader(sharedCodec, shared.get, {\n dependencies: shared.dependencies,\n })\n const surface = Surface.make(app, options.name ?? String(options.documentId), {\n model: () => readOnly,\n messages: durable.constructors,\n })\n const contract: Contract = {\n kind: 'sync',\n name: surface.name,\n owner: app.owner,\n owns: shared.dependencies,\n observes: shared.dependencies,\n messages: [...durable.tags],\n metadata: [],\n }\n return {\n ...sync,\n journalContract,\n surface,\n projection: shared,\n replay,\n messages: durable.constructors,\n contract,\n wiring: () => ({ key: `sync:${contract.name}`, handles: [], contract }),\n }\n }\n\n return {\n withPrincipal: <P>() => build<AppModel, F, Cases, P>(app),\n fragment: config => {\n if (config.durable.owner !== app.owner)\n throw new Error('Sync.fragment: the durable subset belongs to a different application')\n return { shared: config.shared, durable: config.durable }\n },\n compose: ((...fragments: readonly SyncFragment<any, any, any, any>[]) =>\n composeFragments(fragments)) as ApplicationSync<AppModel, F, Cases, Principal>['compose'],\n make: make as ApplicationSync<AppModel, F, Cases, Principal>['make'],\n }\n}\n"],"mappings":";;;;;;;;;;;AA0CA,MAAM,cAAc,gBAA6C;CAC/D,MAAM,UAAW,YAAwE,QACrF,MAAM,KAAK;CACf,OAAO,OAAO,YAAY,WAAW,UAAU,KAAA;AACjD;;AAGA,MAAM,SAAS,YACb,UAAU,YAAY,SAAS,MAAM,KAAK,OAAO,QAAQ,SAAS,WAC9D,OAAO,KAAK,QAAQ,IAAI,IACxB,OAAO,KAAK;;;;;;;;;;;AAuPlB,MAAM,iBAMJ,KACA,WAIkC;CAClC,MAAM,EAAE,SAAS,WAAW;CAK5B,MAAM,QAAQ,IAAI,IAAI,OAAO,aAAa,QAAO,SAAQ,KAAK,WAAW,CAAC,CAAC,CAAC,KAAI,SAAQ,KAAK,EAAE,CAAC;CAChG,MAAM,SAAS,OAAO,QAAQ,IAAI,MAAM,MAAM,CAAC,CAC5C,QAAQ,CAAC,SAAS,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAClC,KACE,CAAC,KAAK,WACL,CAAC,KAAK,OAAO,cAAc,KAA0C,CAAC,CAC1E;CACF,QAAQ,OAAO,YAAY;EACzB,MAAM,SAAS,OAAO,OAAO,IAAI,SAAS,KAAK,GAAG,OAAO;EACzD,IAAI,OAAO,aAAa,KAAA,KAAa,OAAO,SAAS,SAAS,GAC5D,MAAM,IAAI,MACR,iCAAiC,OAAO,UAAU,MAAM,OAAO,SAAS,UAAU,EAAE,aAAa,OAAO,SAAS,OAAO,gDAC1H;EACF,MAAM,OAAO,OAAO,IAAI,OAAO,KAAK;EAGpC,MAAM,UAAU,OAAO,IAA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,SAAS;IAAQ,SAAS,CAAC;IAAG;GAAS;EACvE;CACF;CAEA,OAAO;EACL,qBAAwB,MAA6B,GAAG;EACxD,WAAU,WAAU;GAClB,IAAI,OAAO,QAAQ,UAAU,IAAI,OAC/B,MAAM,IAAI,MAAM,sEAAsE;GACxF,OAAO;IAAE,QAAQ,OAAO;IAAQ,SAAS,OAAO;GAAQ;EAC1D;EACA,WAAW,GAAG,cACZ,iBAAiB,SAAS;EACtB;CACR;AACF"}
@@ -0,0 +1,138 @@
1
+ import { Effect, Exit, Layer, Schema } from "effect";
2
+ import { RunnableApplication } from "foldkit-surface";
3
+ import { DefinedSync } from "./make.js";
4
+ import { Replica } from "./sync.js";
5
+ import { ReplicaError } from "./errors.js";
6
+ import { UrlRequest } from "foldkit/navigation";
7
+ import { Subscriptions } from "foldkit/subscription";
8
+ import * as Url from "foldkit/url";
9
+ import { Document, HtmlBuilder } from "foldkit/html";
10
+ import * as Update from "foldkit/update";
11
+ /**
12
+ * A Command that dispatches `message` as the next transition, which under `Sync.mount`
13
+ * means within this one: the mount applies it straight after the `update` that returned
14
+ * it, and persists it if it is durable, before any other Message is processed. This is
15
+ * how a local intent turns into a durable fact that needs something only the intent's
16
+ * transition knows, such as an id minted from local state, without a later Message
17
+ * seeing the Model before the fact. Elsewhere, or once a parent has mapped the Command,
18
+ * it is an ordinary Command that yields `message`, and so is one a durable Message's
19
+ * update returns: replay would not apply it, and with derived replay the durable Message's
20
+ * persist fails with `ReplayError` as for any Command.
21
+ */
22
+ export declare const fact: <Message>(message: Message) => {
23
+ readonly name: string;
24
+ readonly effect: Effect.Effect<Message>;
25
+ };
26
+ /**
27
+ * The URL as part of the application: `onUrlChange` names the Message the
28
+ * runtime sends for the current URL at start and on every navigation (so a
29
+ * `foldkit-mirror` URL mirror reads back in), `init` reduces the URL into the
30
+ * Model before the first render, and `onUrlRequest` names the Message for a
31
+ * link click; omitted, the mount follows the link itself (an internal one is
32
+ * pushed, an external one loaded).
33
+ */
34
+ export interface MountUrl<Model, Message> {
35
+ readonly init?: ((model: Model, url: Url.Url) => Model) | undefined;
36
+ readonly onUrlChange: (url: Url.Url) => Message;
37
+ readonly onUrlRequest?: ((request: UrlRequest) => Message) | undefined;
38
+ }
39
+ export interface MountOptions<Model, Message, Shared, Resources> {
40
+ /** An open replica of this contract; `mount` does not close it. */
41
+ readonly replica: Replica<Message, Shared>;
42
+ /** The element the application renders into; Foldkit requires it to have an `id`. */
43
+ readonly container: HTMLElement;
44
+ readonly view: (model: Model, h: HtmlBuilder<Message>) => Document;
45
+ readonly subscriptions?: Subscriptions<Model, Message, Resources> | undefined;
46
+ readonly resources?: Layer.Layer<Resources> | undefined;
47
+ /** Route the URL through the application; without it the mount ignores the URL. */
48
+ readonly url?: MountUrl<Model, Message> | undefined;
49
+ /**
50
+ * Reflects a refused or failed persist in the Model, after the durable edit
51
+ * has been reverted. Omitted, the edit is reverted silently.
52
+ */
53
+ readonly onPersistenceFailure?: ((model: Model, error: ReplicaError) => Model) | undefined;
54
+ /**
55
+ * Runs when the mount replaces the shared slice outside `update`: an exchange committed,
56
+ * acknowledged or rejected something, or a persist failed and its edit was reverted.
57
+ * `previous` is the Model before; what it returns is the transition, so an application
58
+ * can carry local state across the change (a selection held by what it points at) or
59
+ * return Commands (a DOM the change has to reach). Omitted, the Model is `next`. It is
60
+ * not called for a status that changes nothing the Model shows, such as the first.
61
+ */
62
+ readonly onReinstall?: ((next: Model, previous: Model, change: Reinstall) => Update.Return<Model, Message, Resources>) | undefined;
63
+ /**
64
+ * Runs on the Model after every update of the mounted application, a durable
65
+ * Message's and a reinstall's included, and never in replay: for local state
66
+ * derived from the shared slice, which a durable transition may not write
67
+ * (the overlays `foldkit-sync/remote` keeps in Remote). With nothing to
68
+ * change it returns the Model it was given.
69
+ */
70
+ readonly afterUpdate?: ((model: Model) => Update.Return<Model, Message, Resources>) | undefined;
71
+ }
72
+ /**
73
+ * What a reinstall came from. `reset` is a server reset: the replica's
74
+ * committed history is a new one, so anything an application derived from
75
+ * the old one (reads cached by commit sequence, say) is to be read again.
76
+ */
77
+ export interface Reinstall {
78
+ readonly reset: boolean;
79
+ }
80
+ /**
81
+ * The shared slice as the server has confirmed it, outside the Model. It is a
82
+ * source for waiting consumers, the shape `Agent.when({ source })` reads, and
83
+ * not a Projection: it does not render and is not derived from the Model.
84
+ */
85
+ export interface CommittedView<Shared> {
86
+ readonly get: () => Shared;
87
+ /** Told after every exchange, including one that moves no cursor (a checkpoint). */
88
+ readonly subscribe: (listener: () => void) => () => void;
89
+ }
90
+ export interface Mounted<Model, Message, Shared = unknown> {
91
+ /** Sends an application Message through the runtime; the `Exit` reports a decode failure. */
92
+ readonly dispatch: (message: Message) => Exit.Exit<void, unknown>;
93
+ /** The Model after the last transition. */
94
+ readonly model: () => Model;
95
+ /** Notified after every transition; with `model` and `dispatch`, the host an agent binds to. */
96
+ readonly subscribe: (listener: () => void) => () => void;
97
+ /**
98
+ * Every application Message the runtime applies, from any origin, so an
99
+ * agent contract that declares a `completion` can see the Message that
100
+ * finishes its work. The mount's private Messages are not reported.
101
+ */
102
+ readonly observe: (listener: (message: Message) => void) => () => void;
103
+ /**
104
+ * The shared slice without pending local edits, for an agent that must not
105
+ * report an optimistic edit as done: `Agent.when({ source: mounted.committed, … })`.
106
+ */
107
+ readonly committed: CommittedView<Shared>;
108
+ /**
109
+ * Resolves once the Model has caught up with the replica: no persist in
110
+ * flight or unanswered, every replica status the mount was told of seen,
111
+ * and every reinstall it asked for applied. It observes and never does the
112
+ * work. Frames are not its to wait for (`Frames.track` in
113
+ * `foldkit-mixins/testing` is), nor I/O a Command started. Rejects after
114
+ * `dispose`.
115
+ */
116
+ readonly settled: () => Promise<void>;
117
+ /** Waits for in-flight persists, then disposes the runtime. The replica stays open. */
118
+ readonly dispose: () => Promise<void>;
119
+ }
120
+ /**
121
+ * A durable edit the Model already shows. `started` is the replica's next local
122
+ * sequence when its submit began, `undefined` while it waits for its turn.
123
+ */
124
+ export interface LocalEdit<Message> {
125
+ readonly message: Message;
126
+ started: number | undefined;
127
+ }
128
+ /**
129
+ * The edits a replica whose next local sequence is `next` does not hold yet.
130
+ * Submits run one at a time, so the one in flight is in the replica exactly
131
+ * when its submit has moved the sequence past `started`.
132
+ */
133
+ export declare const unconfirmedEdits: <Message>(edits: ReadonlyArray<LocalEdit<Message>>, next: number) => ReadonlyArray<Message>;
134
+ /** The application's Message union, as `Surface.application` types it. */
135
+ type MessageOf<App> = App extends RunnableApplication<any, any, any, any> ? Schema.Schema.Type<App['Message']> : never;
136
+ export declare const mount: <Model, F extends Schema.Struct.Fields, Cases extends Record<string, Schema.Struct.Fields>, Fields extends Schema.Struct.Fields, Ms extends readonly unknown[], Resources = never, Principal = unknown>(app: RunnableApplication<Model, F, Cases, Resources>, sync: DefinedSync<Model, Fields, MessageOf<RunnableApplication<Model, F, Cases, Resources>>, Ms, Principal>, options: MountOptions<Model, MessageOf<RunnableApplication<Model, F, Cases, Resources>>, Schema.Struct.Type<Fields>, Resources>) => Mounted<Model, MessageOf<RunnableApplication<Model, F, Cases, Resources>>, Schema.Struct.Type<Fields>>;
137
+ export {};
138
+ //# sourceMappingURL=mount.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mount.d.ts","names":[],"sources":["../src/mount.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;qBAqEa,OAAQ,SAAO,SACjB;WACG;WAAuB,QAAQ,OAAO,OAAO;;;;;;;;;;iBAqB1C,SAAS,OAAO;WACtB,SAAS,OAAO,OAAO,KAAK,IAAI,QAAQ;WACxC,cAAc,KAAK,IAAI,QAAQ;WAC/B,iBAAiB,SAAS,eAAe;;iBAGnC,aAAa,OAAO,SAAS,QAAQ;;WAE3C,SAAS,QAAQ,SAAS;;WAE1B,WAAW;WACX,OAAO,OAAO,OAAO,GAAG,YAAY,aAAa;WACjD,gBAAgB,cAAc,OAAO,SAAS;WAC9C,YAAY,MAAM,MAAM;;WAExB,MAAM,SAAS,OAAO;;;;;WAKtB,yBAAyB,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