@livestore/cli 0.0.0-snapshot-d4638acc3fd24f98ac303e3e4fde7880f0577d91 → 0.0.0-snapshot-29b38715366635e2fffea5f896089d326087c0f2

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 (38) hide show
  1. package/dist/cli.d.ts +15 -1
  2. package/dist/cli.d.ts.map +1 -1
  3. package/dist/cli.js +2 -1
  4. package/dist/cli.js.map +1 -1
  5. package/dist/commands/import-export.d.ts +34 -0
  6. package/dist/commands/import-export.d.ts.map +1 -0
  7. package/dist/commands/import-export.js +123 -0
  8. package/dist/commands/import-export.js.map +1 -0
  9. package/dist/commands/mcp-tool-handlers.d.ts +5 -1
  10. package/dist/commands/mcp-tool-handlers.d.ts.map +1 -1
  11. package/dist/commands/mcp-tool-handlers.js +37 -4
  12. package/dist/commands/mcp-tool-handlers.js.map +1 -1
  13. package/dist/commands/mcp-tools-defs.d.ts +31 -1
  14. package/dist/commands/mcp-tools-defs.d.ts.map +1 -1
  15. package/dist/commands/mcp-tools-defs.js +87 -5
  16. package/dist/commands/mcp-tools-defs.js.map +1 -1
  17. package/dist/commands/new-project.d.ts +1 -1
  18. package/dist/mcp-runtime/runtime.d.ts +4 -3
  19. package/dist/mcp-runtime/runtime.d.ts.map +1 -1
  20. package/dist/mcp-runtime/runtime.js +19 -53
  21. package/dist/mcp-runtime/runtime.js.map +1 -1
  22. package/dist/module-loader.d.ts +22 -0
  23. package/dist/module-loader.d.ts.map +1 -0
  24. package/dist/module-loader.js +75 -0
  25. package/dist/module-loader.js.map +1 -0
  26. package/dist/sync-operations.d.ts +118 -0
  27. package/dist/sync-operations.d.ts.map +1 -0
  28. package/dist/sync-operations.js +164 -0
  29. package/dist/sync-operations.js.map +1 -0
  30. package/dist/tsconfig.tsbuildinfo +1 -1
  31. package/package.json +8 -8
  32. package/src/cli.ts +2 -1
  33. package/src/commands/import-export.ts +262 -0
  34. package/src/commands/mcp-tool-handlers.ts +44 -5
  35. package/src/commands/mcp-tools-defs.ts +92 -4
  36. package/src/mcp-runtime/runtime.ts +32 -65
  37. package/src/module-loader.ts +93 -0
  38. package/src/sync-operations.ts +326 -0
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Shared module loading utility for CLI and MCP.
3
+ * Loads and validates user config modules that export schema, syncBackend, and optional syncPayload.
4
+ */
5
+ import path from 'node:path'
6
+ import { pathToFileURL } from 'node:url'
7
+ import type { SyncBackend } from '@livestore/common'
8
+ import { UnknownError } from '@livestore/common'
9
+ import { isLiveStoreSchema, type LiveStoreSchema } from '@livestore/common/schema'
10
+ import { shouldNeverHappen } from '@livestore/utils'
11
+ import { Effect, FileSystem, Schema } from '@livestore/utils/effect'
12
+
13
+ export interface ModuleConfig {
14
+ schema: LiveStoreSchema
15
+ syncBackendConstructor: SyncBackend.SyncBackendConstructor
16
+ syncPayloadSchema: Schema.Schema<any>
17
+ syncPayload: unknown
18
+ }
19
+
20
+ /**
21
+ * Loads and validates a user config module.
22
+ * The module must export:
23
+ * - `schema`: A valid LiveStore schema
24
+ * - `syncBackend`: A sync backend constructor function
25
+ * - `syncPayloadSchema` (optional): Schema for validating syncPayload
26
+ * - `syncPayload` (optional): Payload data for the sync backend
27
+ */
28
+ export const loadModuleConfig = ({
29
+ configPath,
30
+ }: {
31
+ configPath: string
32
+ }): Effect.Effect<ModuleConfig, UnknownError, FileSystem.FileSystem> =>
33
+ Effect.gen(function* () {
34
+ const abs = path.isAbsolute(configPath) ? configPath : path.resolve(process.cwd(), configPath)
35
+
36
+ const fs = yield* FileSystem.FileSystem
37
+ const exists = yield* fs.exists(abs).pipe(UnknownError.mapToUnknownError)
38
+ if (!exists) {
39
+ return yield* UnknownError.make({
40
+ cause: `Store module not found at ${abs}`,
41
+ note: 'Make sure the path points to a valid LiveStore module',
42
+ })
43
+ }
44
+
45
+ const mod = yield* Effect.tryPromise({
46
+ try: () => import(pathToFileURL(abs).href),
47
+ catch: (cause) =>
48
+ UnknownError.make({
49
+ cause,
50
+ note: `Failed to import module at ${abs}`,
51
+ }),
52
+ })
53
+
54
+ const schema = (mod as any)?.schema
55
+ if (!isLiveStoreSchema(schema)) {
56
+ return yield* UnknownError.make({
57
+ cause: `Module at ${abs} must export a valid LiveStore 'schema'`,
58
+ note: `Ex: export { schema } from './src/livestore/schema.ts'`,
59
+ })
60
+ }
61
+
62
+ const syncBackendConstructor = (mod as any)?.syncBackend
63
+ if (typeof syncBackendConstructor !== 'function') {
64
+ return yield* UnknownError.make({
65
+ cause: `Module at ${abs} must export a 'syncBackend' constructor`,
66
+ note: `Ex: export const syncBackend = makeWsSync({ url })`,
67
+ })
68
+ }
69
+
70
+ const syncPayloadSchemaExport = (mod as any)?.syncPayloadSchema
71
+ const syncPayloadSchema =
72
+ syncPayloadSchemaExport === undefined
73
+ ? Schema.JsonValue
74
+ : Schema.isSchema(syncPayloadSchemaExport)
75
+ ? (syncPayloadSchemaExport as Schema.Schema<any>)
76
+ : shouldNeverHappen(
77
+ `Exported 'syncPayloadSchema' from ${abs} must be an Effect Schema (received ${typeof syncPayloadSchemaExport}).`,
78
+ )
79
+
80
+ const syncPayloadExport = (mod as any)?.syncPayload
81
+ const syncPayload = yield* (
82
+ syncPayloadExport === undefined
83
+ ? Effect.succeed<unknown>(undefined)
84
+ : Schema.decodeUnknown(syncPayloadSchema)(syncPayloadExport)
85
+ ).pipe(UnknownError.mapToUnknownError)
86
+
87
+ return {
88
+ schema,
89
+ syncBackendConstructor,
90
+ syncPayloadSchema,
91
+ syncPayload,
92
+ }
93
+ }).pipe(Effect.withSpan('module-loader:loadModuleConfig'))
@@ -0,0 +1,326 @@
1
+ /**
2
+ * Shared sync operations for CLI and MCP.
3
+ * Contains the core logic for exporting and importing events from sync backends.
4
+ */
5
+ import type { SyncBackend } from '@livestore/common'
6
+ import { UnknownError } from '@livestore/common'
7
+ import { LiveStoreEvent } from '@livestore/common/schema'
8
+ import {
9
+ Cause,
10
+ Chunk,
11
+ Effect,
12
+ type FileSystem,
13
+ type HttpClient,
14
+ KeyValueStore,
15
+ Option,
16
+ Schema,
17
+ type Scope,
18
+ Stream,
19
+ } from '@livestore/utils/effect'
20
+
21
+ import { loadModuleConfig } from './module-loader.ts'
22
+
23
+ /** Connection timeout for sync backend ping (5 seconds) */
24
+ const CONNECTION_TIMEOUT_MS = 5000
25
+
26
+ /**
27
+ * Schema for the export file format.
28
+ * Contains metadata about the export and an array of events in global encoded format.
29
+ */
30
+ export const ExportFileSchema = Schema.Struct({
31
+ /** Format version for future compatibility */
32
+ version: Schema.Literal(1),
33
+ /** Store identifier */
34
+ storeId: Schema.String,
35
+ /** ISO timestamp of when the export was created */
36
+ exportedAt: Schema.String,
37
+ /** Total number of events in the export */
38
+ eventCount: Schema.Number,
39
+ /** Array of events in global encoded format */
40
+ events: Schema.Array(LiveStoreEvent.Global.Encoded),
41
+ })
42
+
43
+ export type ExportFile = typeof ExportFileSchema.Type
44
+
45
+ export class ConnectionError extends Schema.TaggedError<ConnectionError>()('ConnectionError', {
46
+ cause: Schema.Defect,
47
+ note: Schema.String,
48
+ }) {}
49
+
50
+ export class ExportError extends Schema.TaggedError<ExportError>()('ExportError', {
51
+ cause: Schema.Defect,
52
+ note: Schema.String,
53
+ }) {}
54
+
55
+ export class ImportError extends Schema.TaggedError<ImportError>()('ImportError', {
56
+ cause: Schema.Defect,
57
+ note: Schema.String,
58
+ }) {}
59
+
60
+ /**
61
+ * Creates a sync backend connection from a user module and verifies connectivity.
62
+ * This is a simplified version of the MCP runtime that only creates the sync backend.
63
+ */
64
+ export const makeSyncBackend = ({
65
+ configPath,
66
+ storeId,
67
+ clientId,
68
+ }: {
69
+ /** Absolute or cwd-relative path to a module exporting `schema` and `syncBackend`. */
70
+ configPath: string
71
+ /** Identifier to scope the backend connection. */
72
+ storeId: string
73
+ /** Client identifier used when establishing the sync connection. */
74
+ clientId: string
75
+ }): Effect.Effect<
76
+ SyncBackend.SyncBackend,
77
+ UnknownError | ConnectionError,
78
+ FileSystem.FileSystem | HttpClient.HttpClient | Scope.Scope
79
+ > =>
80
+ Effect.gen(function* () {
81
+ const { syncBackendConstructor, syncPayload } = yield* loadModuleConfig({ configPath })
82
+
83
+ const syncBackend = yield* (syncBackendConstructor as SyncBackend.SyncBackendConstructor)({
84
+ storeId,
85
+ clientId,
86
+ /** syncPayload is validated against syncPayloadSchema by loadModuleConfig */
87
+ payload: syncPayload as Schema.JsonValue | undefined,
88
+ }).pipe(Effect.provide(KeyValueStore.layerMemory), UnknownError.mapToUnknownError)
89
+
90
+ /** Connect to the sync backend */
91
+ yield* syncBackend.connect.pipe(
92
+ Effect.mapError(
93
+ (cause) =>
94
+ new ConnectionError({
95
+ cause,
96
+ note: `Failed to connect to sync backend: ${cause._tag === 'IsOfflineError' ? 'Backend is offline or unreachable' : String(cause)}`,
97
+ }),
98
+ ),
99
+ )
100
+
101
+ /** Verify connectivity with a ping (with timeout) */
102
+ yield* syncBackend.ping.pipe(
103
+ Effect.timeout(CONNECTION_TIMEOUT_MS),
104
+ Effect.catchAll((cause) => {
105
+ if (Cause.isTimeoutException(cause)) {
106
+ return Effect.fail(
107
+ new ConnectionError({
108
+ cause,
109
+ note: `Connection timeout: Sync backend did not respond within ${CONNECTION_TIMEOUT_MS}ms`,
110
+ }),
111
+ )
112
+ }
113
+ return Effect.fail(
114
+ new ConnectionError({
115
+ cause,
116
+ note: `Failed to ping sync backend: ${cause._tag === 'IsOfflineError' ? 'Backend is offline or unreachable' : String(cause)}`,
117
+ }),
118
+ )
119
+ }),
120
+ )
121
+
122
+ return syncBackend
123
+ })
124
+
125
+ export interface ExportResult {
126
+ storeId: string
127
+ eventCount: number
128
+ exportedAt: string
129
+ /** The export data as JSON string (for MCP) or written to file (for CLI) */
130
+ data: ExportFile
131
+ }
132
+
133
+ /**
134
+ * Core export operation - pulls all events from sync backend.
135
+ * Returns the export data structure without writing to file.
136
+ */
137
+ export const pullEventsFromSyncBackend = ({
138
+ configPath,
139
+ storeId,
140
+ clientId,
141
+ }: {
142
+ configPath: string
143
+ storeId: string
144
+ clientId: string
145
+ }): Effect.Effect<
146
+ ExportResult,
147
+ ExportError | UnknownError | ConnectionError,
148
+ FileSystem.FileSystem | HttpClient.HttpClient | Scope.Scope
149
+ > =>
150
+ Effect.gen(function* () {
151
+ const syncBackend = yield* makeSyncBackend({ configPath, storeId, clientId })
152
+
153
+ const batchesChunk = yield* syncBackend.pull(Option.none(), { live: false }).pipe(
154
+ Stream.takeUntil((item) => item.pageInfo._tag === 'NoMore'),
155
+ Stream.runCollect,
156
+ Effect.mapError(
157
+ (cause) =>
158
+ new ExportError({
159
+ cause,
160
+ note: `Failed to pull events from sync backend: ${cause}`,
161
+ }),
162
+ ),
163
+ )
164
+
165
+ const events = Chunk.toReadonlyArray(batchesChunk)
166
+ .flatMap((item) => item.batch)
167
+ .map((item) => item.eventEncoded)
168
+
169
+ const exportedAt = new Date().toISOString()
170
+ const exportData: ExportFile = {
171
+ version: 1,
172
+ storeId,
173
+ exportedAt,
174
+ eventCount: events.length,
175
+ events,
176
+ }
177
+
178
+ return {
179
+ storeId,
180
+ eventCount: events.length,
181
+ exportedAt,
182
+ data: exportData,
183
+ }
184
+ }).pipe(Effect.withSpan('sync:pullEvents'))
185
+
186
+ export interface ImportResult {
187
+ storeId: string
188
+ eventCount: number
189
+ /** Whether this was a dry run */
190
+ dryRun: boolean
191
+ }
192
+
193
+ export interface ImportValidationResult {
194
+ storeId: string
195
+ eventCount: number
196
+ sourceStoreId: string
197
+ storeIdMismatch: boolean
198
+ }
199
+
200
+ /**
201
+ * Validates an export file for import.
202
+ * Returns validation info without actually importing.
203
+ */
204
+ export const validateExportData = ({
205
+ data,
206
+ targetStoreId,
207
+ }: {
208
+ data: unknown
209
+ targetStoreId: string
210
+ }): Effect.Effect<ImportValidationResult, ImportError> =>
211
+ Effect.gen(function* () {
212
+ const exportData = yield* Schema.decodeUnknown(ExportFileSchema)(data).pipe(
213
+ Effect.mapError(
214
+ (cause) =>
215
+ new ImportError({
216
+ cause: new Error(`Invalid export file format: ${cause}`),
217
+ note: `Invalid export file format: ${cause}`,
218
+ }),
219
+ ),
220
+ )
221
+
222
+ return {
223
+ storeId: targetStoreId,
224
+ eventCount: exportData.events.length,
225
+ sourceStoreId: exportData.storeId,
226
+ storeIdMismatch: exportData.storeId !== targetStoreId,
227
+ }
228
+ })
229
+
230
+ /**
231
+ * Core import operation - pushes events to sync backend.
232
+ * Validates that the backend is empty before importing.
233
+ */
234
+ export const pushEventsToSyncBackend = ({
235
+ configPath,
236
+ storeId,
237
+ clientId,
238
+ data,
239
+ force,
240
+ dryRun,
241
+ }: {
242
+ configPath: string
243
+ storeId: string
244
+ clientId: string
245
+ /** The export data to import (already parsed) */
246
+ data: unknown
247
+ force: boolean
248
+ dryRun: boolean
249
+ }): Effect.Effect<
250
+ ImportResult,
251
+ ImportError | UnknownError | ConnectionError,
252
+ FileSystem.FileSystem | HttpClient.HttpClient | Scope.Scope
253
+ > =>
254
+ Effect.gen(function* () {
255
+ const exportData = yield* Schema.decodeUnknown(ExportFileSchema)(data).pipe(
256
+ Effect.mapError(
257
+ (cause) =>
258
+ new ImportError({
259
+ cause: new Error(`Invalid export file format: ${cause}`),
260
+ note: `Invalid export file format: ${cause}`,
261
+ }),
262
+ ),
263
+ )
264
+
265
+ if (exportData.storeId !== storeId && !force) {
266
+ return yield* new ImportError({
267
+ cause: new Error(`Store ID mismatch: file has '${exportData.storeId}', expected '${storeId}'`),
268
+ note: `The export file was created for a different store. Use force option to import anyway.`,
269
+ })
270
+ }
271
+
272
+ if (dryRun) {
273
+ return {
274
+ storeId,
275
+ eventCount: exportData.events.length,
276
+ dryRun: true,
277
+ }
278
+ }
279
+
280
+ const syncBackend = yield* makeSyncBackend({ configPath, storeId, clientId })
281
+
282
+ /** Check if events already exist by pulling from the backend first */
283
+ const existingBatchesChunk = yield* syncBackend.pull(Option.none(), { live: false }).pipe(
284
+ Stream.takeUntil((item) => item.pageInfo._tag === 'NoMore'),
285
+ Stream.runCollect,
286
+ Effect.mapError(
287
+ (cause) =>
288
+ new ImportError({
289
+ cause,
290
+ note: `Failed to check existing events: ${cause}`,
291
+ }),
292
+ ),
293
+ )
294
+
295
+ const existingEventCount = Chunk.reduce(existingBatchesChunk, 0, (acc, item) => acc + item.batch.length)
296
+
297
+ if (existingEventCount > 0) {
298
+ return yield* new ImportError({
299
+ cause: new Error(`Sync backend already contains ${existingEventCount} events`),
300
+ note: `Cannot import into a non-empty sync backend. The sync backend must be empty.`,
301
+ })
302
+ }
303
+
304
+ /** Push events in batches of 100 (sync backend constraint) */
305
+ const batchSize = 100
306
+
307
+ for (let i = 0; i < exportData.events.length; i += batchSize) {
308
+ const batch = exportData.events.slice(i, i + batchSize)
309
+
310
+ yield* syncBackend.push(batch).pipe(
311
+ Effect.mapError(
312
+ (cause) =>
313
+ new ImportError({
314
+ cause,
315
+ note: `Failed to push events at position ${i}: ${cause}`,
316
+ }),
317
+ ),
318
+ )
319
+ }
320
+
321
+ return {
322
+ storeId,
323
+ eventCount: exportData.events.length,
324
+ dryRun: false,
325
+ }
326
+ }).pipe(Effect.withSpan('sync:pushEvents'))