hekireki 0.46.0 → 0.48.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 (39) hide show
  1. package/README.md +19 -6
  2. package/dist/bin/activerecord.js +1 -1
  3. package/dist/bin/ajv.js +1 -1
  4. package/dist/bin/arktype.js +1 -1
  5. package/dist/bin/atlas.js +1 -1
  6. package/dist/bin/django.js +1 -1
  7. package/dist/bin/docs.d.ts +1 -0
  8. package/dist/bin/docs.js +5 -0
  9. package/dist/bin/drizzle.js +1 -1
  10. package/dist/bin/ecto.js +1 -1
  11. package/dist/bin/efcore.js +1 -1
  12. package/dist/bin/effect.js +1 -1
  13. package/dist/bin/eloquent.js +1 -1
  14. package/dist/bin/er.js +1 -1
  15. package/dist/bin/exposed.js +1 -1
  16. package/dist/bin/gorm.js +1 -1
  17. package/dist/bin/hekireki.js +5 -5
  18. package/dist/bin/kysely.js +1 -1
  19. package/dist/bin/openapi.js +1 -1
  20. package/dist/bin/pydantic.js +1 -1
  21. package/dist/bin/sea-orm.js +1 -1
  22. package/dist/bin/seed.js +1 -1
  23. package/dist/bin/sqlalchemy.js +1 -1
  24. package/dist/bin/typebox.js +1 -1
  25. package/dist/bin/valibot.js +1 -1
  26. package/dist/bin/zod.js +1 -1
  27. package/dist/{bin-Cqjn5U_r.js → bin-CVcdvi5w.js} +6311 -5388
  28. package/dist/{discover-Dyzb_7x-.js → discover-kVbu9DxT.js} +2 -1
  29. package/dist/{emit-CbBm_I0C.js → emit-DF8ehOFH.js} +1 -1
  30. package/dist/{schema-BRtObhQG.js → errors-0PjX4y1Z.js} +218 -2
  31. package/dist/{migrate-B-EMC7CC.js → migrate-U9pCkJTm.js} +4 -3
  32. package/dist/native-engine-D1iZDp41.js +537 -0
  33. package/dist/{plan-DVBOCKsd.js → plan-ChzbNv7_.js} +5 -220
  34. package/dist/{run-BKHmqvBJ.js → run-Caiu7ebD.js} +4 -4
  35. package/dist/schema-DzF7tKzG.js +571 -0
  36. package/dist/{sql-BYvD2bjK.js → sql-DciD3-lE.js} +30 -300
  37. package/dist/{start-KD0RjI3H.js → start-C1n6SWZ3.js} +8 -505
  38. package/package.json +2 -1
  39. package/dist/prisma-model-D98BBcmY.js +0 -287
