@fatagnus/dink-convex 1.0.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 (49) hide show
  1. package/LICENSE +190 -0
  2. package/README.md +282 -0
  3. package/convex/convex.config.ts +23 -0
  4. package/convex/crons.ts +37 -0
  5. package/convex/http.ts +421 -0
  6. package/convex/index.ts +20 -0
  7. package/convex/install.ts +172 -0
  8. package/convex/outbox.ts +198 -0
  9. package/convex/outboxProcessor.ts +240 -0
  10. package/convex/schema.ts +97 -0
  11. package/convex/sync.ts +327 -0
  12. package/dist/component.d.ts +34 -0
  13. package/dist/component.d.ts.map +1 -0
  14. package/dist/component.js +35 -0
  15. package/dist/component.js.map +1 -0
  16. package/dist/crdt.d.ts +82 -0
  17. package/dist/crdt.d.ts.map +1 -0
  18. package/dist/crdt.js +134 -0
  19. package/dist/crdt.js.map +1 -0
  20. package/dist/factories.d.ts +80 -0
  21. package/dist/factories.d.ts.map +1 -0
  22. package/dist/factories.js +159 -0
  23. package/dist/factories.js.map +1 -0
  24. package/dist/http.d.ts +238 -0
  25. package/dist/http.d.ts.map +1 -0
  26. package/dist/http.js +222 -0
  27. package/dist/http.js.map +1 -0
  28. package/dist/httpFactory.d.ts +39 -0
  29. package/dist/httpFactory.d.ts.map +1 -0
  30. package/dist/httpFactory.js +128 -0
  31. package/dist/httpFactory.js.map +1 -0
  32. package/dist/index.d.ts +68 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +73 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/schema.d.ts +217 -0
  37. package/dist/schema.d.ts.map +1 -0
  38. package/dist/schema.js +195 -0
  39. package/dist/schema.js.map +1 -0
  40. package/dist/syncFactories.d.ts +240 -0
  41. package/dist/syncFactories.d.ts.map +1 -0
  42. package/dist/syncFactories.js +623 -0
  43. package/dist/syncFactories.js.map +1 -0
  44. package/dist/triggers.d.ts +442 -0
  45. package/dist/triggers.d.ts.map +1 -0
  46. package/dist/triggers.js +705 -0
  47. package/dist/triggers.js.map +1 -0
  48. package/package.json +108 -0
  49. package/scripts/check-peer-deps.cjs +132 -0
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Factory functions for simplified @fatagnus/dink-convex setup.
3
+ *
4
+ * These factories reduce boilerplate by providing pre-configured
5
+ * implementations that users can use with minimal code.
6
+ *
7
+ * @module factories
8
+ */
9
+ import { customMutation } from "convex-helpers/server/customFunctions";
10
+ /**
11
+ * Create a sync-enabled mutation wrapper.
12
+ *
13
+ * This factory creates a custom mutation that automatically:
14
+ * - Generates CRDT deltas on insert/update/delete
15
+ * - Stores deltas in sync_deltas and sync_outbox tables
16
+ * - Schedules immediate outbox processing for real-time sync
17
+ *
18
+ * @param mutation - The mutation function from _generated/server
19
+ * @param syncedTables - Array of table names that should be synced
20
+ * @param options - Optional configuration
21
+ * @returns A custom mutation wrapper with sync triggers
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * // convex/syncSetup.ts
26
+ * import { createSyncMutation } from "@fatagnus/dink-convex";
27
+ * import { mutation } from "./_generated/server";
28
+ * import { internal } from "./_generated/api";
29
+ *
30
+ * export const syncMutation = createSyncMutation(mutation, ["tasks"], {
31
+ * getInternal: () => internal,
32
+ * });
33
+ * ```
34
+ */
35
+ export declare function createSyncMutation<MutationType extends (...args: any[]) => any>(mutation: MutationType, syncedTables: string[], options: {
36
+ /** Function that returns the internal API for scheduling */
37
+ getInternal: () => {
38
+ outboxProcessor: {
39
+ processOutboxBatch: unknown;
40
+ };
41
+ };
42
+ }): ReturnType<typeof customMutation>;
43
+ /**
44
+ * Configuration for createSyncCrons.
45
+ */
46
+ export interface SyncCronsConfig {
47
+ /** Cron interval in minutes (default: 1) */
48
+ intervalMinutes?: number;
49
+ }
50
+ /**
51
+ * Create sync cron jobs.
52
+ *
53
+ * This factory creates the cron job definition for outbox processing.
54
+ * Returns the crons object that should be exported as default.
55
+ *
56
+ * @param cronJobs - The cronJobs function from convex/server
57
+ * @param internal - The internal API from _generated/api
58
+ * @param config - Optional configuration
59
+ * @returns Cron jobs definition to export as default
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * // convex/crons.ts
64
+ * import { createSyncCrons } from "@fatagnus/dink-convex";
65
+ * import { cronJobs } from "convex/server";
66
+ * import { internal } from "./_generated/api";
67
+ *
68
+ * export default createSyncCrons(cronJobs, internal);
69
+ * ```
70
+ */
71
+ export declare function createSyncCrons(cronJobs: () => {
72
+ interval: (name: string, interval: {
73
+ minutes: number;
74
+ }, fn: unknown) => void;
75
+ }, internal: {
76
+ outboxProcessor: {
77
+ processOutboxBatch: unknown;
78
+ };
79
+ }, config?: SyncCronsConfig): ReturnType<typeof cronJobs>;
80
+ //# sourceMappingURL=factories.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factories.d.ts","sourceRoot":"","sources":["../src/factories.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,cAAc,EAAa,MAAM,uCAAuC,CAAC;AAiBlF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,kBAAkB,CAEhC,YAAY,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EAE5C,QAAQ,EAAE,YAAY,EACtB,YAAY,EAAE,MAAM,EAAE,EACtB,OAAO,EAAE;IACP,4DAA4D;IAC5D,WAAW,EAAE,MAAM;QAAE,eAAe,EAAE;YAAE,kBAAkB,EAAE,OAAO,CAAA;SAAE,CAAA;KAAE,CAAC;CACzE,GACA,UAAU,CAAC,OAAO,cAAc,CAAC,CA4InC;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,4CAA4C;IAC5C,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,MAAM;IACd,QAAQ,EAAE,CACR,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,EAC7B,EAAE,EAAE,OAAO,KACR,IAAI,CAAC;CACX,EACD,QAAQ,EAAE;IAAE,eAAe,EAAE;QAAE,kBAAkB,EAAE,OAAO,CAAA;KAAE,CAAA;CAAE,EAC9D,MAAM,CAAC,EAAE,eAAe,GACvB,UAAU,CAAC,OAAO,QAAQ,CAAC,CAW7B"}
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Factory functions for simplified @fatagnus/dink-convex setup.
3
+ *
4
+ * These factories reduce boilerplate by providing pre-configured
5
+ * implementations that users can use with minimal code.
6
+ *
7
+ * @module factories
8
+ */
9
+ import { Triggers } from "convex-helpers/server/triggers";
10
+ import { customMutation, customCtx } from "convex-helpers/server/customFunctions";
11
+ import { generateInsertDelta, generateUpdateDelta, generateDeleteDelta, } from "./crdt.js";
12
+ /**
13
+ * Create a sync-enabled mutation wrapper.
14
+ *
15
+ * This factory creates a custom mutation that automatically:
16
+ * - Generates CRDT deltas on insert/update/delete
17
+ * - Stores deltas in sync_deltas and sync_outbox tables
18
+ * - Schedules immediate outbox processing for real-time sync
19
+ *
20
+ * @param mutation - The mutation function from _generated/server
21
+ * @param syncedTables - Array of table names that should be synced
22
+ * @param options - Optional configuration
23
+ * @returns A custom mutation wrapper with sync triggers
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * // convex/syncSetup.ts
28
+ * import { createSyncMutation } from "@fatagnus/dink-convex";
29
+ * import { mutation } from "./_generated/server";
30
+ * import { internal } from "./_generated/api";
31
+ *
32
+ * export const syncMutation = createSyncMutation(mutation, ["tasks"], {
33
+ * getInternal: () => internal,
34
+ * });
35
+ * ```
36
+ */
37
+ export function createSyncMutation(mutation, syncedTables, options) {
38
+ const triggers = new Triggers();
39
+ const syncedTableSet = new Set(syncedTables);
40
+ /**
41
+ * Get the next sequence number using innerDb (bypasses triggers).
42
+ */
43
+ async function getNextSeqFromInnerDb(innerDb) {
44
+ const latest = await innerDb.query("sync_deltas").order("desc").first();
45
+ return (latest?.seq ?? 0) + 1;
46
+ }
47
+ // Create sync trigger handler that uses innerDb for writes
48
+ const syncTriggerHandler = async (ctx, change, tableName) => {
49
+ if (!syncedTableSet.has(tableName))
50
+ return;
51
+ // Use innerDb to get seq and write to sync tables (bypasses triggers to avoid recursion)
52
+ const seq = await getNextSeqFromInnerDb(ctx.innerDb);
53
+ let delta;
54
+ let docId;
55
+ switch (change.operation) {
56
+ case "insert":
57
+ if (!change.newDoc || !change.newDoc.syncId) {
58
+ console.log(`[createSyncMutation] Skipping insert - no newDoc or syncId for ${tableName}`);
59
+ return;
60
+ }
61
+ delta = generateInsertDelta(tableName, change.newDoc.syncId, change.newDoc);
62
+ docId = change.newDoc.syncId;
63
+ console.log(`[createSyncMutation] Generated insert delta for ${tableName}/${docId}, seq=${seq}`);
64
+ break;
65
+ case "update":
66
+ if (!change.oldDoc || !change.newDoc || !change.newDoc.syncId) {
67
+ console.log(`[createSyncMutation] Skipping update - missing docs or syncId for ${tableName}`);
68
+ return;
69
+ }
70
+ delta = generateUpdateDelta(tableName, change.newDoc.syncId, change.oldDoc, change.newDoc);
71
+ docId = change.newDoc.syncId;
72
+ console.log(`[createSyncMutation] Generated update delta for ${tableName}/${docId}, seq=${seq}`);
73
+ break;
74
+ case "delete":
75
+ if (!change.oldDoc || !change.oldDoc.syncId) {
76
+ console.log(`[createSyncMutation] Skipping delete - no oldDoc or syncId for ${tableName}`);
77
+ return;
78
+ }
79
+ delta = generateDeleteDelta(tableName, change.oldDoc.syncId);
80
+ docId = change.oldDoc.syncId;
81
+ console.log(`[createSyncMutation] Generated delete delta for ${tableName}/${docId}, seq=${seq}`);
82
+ break;
83
+ default:
84
+ return;
85
+ }
86
+ // Convert Uint8Array to ArrayBuffer for Convex storage
87
+ const deltaArrayBuffer = delta.buffer.slice(delta.byteOffset, delta.byteOffset + delta.byteLength);
88
+ // Store in sync_deltas and sync_outbox using innerDb (bypasses triggers)
89
+ await ctx.innerDb.insert("sync_deltas", {
90
+ collection: tableName,
91
+ docId,
92
+ bytes: deltaArrayBuffer,
93
+ seq,
94
+ timestamp: Date.now(),
95
+ });
96
+ await ctx.innerDb.insert("sync_outbox", {
97
+ collection: tableName,
98
+ docId,
99
+ delta: deltaArrayBuffer,
100
+ seq,
101
+ status: "pending",
102
+ retries: 0,
103
+ createdAt: Date.now(),
104
+ });
105
+ console.log(`[createSyncMutation] Stored delta and outbox entry for ${tableName}/${docId}`);
106
+ // Schedule immediate outbox processing if scheduler is available
107
+ if (ctx.scheduler) {
108
+ try {
109
+ const internal = options.getInternal();
110
+ await ctx.scheduler.runAfter(0, internal.outboxProcessor.processOutboxBatch, {});
111
+ console.log(`[createSyncMutation] Scheduled immediate outbox processing`);
112
+ }
113
+ catch (err) {
114
+ console.log(`[createSyncMutation] Could not schedule outbox processing: ${err}`);
115
+ }
116
+ }
117
+ };
118
+ // Register trigger for each synced table
119
+ for (const tableName of syncedTables) {
120
+ triggers.register(tableName, ((ctx, change) => syncTriggerHandler(ctx, change, tableName)));
121
+ }
122
+ // Return the custom mutation wrapper
123
+ return customMutation(mutation, customCtx((ctx) => {
124
+ // wrapDB wraps ctx.db with trigger-enabled version and adds innerDb to ctx
125
+ const wrappedCtx = triggers.wrapDB(ctx);
126
+ return {
127
+ ...ctx,
128
+ db: wrappedCtx.db,
129
+ };
130
+ }));
131
+ }
132
+ /**
133
+ * Create sync cron jobs.
134
+ *
135
+ * This factory creates the cron job definition for outbox processing.
136
+ * Returns the crons object that should be exported as default.
137
+ *
138
+ * @param cronJobs - The cronJobs function from convex/server
139
+ * @param internal - The internal API from _generated/api
140
+ * @param config - Optional configuration
141
+ * @returns Cron jobs definition to export as default
142
+ *
143
+ * @example
144
+ * ```typescript
145
+ * // convex/crons.ts
146
+ * import { createSyncCrons } from "@fatagnus/dink-convex";
147
+ * import { cronJobs } from "convex/server";
148
+ * import { internal } from "./_generated/api";
149
+ *
150
+ * export default createSyncCrons(cronJobs, internal);
151
+ * ```
152
+ */
153
+ export function createSyncCrons(cronJobs, internal, config) {
154
+ const crons = cronJobs();
155
+ const intervalMinutes = config?.intervalMinutes ?? 1;
156
+ crons.interval("processOutbox", { minutes: intervalMinutes }, internal.outboxProcessor.processOutboxBatch);
157
+ return crons;
158
+ }
159
+ //# sourceMappingURL=factories.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factories.js","sourceRoot":"","sources":["../src/factories.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,uCAAuC,CAAC;AAElF,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,WAAW,CAAC;AAWnB;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,kBAAkB,CAIhC,QAAsB,EACtB,YAAsB,EACtB,OAGC;IAED,MAAM,QAAQ,GAAG,IAAI,QAAQ,EAAoB,CAAC;IAClD,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,YAAY,CAAC,CAAC;IAc7C;;OAEG;IACH,KAAK,UAAU,qBAAqB,CAAC,OAA8B;QACjE,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,CAAC;QACxE,OAAO,CAAE,MAAM,EAAE,GAAc,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;IAC5C,CAAC;IAED,2DAA2D;IAC3D,MAAM,kBAAkB,GAAG,KAAK,EAC9B,GAAe,EACf,MAIC,EACD,SAAiB,EACF,EAAE;QACjB,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,SAAS,CAAC;YAAE,OAAO;QAE3C,yFAAyF;QACzF,MAAM,GAAG,GAAG,MAAM,qBAAqB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QACrD,IAAI,KAAiB,CAAC;QACtB,IAAI,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AC,GAAG,CAAC,4DAA4D,CAAC,CAAC;YAC5E,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,OAAO,CAAC,GAAG,CAAC,8DAA8D,GAAG,EAAE,CAAC,CAAC;YACnF,CAAC;QACH,CAAC;IACH,CAAC,CAAC;IAEF,yCAAyC;IACzC,KAAK,MAAM,SAAS,IAAI,YAAY,EAAE,CAAC;QACrC,QAAQ,CAAC,QAAQ,CACf,SAAkB,EAClB,CAAC,CAAC,GAAY,EAAE,MAAe,EAAE,EAAE,CACjC,kBAAkB,CAChB,GAAiB,EACjB,MAAkD,EAClD,SAAS,CACV,CAAU,CACd,CAAC;IACJ,CAAC;IAED,qCAAqC;IACrC,OAAO,cAAc,CACnB,QAAQ,EACR,SAAS,CAAC,CAAC,GAAG,EAAE,EAAE;QAChB,2EAA2E;QAC3E,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,GAA4C,CAAC,CAAC;QACjF,OAAO;YACL,GAAG,GAAG;YACN,EAAE,EAAG,UAA8B,CAAC,EAAE;SACvC,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;AACJ,CAAC;AAUD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,eAAe,CAC7B,QAMC,EACD,QAA8D,EAC9D,MAAwB;IAExB,MAAM,KAAK,GAAG,QAAQ,EAAE,CAAC;IACzB,MAAM,eAAe,GAAG,MAAM,EAAE,eAAe,IAAI,CAAC,CAAC;IAErD,KAAK,CAAC,QAAQ,CACZ,eAAe,EACf,EAAE,OAAO,EAAE,eAAe,EAAE,EAC5B,QAAQ,CAAC,eAAe,CAAC,kBAAkB,CAC5C,CAAC;IAEF,OAAO,KAAK,CAAC;AACf,CAAC"}
package/dist/http.d.ts ADDED
@@ -0,0 +1,238 @@
1
+ /**
2
+ * HTTP endpoint utilities for dinkd communication.
3
+ *
4
+ * Provides helpers for the /api/dink/applyDelta HTTP endpoint
5
+ * that receives CRDT deltas from edge devices.
6
+ *
7
+ * @module http
8
+ */
9
+ /**
10
+ * Payload for applying a delta from edge.
11
+ */
12
+ export interface ApplyDeltaPayload {
13
+ /** Collection/table name */
14
+ collection: string;
15
+ /** Document sync ID */
16
+ docId: string;
17
+ /** CRDT delta bytes as number array (JSON-serializable) */
18
+ bytes: number[];
19
+ /** Optional edge ID that originated this delta */
20
+ edgeId?: string;
21
+ }
22
+ /**
23
+ * Parsed delta payload with Uint8Array bytes.
24
+ */
25
+ export interface ParsedDeltaPayload {
26
+ collection: string;
27
+ docId: string;
28
+ bytes: Uint8Array;
29
+ /** Optional edge ID that originated this delta */
30
+ edgeId?: string;
31
+ }
32
+ /**
33
+ * Response from applyDelta endpoint.
34
+ */
35
+ export type ApplyDeltaResponse = {
36
+ success: true;
37
+ seq: number;
38
+ } | {
39
+ success: false;
40
+ error: string;
41
+ };
42
+ /**
43
+ * Parameters for getSnapshot endpoint.
44
+ */
45
+ export interface GetSnapshotParams {
46
+ /** Collection/table name */
47
+ collection: string;
48
+ /** Document sync ID */
49
+ docId: string;
50
+ }
51
+ /**
52
+ * Parsed getSnapshot parameters.
53
+ */
54
+ export interface ParsedGetSnapshotParams {
55
+ collection: string;
56
+ docId: string;
57
+ }
58
+ /**
59
+ * Response from getSnapshot endpoint.
60
+ */
61
+ export type GetSnapshotResponse = {
62
+ success: true;
63
+ bytes: number[];
64
+ seq: number;
65
+ } | {
66
+ success: false;
67
+ error: string;
68
+ status?: number;
69
+ };
70
+ /**
71
+ * Parameters for listDocuments endpoint.
72
+ */
73
+ export interface ListDocumentsParams {
74
+ /** Collection/table name */
75
+ collection: string;
76
+ /** Optional pagination cursor */
77
+ cursor?: string;
78
+ /** Optional limit for number of results (default: 100) */
79
+ limit?: number;
80
+ }
81
+ /**
82
+ * Parsed listDocuments parameters.
83
+ */
84
+ export interface ParsedListDocumentsParams {
85
+ collection: string;
86
+ cursor?: string;
87
+ limit?: number;
88
+ }
89
+ /**
90
+ * Response from listDocuments endpoint.
91
+ */
92
+ export type ListDocumentsResponse = {
93
+ success: true;
94
+ docIds: string[];
95
+ nextCursor?: string;
96
+ } | {
97
+ success: false;
98
+ error: string;
99
+ };
100
+ /**
101
+ * Result of parsing the delta payload.
102
+ */
103
+ export type ParsePayloadResult = {
104
+ success: true;
105
+ data: ParsedDeltaPayload;
106
+ } | {
107
+ success: false;
108
+ error: string;
109
+ };
110
+ /**
111
+ * Result of parsing the getSnapshot parameters.
112
+ */
113
+ export type ParseGetSnapshotResult = {
114
+ success: true;
115
+ data: ParsedGetSnapshotParams;
116
+ } | {
117
+ success: false;
118
+ error: string;
119
+ };
120
+ /**
121
+ * Result of parsing the listDocuments parameters.
122
+ */
123
+ export type ParseListDocumentsResult = {
124
+ success: true;
125
+ data: ParsedListDocumentsParams;
126
+ } | {
127
+ success: false;
128
+ error: string;
129
+ };
130
+ /**
131
+ * Result of encoding document as snapshot.
132
+ */
133
+ export type EncodeSnapshotResult = {
134
+ success: true;
135
+ bytes: Uint8Array;
136
+ } | {
137
+ success: false;
138
+ error: string;
139
+ };
140
+ /**
141
+ * Result of validating the auth header.
142
+ */
143
+ export type AuthValidationResult = {
144
+ valid: true;
145
+ } | {
146
+ valid: false;
147
+ error: string;
148
+ };
149
+ /**
150
+ * Result of applying delta to document.
151
+ */
152
+ export type ApplyDeltaResult = {
153
+ success: true;
154
+ mergedState: Uint8Array;
155
+ fromEdge: true;
156
+ } | {
157
+ success: false;
158
+ error: string;
159
+ };
160
+ /**
161
+ * Validate the Authorization header for applyDelta endpoint.
162
+ *
163
+ * Expects: Authorization: Bearer <appSyncKey>
164
+ *
165
+ * @param header - The Authorization header value
166
+ * @param expectedKey - The expected app sync key
167
+ * @returns Validation result
168
+ */
169
+ export declare function validateAuthHeader(header: string | null, expectedKey: string): AuthValidationResult;
170
+ /**
171
+ * Parse and validate the getSnapshot query parameters.
172
+ *
173
+ * @param params - The query parameters
174
+ * @returns Parsed parameters result
175
+ */
176
+ export declare function parseGetSnapshotParams(params: GetSnapshotParams): ParseGetSnapshotResult;
177
+ /**
178
+ * Parse and validate the listDocuments query parameters.
179
+ *
180
+ * @param params - The query parameters
181
+ * @returns Parsed parameters result
182
+ */
183
+ export declare function parseListDocumentsParams(params: ListDocumentsParams): ParseListDocumentsResult;
184
+ /**
185
+ * Parse and validate the applyDelta request payload.
186
+ *
187
+ * @param payload - The raw request payload
188
+ * @returns Parsed payload result
189
+ */
190
+ export declare function parseApplyDeltaPayload(payload: ApplyDeltaPayload): ParsePayloadResult;
191
+ /**
192
+ * Apply a CRDT delta to an existing document state.
193
+ *
194
+ * Merges the incoming delta with the existing state using Yjs CRDT semantics.
195
+ * This is the core merge function used by the HTTP endpoint.
196
+ *
197
+ * @param delta - The incoming CRDT delta (Yjs update)
198
+ * @param existingState - The existing document state, or null for new document
199
+ * @returns Merged state result with fromEdge flag for skipping outbox
200
+ */
201
+ export declare function applyDeltaToDocument(delta: Uint8Array, existingState: Uint8Array | null): ApplyDeltaResult;
202
+ /**
203
+ * Create a JSON response with proper headers.
204
+ *
205
+ * @param data - Response data to serialize
206
+ * @param status - HTTP status code
207
+ * @returns Response object
208
+ */
209
+ export declare function createJsonResponse(data: unknown, status: number): Response;
210
+ /**
211
+ * Create an error response with proper headers.
212
+ *
213
+ * @param error - Error message
214
+ * @param status - HTTP status code
215
+ * @returns Response object
216
+ */
217
+ export declare function createErrorResponse(error: string, status: number): Response;
218
+ /**
219
+ * Encode a document's data as a Yjs snapshot.
220
+ *
221
+ * Creates a Yjs document with all fields from the document data,
222
+ * compatible with the edge SDK's YjsDocument format.
223
+ *
224
+ * @param documentData - The document data to encode
225
+ * @returns Encoded snapshot result with Uint8Array bytes
226
+ *
227
+ * @example
228
+ * ```typescript
229
+ * const result = encodeDocumentAsSnapshot({
230
+ * _collection: "tasks",
231
+ * syncId: "sync-123",
232
+ * title: "My Task",
233
+ * completed: false,
234
+ * });
235
+ * ```
236
+ */
237
+ export declare function encodeDocumentAsSnapshot(documentData: Record<string, unknown>): EncodeSnapshotResult;
238
+ //# sourceMapping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