foldkit-sync 0.15.0 → 0.17.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 +567 -41
- package/dist/diagnostics.d.ts +74 -3
- package/dist/diagnostics.d.ts.map +1 -1
- package/dist/diagnostics.js +60 -4
- package/dist/diagnostics.js.map +1 -1
- package/dist/do.d.ts +49 -7
- package/dist/do.d.ts.map +1 -1
- package/dist/do.js +91 -8
- package/dist/do.js.map +1 -1
- package/dist/errors.d.ts +92 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +87 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +9 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/dist/journal.d.ts +52 -27
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +176 -64
- package/dist/journal.js.map +1 -1
- package/dist/make.d.ts +48 -17
- package/dist/make.d.ts.map +1 -1
- package/dist/make.js +11 -4
- package/dist/make.js.map +1 -1
- package/dist/migrations.d.ts +37 -0
- package/dist/migrations.d.ts.map +1 -0
- package/dist/migrations.js +56 -0
- package/dist/migrations.js.map +1 -0
- package/dist/mount.d.ts +1 -1
- package/dist/mount.d.ts.map +1 -1
- package/dist/mount.js +12 -6
- package/dist/mount.js.map +1 -1
- package/dist/refusal.d.ts +33 -0
- package/dist/refusal.d.ts.map +1 -0
- package/dist/refusal.js +47 -0
- package/dist/refusal.js.map +1 -0
- package/dist/serverJournal.d.ts +143 -0
- package/dist/serverJournal.d.ts.map +1 -0
- package/dist/serverJournal.js +503 -0
- package/dist/serverJournal.js.map +1 -0
- package/dist/sync.d.ts +150 -14
- package/dist/sync.d.ts.map +1 -1
- package/dist/sync.js +273 -64
- package/dist/sync.js.map +1 -1
- package/dist/transport.d.ts +10 -6
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js.map +1 -1
- package/package.json +11 -8
package/dist/make.d.ts
CHANGED
|
@@ -1,11 +1,28 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
2
|
import { AppScope, Contract, MergeConstructors, MergeFields, MessageSet, RunnableApplication, Surface, Wiring, WritableProjection } from "foldkit-surface";
|
|
3
|
+
import { Migrations } from "./migrations.js";
|
|
3
4
|
import { CommitStamp, JournalContract, Operation, Sync } from "./sync.js";
|
|
4
5
|
import { DocumentId } from "./ids.js";
|
|
5
6
|
type MessageConstructor<Message> = (...args: never[]) => Message;
|
|
6
7
|
/** The Message union a tuple of constructors produces. */
|
|
7
8
|
export type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends ((...args: never[]) => infer M) ? M : never;
|
|
8
9
|
type AppMessage<AppModel, F extends Schema.Struct.Fields, Cases extends Record<string, Schema.Struct.Fields>> = Schema.Schema.Type<AppScope<AppModel, F, Cases>['Message']>;
|
|
10
|
+
type AppMessageEncoded<AppModel, F extends Schema.Struct.Fields, Cases extends Record<string, Schema.Struct.Fields>> = AppScope<AppModel, F, Cases>['Message']['Encoded'];
|
|
11
|
+
/** `make`'s Message history, typed by the application's own Message. */
|
|
12
|
+
export interface HistoryOption<Message, Encoded> {
|
|
13
|
+
/**
|
|
14
|
+
* The Schemas the document's durable Messages were stored in, ending at the
|
|
15
|
+
* application's own `Message` (`Sync.migrations(V1).next(App.Message, up)`):
|
|
16
|
+
* operations written at an older version are upcast wherever they are read.
|
|
17
|
+
* Without it, the Message is version 1.
|
|
18
|
+
*/
|
|
19
|
+
readonly migrations?: Migrations<Message, Encoded> | undefined;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The Messages of the server-only constructors: none for `[]`, which
|
|
23
|
+
* `MsgOf` reads as `unknown` (`never` matches its `infer`).
|
|
24
|
+
*/
|
|
25
|
+
export type ServerMsgOf<SMs extends readonly unknown[]> = [SMs[number]] extends [never] ? never : MsgOf<SMs>;
|
|
9
26
|
/** The `_tag` literal of the Message a constructor produces. */
|
|
10
27
|
type TagOf<C> = C extends ((...args: never[]) => infer M) ? M extends {
|
|
11
28
|
readonly _tag: infer T extends string;
|
|
@@ -53,21 +70,24 @@ export type StampPolicy<Ms extends readonly unknown[]> = { readonly [K in TagOf<
|
|
|
53
70
|
}>, commit: CommitStamp) => Extract<MsgOf<Ms>, {
|
|
54
71
|
readonly _tag: K;
|
|
55
72
|
}>; };
|
|
56
|
-
interface BaseOptions<Principal, Fields extends Schema.Struct.Fields, Ms extends readonly unknown[]> {
|
|
73
|
+
interface BaseOptions<Principal, Fields extends Schema.Struct.Fields, Ms extends readonly unknown[], SMs extends readonly unknown[] = []> {
|
|
57
74
|
readonly documentId: DocumentId;
|
|
58
75
|
/** Name for the generated `surface`; defaults to the document id. */
|
|
59
76
|
readonly name?: string;
|
|
60
77
|
/**
|
|
61
78
|
* Replaces the replay derived from the application's `update`. It is a pure
|
|
62
|
-
* reducer over the shared subset; only durable Messages reach
|
|
63
|
-
* during admission, replay, and optimistic projection. It is
|
|
64
|
-
* author owns its agreement with `update`.
|
|
79
|
+
* reducer over the shared subset; only durable and server-only Messages reach
|
|
80
|
+
* it, and it runs during admission, replay, and optimistic projection. It is
|
|
81
|
+
* not guarded: the author owns its agreement with `update`.
|
|
65
82
|
*/
|
|
66
|
-
readonly replay?: (shared: Schema.Struct.Type<NoInfer<Fields>>, message: MsgOf<NoInfer<Ms>>) => Schema.Struct.Type<NoInfer<Fields>>;
|
|
67
|
-
/**
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
83
|
+
readonly replay?: (shared: Schema.Struct.Type<NoInfer<Fields>>, message: MsgOf<NoInfer<Ms>> | ServerMsgOf<NoInfer<SMs>>) => Schema.Struct.Type<NoInfer<Fields>>;
|
|
84
|
+
/**
|
|
85
|
+
* Authorization the server journal applies before committing, keyed by
|
|
86
|
+
* durable or server-only tag; see `AuthorizePolicy`.
|
|
87
|
+
*/
|
|
88
|
+
readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<[...Ms, ...SMs]>>;
|
|
89
|
+
/** What the server's commit writes into a stored Message; see `StampPolicy`. */
|
|
90
|
+
readonly stamp?: StampPolicy<NoInfer<[...Ms, ...SMs]>>;
|
|
71
91
|
/**
|
|
72
92
|
* Merges a durable Message into the one submitted before it while that one is unsent,
|
|
73
93
|
* so a burst of edits is one operation. Replaying the result must equal replaying
|
|
@@ -75,11 +95,17 @@ interface BaseOptions<Principal, Fields extends Schema.Struct.Fields, Ms extends
|
|
|
75
95
|
*/
|
|
76
96
|
readonly coalesce?: (last: MsgOf<NoInfer<Ms>>, next: MsgOf<NoInfer<Ms>>) => MsgOf<NoInfer<Ms>> | undefined;
|
|
77
97
|
}
|
|
78
|
-
export interface MakeOptions<AppModel, Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<any>[], Principal = unknown> extends BaseOptions<Principal, Fields, Ms> {
|
|
98
|
+
export interface MakeOptions<AppModel, Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<any>[], Principal = unknown, ServerSubset = never, SMs extends readonly MessageConstructor<any>[] = []> extends BaseOptions<Principal, Fields, Ms, SMs> {
|
|
79
99
|
/** The writable projection of the shared fields. */
|
|
80
100
|
readonly shared: WritableProjection<AppModel, Fields>;
|
|
81
|
-
/** The Message subset
|
|
101
|
+
/** The Message subset a replica submits, records and replays. */
|
|
82
102
|
readonly durable: MessageSet<AppModel, any, Subset, Ms>;
|
|
103
|
+
/**
|
|
104
|
+
* The Messages only the server appends (`foldkit-sync/journal`'s
|
|
105
|
+
* `serverJournal`): stored and replayed like durable ones, refused from a
|
|
106
|
+
* replica. A Message in both sets is a type error, and a throw here.
|
|
107
|
+
*/
|
|
108
|
+
readonly serverOnly?: MessageSet<AppModel, any, ServerSubset, SMs> | undefined;
|
|
83
109
|
}
|
|
84
110
|
/**
|
|
85
111
|
* One feature's contribution to a document: the fields it shares and the
|
|
@@ -106,13 +132,18 @@ export type FragmentMessages<Fs extends readonly SyncFragment<any, any, any, any
|
|
|
106
132
|
*/
|
|
107
133
|
export interface DefinedSync<AppModel, Fields extends Schema.Struct.Fields, Message, Ms extends readonly unknown[], Principal = unknown,
|
|
108
134
|
/** `true` when `make` was given `authorize`, so the contract's `authorize` is present. */
|
|
109
|
-
Authorized extends boolean = false
|
|
135
|
+
Authorized extends boolean = false,
|
|
136
|
+
/** The server-only constructors, `[]` when `make` was given none. */
|
|
137
|
+
SMs extends readonly unknown[] = []> extends Sync<Message, Schema.Struct.Type<Fields>, MsgOf<Ms>> {
|
|
110
138
|
readonly surface: Surface<AppModel, Schema.Struct.Type<Fields>, MsgOf<Ms>, void>;
|
|
111
139
|
readonly projection: WritableProjection<AppModel, Fields>;
|
|
112
140
|
/** The reducer the replica replays durable Messages with: derived from `update`, or `make`'s `replay`. */
|
|
113
141
|
readonly replay: (shared: Schema.Struct.Type<Fields>, message: Message) => Schema.Struct.Type<Fields>;
|
|
142
|
+
/** The durable constructors: what a replica submits. */
|
|
114
143
|
readonly messages: Ms;
|
|
115
|
-
/**
|
|
144
|
+
/** The server-only constructors: what only the server appends. */
|
|
145
|
+
readonly serverOnlyMessages: SMs;
|
|
146
|
+
/** For `Module`: this contract owns the shared projection's paths and records the durable and server-only tags. */
|
|
116
147
|
readonly contract: Contract;
|
|
117
148
|
/**
|
|
118
149
|
* How this contract joins an assembly: contract-only, so the Module sees it.
|
|
@@ -143,10 +174,10 @@ export interface ApplicationSync<AppModel, F extends Schema.Struct.Fields, Cases
|
|
|
143
174
|
*/
|
|
144
175
|
readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(...fragments: Fs) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>;
|
|
145
176
|
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>;
|
|
177
|
+
<Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[], ServerSubset = never, SMs extends readonly MessageConstructor<Exclude<AppMessage<AppModel, F, Cases>, MsgOf<Ms>>>[] = []>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal, ServerSubset, SMs> & HistoryOption<AppMessage<AppModel, F, Cases>, AppMessageEncoded<AppModel, F, Cases>> & {
|
|
178
|
+
readonly authorize: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<[...Ms, ...SMs]>>;
|
|
179
|
+
}): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, true, SMs>;
|
|
180
|
+
<Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[], ServerSubset = never, SMs extends readonly MessageConstructor<Exclude<AppMessage<AppModel, F, Cases>, MsgOf<Ms>>>[] = []>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal, ServerSubset, SMs> & HistoryOption<AppMessage<AppModel, F, Cases>, AppMessageEncoded<AppModel, F, Cases>>): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, false, SMs>;
|
|
150
181
|
};
|
|
151
182
|
}
|
|
152
183
|
/**
|
package/dist/make.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"make.d.ts","names":[],"sources":["../src/make.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"make.d.ts","names":[],"sources":["../src/make.ts"],"mappings":";;;;;KA6BK,mBAA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
65
65
|
const decodeMessage = Schema.decodeUnknownSync(app.Message);
|
|
66
66
|
const make = (options) => {
|
|
67
|
-
const { shared, durable } = options;
|
|
67
|
+
const { shared, durable, migrations, serverOnly } = options;
|
|
68
|
+
if (migrations !== void 0 && migrations.current !== app.Message) throw new Error("Sync.make: the Message history must end at the application's own Message");
|
|
68
69
|
if (durable.owner !== app.owner) throw new Error("Sync.make: the durable subset belongs to a different application");
|
|
70
|
+
if (serverOnly !== void 0 && serverOnly.owner !== app.owner) throw new Error("Sync.make: the server-only subset belongs to a different application");
|
|
69
71
|
const replay = options.replay === void 0 ? derivedReplay(app, shared) : (value, message) => options.replay(value, message);
|
|
70
|
-
const
|
|
72
|
+
const tagsOf = (constructors) => new Set(constructors.map(messageTag).filter((tag) => tag !== void 0));
|
|
73
|
+
const durableTags = tagsOf(durable.constructors);
|
|
74
|
+
const serverTags = tagsOf(serverOnly?.constructors ?? []);
|
|
75
|
+
for (const tag of serverTags) if (durableTags.has(tag)) throw new Error(`Sync.make: "${tag}" is both durable and server-only`);
|
|
71
76
|
const sharedCodec = shared.schema;
|
|
72
77
|
const stamps = options.stamp;
|
|
73
78
|
const sync = defineSync({
|
|
74
79
|
documentId: options.documentId,
|
|
75
|
-
message: app.Message,
|
|
80
|
+
...migrations === void 0 ? { message: app.Message } : { migrations },
|
|
76
81
|
shared: sharedCodec,
|
|
77
82
|
empty: shared.get(app.initial),
|
|
78
83
|
durable: (message) => Option.exists(tagOf(message), (tag) => durableTags.has(tag)),
|
|
84
|
+
serverOnly: (message) => Option.exists(tagOf(message), (tag) => serverTags.has(tag)),
|
|
79
85
|
replay,
|
|
80
86
|
coalesce: options.coalesce,
|
|
81
87
|
...stamps === void 0 ? {} : { stamp: (message, commit) => Option.match(Option.flatMapNullishOr(tagOf(message), (tag) => stamps[tag]), {
|
|
@@ -117,7 +123,7 @@ const build = (app) => {
|
|
|
117
123
|
owner: app.owner,
|
|
118
124
|
owns: shared.dependencies,
|
|
119
125
|
observes: shared.dependencies,
|
|
120
|
-
messages: [...durable.tags],
|
|
126
|
+
messages: [...durable.tags, ...serverTags],
|
|
121
127
|
metadata: []
|
|
122
128
|
};
|
|
123
129
|
return {
|
|
@@ -127,6 +133,7 @@ const build = (app) => {
|
|
|
127
133
|
projection: shared,
|
|
128
134
|
replay,
|
|
129
135
|
messages: durable.constructors,
|
|
136
|
+
serverOnlyMessages: serverOnly?.constructors ?? [],
|
|
130
137
|
contract,
|
|
131
138
|
wiring: () => ({
|
|
132
139
|
key: `sync:${contract.name}`,
|
package/dist/make.js.map
CHANGED
|
@@ -1 +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,aAA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,OAAO,IAAI;GACX,MAAM,OAAO;GACb,UAAU,OAAO;GACjB,UAAU,CAAC,GAAG,QAAQ,IAAI;GAC1B,UAAU,CAAC;EACb;EACA,OAAO;GACL,GAAG;GACH;GACA;GACA,YAAY;GACZ;GACA,UAAU,QAAQ;GAClB;GACA,eAAe;IAAE,KAAK,QAAQ,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"}
|
|
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 type { Migrations } from './migrations.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\ntype AppMessageEncoded<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n> = AppScope<AppModel, F, Cases>['Message']['Encoded']\n\n/** `make`'s Message history, typed by the application's own Message. */\nexport interface HistoryOption<Message, Encoded> {\n /**\n * The Schemas the document's durable Messages were stored in, ending at the\n * application's own `Message` (`Sync.migrations(V1).next(App.Message, up)`):\n * operations written at an older version are upcast wherever they are read.\n * Without it, the Message is version 1.\n */\n readonly migrations?: Migrations<Message, Encoded> | undefined\n}\n\n/**\n * The Messages of the server-only constructors: none for `[]`, which\n * `MsgOf` reads as `unknown` (`never` matches its `infer`).\n */\nexport type ServerMsgOf<SMs extends readonly unknown[]> = [SMs[number]] extends [never]\n ? never\n : MsgOf<SMs>\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 SMs 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 and server-only Messages reach\n * it, and it runs during admission, replay, and optimistic projection. It is\n * not guarded: the author owns its agreement with `update`.\n */\n readonly replay?: (\n shared: Schema.Struct.Type<NoInfer<Fields>>,\n message: MsgOf<NoInfer<Ms>> | ServerMsgOf<NoInfer<SMs>>,\n ) => Schema.Struct.Type<NoInfer<Fields>>\n /**\n * Authorization the server journal applies before committing, keyed by\n * durable or server-only tag; see `AuthorizePolicy`.\n */\n readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<[...Ms, ...SMs]>>\n /** What the server's commit writes into a stored Message; see `StampPolicy`. */\n readonly stamp?: StampPolicy<NoInfer<[...Ms, ...SMs]>>\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 ServerSubset = never,\n SMs extends readonly MessageConstructor<any>[] = [],\n> extends BaseOptions<Principal, Fields, Ms, SMs> {\n /** The writable projection of the shared fields. */\n readonly shared: WritableProjection<AppModel, Fields>\n /** The Message subset a replica submits, records and replays. */\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n /**\n * The Messages only the server appends (`foldkit-sync/journal`'s\n * `serverJournal`): stored and replayed like durable ones, refused from a\n * replica. A Message in both sets is a type error, and a throw here.\n */\n readonly serverOnly?: MessageSet<AppModel, any, ServerSubset, SMs> | undefined\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 /** The server-only constructors, `[]` when `make` was given none. */\n SMs extends readonly unknown[] = [],\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 /** The durable constructors: what a replica submits. */\n readonly messages: Ms\n /** The server-only constructors: what only the server appends. */\n readonly serverOnlyMessages: SMs\n /** For `Module`: this contract owns the shared projection's paths and records the durable and server-only 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 ServerSubset = never,\n // A server-only constructor makes a Message no durable one does, so a\n // variant in both sets fails here, at `serverOnly`.\n SMs extends readonly MessageConstructor<\n Exclude<AppMessage<AppModel, F, Cases>, MsgOf<Ms>>\n >[] = [],\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal, ServerSubset, SMs> &\n HistoryOption<AppMessage<AppModel, F, Cases>, AppMessageEncoded<AppModel, F, Cases>> & {\n readonly authorize: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<[...Ms, ...SMs]>>\n },\n ): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, true, SMs>\n <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n ServerSubset = never,\n SMs extends readonly MessageConstructor<\n Exclude<AppMessage<AppModel, F, Cases>, MsgOf<Ms>>\n >[] = [],\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal, ServerSubset, SMs> &\n HistoryOption<AppMessage<AppModel, F, Cases>, AppMessageEncoded<AppModel, F, Cases>>,\n ): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, false, SMs>\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, any, any> &\n HistoryOption<Message, unknown>,\n ): DefinedSync<AppModel, any, Message, any, Principal, boolean, any> => {\n type Shared = Record<string, unknown>\n const { shared, durable, migrations, serverOnly } = options\n // A Schema of an older version can equal the current one structurally, so\n // the types cannot tell a history that stops short; identity can.\n if (migrations !== undefined && (migrations.current as unknown) !== app.Message)\n throw new Error(\"Sync.make: the Message history must end at the application's own Message\")\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 if (serverOnly !== undefined && serverOnly.owner !== app.owner)\n throw new Error('Sync.make: the server-only 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 tagsOf = (constructors: readonly unknown[]): ReadonlySet<string> =>\n new Set(constructors.map(messageTag).filter((tag): tag is string => tag !== undefined))\n const durableTags = tagsOf(durable.constructors)\n const serverTags = tagsOf(serverOnly?.constructors ?? [])\n // The types refuse this too; a set built by `MessageSet.union` at run time may not be typed.\n for (const tag of serverTags)\n if (durableTags.has(tag))\n throw new Error(`Sync.make: \"${tag}\" is both durable and server-only`)\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 ...(migrations === undefined\n ? { message: app.Message as unknown as Schema.Codec<Message, unknown> }\n : { migrations }),\n shared: sharedCodec,\n empty: shared.get(app.initial),\n durable: message => Option.exists(tagOf(message), tag => durableTags.has(tag)),\n serverOnly: message => Option.exists(tagOf(message), tag => serverTags.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, ...serverTags],\n metadata: [],\n }\n return {\n ...sync,\n journalContract,\n surface,\n projection: shared,\n replay,\n messages: durable.constructors,\n serverOnlyMessages: serverOnly?.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}\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AAM;GACN,MAAM,QAAQ;GACd,OAAO,IAAI;GACX,MAAM,OAAO;GACb,UAAU,OAAO;GACjB,UAAU,CAAC,GAAG,QAAQ,MAAM,GAAG,UAAU;GACzC,UAAU,CAAC;EACb;EACA,OAAO;GACL,GAAG;GACH;GACA;GACA,YAAY;GACZ;GACA,UAAU,QAAQ;GAClB,oBAAoB,YAAY,gBAAgB,CAAC;GACjD;GACA,eAAe;IAAE,KAAK,QAAQ,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,37 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
/**
|
|
3
|
+
* The Message history a document's operations may be stored in. Version 1 is
|
|
4
|
+
* the first Schema; each `next` adds one. Steps are written once and never
|
|
5
|
+
* changed: a later change adds a step after them. Made by `Sync.migrations`.
|
|
6
|
+
*/
|
|
7
|
+
export interface Migrations<Type, Encoded> {
|
|
8
|
+
/** The current version: 1 for the first Schema, one more for each `next`. */
|
|
9
|
+
readonly version: number;
|
|
10
|
+
/** The current Schema: the document's Message. */
|
|
11
|
+
readonly current: Schema.Codec<Type, Encoded, never, never>;
|
|
12
|
+
/**
|
|
13
|
+
* The next version: its Schema, and how a Message of the version before,
|
|
14
|
+
* encoded, becomes one of this version, encoded. `up` must be pure and
|
|
15
|
+
* deterministic: the server reads an entry more than once (its `admit`, then
|
|
16
|
+
* the journal), so a clock or a random id in it would let `admit` judge one
|
|
17
|
+
* Message and the journal commit another.
|
|
18
|
+
*/
|
|
19
|
+
readonly next: <T, E>(schema: Schema.Codec<T, E, never, never>, up: (previous: Encoded) => NoInfer<E>) => Migrations<T, E>;
|
|
20
|
+
}
|
|
21
|
+
/** What Sync reads a history with. Kept off the public interface: a step is not an API. */
|
|
22
|
+
export interface History {
|
|
23
|
+
readonly version: number;
|
|
24
|
+
/** An encoded Message of `version` (from 1 to `version - 1`), upcast to the current version, encoded and unchecked. Throws when a step refuses it. */
|
|
25
|
+
readonly upcast: (version: number, encoded: unknown) => unknown;
|
|
26
|
+
/** An encoded Message of `version`, checked and encoded again by that version's own Schema. Throws when it refuses it. */
|
|
27
|
+
readonly normalize: (version: number, encoded: unknown) => unknown;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Starts a document's Message history at its first Schema:
|
|
31
|
+
* `Sync.migrations(V1).next(V2, up)`. Pass it to `Sync.define` in place of
|
|
32
|
+
* `message`, or to `Sync.forApplication(App).make` as `migrations`.
|
|
33
|
+
*/
|
|
34
|
+
export declare const migrations: <T, E>(first: Schema.Codec<T, E, never, never>) => Migrations<T, E>;
|
|
35
|
+
/** The history behind a `Migrations`; one made by hand has none, and is refused. */
|
|
36
|
+
export declare const historyOf: (value: Migrations<unknown, unknown>) => History;
|
|
37
|
+
//# sourceMappingURL=migrations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrations.d.ts","names":[],"sources":["../src/migrations.ts"],"mappings":";;;;;;iBAaiB,WAAW,MAAM;;WAEvB;;WAEA,SAAS,OAAO,MAAM,MAAM;;;;;;;;WAQ5B,OAAO,GAAG,GACjB,QAAQ,OAAO,MAAM,GAAG,kBACxB,KAAK,UAAU,YAAY,QAAQ,OAChC,WAAW,GAAG;;;iBAWJ;WACN;;WAEA,SAAS,iBAAiB;;WAE1B,YAAY,iBAAiB;;;;;;;qBAoD3B,aAAc,GAAG,GAAC,OAAS,OAAO,MAAM,GAAG,qBAAmB,WAAW,GAAG;;qBAM5E,YAAS,OAAW,iCAA+B"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
// src/migrations.ts
|
|
3
|
+
/**
|
|
4
|
+
* A document's Message history: the Schemas its durable Messages have been
|
|
5
|
+
* stored in, oldest first, and how each becomes the next. An operation keeps
|
|
6
|
+
* the version it was written at, in its outbox and on the wire; every reader
|
|
7
|
+
* of its meaning sees it upcast to the current version.
|
|
8
|
+
*/
|
|
9
|
+
const histories = /* @__PURE__ */ new WeakMap();
|
|
10
|
+
const stepOf = (schema) => {
|
|
11
|
+
const decode = Schema.decodeUnknownSync(schema, { onExcessProperty: "error" });
|
|
12
|
+
const encode = Schema.encodeSync(schema);
|
|
13
|
+
return (encoded) => encode(decode(encoded));
|
|
14
|
+
};
|
|
15
|
+
const chain = (schemas, steps) => {
|
|
16
|
+
const history = {
|
|
17
|
+
version: steps.length,
|
|
18
|
+
upcast: (version, encoded) => {
|
|
19
|
+
let value = encoded;
|
|
20
|
+
for (let at = version; at < steps.length; at++) value = steps[at].up(steps[at - 1].normalize(value));
|
|
21
|
+
return value;
|
|
22
|
+
},
|
|
23
|
+
normalize: (version, encoded) => steps[version - 1].normalize(encoded)
|
|
24
|
+
};
|
|
25
|
+
const migrations = {
|
|
26
|
+
version: steps.length,
|
|
27
|
+
current: schemas[schemas.length - 1],
|
|
28
|
+
next: (schema, up) => chain([...schemas, schema], [...steps, {
|
|
29
|
+
normalize: stepOf(schema),
|
|
30
|
+
up
|
|
31
|
+
}])
|
|
32
|
+
};
|
|
33
|
+
histories.set(migrations, history);
|
|
34
|
+
return migrations;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Starts a document's Message history at its first Schema:
|
|
38
|
+
* `Sync.migrations(V1).next(V2, up)`. Pass it to `Sync.define` in place of
|
|
39
|
+
* `message`, or to `Sync.forApplication(App).make` as `migrations`.
|
|
40
|
+
*/
|
|
41
|
+
const migrations = (first) => {
|
|
42
|
+
const schema = first;
|
|
43
|
+
return chain([schema], [{
|
|
44
|
+
normalize: stepOf(schema),
|
|
45
|
+
up: void 0
|
|
46
|
+
}]);
|
|
47
|
+
};
|
|
48
|
+
/** The history behind a `Migrations`; one made by hand has none, and is refused. */
|
|
49
|
+
const historyOf = (value) => {
|
|
50
|
+
const history = histories.get(value);
|
|
51
|
+
if (history === void 0) throw new Error("Sync: a Message history comes from Sync.migrations");
|
|
52
|
+
return history;
|
|
53
|
+
};
|
|
54
|
+
export { historyOf, migrations };
|
|
55
|
+
|
|
56
|
+
//# sourceMappingURL=migrations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrations.js","names":[],"sources":["../src/migrations.ts"],"sourcesContent":["/**\n * A document's Message history: the Schemas its durable Messages have been\n * stored in, oldest first, and how each becomes the next. An operation keeps\n * the version it was written at, in its outbox and on the wire; every reader\n * of its meaning sees it upcast to the current version.\n */\nimport { Schema } from 'effect'\n\n/**\n * The Message history a document's operations may be stored in. Version 1 is\n * the first Schema; each `next` adds one. Steps are written once and never\n * changed: a later change adds a step after them. Made by `Sync.migrations`.\n */\nexport interface Migrations<Type, Encoded> {\n /** The current version: 1 for the first Schema, one more for each `next`. */\n readonly version: number\n /** The current Schema: the document's Message. */\n readonly current: Schema.Codec<Type, Encoded, never, never>\n /**\n * The next version: its Schema, and how a Message of the version before,\n * encoded, becomes one of this version, encoded. `up` must be pure and\n * deterministic: the server reads an entry more than once (its `admit`, then\n * the journal), so a clock or a random id in it would let `admit` judge one\n * Message and the journal commit another.\n */\n readonly next: <T, E>(\n schema: Schema.Codec<T, E, never, never>,\n up: (previous: Encoded) => NoInfer<E>,\n ) => Migrations<T, E>\n}\n\ninterface Step {\n /** Checks an encoded Message of this version strictly, and returns it normalized. */\n readonly normalize: (encoded: unknown) => unknown\n /** From the version before, encoded, to this one, encoded. Absent for version 1. */\n readonly up: ((previous: unknown) => unknown) | undefined\n}\n\n/** What Sync reads a history with. Kept off the public interface: a step is not an API. */\nexport interface History {\n readonly version: number\n /** An encoded Message of `version` (from 1 to `version - 1`), upcast to the current version, encoded and unchecked. Throws when a step refuses it. */\n readonly upcast: (version: number, encoded: unknown) => unknown\n /** An encoded Message of `version`, checked and encoded again by that version's own Schema. Throws when it refuses it. */\n readonly normalize: (version: number, encoded: unknown) => unknown\n}\n\nconst histories = new WeakMap<object, History>()\n\nconst stepOf = (schema: Schema.Codec<unknown, unknown, never, never>): Step['normalize'] => {\n const decode = Schema.decodeUnknownSync(schema, { onExcessProperty: 'error' })\n const encode = Schema.encodeSync(schema)\n return encoded => encode(decode(encoded))\n}\n\nconst chain = <Type, Encoded>(\n schemas: ReadonlyArray<Schema.Codec<unknown, unknown, never, never>>,\n steps: ReadonlyArray<Step>,\n): Migrations<Type, Encoded> => {\n const history: History = {\n version: steps.length,\n upcast: (version, encoded) => {\n let value = encoded\n // Each step is given its version's value checked and normalized, the\n // form the payload is compared by, so what is hashed and what is read\n // cannot differ under one operation id.\n for (let at = version; at < steps.length; at++)\n value = steps[at]!.up!(steps[at - 1]!.normalize(value))\n return value\n },\n normalize: (version, encoded) => steps[version - 1]!.normalize(encoded),\n }\n const migrations: Migrations<Type, Encoded> = {\n version: steps.length,\n current: schemas[schemas.length - 1] as Schema.Codec<Type, Encoded, never, never>,\n next: (schema, up) =>\n chain(\n [...schemas, schema as Schema.Codec<unknown, unknown, never, never>],\n [\n ...steps,\n {\n normalize: stepOf(schema as Schema.Codec<unknown, unknown, never, never>),\n up: up as (previous: unknown) => unknown,\n },\n ],\n ),\n }\n histories.set(migrations, history)\n return migrations\n}\n\n/**\n * Starts a document's Message history at its first Schema:\n * `Sync.migrations(V1).next(V2, up)`. Pass it to `Sync.define` in place of\n * `message`, or to `Sync.forApplication(App).make` as `migrations`.\n */\nexport const migrations = <T, E>(first: Schema.Codec<T, E, never, never>): Migrations<T, E> => {\n const schema = first as Schema.Codec<unknown, unknown, never, never>\n return chain([schema], [{ normalize: stepOf(schema), up: undefined }])\n}\n\n/** The history behind a `Migrations`; one made by hand has none, and is refused. */\nexport const historyOf = (value: Migrations<unknown, unknown>): History => {\n const history = histories.get(value)\n if (history === undefined) throw new Error('Sync: a Message history comes from Sync.migrations')\n return history\n}\n"],"mappings":";;;;;;;;AA+CA,MAAM,4BAAY,IAAI,QAAyB;AAE/C,MAAM,UAAU,WAA4E;CAC1F,MAAM,SAAS,OAAO,kBAAkB,QAAQ,EAAE,kBAAkB,QAAQ,CAAC;CAC7E,MAAM,SAAS,OAAO,WAAW,MAAM;CACvC,QAAO,YAAW,OAAO,OAAO,OAAO,CAAC;AAC1C;AAEA,MAAM,SACJ,SACA,UAC8B;CAC9B,MAAM,UAAmB;EACvB,SAAS,MAAM;EACf,SAAS,SAAS,YAAY;GAC5B,IAAI,QAAQ;GAIZ,KAAK,IAAI,KAAK,SAAS,KAAK,MAAM,QAAQ,MACxC,QAAQ,MAAM,GAAG,CAAE,GAAI,MAAM,KAAK,EAAE,CAAE,UAAU,KAAK,CAAC;GACxD,OAAO;EACT;EACA,YAAY,SAAS,YAAY,MAAM,UAAU,EAAE,CAAE,UAAU,OAAO;CACxE;CACA,MAAM,aAAwC;EAC5C,SAAS,MAAM;EACf,SAAS,QAAQ,QAAQ,SAAS;EAClC,OAAO,QAAQ,OACb,MACE,CAAC,GAAG,SAAS,MAAsD,GACnE,CACE,GAAG,OACH;GACE,WAAW,OAAO,MAAsD;GACpE;EACN,CACF,CACF;CACJ;CACA,UAAU,IAAI,YAAY,OAAO;CACjC,OAAO;AACT;;;;;;AAOA,MAAa,cAAoB,UAA8D;CAC7F,MAAM,SAAS;CACf,OAAO,MAAM,CAAC,MAAM,GAAG,CAAC;EAAE,WAAW,OAAO,MAAM;EAAG,IAAI,KAAA;CAAU,CAAC,CAAC;AACvE;;AAGA,MAAa,aAAa,UAAiD;CACzE,MAAM,UAAU,UAAU,IAAI,KAAK;CACnC,IAAI,YAAY,KAAA,GAAW,MAAM,IAAI,MAAM,oDAAoD;CAC/F,OAAO;AACT"}
|
package/dist/mount.d.ts
CHANGED
|
@@ -133,6 +133,6 @@ export interface LocalEdit<Message> {
|
|
|
133
133
|
export declare const unconfirmedEdits: <Message>(edits: ReadonlyArray<LocalEdit<Message>>, next: number) => ReadonlyArray<Message>;
|
|
134
134
|
/** The application's Message union, as `Surface.application` types it. */
|
|
135
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>>;
|
|
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, Authorized extends boolean = false, SMs extends readonly unknown[] = []>(app: RunnableApplication<Model, F, Cases, Resources>, sync: DefinedSync<Model, Fields, MessageOf<RunnableApplication<Model, F, Cases, Resources>>, Ms, Principal, Authorized, SMs>, 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
137
|
export {};
|
|
138
138
|
//# sourceMappingURL=mount.d.ts.map
|
package/dist/mount.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mount.d.ts","names":[],"sources":["../src/mount.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;qBAqEa,OAAQ,SAAO,SACjB;WACG;WAAuB,QAAQ,OAAO,OAAO;;;;;;;;;;iBAqB1C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,OAAO,aAC/C,OAAO,OAAO,KAAK"}
|
package/dist/mount.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Effect, Exit, Option, Schema, Stream } from "effect";
|
|
1
|
+
import { Effect, Exit, Option, Result, Schema, Stream } from "effect";
|
|
2
2
|
import { absurd } from "effect/Function";
|
|
3
3
|
import * as Navigation from "foldkit/navigation";
|
|
4
4
|
import * as Port from "foldkit/port";
|
|
@@ -149,7 +149,10 @@ const mount = (app, sync, options) => {
|
|
|
149
149
|
model,
|
|
150
150
|
commands: [{
|
|
151
151
|
name: "foldkit-sync/navigate",
|
|
152
|
-
effect:
|
|
152
|
+
effect: Navigation.UrlRequest.match(request, {
|
|
153
|
+
Internal: ({ url }) => Navigation.pushUrl(Url.toString(url)),
|
|
154
|
+
External: ({ href }) => Navigation.load(href)
|
|
155
|
+
}).pipe(Effect.as({ _tag: NAVIGATED }))
|
|
153
156
|
}]
|
|
154
157
|
};
|
|
155
158
|
}
|
|
@@ -203,10 +206,13 @@ const mount = (app, sync, options) => {
|
|
|
203
206
|
yield* Effect.promise(() => previous);
|
|
204
207
|
edit.started = (yield* replica.snapshot).nextLocalSequence;
|
|
205
208
|
const outcome = yield* Effect.result(replica.submit(edit.message));
|
|
206
|
-
return outcome
|
|
207
|
-
_tag:
|
|
208
|
-
|
|
209
|
-
|
|
209
|
+
return Result.match(outcome, {
|
|
210
|
+
onSuccess: () => ({ _tag: PERSISTED }),
|
|
211
|
+
onFailure: (error) => ({
|
|
212
|
+
_tag: FAILED,
|
|
213
|
+
error
|
|
214
|
+
})
|
|
215
|
+
});
|
|
210
216
|
}).pipe(Effect.ensuring(Effect.sync(release)))
|
|
211
217
|
};
|
|
212
218
|
return {
|