@@ -0,0 +1,537 @@
1
+ import { a as readBytes, o as readDirectory, t as exists } from "./file-BAVQ-zst.js";
2
+ import { o as environmentVariable } from "./schema-DzF7tKzG.js";
3
+ import { a as splitStatements, c as sqliteAffinity, r as MigrateEngineError } from "./errors-0PjX4y1Z.js";
4
+ import { createRequire } from "node:module";
5
+ import { Effect, Semaphore, Stream } from "effect";
6
+ import path from "node:path";
7
+ import * as z from "zod";
8
+ import { pathToFileURL } from "node:url";
9
+ import { spawn } from "node:child_process";
10
+ import { createInterface } from "node:readline";
11
+ import { text } from "node:stream/consumers";
12
+ import { getEnginesPath } from "@prisma/engines";
13
+ // src/migrate/adapter/column-types.ts
14
+ /**
15
+ * The `ColumnType` codes the Prisma schema engine reads a result set by; it converts every value
16
+ * it is handed according to the code the column was given, so a wrong code is a wrong value.
17
+ * Taken from `ColumnTypeEnum` of `@prisma/driver-adapter-utils`.
18
+ */
19
+ const COLUMN_TYPE = {
20
+ int32: 0,
21
+ int64: 1,
22
+ float: 2,
23
+ double: 3,
24
+ numeric: 4,
25
+ boolean: 5,
26
+ character: 6,
27
+ text: 7,
28
+ date: 8,
29
+ time: 9,
30
+ datetime: 10,
31
+ json: 11,
32
+ enum: 12,
33
+ bytes: 13,
34
+ set: 14,
35
+ uuid: 15,
36
+ int32Array: 64,
37
+ int64Array: 65,
38
+ floatArray: 66,
39
+ doubleArray: 67,
40
+ numericArray: 68,
41
+ booleanArray: 69,
42
+ characterArray: 70,
43
+ textArray: 71,
44
+ dateArray: 72,
45
+ timeArray: 73,
46
+ datetimeArray: 74,
47
+ jsonArray: 75,
48
+ enumArray: 76,
49
+ bytesArray: 77,
50
+ uuidArray: 78
51
+ };
52
+ /** The type OID of `pg_type`, as `pg` reports it on every column it returns. */
53
+ const POSTGRES_OIDS = {
54
+ 16: COLUMN_TYPE.boolean,
55
+ 17: COLUMN_TYPE.bytes,
56
+ 18: COLUMN_TYPE.character,
57
+ 19: COLUMN_TYPE.text,
58
+ 20: COLUMN_TYPE.int64,
59
+ 21: COLUMN_TYPE.int32,
60
+ 23: COLUMN_TYPE.int32,
61
+ 25: COLUMN_TYPE.text,
62
+ 26: COLUMN_TYPE.int64,
63
+ 114: COLUMN_TYPE.json,
64
+ 700: COLUMN_TYPE.float,
65
+ 701: COLUMN_TYPE.double,
66
+ 1042: COLUMN_TYPE.character,
67
+ 1043: COLUMN_TYPE.text,
68
+ 1082: COLUMN_TYPE.date,
69
+ 1083: COLUMN_TYPE.time,
70
+ 1114: COLUMN_TYPE.datetime,
71
+ 1184: COLUMN_TYPE.datetime,
72
+ 1266: COLUMN_TYPE.time,
73
+ 1700: COLUMN_TYPE.numeric,
74
+ 2950: COLUMN_TYPE.uuid,
75
+ 3802: COLUMN_TYPE.json,
76
+ 1e3: COLUMN_TYPE.booleanArray,
77
+ 1001: COLUMN_TYPE.bytesArray,
78
+ 1002: COLUMN_TYPE.characterArray,
79
+ 1005: COLUMN_TYPE.int32Array,
80
+ 1007: COLUMN_TYPE.int32Array,
81
+ 1009: COLUMN_TYPE.textArray,
82
+ 1014: COLUMN_TYPE.characterArray,
83
+ 1015: COLUMN_TYPE.textArray,
84
+ 1016: COLUMN_TYPE.int64Array,
85
+ 1021: COLUMN_TYPE.floatArray,
86
+ 1022: COLUMN_TYPE.doubleArray,
87
+ 1028: COLUMN_TYPE.int64Array,
88
+ 1115: COLUMN_TYPE.datetimeArray,
89
+ 1182: COLUMN_TYPE.dateArray,
90
+ 1183: COLUMN_TYPE.timeArray,
91
+ 1185: COLUMN_TYPE.datetimeArray,
92
+ 1231: COLUMN_TYPE.numericArray,
93
+ 199: COLUMN_TYPE.jsonArray,
94
+ 3807: COLUMN_TYPE.jsonArray,
95
+ 2951: COLUMN_TYPE.uuidArray
96
+ };
97
+ /** The type code of the MySQL protocol, as `mysql2` reports it on every column. */
98
+ const MYSQL_CODES = {
99
+ 0: COLUMN_TYPE.numeric,
100
+ 1: COLUMN_TYPE.int32,
101
+ 2: COLUMN_TYPE.int32,
102
+ 3: COLUMN_TYPE.int32,
103
+ 4: COLUMN_TYPE.float,
104
+ 5: COLUMN_TYPE.double,
105
+ 7: COLUMN_TYPE.datetime,
106
+ 8: COLUMN_TYPE.int64,
107
+ 9: COLUMN_TYPE.int32,
108
+ 10: COLUMN_TYPE.date,
109
+ 11: COLUMN_TYPE.time,
110
+ 12: COLUMN_TYPE.datetime,
111
+ 13: COLUMN_TYPE.int32,
112
+ 15: COLUMN_TYPE.text,
113
+ 16: COLUMN_TYPE.bytes,
114
+ 245: COLUMN_TYPE.json,
115
+ 246: COLUMN_TYPE.numeric,
116
+ 247: COLUMN_TYPE.enum,
117
+ 248: COLUMN_TYPE.set,
118
+ 249: COLUMN_TYPE.bytes,
119
+ 250: COLUMN_TYPE.bytes,
120
+ 251: COLUMN_TYPE.bytes,
121
+ 252: COLUMN_TYPE.bytes,
122
+ 253: COLUMN_TYPE.text,
123
+ 254: COLUMN_TYPE.text,
124
+ 255: COLUMN_TYPE.bytes
125
+ };
126
+ /** The declared type of a SQLite column; a `PRAGMA` or an expression has none. */
127
+ function sqliteColumnType(declared) {
128
+ const upper = declared.toUpperCase().replace(/\(.*\)$/u, "").trim();
129
+ if (upper === "BOOLEAN") return COLUMN_TYPE.boolean;
130
+ if (upper === "DATETIME" || upper === "TIMESTAMP") return COLUMN_TYPE.datetime;
131
+ if (upper === "DATE") return COLUMN_TYPE.date;
132
+ if (upper === "TIME") return COLUMN_TYPE.time;
133
+ if (upper === "JSON" || upper === "JSONB") return COLUMN_TYPE.json;
134
+ if (upper === "BLOB") return COLUMN_TYPE.bytes;
135
+ if (upper === "DECIMAL" || upper === "NUMERIC") return COLUMN_TYPE.numeric;
136
+ const affinity = sqliteAffinity(upper);
137
+ if (affinity === "integer") return COLUMN_TYPE.int64;
138
+ if (affinity === "text") return COLUMN_TYPE.text;
139
+ if (affinity === "real") return COLUMN_TYPE.double;
140
+ return null;
141
+ }
142
+ /** What a value says about its column, for a column the database gives no type for. */
143
+ function columnTypeOfValue(value) {
144
+ if (typeof value === "bigint") return COLUMN_TYPE.int64;
145
+ if (typeof value === "number") return Number.isInteger(value) ? COLUMN_TYPE.int32 : COLUMN_TYPE.double;
146
+ if (typeof value === "boolean") return COLUMN_TYPE.boolean;
147
+ if (value instanceof Uint8Array) return COLUMN_TYPE.bytes;
148
+ return COLUMN_TYPE.text;
149
+ }
150
+ /**
151
+ * The `ColumnType` of a column as the database types it: the OID on PostgreSQL, the protocol type
152
+ * code on MySQL, the declared type on SQLite. Null for a type not listed, and for the columns of a
153
+ * `PRAGMA`, so the caller reads those from the values instead.
154
+ */
155
+ function columnTypeOfNative(dialect, nativeType) {
156
+ if (nativeType === null) return null;
157
+ if (dialect === "postgresql") return typeof nativeType === "number" ? POSTGRES_OIDS[nativeType] ?? null : null;
158
+ if (dialect === "mysql") return typeof nativeType === "number" ? MYSQL_CODES[nativeType] ?? null : null;
159
+ return typeof nativeType === "string" ? sqliteColumnType(nativeType) : null;
160
+ }
161
+ // src/migrate/adapter/engine-adapter.ts
162
+ function engineSuccess(value) {
163
+ return {
164
+ ok: true,
165
+ value,
166
+ map: (fn) => engineSuccess(fn(value)),
167
+ flatMap: (fn) => fn(value)
168
+ };
169
+ }
170
+ function engineFailure(error) {
171
+ return {
172
+ ok: false,
173
+ error,
174
+ map: () => engineFailure(error),
175
+ flatMap: () => engineFailure(error)
176
+ };
177
+ }
178
+ /**
179
+ * A driver failure as the engine reads it. The message is what reaches the user; the codes are
180
+ * each dialect's "unspecified error", because `Driver` reports a failure as its message and the
181
+ * engine acts on none of the others.
182
+ */
183
+ function adapterError(dialect, message) {
184
+ if (dialect === "postgresql") return {
185
+ kind: "postgres",
186
+ code: "XX000",
187
+ severity: "ERROR",
188
+ message,
189
+ detail: void 0,
190
+ column: void 0,
191
+ hint: void 0
192
+ };
193
+ if (dialect === "mysql") return {
194
+ kind: "mysql",
195
+ code: 1105,
196
+ message,
197
+ state: "HY000"
198
+ };
199
+ return {
200
+ kind: "sqlite",
201
+ extendedCode: 1,
202
+ message
203
+ };
204
+ }
205
+ /** The three column types the engine reads as a string, whatever the database keeps them as. */
206
+ const INSTANTS = /* @__PURE__ */ new Set([
207
+ COLUMN_TYPE.datetime,
208
+ COLUMN_TYPE.date,
209
+ COLUMN_TYPE.time
210
+ ]);
211
+ /** What the engine sends to hold a SQLite file for itself: `PRAGMA main.locking_mode=EXCLUSIVE`. */
212
+ const EXCLUSIVE_LOCK = /^\s*PRAGMA\s+(?:\w+\.)?locking_mode\s*=\s*EXCLUSIVE\s*;?\s*$/iu;
213
+ /** Runs a driver operation for the engine, its failure handed back as an error the engine reads. */
214
+ function runForEngine(dialect, operation) {
215
+ return Effect.runPromise(operation.pipe(Effect.match({
216
+ onFailure: (error) => engineFailure(adapterError(dialect, error.cause)),
217
+ onSuccess: (value) => engineSuccess(value)
218
+ })));
219
+ }
220
+ /**
221
+ * The open connection the engine sends its statements through. Only `queryRaw`, `executeRaw` and
222
+ * `executeScript` are ever reached for: the schema engine reads catalogues and runs DDL, and does
223
+ * none of the value conversion the query engine needs a full adapter for.
224
+ */
225
+ function connection(driver, dispose = () => Promise.resolve(engineSuccess(void 0))) {
226
+ return {
227
+ provider: driver.dialect === "postgresql" ? "postgres" : driver.dialect,
228
+ adapterName: "hekireki",
229
+ queryRaw: (query) => runForEngine(driver.dialect, driver.queryRaw({
230
+ sql: query.sql,
231
+ params: query.args
232
+ }).pipe(Effect.map((rows) => {
233
+ const columnTypes = rows.columns.map((column, index) => {
234
+ const declared = columnTypeOfNative(driver.dialect, column.nativeType);
235
+ if (declared !== null) return declared;
236
+ return columnTypeOfValue(rows.rows.find((candidate) => candidate[index] !== null)?.[index] ?? null);
237
+ });
238
+ return {
239
+ columnNames: rows.columns.map((column) => column.name),
240
+ columnTypes,
241
+ rows: rows.rows.map((row) => row.map((value, index) => {
242
+ const plain = typeof value === "bigint" ? Number(value) : value;
243
+ return INSTANTS.has(columnTypes[index] ?? COLUMN_TYPE.text) && typeof plain === "number" ? new Date(plain).toISOString() : plain;
244
+ }))
245
+ };
246
+ }))),
247
+ executeRaw: (query) => driver.dialect === "sqlite" && EXCLUSIVE_LOCK.test(query.sql) ? Promise.resolve(engineSuccess(0)) : query.args.length === 0 && splitStatements(query.sql).filter((statement) => statement.trim() !== "").length > 1 ? runForEngine(driver.dialect, driver.executeScript(query.sql).pipe(Effect.as(0))) : runForEngine(driver.dialect, driver.executeRaw({
248
+ sql: query.sql,
249
+ params: query.args
250
+ })),
251
+ executeScript: (script) => runForEngine(driver.dialect, driver.executeScript(script)),
252
+ dispose
253
+ };
254
+ }
255
+ /**
256
+ * The database Studio already has open, as the Prisma schema engine takes it. Studio ships no
257
+ * driver adapter of its own and reaches for none in the project: the connection the rest of
258
+ * Studio reads and writes through is the one the engine migrates. `dispose` does nothing, because
259
+ * the connection outlives any one command and is closed with Studio itself.
260
+ *
261
+ * @param driver - the open connection every statement of the engine goes through
262
+ * @returns the adapter factory `openSchemaEngine` is given
263
+ */
264
+ function makeSchemaEngineAdapter(driver, openShadow) {
265
+ const opened = connection(driver);
266
+ return {
267
+ provider: opened.provider,
268
+ adapterName: opened.adapterName,
269
+ connect: () => Promise.resolve(engineSuccess(opened)),
270
+ ...openShadow === void 0 ? {} : { connectToShadowDb: () => runForEngine(driver.dialect, openShadow().pipe(Effect.mapError((error) => ({ cause: error.reason })), Effect.map((shadow) => connection(shadow, () => Effect.runPromise(shadow.close.pipe(Effect.as(engineSuccess(void 0)))))))) }
271
+ };
272
+ }
273
+ /**
274
+ * An adapter with no database behind it, for the commands that read only the schema: the
275
+ * migration from an empty database to it. The engine still connects as it starts, and asks
276
+ * PostgreSQL for its version and to make `public`; every statement is answered with nothing,
277
+ * which is what an empty database has to say.
278
+ *
279
+ * @param dialect - the SQL the engine writes: PostgreSQL's or SQLite's (the wasm engine has no
280
+ * MySQL connector)
281
+ * @returns the adapter factory `openSchemaEngine` is given
282
+ */
283
+ function makeOfflineSchemaEngineAdapter(dialect) {
284
+ const provider = dialect === "postgresql" ? "postgres" : dialect;
285
+ const empty = {
286
+ columnNames: [],
287
+ columnTypes: [],
288
+ rows: []
289
+ };
290
+ return {
291
+ provider,
292
+ adapterName: "hekireki",
293
+ connect: () => Promise.resolve(engineSuccess({
294
+ provider,
295
+ adapterName: "hekireki",
296
+ queryRaw: () => Promise.resolve(engineSuccess(empty)),
297
+ executeRaw: () => Promise.resolve(engineSuccess(0)),
298
+ executeScript: () => Promise.resolve(engineSuccess(void 0)),
299
+ dispose: () => Promise.resolve(engineSuccess(void 0))
300
+ }))
301
+ };
302
+ }
303
+ // src/migrate/adapter/engine.ts
304
+ const WasmStart = z.custom((value) => typeof value === "function").meta({ description: "The start hook wasm-bindgen puts on the instantiated module." });
305
+ /**
306
+ * Where a panic in the engine writes its message before the WebAssembly trap unwinds. Without
307
+ * this global the trap surfaces as `Cannot read properties of undefined (reading 'set_message')`,
308
+ * which says nothing about what went wrong.
309
+ */
310
+ const panics = { message: null };
311
+ /**
312
+ * What a failed command is reported as: the panic the engine wrote, else the thrown error. The
313
+ * panic is taken as it is read, so a later failure cannot report a stale one.
314
+ */
315
+ function engineError(error) {
316
+ const { message } = panics;
317
+ panics.message = null;
318
+ return new MigrateEngineError({ message: message ?? (error instanceof Error ? error.message : String(error)) });
319
+ }
320
+ /**
321
+ * The bindings, instantiated once. `schema_engine_bg.js` holds the instance in a module-level
322
+ * cell that `__wbg_set_wasm` writes, so a second instantiation would pull the memory out from
323
+ * under the first engine.
324
+ */
325
+ const loaded = { bindings: null };
326
+ const lock = Semaphore.makeUnsafe(1);
327
+ function instantiate() {
328
+ return Effect.gen(function* () {
329
+ const entry = yield* Effect.try({
330
+ try: () => createRequire(import.meta.url).resolve("@prisma/schema-engine-wasm/schema_engine_bg"),
331
+ catch: engineError
332
+ });
333
+ const bindings = yield* Effect.tryPromise({
334
+ try: () => import(pathToFileURL(entry).href),
335
+ catch: engineError
336
+ });
337
+ const bytes = yield* readBytes(path.join(path.dirname(entry), "schema_engine_bg.wasm")).pipe(Effect.mapError(engineError));
338
+ return yield* Effect.try({
339
+ try: () => {
340
+ const instance = new WebAssembly.Instance(new WebAssembly.Module(Uint8Array.from(bytes)), { "./schema_engine_bg.js": bindings });
341
+ const result = WasmStart.safeParse(instance.exports.__wbindgen_start);
342
+ if (!result.success) throw new TypeError("The engine module exports no __wbindgen_start.");
343
+ bindings.__wbg_set_wasm(instance.exports);
344
+ result.data();
345
+ return bindings;
346
+ },
347
+ catch: engineError
348
+ });
349
+ });
350
+ }
351
+ /** The bindings of the engine, loaded the first time they are asked for. */
352
+ function schemaEngineBindings() {
353
+ return Effect.gen(function* () {
354
+ Reflect.set(globalThis, "PRISMA_WASM_PANIC_REGISTRY", { set_message: (message) => {
355
+ panics.message = message;
356
+ } });
357
+ if (loaded.bindings !== null) return loaded.bindings;
358
+ const bindings = yield* instantiate();
359
+ loaded.bindings = bindings;
360
+ return bindings;
361
+ }).pipe(Semaphore.withPermit(lock));
362
+ }
363
+ /**
364
+ * An engine connected through `adapter`, reading `files` as its datamodel. The engine panics on
365
+ * an empty datamodel (`psl::validate_multi_file() must be called with at least one file`), so
366
+ * only a schema that parsed is ever handed to it.
367
+ *
368
+ * @param input - the schema files the commands are read against, the adapter every statement
369
+ * goes through, and where the engine's log lines go
370
+ */
371
+ function openSchemaEngine(input) {
372
+ return Effect.gen(function* () {
373
+ if (input.files.length === 0) return yield* new MigrateEngineError({ message: "The schema engine needs at least one schema file." });
374
+ const bindings = yield* schemaEngineBindings();
375
+ return yield* Effect.tryPromise({
376
+ try: () => bindings.SchemaEngine.new({ datamodels: input.files.map((file) => [file.path, file.content]) }, input.onLog ?? ((line) => line), input.adapter),
377
+ catch: engineError
378
+ });
379
+ });
380
+ }
381
+ /** Sends one command to the engine, a panic reported as the message the engine wrote. */
382
+ function engineCommand(run) {
383
+ return Effect.tryPromise({
384
+ try: run,
385
+ catch: engineError
386
+ });
387
+ }
388
+ // src/migrate/adapter/native-engine.ts
389
+ const RpcMessage = z.object({
390
+ id: z.number().optional().meta({
391
+ description: "The request it answers, or its own.",
392
+ example: 1
393
+ }),
394
+ method: z.string().optional().meta({
395
+ description: "A request of the engine to its caller.",
396
+ example: "print"
397
+ }),
398
+ params: z.object({ content: z.string().optional().meta({
399
+ description: "What to print.",
400
+ example: "-- AlterTable"
401
+ }) }).optional().meta({ description: "The parameters of a request of the engine." }),
402
+ result: z.unknown().optional().meta({ description: "What the command returned." }),
403
+ error: z.object({
404
+ message: z.string().meta({
405
+ description: "The JSON-RPC message.",
406
+ example: "An error happened."
407
+ }),
408
+ data: z.object({ message: z.string().optional().meta({
409
+ description: "The engine's own words for it.",
410
+ example: "P3005"
411
+ }) }).optional().meta({ description: "What the engine adds to it." })
412
+ }).optional().meta({ description: "Why the command failed." })
413
+ }).meta({ description: "One line the schema engine writes on its stdout" });
414
+ const DiffResult = z.custom((value) => typeof value === "object" && value !== null && "exitCode" in value).meta({ description: "What `diff` returns: its exit code, and the script when it was not printed." });
415
+ const DiagnoseResult = z.custom((value) => typeof value === "object" && value !== null && "failedMigrationNames" in value).meta({ description: "What `diagnoseMigrationHistory` returns." });
416
+ const ApplyResult = z.custom((value) => typeof value === "object" && value !== null && "appliedMigrationNames" in value).meta({ description: "What `applyMigrations` returns." });
417
+ const MarkedResult = z.custom((value) => typeof value === "object" && value !== null).meta({ description: "What `markMigrationApplied` and `markMigrationRolledBack` return." });
418
+ /**
419
+ * Where the native schema engine is: `PRISMA_SCHEMA_ENGINE_BINARY` when it is set, as the Prisma
420
+ * CLI reads it, else the `schema-engine-<platform>` `@prisma/engines` downloaded as it installed.
421
+ *
422
+ * @param cwd - what a relative `PRISMA_SCHEMA_ENGINE_BINARY` is resolved from
423
+ * @returns the binary, or null when there is none to run
424
+ */
425
+ function findSchemaEngineBinary(cwd) {
426
+ return Effect.gen(function* () {
427
+ const configured = yield* environmentVariable("PRISMA_SCHEMA_ENGINE_BINARY");
428
+ if (configured !== null) {
429
+ const file = path.resolve(cwd, configured);
430
+ return (yield* exists(file).pipe(Effect.orElseSucceed(() => false))) ? file : null;
431
+ }
432
+ const directory = yield* Effect.try({
433
+ try: () => getEnginesPath(),
434
+ catch: () => null
435
+ }).pipe(Effect.orElseSucceed(() => null));
436
+ if (directory === null) return null;
437
+ const found = (yield* readDirectory(directory).pipe(Effect.orElseSucceed(() => []))).find((name) => /^schema-engine-[\w.-]+$/u.test(name) && !name.endsWith(".gz"));
438
+ return found === void 0 ? null : path.join(directory, found);
439
+ });
440
+ }
441
+ /**
442
+ * One command of the native engine: the binary started on the schema and the URL, the request
443
+ * written, every `print` it asks for answered (a script it writes comes that way, not in the
444
+ * result), and the binary let go once it has answered. A process per command: the datamodel is
445
+ * fixed when the engine starts, and nothing is left running between requests.
446
+ */
447
+ async function command(input, method, params) {
448
+ const child = spawn(input.binary, [
449
+ ...input.files.flatMap((file) => ["--datamodels", file.path]),
450
+ "--datasource",
451
+ JSON.stringify({ url: input.url })
452
+ ], {
453
+ cwd: input.cwd,
454
+ stdio: [
455
+ "pipe",
456
+ "pipe",
457
+ "pipe"
458
+ ],
459
+ env: {
460
+ ...process.env,
461
+ RUST_BACKTRACE: "1"
462
+ }
463
+ });
464
+ const lines = createInterface({
465
+ input: child.stdout,
466
+ crlfDelay: Infinity
467
+ });
468
+ lines.on("line", (line) => {
469
+ const message = RpcMessage.safeParse(JSON.parse(line));
470
+ if (!message.success) return;
471
+ if (message.data.method === "print") child.stdin.write(`${JSON.stringify({
472
+ jsonrpc: "2.0",
473
+ id: message.data.id,
474
+ result: {}
475
+ })}\n`);
476
+ else if (message.data.id === 1) child.stdin.end();
477
+ });
478
+ const logs = text(child.stderr);
479
+ child.stdin.write(`${JSON.stringify({
480
+ jsonrpc: "2.0",
481
+ id: 1,
482
+ method,
483
+ params
484
+ })}\n`);
485
+ const messages = (await Effect.runPromise(Stream.runCollect(Stream.fromAsyncIterable(lines, (error) => error)))).flatMap((line) => {
486
+ const message = RpcMessage.safeParse(JSON.parse(line));
487
+ return message.success ? [message.data] : [];
488
+ });
489
+ const answer = messages.find((message) => message.id === 1 && message.method === void 0);
490
+ if (answer === void 0) {
491
+ const written = await logs;
492
+ throw new Error(`The schema engine stopped without answering ${method}: ${written}`);
493
+ }
494
+ if (answer.error !== void 0) throw new Error(answer.error.data?.message ?? answer.error.message);
495
+ const printed = messages.flatMap((message) => message.method === "print" && message.params?.content !== void 0 ? [message.params.content] : []);
496
+ return {
497
+ result: answer.result,
498
+ printed
499
+ };
500
+ }
501
+ /**
502
+ * The native engine on the schema and the database's URL, answering the commands Studio sends
503
+ * with the shapes the wasm engine answers them with.
504
+ *
505
+ * @param input - the binary, the schema files (read from where they are), the URL and the directory
506
+ * the engine runs in
507
+ * @returns the engine
508
+ */
509
+ function openNativeSchemaEngine(input) {
510
+ return {
511
+ diff: async (params) => {
512
+ const { result, printed } = await command(input, "diff", params);
513
+ const read = DiffResult.parse(result);
514
+ return {
515
+ ...read,
516
+ stdout: printed.length === 0 ? read.stdout ?? null : `${printed.join("\n")}\n`
517
+ };
518
+ },
519
+ diagnoseMigrationHistory: async (params) => {
520
+ const { result } = await command(input, "diagnoseMigrationHistory", params);
521
+ return DiagnoseResult.parse(result);
522
+ },
523
+ applyMigrations: async (params) => {
524
+ const { result } = await command(input, "applyMigrations", params);
525
+ return ApplyResult.parse(result);
526
+ },
527
+ markMigrationApplied: async (params) => {
528
+ const { result } = await command(input, "markMigrationApplied", params);
529
+ return MarkedResult.parse(result);
530
+ },
531
+ markMigrationRolledBack: async (params) => {
532
+ const { result } = await command(input, "markMigrationRolledBack", params);
533
+ return MarkedResult.parse(result);
534
+ }
535
+ };
536
+ }
537
+ export { makeOfflineSchemaEngineAdapter as a, openSchemaEngine as i, openNativeSchemaEngine as n, makeSchemaEngineAdapter as o, engineCommand as r, findSchemaEngineBinary as t };