markdown-sql 0.0.0-stage → 0.1.1

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/dist/pg.js ADDED
@@ -0,0 +1,1279 @@
1
+ import { parseDocument, isAlias, isScalar, isSeq, isNode, isMap } from 'yaml';
2
+ import { types, PGlite } from '@electric-sql/pglite';
3
+ import { live } from '@electric-sql/pglite/live';
4
+ import { drizzle } from 'drizzle-orm/pg-proxy';
5
+ import { resolve, dirname, join, relative, sep } from 'node:path';
6
+ import { createHash } from 'node:crypto';
7
+ import { readFile, readdir } from 'node:fs/promises';
8
+ import { watch } from 'node:fs';
9
+ import { is, getTableName, getTableColumns, SQL, sql } from 'drizzle-orm';
10
+ import { PgDialect, PgTable, getTableConfig, PgArray, PgEnumColumn, PgEnumObjectColumn, IndexedColumn } from 'drizzle-orm/pg-core';
11
+ import { SQLiteSyncDialect } from 'drizzle-orm/sqlite-core';
12
+ import { createRequire } from 'node:module';
13
+
14
+ // src/errors.ts
15
+ var createMarkdownSqlError = (code, message, extras = {}) => Object.assign(
16
+ new Error(message, extras.cause === void 0 ? void 0 : { cause: extras.cause }),
17
+ {
18
+ name: "MarkdownSqlError",
19
+ code,
20
+ diagnostics: extras.diagnostics ?? []
21
+ }
22
+ );
23
+ var ERROR_CODES = ["READ_ONLY", "VALIDATION", "CONFIG", "CLOSED"];
24
+ var isOwnError = (error) => error instanceof Error && error.name === "MarkdownSqlError" && "code" in error && typeof error.code === "string" && ERROR_CODES.includes(error.code) && "diagnostics" in error && Array.isArray(error.diagnostics);
25
+ var findMarkdownSqlError = (error) => {
26
+ if (isOwnError(error)) {
27
+ return error;
28
+ }
29
+ if (error instanceof Error && error.cause !== void 0) {
30
+ return findMarkdownSqlError(error.cause);
31
+ }
32
+ return void 0;
33
+ };
34
+ var isMarkdownSqlError = (error, code) => {
35
+ const found = findMarkdownSqlError(error);
36
+ return found !== void 0 && (code === void 0 || found.code === code);
37
+ };
38
+ var formatDiagnostic = (diagnostic) => `${diagnostic.file}${diagnostic.column === void 0 ? "" : ` (${diagnostic.column})`}: ${diagnostic.message}`;
39
+
40
+ // src/json.ts
41
+ var isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
42
+
43
+ // src/frontmatter.ts
44
+ var OPEN_FENCE = /^---[ \t]*\r?\n/;
45
+ var CLOSE_FENCE = /^(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/m;
46
+ var LEADING_LINE_BREAKS = /^(?:\r?\n)+/;
47
+ var toJson = (node, doc) => {
48
+ if (isAlias(node)) {
49
+ const target = node.resolve(doc);
50
+ if (target === void 0) {
51
+ throw new Error(`unresolved alias *${node.source}`);
52
+ }
53
+ return toJson(target, doc);
54
+ }
55
+ if (isScalar(node)) {
56
+ const { value } = node;
57
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
58
+ return value;
59
+ }
60
+ if (typeof value === "number") {
61
+ if (!Number.isFinite(value)) {
62
+ throw new Error(`non-finite number ${String(value)} is not supported`);
63
+ }
64
+ return value;
65
+ }
66
+ throw new Error(`unsupported YAML scalar ${String(value)}`);
67
+ }
68
+ if (isSeq(node)) {
69
+ return node.items.map((item) => isNode(item) ? toJson(item, doc) : null);
70
+ }
71
+ if (isMap(node)) {
72
+ const entries = node.items.map((pair) => {
73
+ if (!isScalar(pair.key)) {
74
+ throw new Error("only plain scalar keys are supported in frontmatter");
75
+ }
76
+ const key = String(pair.key.value);
77
+ return [key, isNode(pair.value) ? toJson(pair.value, doc) : null];
78
+ });
79
+ return Object.fromEntries(entries);
80
+ }
81
+ throw new Error("unsupported YAML node");
82
+ };
83
+ var parseYaml = (source) => {
84
+ const doc = parseDocument(source, { schema: "core", uniqueKeys: true, prettyErrors: false });
85
+ const [error] = doc.errors;
86
+ if (error !== void 0) {
87
+ throw new Error(error.message);
88
+ }
89
+ return doc.contents === null ? null : toJson(doc.contents, doc);
90
+ };
91
+ var parseMarkdown = (source) => {
92
+ const text = source.startsWith("\uFEFF") ? source.slice(1) : source;
93
+ const open = OPEN_FENCE.exec(text);
94
+ if (open === null) {
95
+ return { ok: true, file: { data: {}, body: text } };
96
+ }
97
+ const rest = text.slice(open[0].length);
98
+ const close = CLOSE_FENCE.exec(rest);
99
+ if (close === null) {
100
+ return { ok: false, message: "frontmatter opened with --- but never closed" };
101
+ }
102
+ const yamlSource = rest.slice(0, close.index);
103
+ const body = rest.slice(close.index + close[0].length).replace(LEADING_LINE_BREAKS, "");
104
+ let data;
105
+ try {
106
+ data = parseYaml(yamlSource);
107
+ } catch (error) {
108
+ return {
109
+ ok: false,
110
+ message: `invalid YAML: ${error instanceof Error ? error.message : String(error)}`
111
+ };
112
+ }
113
+ if (data === null) {
114
+ return { ok: true, file: { data: {}, body } };
115
+ }
116
+ if (!isJsonObject(data)) {
117
+ return { ok: false, message: "frontmatter must be a YAML mapping" };
118
+ }
119
+ return { ok: true, file: { data, body } };
120
+ };
121
+ var quoteIdentifier = (name) => `"${name.replaceAll('"', '""')}"`;
122
+ var schemaHash = (models) => {
123
+ const shape = models.map((model) => ({
124
+ table: model.name,
125
+ dir: model.dir,
126
+ ddl: model.ddl,
127
+ columns: model.columns.map((column) => [column.key, column.role, column.spec.kind])
128
+ }));
129
+ return createHash("sha256").update(JSON.stringify(shape)).digest("hex");
130
+ };
131
+
132
+ // src/coerce.ts
133
+ var ISO_DATE = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;
134
+ var INTEGER_TEXT = /^-?\d+$/;
135
+ var INTEGER_TYPES = [
136
+ "integer",
137
+ "smallint",
138
+ "bigint",
139
+ "serial",
140
+ "smallserial",
141
+ "bigserial"
142
+ ];
143
+ var ok = (value) => ({ ok: true, value });
144
+ var mismatch = (message) => ({ ok: false, code: "type-mismatch", message });
145
+ var describe = (value) => {
146
+ if (value === null) {
147
+ return "null";
148
+ }
149
+ if (Array.isArray(value)) {
150
+ return "a list";
151
+ }
152
+ return typeof value === "object" ? "a mapping" : `${typeof value} ${JSON.stringify(value)}`;
153
+ };
154
+ var coerceString = (column, value) => {
155
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
156
+ return mismatch(`expected text, got ${describe(value)}`);
157
+ }
158
+ const text = String(value);
159
+ const allowed = column.enumValues;
160
+ if (allowed !== void 0 && allowed.length > 0 && !allowed.includes(text)) {
161
+ return mismatch(
162
+ `expected one of ${allowed.map((v) => JSON.stringify(v)).join(", ")}, got ${JSON.stringify(text)}`
163
+ );
164
+ }
165
+ return ok(text);
166
+ };
167
+ var coerceNumber = (column, value) => {
168
+ if (typeof value !== "number") {
169
+ return mismatch(`expected a number, got ${describe(value)}`);
170
+ }
171
+ if (INTEGER_TYPES.includes(column.sqlType) && !Number.isInteger(value)) {
172
+ return mismatch(`expected an integer, got ${value}`);
173
+ }
174
+ return ok(value);
175
+ };
176
+ var coerceBigint = (value) => {
177
+ if (typeof value === "number" && Number.isSafeInteger(value)) {
178
+ return ok(BigInt(value));
179
+ }
180
+ if (typeof value === "string" && INTEGER_TEXT.test(value)) {
181
+ return ok(BigInt(value));
182
+ }
183
+ return mismatch(`expected an integer, got ${describe(value)}`);
184
+ };
185
+ var coerceDate = (value) => {
186
+ if (typeof value !== "string" || !ISO_DATE.test(value)) {
187
+ return mismatch(
188
+ `expected an ISO 8601 date such as 2026-11-23 or 2026-11-23T09:00:00Z, got ${describe(value)}`
189
+ );
190
+ }
191
+ const date = new Date(value);
192
+ return Number.isNaN(date.getTime()) ? mismatch(`invalid date ${JSON.stringify(value)}`) : ok(date);
193
+ };
194
+ var coerceArray = (column, value) => {
195
+ if (!Array.isArray(value)) {
196
+ return mismatch(`expected a list, got ${describe(value)}`);
197
+ }
198
+ const { element } = column;
199
+ if (element === void 0) {
200
+ return ok(value);
201
+ }
202
+ const items = [];
203
+ for (const [index, item] of value.entries()) {
204
+ if (item === null) {
205
+ return mismatch(`item ${index + 1}: null is not allowed in a list`);
206
+ }
207
+ const coerced = coerceValue(element, item);
208
+ if (!coerced.ok) {
209
+ return { ...coerced, message: `item ${index + 1}: ${coerced.message}` };
210
+ }
211
+ items.push(coerced.value);
212
+ }
213
+ return ok(items);
214
+ };
215
+ var coerceValue = (column, value) => {
216
+ switch (column.kind) {
217
+ case "string":
218
+ return coerceString(column, value);
219
+ case "number":
220
+ return coerceNumber(column, value);
221
+ case "bigint":
222
+ return coerceBigint(value);
223
+ case "boolean":
224
+ return typeof value === "boolean" ? ok(value) : mismatch(`expected true or false, got ${describe(value)}`);
225
+ case "date":
226
+ return coerceDate(value);
227
+ case "array":
228
+ return coerceArray(column, value);
229
+ case "json":
230
+ case "custom":
231
+ return ok(value);
232
+ default:
233
+ return mismatch(`columns of type ${column.typeName} cannot be read from frontmatter`);
234
+ }
235
+ };
236
+ var keyValue = (model, stem) => {
237
+ const { kind: dataType } = model.spec;
238
+ if (dataType === "string") {
239
+ return coerceString(model.spec, stem);
240
+ }
241
+ if ((dataType === "number" || dataType === "bigint") && INTEGER_TEXT.test(stem)) {
242
+ return dataType === "number" ? ok(Number(stem)) : ok(BigInt(stem));
243
+ }
244
+ return {
245
+ ok: false,
246
+ code: "invalid-key",
247
+ message: `file name "${stem}" is not a valid ${model.spec.sqlType} key`
248
+ };
249
+ };
250
+ var buildRow = async (model, file, stem, relativePath, context) => {
251
+ const { toParam } = context;
252
+ const diagnostics = [];
253
+ const columns = [];
254
+ const params = [];
255
+ let key = toParam(null);
256
+ const report = (code, column, message) => {
257
+ diagnostics.push({ code, table: model.schemaKey, file: relativePath, column, message });
258
+ };
259
+ const dataKeys = new Set(model.columns.filter((c) => c.role === "data").map((c) => c.key));
260
+ const unknownKeys = Object.keys(file.data).filter((k) => !dataKeys.has(k));
261
+ for (const columnModel of model.columns) {
262
+ const { spec: column } = columnModel;
263
+ let coerced;
264
+ if (columnModel.role === "key") {
265
+ coerced = keyValue(columnModel, stem);
266
+ } else if (columnModel.role === "body") {
267
+ coerced = ok(file.body);
268
+ } else {
269
+ const raw = Object.hasOwn(file.data, columnModel.key) ? file.data[columnModel.key] : void 0;
270
+ if (raw === null && !column.notNull) {
271
+ coerced = ok(null);
272
+ } else if (raw !== void 0 && raw !== null) {
273
+ coerced = coerceValue(column, raw);
274
+ }
275
+ }
276
+ if (coerced === void 0) {
277
+ const fallback = await column.resolveDefault(context);
278
+ if (fallback.found) {
279
+ columns.push(columnModel.name);
280
+ params.push(fallback.param);
281
+ } else if (column.notNull) {
282
+ report(
283
+ "missing-required",
284
+ columnModel.key,
285
+ `required column "${columnModel.key}" is missing`
286
+ );
287
+ } else {
288
+ columns.push(columnModel.name);
289
+ params.push(toParam(null));
290
+ }
291
+ continue;
292
+ }
293
+ if (!coerced.ok) {
294
+ report(coerced.code, columnModel.key, coerced.message);
295
+ continue;
296
+ }
297
+ const param = coerced.value === null ? toParam(null) : column.bind(coerced.value, toParam);
298
+ if (columnModel.role === "key") {
299
+ key = param;
300
+ }
301
+ columns.push(columnModel.name);
302
+ params.push(param);
303
+ }
304
+ if (diagnostics.length > 0) {
305
+ return { ok: false, diagnostics, unknownKeys };
306
+ }
307
+ return { ok: true, row: { key, columns, params }, unknownKeys };
308
+ };
309
+
310
+ // src/store.ts
311
+ var TEMP_SUFFIXES = ["~", ".swp", ".swx", ".tmp", ".bak"];
312
+ var errorCode = (error) => error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : void 0;
313
+ var errorMessage = (error) => error instanceof Error ? error.message : String(error);
314
+ var createStore = (options) => {
315
+ const { backend, onDiagnostic } = options;
316
+ const extensions = options.extensions.map((extension) => extension.toLowerCase());
317
+ const tables = options.models.map(
318
+ (model) => ({
319
+ model,
320
+ absoluteDir: join(options.root, model.dir),
321
+ files: /* @__PURE__ */ new Map()
322
+ })
323
+ );
324
+ const isRowFile = (fileName) => {
325
+ const lower = fileName.toLowerCase();
326
+ return !fileName.startsWith(".") && !fileName.startsWith("#") && !TEMP_SUFFIXES.some((suffix) => lower.endsWith(suffix)) && extensions.some((extension) => lower.endsWith(extension) && lower.length > extension.length);
327
+ };
328
+ const stemOf = (fileName) => {
329
+ const lower = fileName.toLowerCase();
330
+ const extension = extensions.find((candidate) => lower.endsWith(candidate)) ?? "";
331
+ return fileName.slice(0, fileName.length - extension.length);
332
+ };
333
+ const relativePath = (state, fileName) => relative(options.root, join(state.absoluteDir, fileName)).split(sep).join("/");
334
+ const event = (type, state, fileName, diagnostics2 = []) => ({
335
+ type,
336
+ table: state.model.schemaKey,
337
+ file: relativePath(state, fileName),
338
+ key: stemOf(fileName),
339
+ diagnostics: diagnostics2
340
+ });
341
+ const planFile = async (state, fileName) => {
342
+ if (!isRowFile(fileName)) {
343
+ return { kind: "unchanged" };
344
+ }
345
+ const file = relativePath(state, fileName);
346
+ const invalid = (checksum2, diagnostics2, unknownKeys = []) => ({ kind: "invalid", checksum: checksum2, diagnostics: diagnostics2, unknownKeys });
347
+ let source;
348
+ try {
349
+ source = await readFile(join(state.absoluteDir, fileName), "utf8");
350
+ } catch (error) {
351
+ const code = errorCode(error);
352
+ if (code === "ENOENT" || code === "ENOTDIR") {
353
+ return { kind: "remove" };
354
+ }
355
+ if (code === "EISDIR") {
356
+ return { kind: "unchanged" };
357
+ }
358
+ return invalid("", [
359
+ { code: "read-error", table: state.model.schemaKey, file, message: errorMessage(error) }
360
+ ]);
361
+ }
362
+ const checksum = createHash("sha256").update(source).digest("hex");
363
+ if (state.files.get(fileName)?.checksum === checksum) {
364
+ return { kind: "unchanged" };
365
+ }
366
+ const parsed = parseMarkdown(source);
367
+ if (!parsed.ok) {
368
+ return invalid(checksum, [
369
+ {
370
+ code: "invalid-frontmatter",
371
+ table: state.model.schemaKey,
372
+ file,
373
+ message: parsed.message
374
+ }
375
+ ]);
376
+ }
377
+ const outcome = await buildRow(state.model, parsed.file, stemOf(fileName), file, backend);
378
+ if (!outcome.ok) {
379
+ return invalid(checksum, outcome.diagnostics, outcome.unknownKeys);
380
+ }
381
+ return { kind: "row", checksum, row: outcome.row, unknownKeys: outcome.unknownKeys };
382
+ };
383
+ const record = (state, item) => {
384
+ const { fileName, plan } = item;
385
+ const entries = state.files;
386
+ const previous = entries.get(fileName);
387
+ switch (plan.kind) {
388
+ case "unchanged":
389
+ return void 0;
390
+ case "remove":
391
+ if (previous === void 0) {
392
+ return void 0;
393
+ }
394
+ entries.delete(fileName);
395
+ return event("unlink", state, fileName);
396
+ case "invalid":
397
+ entries.set(fileName, {
398
+ checksum: plan.checksum,
399
+ key: void 0,
400
+ diagnostics: plan.diagnostics,
401
+ unknownKeys: plan.unknownKeys
402
+ });
403
+ for (const diagnostic of plan.diagnostics) {
404
+ onDiagnostic(diagnostic);
405
+ }
406
+ return event("invalid", state, fileName, plan.diagnostics);
407
+ case "row":
408
+ entries.set(fileName, {
409
+ checksum: plan.checksum,
410
+ key: plan.row.key,
411
+ diagnostics: [],
412
+ unknownKeys: plan.unknownKeys
413
+ });
414
+ return event(previous?.key === void 0 ? "add" : "change", state, fileName);
415
+ }
416
+ };
417
+ const changesFor = (state, items) => {
418
+ const entries = state.files;
419
+ const deleteKeys = [];
420
+ const rows = [];
421
+ for (const { fileName, plan } of items) {
422
+ const previousKey = entries.get(fileName)?.key;
423
+ if (previousKey !== void 0) {
424
+ deleteKeys.push(previousKey);
425
+ }
426
+ if (plan.kind === "row") {
427
+ deleteKeys.push(plan.row.key);
428
+ rows.push(plan.row);
429
+ }
430
+ }
431
+ return { deleteKeys, rows };
432
+ };
433
+ const commit = async (state, planned) => {
434
+ const items = planned.filter((item) => item.plan.kind !== "unchanged");
435
+ const changes = changesFor(state, items);
436
+ try {
437
+ if (changes.deleteKeys.length > 0 || changes.rows.length > 0) {
438
+ await backend.apply(state.model, changes);
439
+ }
440
+ } catch (error) {
441
+ const [only] = items;
442
+ if (items.length > 1) {
443
+ const events = [];
444
+ for (const item of items) {
445
+ events.push(...await commit(state, [item]));
446
+ }
447
+ return events;
448
+ }
449
+ if (only === void 0 || only.plan.kind !== "row") {
450
+ throw error;
451
+ }
452
+ const sqlError = {
453
+ fileName: only.fileName,
454
+ plan: {
455
+ kind: "invalid",
456
+ checksum: only.plan.checksum,
457
+ diagnostics: [
458
+ {
459
+ code: "sql-error",
460
+ table: state.model.schemaKey,
461
+ file: relativePath(state, only.fileName),
462
+ message: errorMessage(error)
463
+ }
464
+ ],
465
+ unknownKeys: []
466
+ }
467
+ };
468
+ return commit(state, [sqlError]);
469
+ }
470
+ return items.flatMap((item) => {
471
+ const recorded = record(state, item);
472
+ return recorded === void 0 ? [] : [recorded];
473
+ });
474
+ };
475
+ const syncFile = async (state, fileName) => {
476
+ const [changed] = await commit(state, [{ fileName, plan: await planFile(state, fileName) }]);
477
+ return changed;
478
+ };
479
+ const listFiles = async (state) => {
480
+ try {
481
+ const entries = await readdir(state.absoluteDir, { withFileTypes: true });
482
+ return entries.filter((entry) => entry.isFile() && isRowFile(entry.name)).map((entry) => entry.name).sort();
483
+ } catch (error) {
484
+ if (errorCode(error) === "ENOENT") {
485
+ return [];
486
+ }
487
+ throw error;
488
+ }
489
+ };
490
+ const syncTable = async (state) => {
491
+ const present = await listFiles(state);
492
+ const planned = [...state.files.keys()].filter((fileName) => !present.includes(fileName)).map((fileName) => ({ fileName, plan: { kind: "remove" } }));
493
+ for (const fileName of present) {
494
+ planned.push({ fileName, plan: await planFile(state, fileName) });
495
+ }
496
+ return commit(state, planned);
497
+ };
498
+ const syncAll = async () => {
499
+ const events = [];
500
+ for (const state of tables) {
501
+ events.push(...await syncTable(state));
502
+ }
503
+ return events;
504
+ };
505
+ const diagnostics = () => tables.flatMap((state) => [...state.files.values()].flatMap((entry) => entry.diagnostics));
506
+ const report = () => tables.map((state) => {
507
+ const entries = [...state.files.values()];
508
+ const counts = /* @__PURE__ */ new Map();
509
+ for (const key of entries.flatMap((entry) => entry.unknownKeys)) {
510
+ counts.set(key, (counts.get(key) ?? 0) + 1);
511
+ }
512
+ const unknownKeys = Object.fromEntries([...counts].sort(([a], [b]) => a.localeCompare(b)));
513
+ return {
514
+ table: state.model.schemaKey,
515
+ dir: state.model.dir,
516
+ rows: entries.filter((entry) => entry.key !== void 0).length,
517
+ skipped: entries.filter((entry) => entry.key === void 0).length,
518
+ unknownKeys
519
+ };
520
+ });
521
+ return { tables, isRowFile, syncFile, syncTable, syncAll, diagnostics, report };
522
+ };
523
+ var WHOLE_TABLE = /* @__PURE__ */ Symbol("whole table");
524
+ var startWatcher = (context, options = {}) => {
525
+ const { store, enqueue, onDiagnostic } = context;
526
+ const debounceMs = options.debounceMs ?? 50;
527
+ const timers = /* @__PURE__ */ new Map();
528
+ const watchers = [];
529
+ const schedule = (state, fileName) => {
530
+ const timerKey = `${state.model.schemaKey}\0${typeof fileName === "string" ? fileName : "*"}`;
531
+ clearTimeout(timers.get(timerKey));
532
+ const timer = setTimeout(() => {
533
+ timers.delete(timerKey);
534
+ enqueue(async () => {
535
+ if (typeof fileName !== "string") {
536
+ return store.syncTable(state);
537
+ }
538
+ const changed = await store.syncFile(state, fileName);
539
+ return changed === void 0 ? [] : [changed];
540
+ });
541
+ }, debounceMs);
542
+ if (options.persistent === false) {
543
+ timer.unref();
544
+ }
545
+ timers.set(timerKey, timer);
546
+ };
547
+ for (const state of store.tables) {
548
+ try {
549
+ const watcher = watch(
550
+ state.absoluteDir,
551
+ { persistent: options.persistent ?? true },
552
+ (_, fileName) => {
553
+ if (fileName === null) {
554
+ schedule(state, WHOLE_TABLE);
555
+ } else if (store.isRowFile(fileName)) {
556
+ schedule(state, fileName);
557
+ }
558
+ }
559
+ );
560
+ watcher.on("error", (error) => {
561
+ onDiagnostic({
562
+ code: "watch-error",
563
+ table: state.model.schemaKey,
564
+ file: state.model.dir,
565
+ message: error.message
566
+ });
567
+ });
568
+ watchers.push(watcher);
569
+ } catch (error) {
570
+ onDiagnostic({
571
+ code: "watch-error",
572
+ table: state.model.schemaKey,
573
+ file: state.model.dir,
574
+ message: `cannot watch folder: ${error instanceof Error ? error.message : String(error)}`
575
+ });
576
+ }
577
+ }
578
+ return {
579
+ close: () => {
580
+ for (const watcher of watchers) {
581
+ watcher.close();
582
+ }
583
+ for (const timer of timers.values()) {
584
+ clearTimeout(timer);
585
+ }
586
+ timers.clear();
587
+ }
588
+ };
589
+ };
590
+
591
+ // src/core.ts
592
+ var openIndex = async (open) => {
593
+ const { options, models, backend, closeBackend, afterLoad } = open;
594
+ const userDiagnostic = options.onDiagnostic ?? (() => void 0);
595
+ const store = createStore({
596
+ backend,
597
+ models,
598
+ root: resolve(options.root),
599
+ extensions: options.extensions ?? [".md"],
600
+ onDiagnostic: (diagnostic) => userDiagnostic(diagnostic)
601
+ });
602
+ try {
603
+ await store.syncAll();
604
+ await afterLoad?.();
605
+ } catch (error) {
606
+ await closeBackend();
607
+ throw error;
608
+ }
609
+ const initial = store.diagnostics();
610
+ if ((options.onInvalid ?? "throw") === "throw" && initial.length > 0) {
611
+ await closeBackend();
612
+ throw createMarkdownSqlError(
613
+ "VALIDATION",
614
+ `${initial.length} markdown file problem(s):
615
+ ${initial.map(formatDiagnostic).join("\n")}`,
616
+ { diagnostics: initial }
617
+ );
618
+ }
619
+ let closed = false;
620
+ let queue = Promise.resolve();
621
+ let watcher;
622
+ const listeners = /* @__PURE__ */ new Set();
623
+ const emit = (events) => {
624
+ if (events.length === 0) {
625
+ return;
626
+ }
627
+ for (const listener of listeners) {
628
+ listener(events);
629
+ }
630
+ };
631
+ const enqueue = (task) => {
632
+ const next = queue.then(async () => {
633
+ if (closed) {
634
+ return [];
635
+ }
636
+ const events = await task();
637
+ emit(events);
638
+ return events;
639
+ });
640
+ queue = next.then(
641
+ () => void 0,
642
+ (error) => {
643
+ userDiagnostic({
644
+ code: "watch-error",
645
+ table: "",
646
+ file: "",
647
+ message: error instanceof Error ? error.message : String(error)
648
+ });
649
+ }
650
+ );
651
+ return next;
652
+ };
653
+ const watch2 = (watchOptions) => {
654
+ if (watcher !== void 0 || closed) {
655
+ return;
656
+ }
657
+ watcher = startWatcher(
658
+ {
659
+ store,
660
+ enqueue: (task) => {
661
+ void enqueue(task);
662
+ },
663
+ onDiagnostic: userDiagnostic
664
+ },
665
+ watchOptions
666
+ );
667
+ };
668
+ if (options.watch !== void 0 && options.watch !== false) {
669
+ watch2(options.watch === true ? {} : options.watch);
670
+ }
671
+ return {
672
+ isClosed: () => closed,
673
+ diagnostics: () => store.diagnostics(),
674
+ report: () => ({
675
+ schemaHash: schemaHash(models),
676
+ tables: store.report(),
677
+ diagnostics: store.diagnostics()
678
+ }),
679
+ reload: () => enqueue(() => store.syncAll()),
680
+ watch: watch2,
681
+ subscribe: (listener) => {
682
+ listeners.add(listener);
683
+ return () => {
684
+ listeners.delete(listener);
685
+ };
686
+ },
687
+ settled: () => queue,
688
+ close: async () => {
689
+ if (closed) {
690
+ return;
691
+ }
692
+ watcher?.close();
693
+ watcher = void 0;
694
+ await queue;
695
+ closed = true;
696
+ listeners.clear();
697
+ await closeBackend();
698
+ }
699
+ };
700
+ };
701
+ new SQLiteSyncDialect();
702
+ var KINDS = [
703
+ "string",
704
+ "number",
705
+ "bigint",
706
+ "boolean",
707
+ "date",
708
+ "array",
709
+ "json",
710
+ "custom"
711
+ ];
712
+ var kindOf = (column) => KINDS.find((kind) => kind === column.dataType) ?? "unsupported";
713
+ var columnSpec = (column, compileDefault) => {
714
+ const element = is(column, PgArray) ? columnSpec(column.baseColumn, compileDefault) : void 0;
715
+ const enumValues = column.enumValues;
716
+ return {
717
+ kind: kindOf(column),
718
+ sqlType: column.getSQLType(),
719
+ notNull: column.notNull,
720
+ ...enumValues === void 0 ? {} : { enumValues },
721
+ ...element === void 0 ? {} : { element },
722
+ typeName: column.columnType,
723
+ bind: (value, toParam) => toParam(column.mapToDriverValue(value)),
724
+ resolveDefault: async (context) => {
725
+ const fromDefault = column.defaultFn === void 0 ? column.default : column.defaultFn();
726
+ if (fromDefault === void 0) {
727
+ return { found: false };
728
+ }
729
+ if (is(fromDefault, SQL)) {
730
+ const query = compileDefault(fromDefault);
731
+ return {
732
+ found: true,
733
+ param: await context.evaluate({
734
+ sql: query.sql,
735
+ params: query.params.map(context.toParam)
736
+ })
737
+ };
738
+ }
739
+ return { found: true, param: context.toParam(column.mapToDriverValue(fromDefault)) };
740
+ }
741
+ };
742
+ };
743
+ var columnDdl = (model, columnType2) => {
744
+ const { column } = model;
745
+ const parts = [quoteIdentifier(model.name), columnType2(column)];
746
+ if (column.notNull) {
747
+ parts.push("NOT NULL");
748
+ }
749
+ return parts.join(" ");
750
+ };
751
+ var tableDdl = (name, columns, primaryKey, columnType2) => {
752
+ const definitions = columns.map((model) => columnDdl(model, columnType2));
753
+ if (primaryKey.length > 0) {
754
+ definitions.push(`PRIMARY KEY (${primaryKey.map(quoteIdentifier).join(", ")})`);
755
+ }
756
+ return `CREATE TABLE ${quoteIdentifier(name)} (${definitions.join(", ")})`;
757
+ };
758
+ var roleOf = (key, keyName, bodyName) => {
759
+ if (key === keyName) {
760
+ return "key";
761
+ }
762
+ return key === bodyName ? "body" : "data";
763
+ };
764
+ var buildTableModel = (schemaKey, table, options, dialect3) => {
765
+ dialect3.checkTable?.(schemaKey, table);
766
+ const name = getTableName(table);
767
+ const keyName = options.key ?? "id";
768
+ const bodyName = options.body ?? "body";
769
+ const tableColumns = getTableColumns(table);
770
+ const columns = Object.entries(tableColumns).map(
771
+ ([key, column]) => ({
772
+ key,
773
+ name: column.name,
774
+ role: roleOf(key, keyName, bodyName),
775
+ column,
776
+ spec: columnSpec(column, dialect3.compileDefault)
777
+ })
778
+ );
779
+ const generated = columns.find((model) => model.column.generated !== void 0);
780
+ if (generated !== void 0) {
781
+ throw createMarkdownSqlError(
782
+ "CONFIG",
783
+ `Table "${schemaKey}": generated column "${generated.key}" is not supported yet.`
784
+ );
785
+ }
786
+ const keyColumn = columns.find((model) => model.role === "key");
787
+ if (keyColumn === void 0) {
788
+ throw createMarkdownSqlError(
789
+ "CONFIG",
790
+ `Table "${schemaKey}" has no column "${keyName}" for the file name. Add one or set tables.${schemaKey}.key.`
791
+ );
792
+ }
793
+ const bodyColumn = columns.find((model) => model.role === "body");
794
+ if (options.body !== void 0 && options.body !== false && bodyColumn === void 0) {
795
+ throw createMarkdownSqlError(
796
+ "CONFIG",
797
+ `Table "${schemaKey}" has no column "${options.body}" for the markdown body.`
798
+ );
799
+ }
800
+ const primaryKey = [
801
+ ...columns.filter((model) => model.column.primary).map((model) => model.name),
802
+ ...dialect3.compositePrimaryKeys(table)
803
+ ];
804
+ return {
805
+ schemaKey,
806
+ name,
807
+ dir: options.dir ?? name,
808
+ table,
809
+ columns,
810
+ keyColumn,
811
+ ddl: tableDdl(name, columns, primaryKey, dialect3.columnType)
812
+ };
813
+ };
814
+ var buildModels = (schema, tables = {}, dialect3) => {
815
+ const options = tables;
816
+ const models = Object.entries(schema).flatMap(
817
+ ([schemaKey, value]) => dialect3.isTable(value) ? [buildTableModel(schemaKey, value, options[schemaKey] ?? {}, dialect3)] : []
818
+ );
819
+ if (models.length === 0) {
820
+ throw createMarkdownSqlError("CONFIG", `The schema has no Drizzle ${dialect3.label} tables.`);
821
+ }
822
+ const unknownOptions = Object.keys(options).filter(
823
+ (key) => !models.some((model) => model.schemaKey === key)
824
+ );
825
+ if (unknownOptions.length > 0) {
826
+ throw createMarkdownSqlError(
827
+ "CONFIG",
828
+ `tables has options for ${unknownOptions.map((key) => `"${key}"`).join(", ")}, which are not tables in the schema.`
829
+ );
830
+ }
831
+ const names = /* @__PURE__ */ new Set();
832
+ for (const model of models) {
833
+ if (names.has(model.name)) {
834
+ throw createMarkdownSqlError(
835
+ "CONFIG",
836
+ `Two schema entries use the SQL table name "${model.name}".`
837
+ );
838
+ }
839
+ names.add(model.name);
840
+ }
841
+ return models;
842
+ };
843
+
844
+ // src/read-only.ts
845
+ var READ_STATEMENT = /^(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*(?:select|with|values|explain)\b/i;
846
+ var readOnlyError = (statement, cause) => createMarkdownSqlError(
847
+ "READ_ONLY",
848
+ `MarkdownSQL is read-only in this version: edit the markdown files instead. Rejected: ${statement.trim().slice(0, 80)}`,
849
+ cause === void 0 ? {} : { cause }
850
+ );
851
+ var closedError = () => createMarkdownSqlError("CLOSED", "This MarkdownSQL instance is closed.");
852
+
853
+ // src/pg/backend.ts
854
+ var toPgParam = (value) => {
855
+ if (value === null || value === void 0) {
856
+ return null;
857
+ }
858
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
859
+ return value;
860
+ }
861
+ if (typeof value === "bigint") {
862
+ return value.toString();
863
+ }
864
+ if (value instanceof Date) {
865
+ return value.toISOString();
866
+ }
867
+ if (value instanceof Uint8Array) {
868
+ return value;
869
+ }
870
+ throw new TypeError(`Cannot bind a value of type ${typeof value} to Postgres.`);
871
+ };
872
+ var copyField = (value) => {
873
+ if (value === null) {
874
+ return "\\N";
875
+ }
876
+ const text = value instanceof Uint8Array ? `\\x${Buffer.from(value).toString("hex")}` : `${value}`;
877
+ return text.replaceAll("\\", "\\\\").replaceAll(" ", "\\t").replaceAll("\n", "\\n").replaceAll("\r", "\\r");
878
+ };
879
+ var columnList = (row) => row.columns.map(quoteIdentifier).join(", ");
880
+ var copyRows = async (tx, table, rows) => {
881
+ const text = rows.map((row) => `${row.params.map(copyField).join(" ")}
882
+ `).join("");
883
+ await tx.query(`COPY ${table} (${columnList(rows[0])}) FROM '/dev/blob'`, [], {
884
+ blob: new Blob([text])
885
+ });
886
+ };
887
+ var insertRow = async (tx, table, row) => {
888
+ const placeholders = row.params.map((_, index) => `$${index + 1}`).join(", ");
889
+ await tx.query(`INSERT INTO ${table} (${columnList(row)}) VALUES (${placeholders})`, [
890
+ ...row.params
891
+ ]);
892
+ };
893
+ var byColumns = (rows) => {
894
+ const groups = /* @__PURE__ */ new Map();
895
+ for (const row of rows) {
896
+ const key = row.columns.join("\0");
897
+ const group = groups.get(key);
898
+ groups.set(key, group === void 0 ? [row] : [...group, row]);
899
+ }
900
+ return [...groups.values()];
901
+ };
902
+ var createPgliteBackend = (client) => {
903
+ return {
904
+ toParam: toPgParam,
905
+ evaluate: async (query) => {
906
+ const result = await client.query(query.sql, [...query.params], {
907
+ rowMode: "array"
908
+ });
909
+ return result.rows[0]?.[0] ?? null;
910
+ },
911
+ apply: (model, changes) => client.transaction(async (tx) => {
912
+ const table = quoteIdentifier(model.name);
913
+ if (changes.deleteKeys.length > 0) {
914
+ await tx.query(
915
+ `DELETE FROM ${table} WHERE ${quoteIdentifier(model.keyColumn.name)} = ANY($1)`,
916
+ [changes.deleteKeys]
917
+ );
918
+ }
919
+ for (const group of byColumns(changes.rows)) {
920
+ if (group.length === 1) {
921
+ await insertRow(tx, table, group[0]);
922
+ } else {
923
+ await copyRows(tx, table, group);
924
+ }
925
+ }
926
+ })
927
+ };
928
+ };
929
+ var dialect = new PgDialect();
930
+ var unsupported = (table, label, reason) => createMarkdownSqlError("CONFIG", `Table "${table}", index ${label}: ${reason}`);
931
+ var renderSql = (expression, table, label) => {
932
+ const query = dialect.sqlToQuery(expression, "indexes");
933
+ if (query.params.length > 0) {
934
+ throw unsupported(
935
+ table,
936
+ label,
937
+ "expressions and WHERE clauses cannot use bound values. Write literal values into the SQL text (e.g. status = 'published') or use sql.raw()."
938
+ );
939
+ }
940
+ return query.sql;
941
+ };
942
+ var renderPart = (part, table, label) => {
943
+ if (is(part, SQL)) {
944
+ return `(${renderSql(part, table, label)})`;
945
+ }
946
+ if (!is(part, IndexedColumn) || part.name === void 0) {
947
+ throw unsupported(table, label, "only columns and sql`` expressions can be indexed.");
948
+ }
949
+ const { opClass, order, nulls } = part.indexConfig;
950
+ const words = [quoteIdentifier(part.name)];
951
+ if (opClass !== void 0) {
952
+ words.push(opClass);
953
+ }
954
+ if (order === "desc") {
955
+ words.push("DESC");
956
+ }
957
+ if (nulls !== void 0 && nulls !== (order === "desc" ? "first" : "last")) {
958
+ words.push(`NULLS ${nulls.toUpperCase()}`);
959
+ }
960
+ return words.join(" ");
961
+ };
962
+ var isWithValue = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean";
963
+ var renderWith = (options, table, label) => Object.entries(options).map(([key, value]) => {
964
+ if (!isWithValue(value)) {
965
+ throw unsupported(
966
+ table,
967
+ label,
968
+ `WITH option "${key}" must be a string, number or boolean.`
969
+ );
970
+ }
971
+ return `${key} = ${typeof value === "string" ? `'${value.replaceAll("'", "''")}'` : value}`;
972
+ }).join(", ");
973
+ var indexDdl = (models) => models.flatMap((model) => {
974
+ if (!is(model.table, PgTable)) {
975
+ return [];
976
+ }
977
+ return getTableConfig(model.table).indexes.map((index, position) => {
978
+ const { config } = index;
979
+ const label = config.name === void 0 ? `#${position + 1}` : `"${config.name}"`;
980
+ const parts = config.columns.map((part) => renderPart(part, model.schemaKey, label));
981
+ const clauses = [
982
+ `CREATE${config.unique ? " UNIQUE" : ""} INDEX`,
983
+ ...config.name === void 0 ? [] : [quoteIdentifier(config.name)],
984
+ // `only` is left out: the index tables are never partitioned (and `.using()` always sets it).
985
+ `ON ${quoteIdentifier(model.name)}`,
986
+ ...config.method === void 0 || config.method === "btree" ? [] : [`USING ${config.method}`],
987
+ `(${parts.join(", ")})`,
988
+ ...config.with === void 0 || Object.keys(config.with).length === 0 ? [] : [`WITH (${renderWith(config.with, model.schemaKey, label)})`],
989
+ ...config.where === void 0 ? [] : [`WHERE ${renderSql(config.where, model.schemaKey, label)}`]
990
+ ];
991
+ return { table: model.schemaKey, label, unique: config.unique, sql: clauses.join(" ") };
992
+ });
993
+ });
994
+ var enumOf = (column) => {
995
+ if (is(column, PgArray)) {
996
+ return enumOf(column.baseColumn);
997
+ }
998
+ if (is(column, PgEnumColumn) || is(column, PgEnumObjectColumn)) {
999
+ return column.enum;
1000
+ }
1001
+ return void 0;
1002
+ };
1003
+ var columnType = (column) => {
1004
+ if (is(column, PgArray)) {
1005
+ return `${columnType(column.baseColumn)}[${column.size ?? ""}]`;
1006
+ }
1007
+ const enumType = enumOf(column);
1008
+ return enumType === void 0 ? column.getSQLType() : quoteIdentifier(enumType.enumName);
1009
+ };
1010
+ var dialect2 = new PgDialect();
1011
+ var pgDialect = {
1012
+ label: "Postgres",
1013
+ isTable: (value) => is(value, PgTable),
1014
+ compositePrimaryKeys: (table) => getTableConfig(table).primaryKeys.flatMap((pk) => pk.columns.map((column) => column.name)),
1015
+ columnType,
1016
+ // Casting to text keeps every default in Postgres' own input format.
1017
+ compileDefault: (expression) => dialect2.sqlToQuery(sql`select (${expression})::text`),
1018
+ checkTable: (schemaKey, table) => {
1019
+ const { schema } = getTableConfig(table);
1020
+ if (schema !== void 0 && schema !== "public") {
1021
+ throw createMarkdownSqlError(
1022
+ "CONFIG",
1023
+ `Table "${schemaKey}" is in the Postgres schema "${schema}". Only tables in the default schema are supported yet.`
1024
+ );
1025
+ }
1026
+ }
1027
+ };
1028
+ var literal = (value) => `'${value.replaceAll("'", "''")}'`;
1029
+ var enumDdl = (models) => {
1030
+ const enums = /* @__PURE__ */ new Map();
1031
+ for (const column of models.flatMap((model) => model.columns)) {
1032
+ const enumType = enumOf(column.column);
1033
+ if (enumType === void 0) {
1034
+ continue;
1035
+ }
1036
+ if (enumType.schema !== void 0 && enumType.schema !== "public") {
1037
+ throw createMarkdownSqlError(
1038
+ "CONFIG",
1039
+ `Enum "${enumType.enumName}" is in the Postgres schema "${enumType.schema}". Only the default schema is supported yet.`
1040
+ );
1041
+ }
1042
+ enums.set(enumType.enumName, enumType);
1043
+ }
1044
+ return [...enums.values()].map(
1045
+ (enumType) => `CREATE TYPE ${quoteIdentifier(enumType.enumName)} AS ENUM (${enumType.enumValues.map(literal).join(", ")})`
1046
+ );
1047
+ };
1048
+ var readVersion = async (file, name) => {
1049
+ try {
1050
+ const parsed = JSON.parse(await readFile(file, "utf8"));
1051
+ return isJsonObject(parsed) && parsed.name === name && typeof parsed.version === "string" ? parsed.version : void 0;
1052
+ } catch {
1053
+ return void 0;
1054
+ }
1055
+ };
1056
+ var packageVersion = async (name) => {
1057
+ let dir;
1058
+ try {
1059
+ dir = dirname(createRequire(import.meta.url).resolve(name));
1060
+ } catch {
1061
+ return void 0;
1062
+ }
1063
+ for (; ; ) {
1064
+ const version = await readVersion(join(dir, "package.json"), name);
1065
+ if (version !== void 0) {
1066
+ return version;
1067
+ }
1068
+ const parent = dirname(dir);
1069
+ if (parent === dir) {
1070
+ return void 0;
1071
+ }
1072
+ dir = parent;
1073
+ }
1074
+ };
1075
+
1076
+ // src/pg/snapshot.ts
1077
+ var PGLITE = "@electric-sql/pglite";
1078
+ var PREPOPULATED = "@electric-sql/pglite-prepopulatedfs";
1079
+ var defaultSource = {
1080
+ version: packageVersion,
1081
+ load: async () => {
1082
+ const { dataDir } = await import('@electric-sql/pglite-prepopulatedfs');
1083
+ return dataDir();
1084
+ }
1085
+ };
1086
+ var chooseSnapshot = async (prepopulated, source = defaultSource) => {
1087
+ if (prepopulated === false) {
1088
+ return { dataDir: void 0 };
1089
+ }
1090
+ const required = prepopulated === true;
1091
+ const [pgliteVersion, snapshotVersion] = await Promise.all([
1092
+ source.version(PGLITE),
1093
+ source.version(PREPOPULATED)
1094
+ ]);
1095
+ const fail = (message, cause) => {
1096
+ if (required) {
1097
+ throw createMarkdownSqlError(
1098
+ "CONFIG",
1099
+ `prepopulated: true, but ${message}`,
1100
+ cause === void 0 ? {} : { cause }
1101
+ );
1102
+ }
1103
+ return { dataDir: void 0, warning: `${message}; starting PGlite without the snapshot.` };
1104
+ };
1105
+ if (snapshotVersion === void 0) {
1106
+ return required ? fail(`${PREPOPULATED} is not installed`) : { dataDir: void 0 };
1107
+ }
1108
+ if (snapshotVersion !== pgliteVersion) {
1109
+ return fail(
1110
+ `${PREPOPULATED} ${snapshotVersion} does not match ${PGLITE} ${pgliteVersion ?? "(not found)"}; install the same version of both`
1111
+ );
1112
+ }
1113
+ try {
1114
+ return { dataDir: await source.load() };
1115
+ } catch (error) {
1116
+ const cause = error instanceof Error ? error : new Error(String(error));
1117
+ return fail(`loading the ${PREPOPULATED} snapshot failed: ${cause.message}`, cause);
1118
+ }
1119
+ };
1120
+
1121
+ // src/pg/drizzle-md.ts
1122
+ var READER_ROLE = "md_reader";
1123
+ var READ_ONLY_STATES = ["25006", "25001", "42501"];
1124
+ var isPgReadOnlyError = (error) => error instanceof Error && "code" in error && typeof error.code === "string" && READ_ONLY_STATES.includes(error.code);
1125
+ var RAW_DATES = {
1126
+ [types.TIMESTAMP]: (value) => value,
1127
+ [types.TIMESTAMPTZ]: (value) => value,
1128
+ [types.INTERVAL]: (value) => value,
1129
+ [types.DATE]: (value) => value
1130
+ };
1131
+ var toError = (error) => error instanceof Error ? error : new Error(String(error));
1132
+ var drizzleMd = async (options) => {
1133
+ const models = buildModels(options.schema, options.tables, pgDialect);
1134
+ const enums = enumDdl(models);
1135
+ const indexes = indexDdl(models);
1136
+ const snapshot = await chooseSnapshot(options.prepopulated);
1137
+ if (snapshot.warning !== void 0) {
1138
+ options.onDiagnostic?.({
1139
+ code: "startup-warning",
1140
+ table: "",
1141
+ file: "",
1142
+ message: snapshot.warning
1143
+ });
1144
+ }
1145
+ const pgliteOptions = options.pglite ?? {};
1146
+ const client = await PGlite.create({
1147
+ ...pgliteOptions,
1148
+ ...snapshot.dataDir === void 0 ? {} : { loadDataDir: snapshot.dataDir },
1149
+ extensions: { ...pgliteOptions.extensions, live: live }
1150
+ });
1151
+ const createIndexes = async (statements) => {
1152
+ for (const statement of statements) {
1153
+ try {
1154
+ await client.exec(statement.sql);
1155
+ } catch (error) {
1156
+ throw createMarkdownSqlError(
1157
+ "CONFIG",
1158
+ `Table "${statement.table}", index ${statement.label} could not be created: ${error instanceof Error ? error.message : String(error)}`,
1159
+ error instanceof Error ? { cause: error } : {}
1160
+ );
1161
+ }
1162
+ }
1163
+ };
1164
+ try {
1165
+ await client.exec(
1166
+ [
1167
+ ...enums,
1168
+ ...models.map((model) => model.ddl),
1169
+ ...options.setup === void 0 ? [] : [options.setup]
1170
+ ].join(";\n")
1171
+ );
1172
+ await createIndexes(indexes.filter((statement) => statement.unique));
1173
+ await client.exec(
1174
+ [
1175
+ `CREATE ROLE ${READER_ROLE} NOLOGIN`,
1176
+ `GRANT USAGE ON SCHEMA public TO ${READER_ROLE}`,
1177
+ `GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${READER_ROLE}`
1178
+ ].join(";\n")
1179
+ );
1180
+ } catch (error) {
1181
+ await client.close();
1182
+ throw error;
1183
+ }
1184
+ const subscriptions = /* @__PURE__ */ new Set();
1185
+ const index = await openIndex({
1186
+ options,
1187
+ models,
1188
+ backend: createPgliteBackend(client),
1189
+ // Other indexes are built once over the loaded rows, which is faster than updating them per row.
1190
+ afterLoad: async () => {
1191
+ await createIndexes(indexes.filter((statement) => !statement.unique));
1192
+ await client.exec("ANALYZE");
1193
+ },
1194
+ closeBackend: async () => {
1195
+ for (const subscription of [...subscriptions]) {
1196
+ await subscription.unsubscribe();
1197
+ }
1198
+ await client.close();
1199
+ }
1200
+ });
1201
+ const callback = async (statement, params, method) => {
1202
+ if (index.isClosed()) {
1203
+ throw closedError();
1204
+ }
1205
+ if (!READ_STATEMENT.test(statement)) {
1206
+ throw readOnlyError(statement);
1207
+ }
1208
+ try {
1209
+ const rows = await client.transaction(async (tx) => {
1210
+ await tx.exec(`SET TRANSACTION READ ONLY; SET LOCAL ROLE ${READER_ROLE}`);
1211
+ try {
1212
+ const result = await tx.query(statement, params, {
1213
+ rowMode: method === "all" ? "array" : "object",
1214
+ parsers: RAW_DATES
1215
+ });
1216
+ return result.rows;
1217
+ } finally {
1218
+ await tx.rollback();
1219
+ }
1220
+ });
1221
+ return { rows };
1222
+ } catch (error) {
1223
+ if (isPgReadOnlyError(error) && findMarkdownSqlError(error) === void 0) {
1224
+ throw readOnlyError(statement, error);
1225
+ }
1226
+ throw error;
1227
+ }
1228
+ };
1229
+ const db = drizzle(callback, { schema: options.schema });
1230
+ const live$1 = async (query, onResult, onError = () => void 0) => {
1231
+ await query;
1232
+ const { sql: text, params } = query.toSQL();
1233
+ let active = true;
1234
+ let created = false;
1235
+ let runs = Promise.resolve();
1236
+ const rerun = () => {
1237
+ runs = runs.then(async () => {
1238
+ if (!active) {
1239
+ return;
1240
+ }
1241
+ try {
1242
+ const result = await query;
1243
+ if (active) {
1244
+ onResult(result);
1245
+ }
1246
+ } catch (error) {
1247
+ onError(toError(error));
1248
+ }
1249
+ });
1250
+ };
1251
+ const handle = await client.live.query(text, params, () => {
1252
+ if (created) {
1253
+ rerun();
1254
+ }
1255
+ });
1256
+ created = true;
1257
+ const subscription = {
1258
+ unsubscribe: async () => {
1259
+ if (!active) {
1260
+ return;
1261
+ }
1262
+ active = false;
1263
+ subscriptions.delete(subscription);
1264
+ await handle.unsubscribe();
1265
+ await runs;
1266
+ }
1267
+ };
1268
+ rerun();
1269
+ await runs;
1270
+ subscriptions.add(subscription);
1271
+ return subscription;
1272
+ };
1273
+ const { isClosed: _, ...rest } = index;
1274
+ return { db, live: live$1, ...rest };
1275
+ };
1276
+
1277
+ export { drizzleMd, findMarkdownSqlError, formatDiagnostic, isMarkdownSqlError, parseMarkdown };
1278
+ //# sourceMappingURL=pg.js.map
1279
+ //# sourceMappingURL=pg.js.map