@kousaku-maron/diffshape 0.0.0-stage → 0.1.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.
@@ -0,0 +1,2316 @@
1
+ // ../core/src/git.ts
2
+ import { execFile, spawn } from "node:child_process";
3
+ import { readFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ var execFileAsync = promisify(execFile);
7
+ async function git(cwd, args) {
8
+ const { stdout } = await execFileAsync("git", args, {
9
+ cwd,
10
+ maxBuffer: 512 * 1024 * 1024
11
+ });
12
+ return stdout;
13
+ }
14
+ async function repoRoot(cwd) {
15
+ return (await git(cwd, ["rev-parse", "--show-toplevel"])).trim();
16
+ }
17
+ async function resolveRev(root, rev) {
18
+ try {
19
+ return (await git(root, ["rev-parse", "--verify", "--quiet", `${rev}^{commit}`])).trim();
20
+ } catch {
21
+ throw new Error(`\u30EA\u30D3\u30B8\u30E7\u30F3 '${rev}' \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`);
22
+ }
23
+ }
24
+ async function mergeBase(root, a, b) {
25
+ return (await git(root, ["merge-base", a, b])).trim();
26
+ }
27
+ async function listFiles(root, source) {
28
+ let out;
29
+ switch (source.kind) {
30
+ case "rev":
31
+ out = await git(root, ["ls-tree", "-r", "-z", "--name-only", source.rev]);
32
+ break;
33
+ case "index":
34
+ out = await git(root, ["ls-files", "-z", "--cached"]);
35
+ break;
36
+ case "worktree":
37
+ out = await git(root, ["ls-files", "-z", "--cached", "--others", "--exclude-standard"]);
38
+ break;
39
+ }
40
+ return [...new Set(out.split("\0").filter(Boolean))];
41
+ }
42
+ async function readFiles(root, source, paths) {
43
+ const result = /* @__PURE__ */ new Map();
44
+ if (paths.length === 0) return result;
45
+ if (source.kind === "worktree") {
46
+ await Promise.all(
47
+ paths.map(async (p) => {
48
+ try {
49
+ result.set(p, await readFile(join(root, p), "utf8"));
50
+ } catch {
51
+ }
52
+ })
53
+ );
54
+ return result;
55
+ }
56
+ const prefix = source.kind === "rev" ? `${source.rev}:` : ":";
57
+ const blobs = await catFileBatch(root, paths.map((p) => prefix + p));
58
+ paths.forEach((p, i) => {
59
+ const b = blobs[i];
60
+ if (b !== null) result.set(p, b);
61
+ });
62
+ return result;
63
+ }
64
+ function catFileBatch(root, specs) {
65
+ return new Promise((resolve, reject) => {
66
+ const proc = spawn("git", ["cat-file", "--batch"], { cwd: root });
67
+ const chunks = [];
68
+ proc.stdout.on("data", (d) => chunks.push(d));
69
+ proc.on("error", reject);
70
+ proc.on("close", (code) => {
71
+ if (code !== 0) return reject(new Error(`git cat-file exited with ${code}`));
72
+ const buf = Buffer.concat(chunks);
73
+ const out = [];
74
+ let pos = 0;
75
+ for (let i = 0; i < specs.length; i++) {
76
+ const nl = buf.indexOf(10, pos);
77
+ const header = buf.subarray(pos, nl).toString("utf8");
78
+ pos = nl + 1;
79
+ if (header.endsWith(" missing") || header.endsWith(" ambiguous")) {
80
+ out.push(null);
81
+ continue;
82
+ }
83
+ const size = Number(header.split(" ")[2]);
84
+ out.push(buf.subarray(pos, pos + size).toString("utf8"));
85
+ pos += size + 1;
86
+ }
87
+ resolve(out);
88
+ });
89
+ proc.stdin.end(specs.join("\n") + "\n");
90
+ });
91
+ }
92
+
93
+ // ../core/src/compare.ts
94
+ async function resolveSources(cwd, opts) {
95
+ const root = await repoRoot(cwd);
96
+ const targetArg = opts.target ?? ".";
97
+ let target;
98
+ let defaultBase;
99
+ let targetLabel;
100
+ if (targetArg === ".") {
101
+ target = { kind: "worktree" };
102
+ defaultBase = "HEAD";
103
+ targetLabel = "\u4F5C\u696D\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\uFF08\u672A\u30B3\u30DF\u30C3\u30C8\u306E\u5909\u66F4\u3092\u542B\u3080\uFF09";
104
+ } else if (targetArg === "staged") {
105
+ target = { kind: "index" };
106
+ defaultBase = "HEAD";
107
+ targetLabel = "\u30B9\u30C6\u30FC\u30B8\u6E08\u307F\u306E\u5909\u66F4";
108
+ } else if (targetArg === "working") {
109
+ target = { kind: "worktree" };
110
+ defaultBase = { kind: "index" };
111
+ targetLabel = "\u672A\u30B9\u30C6\u30FC\u30B8\u306E\u5909\u66F4";
112
+ } else {
113
+ const rev = targetArg === "@" ? "HEAD" : targetArg;
114
+ target = { kind: "rev", rev: await resolveRev(root, rev) };
115
+ defaultBase = `${rev}^`;
116
+ targetLabel = rev;
117
+ }
118
+ let base;
119
+ let baseLabel;
120
+ if (opts.base) {
121
+ const baseRev = opts.base === "@" ? "HEAD" : opts.base;
122
+ if (opts.mergeBase) {
123
+ const other = target.kind === "rev" ? target.rev : "HEAD";
124
+ base = { kind: "rev", rev: await mergeBase(root, baseRev, other) };
125
+ baseLabel = `${baseRev} \u3068\u306E\u5206\u5C90\u70B9\uFF08merge-base: ${base.rev.slice(0, 8)}\uFF09`;
126
+ } else {
127
+ base = { kind: "rev", rev: await resolveRev(root, baseRev) };
128
+ baseLabel = baseRev;
129
+ }
130
+ } else if (typeof defaultBase === "string") {
131
+ base = { kind: "rev", rev: await resolveRev(root, defaultBase) };
132
+ baseLabel = defaultBase;
133
+ } else {
134
+ base = defaultBase;
135
+ baseLabel = "\u30B9\u30C6\u30FC\u30B8\u6E08\u307F\u306E\u72B6\u614B";
136
+ }
137
+ return { root, target, base, targetLabel, baseLabel };
138
+ }
139
+
140
+ // ../core/src/server.ts
141
+ import { spawn as spawn2 } from "node:child_process";
142
+ import { readFile as readFile2 } from "node:fs/promises";
143
+ import { createServer } from "node:http";
144
+ import { extname, join as join2, normalize } from "node:path";
145
+ var LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
146
+ function hostAllowed(listenHost, hostHeader) {
147
+ if (!LOOPBACK.has(listenHost)) return true;
148
+ if (!hostHeader) return false;
149
+ try {
150
+ return LOOPBACK.has(new URL(`http://${hostHeader}`).hostname);
151
+ } catch {
152
+ return false;
153
+ }
154
+ }
155
+ var MIME = {
156
+ ".html": "text/html; charset=utf-8",
157
+ ".js": "text/javascript; charset=utf-8",
158
+ ".css": "text/css; charset=utf-8",
159
+ ".svg": "image/svg+xml",
160
+ ".json": "application/json; charset=utf-8"
161
+ };
162
+ async function startServer(opts) {
163
+ const server = createServer(async (req, res) => {
164
+ try {
165
+ if (!hostAllowed(opts.host, req.headers.host)) {
166
+ res.writeHead(403, { "content-type": "text/plain; charset=utf-8" }).end("forbidden host");
167
+ return;
168
+ }
169
+ const url = new URL(req.url ?? "/", "http://localhost");
170
+ const handler = opts.api[url.pathname];
171
+ if (handler) {
172
+ const body2 = await handler(url);
173
+ res.writeHead(200, { "content-type": MIME[".json"], "cache-control": "no-store" });
174
+ res.end(JSON.stringify(body2));
175
+ return;
176
+ }
177
+ const rel = url.pathname === "/" ? "index.html" : normalize(url.pathname).replace(/^([/\\])+/, "");
178
+ if (rel.includes("..")) {
179
+ res.writeHead(400).end();
180
+ return;
181
+ }
182
+ const body = await readFile2(join2(opts.uiDir, rel)).catch(() => null);
183
+ if (!body) {
184
+ res.writeHead(404).end("not found");
185
+ return;
186
+ }
187
+ const cache = rel === "index.html" ? { "cache-control": "no-cache" } : {};
188
+ res.writeHead(200, { "content-type": MIME[extname(rel)] ?? "application/octet-stream", ...cache });
189
+ res.end(body);
190
+ } catch (e) {
191
+ res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
192
+ res.end(e instanceof Error ? e.message : String(e));
193
+ }
194
+ });
195
+ const port = await listen(server, opts.host, opts.port);
196
+ return { server, url: `http://${opts.host}:${port}` };
197
+ }
198
+ function listen(server, host, port, attempts = 20) {
199
+ return new Promise((resolve, reject) => {
200
+ const onError = (err) => {
201
+ server.off("listening", onListening);
202
+ if (err.code === "EADDRINUSE" && attempts > 1) {
203
+ resolve(listen(server, host, port + 1, attempts - 1));
204
+ } else {
205
+ reject(err);
206
+ }
207
+ };
208
+ const onListening = () => {
209
+ server.off("error", onError);
210
+ resolve(port);
211
+ };
212
+ server.once("error", onError);
213
+ server.once("listening", onListening);
214
+ server.listen(port, host);
215
+ });
216
+ }
217
+ function openBrowser(url) {
218
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
219
+ const cmdArgs = process.platform === "win32" ? ["/c", "start", "", url] : [url];
220
+ spawn2(cmd, cmdArgs, { stdio: "ignore", detached: true }).on("error", () => {
221
+ }).unref();
222
+ }
223
+
224
+ // ../dbshape/src/analyze.ts
225
+ import { posix as posix2 } from "node:path";
226
+ import { loadModule, parseSync } from "libpg-query";
227
+
228
+ // ../dbshape/src/diff.ts
229
+ var byName = (items, name) => new Map(items.map((i) => [name(i), i]));
230
+ function setDiff(before, after) {
231
+ const b = new Set(before);
232
+ const a = new Set(after);
233
+ return { added: after.filter((v) => !b.has(v)), removed: before.filter((v) => !a.has(v)) };
234
+ }
235
+ function columnChanges(before, after) {
236
+ const out = [];
237
+ const b = byName(before, (c) => c.view.name);
238
+ const a = byName(after, (c) => c.view.name);
239
+ for (const c of after) {
240
+ const old = b.get(c.view.name);
241
+ if (!old) {
242
+ out.push({ name: c.view.name, status: "added", after: c.view });
243
+ continue;
244
+ }
245
+ const changed = [];
246
+ if (old.key.type !== c.key.type) changed.push("type");
247
+ if (old.view.notNull !== c.view.notNull) changed.push("notNull");
248
+ if (old.key.default !== c.key.default) changed.push("default");
249
+ if (old.view.identity !== c.view.identity) changed.push("identity");
250
+ if (old.key.generated !== c.key.generated) changed.push("generated");
251
+ if (old.view.comment !== c.view.comment) changed.push("comment");
252
+ if (changed.length) out.push({ name: c.view.name, status: "modified", before: old.view, after: c.view, changed });
253
+ }
254
+ for (const c of before) if (!a.has(c.view.name)) out.push({ name: c.view.name, status: "removed", before: c.view });
255
+ return out;
256
+ }
257
+ function constraintChanges(before, after) {
258
+ const out = [];
259
+ const b = byName(before, (c) => c.view.name);
260
+ const a = byName(after, (c) => c.view.name);
261
+ for (const c of after) {
262
+ const old = b.get(c.view.name);
263
+ if (!old) out.push({ name: c.view.name, kind: c.view.kind, status: "added", after: c.view });
264
+ else if (old.key !== c.key) out.push({ name: c.view.name, kind: c.view.kind, status: "modified", before: old.view, after: c.view });
265
+ }
266
+ for (const c of before) if (!a.has(c.view.name)) out.push({ name: c.view.name, kind: c.view.kind, status: "removed", before: c.view });
267
+ return out;
268
+ }
269
+ function indexChanges(before, after) {
270
+ const out = [];
271
+ const b = byName(before, (i) => i.view.name);
272
+ const a = byName(after, (i) => i.view.name);
273
+ for (const i of after) {
274
+ const old = b.get(i.view.name);
275
+ if (!old) out.push({ name: i.view.name, status: "added", after: i.view });
276
+ else if (old.key !== i.key) out.push({ name: i.view.name, status: "modified", before: old.view, after: i.view });
277
+ }
278
+ for (const i of before) if (!a.has(i.view.name)) out.push({ name: i.view.name, status: "removed", before: i.view });
279
+ return out;
280
+ }
281
+ function allOf(t, status) {
282
+ const side = status === "added" ? "after" : "before";
283
+ return {
284
+ columns: t.columns.map((c) => ({ name: c.view.name, status, [side]: c.view })),
285
+ constraints: t.constraints.map((c) => ({ name: c.view.name, kind: c.view.kind, status, [side]: c.view })),
286
+ indexes: t.indexes.map((i) => ({ name: i.view.name, status, [side]: i.view }))
287
+ };
288
+ }
289
+ function checkValueChanges(name, before, after) {
290
+ const out = [];
291
+ const withValues = (t) => t.constraints.map((c) => c.view).filter((v) => !!v.values);
292
+ const b = withValues(before);
293
+ const a = withValues(after);
294
+ const afterCols = new Set(after.columns.map((c) => c.view.name));
295
+ const beforeCols = new Set(before.columns.map((c) => c.view.name));
296
+ const used = /* @__PURE__ */ new Set();
297
+ const pair = (c) => {
298
+ const old = b.find((x) => !used.has(x) && x.name === c.name) ?? b.find((x) => !used.has(x) && x.values.column === c.values.column);
299
+ if (old) used.add(old);
300
+ return old;
301
+ };
302
+ for (const c of a) {
303
+ const old = pair(c);
304
+ const column2 = c.values.column;
305
+ if (!old) {
306
+ if (beforeCols.has(column2)) {
307
+ out.push({ source: "check", table: name, column: column2, constraint: c.name, status: "added", added: c.values.values, removed: [], after: c.values.values });
308
+ }
309
+ continue;
310
+ }
311
+ const d = setDiff(old.values.values, c.values.values);
312
+ if (d.added.length || d.removed.length) {
313
+ out.push({ source: "check", table: name, column: column2, constraint: c.name, status: "modified", ...d, before: old.values.values, after: c.values.values });
314
+ }
315
+ }
316
+ for (const old of b) {
317
+ if (used.has(old)) continue;
318
+ const column2 = old.values.column;
319
+ if (afterCols.has(column2)) {
320
+ out.push({ source: "check", table: name, column: column2, constraint: old.name, status: "removed", added: [], removed: old.values.values, before: old.values.values });
321
+ }
322
+ }
323
+ return out;
324
+ }
325
+ function usersOf(s, type) {
326
+ const short = type.split(".").pop();
327
+ const out = [];
328
+ for (const [tname, t] of s.tables) {
329
+ for (const c of t.columns) {
330
+ const ct = c.view.type.replace(/\[\]$/, "");
331
+ if (ct === type || ct === short) out.push(`${tname}.${c.view.name}`);
332
+ }
333
+ }
334
+ return out;
335
+ }
336
+ function failedFiles(before, after) {
337
+ return /* @__PURE__ */ new Set([...before.errors.keys(), ...after.errors.keys()]);
338
+ }
339
+ function diffSchemas(before, after) {
340
+ const skip = failedFiles(before, after);
341
+ const keep = (t) => !skip.has(t.file);
342
+ const tables = [];
343
+ const values2 = [];
344
+ let unchanged = 0;
345
+ const names2 = [.../* @__PURE__ */ new Set([...before.tables.keys(), ...after.tables.keys()])].sort();
346
+ for (const name of names2) {
347
+ const b = before.tables.get(name);
348
+ const a = after.tables.get(name);
349
+ if (b && !keep(b) || a && !keep(a)) continue;
350
+ const t = a ?? b;
351
+ const head = { name, schema: t.schema, table: t.name };
352
+ if (!b) {
353
+ tables.push({ ...head, status: "added", file: a.file, ...allOf(a, "added"), ...a.comment !== void 0 && { comment: { after: a.comment } } });
354
+ continue;
355
+ }
356
+ if (!a) {
357
+ tables.push({ ...head, status: "removed", file: b.file, ...allOf(b, "removed"), ...b.comment !== void 0 && { comment: { before: b.comment } } });
358
+ continue;
359
+ }
360
+ const columns = columnChanges(b.columns, a.columns);
361
+ const constraints = constraintChanges(b.constraints, a.constraints);
362
+ const indexes = indexChanges(b.indexes, a.indexes);
363
+ const commentChanged = b.comment !== a.comment;
364
+ values2.push(...checkValueChanges(name, b, a));
365
+ if (columns.length || constraints.length || indexes.length || commentChanged) {
366
+ tables.push({
367
+ ...head,
368
+ status: "modified",
369
+ file: a.file,
370
+ columns,
371
+ constraints,
372
+ indexes,
373
+ ...commentChanged && { comment: { before: b.comment, after: a.comment } },
374
+ unchanged: {
375
+ columns: a.columns.filter((c) => !columns.some((x) => x.name === c.view.name)).map((c) => c.view),
376
+ constraints: a.constraints.filter((c) => !constraints.some((x) => x.name === c.view.name)).map((c) => c.view),
377
+ indexes: a.indexes.filter((i) => !indexes.some((x) => x.name === i.view.name)).map((i) => i.view)
378
+ }
379
+ });
380
+ } else {
381
+ unchanged++;
382
+ }
383
+ }
384
+ const enums = [];
385
+ for (const name of [.../* @__PURE__ */ new Set([...before.enums.keys(), ...after.enums.keys()])].sort()) {
386
+ const b = before.enums.get(name);
387
+ const a = after.enums.get(name);
388
+ if (b && skip.has(b.file) || a && skip.has(a.file)) continue;
389
+ if (!b) enums.push({ name, status: "added", after: a.view });
390
+ else if (!a) enums.push({ name, status: "removed", before: b.view });
391
+ else {
392
+ const d = setDiff(b.view.values, a.view.values);
393
+ if (d.added.length || d.removed.length || b.view.values.join("\0") !== a.view.values.join("\0")) {
394
+ enums.push({ name, status: "modified", before: b.view, after: a.view });
395
+ }
396
+ if (d.added.length || d.removed.length) {
397
+ values2.push({ source: "enum", type: name, usedBy: usersOf(after, name), status: "modified", ...d, before: b.view.values, after: a.view.values });
398
+ }
399
+ }
400
+ }
401
+ const domains = [];
402
+ for (const name of [.../* @__PURE__ */ new Set([...before.domains.keys(), ...after.domains.keys()])].sort()) {
403
+ const b = before.domains.get(name);
404
+ const a = after.domains.get(name);
405
+ if (b && skip.has(b.file) || a && skip.has(a.file)) continue;
406
+ if (!b) domains.push({ name, status: "added", after: a.view });
407
+ else if (!a) domains.push({ name, status: "removed", before: b.view });
408
+ else if (b.key !== a.key) {
409
+ domains.push({ name, status: "modified", before: b.view, after: a.view });
410
+ const bv = b.view.checks.flatMap((c) => c.values?.values ?? []);
411
+ const av = a.view.checks.flatMap((c) => c.values?.values ?? []);
412
+ const d = setDiff(bv, av);
413
+ if (d.added.length || d.removed.length) {
414
+ values2.push({ source: "domain", type: name, usedBy: usersOf(after, name), status: "modified", ...d, before: bv, after: av });
415
+ }
416
+ }
417
+ }
418
+ return { tables, enums, domains, values: values2, unchangedTables: unchanged };
419
+ }
420
+
421
+ // ../dbshape/src/er.ts
422
+ function foreignKeys(t) {
423
+ return t.constraints.filter((c) => c.view.kind === "foreign" && c.view.references).map((c) => ({ name: c.view.name, columns: c.view.columns, table: c.view.references.table, refColumns: c.view.references.columns, status: "unchanged" }));
424
+ }
425
+ function primaryColumns(t) {
426
+ return new Set(t.constraints.filter((c) => c.view.kind === "primary").flatMap((c) => c.view.columns));
427
+ }
428
+ function erTables(before, after, diff) {
429
+ const skip = /* @__PURE__ */ new Set([...before.errors.keys(), ...after.errors.keys()]);
430
+ const changes = new Map(diff.tables.map((t) => [t.name, t]));
431
+ const valueColumns = /* @__PURE__ */ new Set();
432
+ for (const v of diff.values) {
433
+ if (v.source === "check" && v.table && v.column) valueColumns.add(`${v.table}.${v.column}`);
434
+ for (const u of v.usedBy ?? []) valueColumns.add(u);
435
+ }
436
+ const out = [];
437
+ const names2 = [.../* @__PURE__ */ new Set([...after.tables.keys(), ...before.tables.keys()])].sort();
438
+ for (const name of names2) {
439
+ const a = after.tables.get(name);
440
+ const b = before.tables.get(name);
441
+ if (a && skip.has(a.file) || b && skip.has(b.file)) continue;
442
+ const t = a ?? b;
443
+ const change = changes.get(name);
444
+ const status = change?.status ?? "unchanged";
445
+ const pk = primaryColumns(t);
446
+ const colStatus = new Map(change?.columns.map((c) => [c.name, c]) ?? []);
447
+ const columns = t.columns.map((c) => {
448
+ const ch = colStatus.get(c.view.name);
449
+ const s = status === "added" || status === "removed" ? status : ch?.status ?? "unchanged";
450
+ const typeChanged = ch?.status === "modified" && ch.changed?.includes("type");
451
+ return {
452
+ name: c.view.name,
453
+ type: c.view.type,
454
+ ...typeChanged && { beforeType: ch.before.type },
455
+ status: s,
456
+ notNull: c.view.notNull,
457
+ primary: pk.has(c.view.name),
458
+ ...valueColumns.has(`${name}.${c.view.name}`) && { values: true }
459
+ };
460
+ });
461
+ if (a && b) {
462
+ const bpk = primaryColumns(b);
463
+ for (const c of change?.columns ?? []) {
464
+ if (c.status !== "removed") continue;
465
+ columns.push({ name: c.name, type: c.before.type, status: "removed", notNull: c.before.notNull, primary: bpk.has(c.name) });
466
+ }
467
+ }
468
+ const fks = foreignKeys(t).map((fk) => ({ ...fk, status: status === "added" || status === "removed" ? status : fk.status }));
469
+ let other = { constraints: 0, indexes: 0, comment: false };
470
+ if (change && a && b) {
471
+ const fkChange = new Map(change.constraints.filter((c) => c.kind === "foreign").map((c) => [c.name, c.status]));
472
+ for (const fk of fks) fk.status = fkChange.get(fk.name) ?? "unchanged";
473
+ for (const c of change.constraints) {
474
+ if (c.kind === "foreign" && c.status === "removed" && c.before?.references) {
475
+ fks.push({ name: c.name, columns: c.before.columns, table: c.before.references.table, refColumns: c.before.references.columns, status: "removed" });
476
+ }
477
+ }
478
+ other = {
479
+ constraints: change.constraints.filter((c) => c.kind !== "foreign").length,
480
+ indexes: change.indexes.length,
481
+ comment: !!change.comment
482
+ };
483
+ }
484
+ out.push({ name, schema: t.schema, table: t.name, status, columns, foreignKeys: fks, otherChanges: other });
485
+ }
486
+ return out;
487
+ }
488
+
489
+ // ../dbshape/src/sql.ts
490
+ var POSITION_KEYS = /* @__PURE__ */ new Set(["location", "stmt_location", "stmt_len", "rexpr_list_start", "rexpr_list_end"]);
491
+ function nodeKey(n) {
492
+ return JSON.stringify(n ?? null, (k, v) => POSITION_KEYS.has(k) ? void 0 : v);
493
+ }
494
+ function str(n) {
495
+ return n?.String?.sval ?? n?.sval ?? "";
496
+ }
497
+ function unwrap(n) {
498
+ const k = Object.keys(n ?? {})[0];
499
+ return [k ?? "", k ? n[k] : void 0];
500
+ }
501
+ var SIMPLE_IDENT = /^[a-z_][a-z0-9_$]*$/;
502
+ function ident(name) {
503
+ return SIMPLE_IDENT.test(name) ? name : `"${name.replace(/"/g, '""')}"`;
504
+ }
505
+ var CATALOG_TYPES = {
506
+ int2: "smallint",
507
+ int4: "integer",
508
+ int8: "bigint",
509
+ float4: "real",
510
+ float8: "double precision",
511
+ bool: "boolean",
512
+ bpchar: "char"
513
+ };
514
+ var CATALOG_NAMES = /* @__PURE__ */ new Set(["int2", "int4", "int8", "float4", "float8", "bool", "varchar", "bpchar", "numeric", "timestamp", "timestamptz", "time", "timetz", "interval", "bit", "varbit"]);
515
+ function typeNames(t) {
516
+ const names2 = (t?.names ?? []).map(str);
517
+ return names2.length === 1 && CATALOG_NAMES.has(names2[0]) ? ["pg_catalog", names2[0]] : names2;
518
+ }
519
+ function typeText(t) {
520
+ const names2 = typeNames(t);
521
+ let name = names2.length === 2 && names2[0] === "pg_catalog" ? CATALOG_TYPES[names2[1]] ?? names2[1] : names2.map(ident).join(".");
522
+ const mods = (t?.typmods ?? []).map(exprText);
523
+ if (mods.length && !name.startsWith("interval")) name += `(${mods.join(",")})`;
524
+ if (t?.arrayBounds?.length) name += "[]".repeat(t.arrayBounds.length);
525
+ if (t?.setof) name = `SETOF ${name}`;
526
+ return name;
527
+ }
528
+ function typeKey(t) {
529
+ return nodeKey({ names: typeNames(t), typmods: t?.typmods, arrayBounds: t?.arrayBounds });
530
+ }
531
+ function constText(c) {
532
+ if (c.isnull) return "NULL";
533
+ if (c.sval) return `'${(c.sval.sval ?? "").replace(/'/g, "''")}'`;
534
+ if (c.ival) return String(c.ival.ival ?? 0);
535
+ if (c.fval) return c.fval.fval ?? "0";
536
+ if (c.boolval) return c.boolval.boolval ? "true" : "false";
537
+ if (c.bsval) return c.bsval.bsval ?? "";
538
+ return "NULL";
539
+ }
540
+ var SVF = {
541
+ SVFOP_CURRENT_DATE: "CURRENT_DATE",
542
+ SVFOP_CURRENT_TIME: "CURRENT_TIME",
543
+ SVFOP_CURRENT_TIMESTAMP: "CURRENT_TIMESTAMP",
544
+ SVFOP_LOCALTIME: "LOCALTIME",
545
+ SVFOP_LOCALTIMESTAMP: "LOCALTIMESTAMP",
546
+ SVFOP_CURRENT_ROLE: "CURRENT_ROLE",
547
+ SVFOP_CURRENT_USER: "CURRENT_USER",
548
+ SVFOP_USER: "USER",
549
+ SVFOP_SESSION_USER: "SESSION_USER",
550
+ SVFOP_CURRENT_CATALOG: "CURRENT_CATALOG",
551
+ SVFOP_CURRENT_SCHEMA: "CURRENT_SCHEMA"
552
+ };
553
+ function wrap(n) {
554
+ const [k] = unwrap(n);
555
+ return k === "A_Expr" || k === "BoolExpr" ? `(${exprText(n)})` : exprText(n);
556
+ }
557
+ function opName(names2) {
558
+ return (names2 ?? []).map(str).filter((s) => s !== "pg_catalog").join(".");
559
+ }
560
+ function exprText(n) {
561
+ if (n === void 0 || n === null) return "";
562
+ const [k, v] = unwrap(n);
563
+ switch (k) {
564
+ case "A_Const":
565
+ return constText(v);
566
+ case "Integer":
567
+ return String(v.ival ?? 0);
568
+ case "String":
569
+ return v.sval ?? "";
570
+ case "ColumnRef":
571
+ return (v.fields ?? []).map((f) => f.A_Star ? "*" : ident(str(f))).join(".");
572
+ case "TypeCast":
573
+ return `${wrap(v.arg)}::${typeText(v.typeName)}`;
574
+ case "FuncCall": {
575
+ const name = (v.funcname ?? []).map(str).filter((s) => s !== "pg_catalog").join(".");
576
+ const args = v.agg_star ? "*" : (v.args ?? []).map(exprText).join(", ");
577
+ return `${name}(${args})`;
578
+ }
579
+ case "A_Expr": {
580
+ const op = opName(v.name);
581
+ switch (v.kind) {
582
+ case "AEXPR_OP":
583
+ return v.lexpr ? `${wrap(v.lexpr)} ${op} ${wrap(v.rexpr)}` : `${op} ${wrap(v.rexpr)}`;
584
+ case "AEXPR_OP_ANY":
585
+ return `${wrap(v.lexpr)} ${op} ANY (${exprText(v.rexpr)})`;
586
+ case "AEXPR_OP_ALL":
587
+ return `${wrap(v.lexpr)} ${op} ALL (${exprText(v.rexpr)})`;
588
+ case "AEXPR_IN":
589
+ return `${wrap(v.lexpr)} ${op === "=" ? "IN" : "NOT IN"} (${exprText(v.rexpr)})`;
590
+ case "AEXPR_BETWEEN":
591
+ case "AEXPR_NOT_BETWEEN": {
592
+ const [lo, hi] = v.rexpr?.List?.items ?? [];
593
+ return `${wrap(v.lexpr)} ${v.kind === "AEXPR_BETWEEN" ? "BETWEEN" : "NOT BETWEEN"} ${wrap(lo)} AND ${wrap(hi)}`;
594
+ }
595
+ case "AEXPR_LIKE":
596
+ return `${wrap(v.lexpr)} ${op === "~~" ? "LIKE" : "NOT LIKE"} ${wrap(v.rexpr)}`;
597
+ case "AEXPR_ILIKE":
598
+ return `${wrap(v.lexpr)} ${op === "~~*" ? "ILIKE" : "NOT ILIKE"} ${wrap(v.rexpr)}`;
599
+ case "AEXPR_DISTINCT":
600
+ return `${wrap(v.lexpr)} IS DISTINCT FROM ${wrap(v.rexpr)}`;
601
+ case "AEXPR_NOT_DISTINCT":
602
+ return `${wrap(v.lexpr)} IS NOT DISTINCT FROM ${wrap(v.rexpr)}`;
603
+ case "AEXPR_NULLIF":
604
+ return `NULLIF(${exprText(v.lexpr)}, ${exprText(v.rexpr)})`;
605
+ default:
606
+ return `${wrap(v.lexpr)} ${op} ${wrap(v.rexpr)}`;
607
+ }
608
+ }
609
+ case "BoolExpr": {
610
+ if (v.boolop === "NOT_EXPR") return `NOT ${wrap(v.args?.[0])}`;
611
+ const args = (v.args ?? []).map((a) => a?.BoolExpr ? `(${exprText(a)})` : exprText(a));
612
+ return args.join(v.boolop === "AND_EXPR" ? " AND " : " OR ");
613
+ }
614
+ case "NullTest":
615
+ return `${wrap(v.arg)} IS ${v.nulltesttype === "IS_NOT_NULL" ? "NOT " : ""}NULL`;
616
+ case "BooleanTest":
617
+ return `${wrap(v.arg)} ${String(v.booltesttype ?? "").replace(/_/g, " ")}`;
618
+ case "A_ArrayExpr":
619
+ return `ARRAY[${(v.elements ?? []).map(exprText).join(", ")}]`;
620
+ case "List":
621
+ return (v.items ?? []).map(exprText).join(", ");
622
+ case "SQLValueFunction":
623
+ return SVF[v.op] ?? String(v.op ?? "");
624
+ case "CoalesceExpr":
625
+ return `COALESCE(${(v.args ?? []).map(exprText).join(", ")})`;
626
+ case "MinMaxExpr":
627
+ return `${v.op === "IS_LEAST" ? "LEAST" : "GREATEST"}(${(v.args ?? []).map(exprText).join(", ")})`;
628
+ case "ParamRef":
629
+ return `$${v.number ?? 0}`;
630
+ case "CaseExpr": {
631
+ const whens = (v.args ?? []).map((w) => `WHEN ${exprText(w.CaseWhen?.expr)} THEN ${exprText(w.CaseWhen?.result)}`);
632
+ return `CASE ${v.arg ? `${exprText(v.arg)} ` : ""}${whens.join(" ")}${v.defresult ? ` ELSE ${exprText(v.defresult)}` : ""} END`;
633
+ }
634
+ case "RowExpr":
635
+ return `ROW(${(v.args ?? []).map(exprText).join(", ")})`;
636
+ case "CollateClause":
637
+ return `${wrap(v.arg)} COLLATE ${(v.collname ?? []).map(str).join(".")}`;
638
+ default:
639
+ return `\u2039${k}\u203A`;
640
+ }
641
+ }
642
+
643
+ // ../dbshape/src/checks.ts
644
+ function stripCasts(n) {
645
+ while (n?.TypeCast) n = n.TypeCast.arg;
646
+ return n;
647
+ }
648
+ function columnOf(n) {
649
+ const c = stripCasts(n)?.ColumnRef;
650
+ if (!c?.fields?.length) return null;
651
+ const last = c.fields[c.fields.length - 1];
652
+ return last.String ? str(last) : null;
653
+ }
654
+ function textOf(n) {
655
+ const c = stripCasts(n)?.A_Const;
656
+ return c?.sval ? c.sval.sval ?? "" : null;
657
+ }
658
+ function texts(nodes) {
659
+ if (!nodes?.length) return null;
660
+ const out = [];
661
+ for (const n of nodes) {
662
+ const t = textOf(n);
663
+ if (t === null) return null;
664
+ out.push(t);
665
+ }
666
+ return out;
667
+ }
668
+ function arrayItems(n) {
669
+ return stripCasts(n)?.A_ArrayExpr?.elements;
670
+ }
671
+ function eqName(e) {
672
+ const names2 = (e.name ?? []).map(str);
673
+ return names2.length === 1 && names2[0] === "=";
674
+ }
675
+ function checkValues(expr) {
676
+ const e = expr?.A_Expr;
677
+ if (e && eqName(e)) {
678
+ if (e.kind === "AEXPR_IN") {
679
+ const column2 = columnOf(e.lexpr);
680
+ const values2 = texts(e.rexpr?.List?.items);
681
+ return column2 && values2 ? { column: column2, values: values2 } : null;
682
+ }
683
+ if (e.kind === "AEXPR_OP_ANY") {
684
+ const column2 = columnOf(e.lexpr);
685
+ const values2 = texts(arrayItems(e.rexpr));
686
+ return column2 && values2 ? { column: column2, values: values2 } : null;
687
+ }
688
+ if (e.kind === "AEXPR_OP") {
689
+ const column2 = columnOf(e.lexpr) ?? columnOf(e.rexpr);
690
+ const value = textOf(e.rexpr) ?? textOf(e.lexpr);
691
+ return column2 && value !== null ? { column: column2, values: [value] } : null;
692
+ }
693
+ return null;
694
+ }
695
+ const b = expr?.BoolExpr;
696
+ if (b?.boolop === "OR_EXPR") {
697
+ let column2 = null;
698
+ const values2 = [];
699
+ let nullTests = 0;
700
+ for (const arg of b.args ?? []) {
701
+ if (arg.NullTest?.nulltesttype === "IS_NULL") {
702
+ nullTests++;
703
+ const c = columnOf(arg.NullTest.arg);
704
+ if (!c || column2 && c !== column2) return null;
705
+ column2 = c;
706
+ continue;
707
+ }
708
+ const part = checkValues(arg);
709
+ if (!part || column2 && part.column !== column2) return null;
710
+ column2 = part.column;
711
+ values2.push(...part.values);
712
+ }
713
+ if (!column2 || values2.length === 0 || nullTests > 1) return null;
714
+ return { column: column2, values: [...new Set(values2)] };
715
+ }
716
+ return null;
717
+ }
718
+
719
+ // ../dbshape/src/schema.ts
720
+ var qualified = (schema, name) => `${schema}.${name}`;
721
+ var FK_ACTIONS = { r: "RESTRICT", c: "CASCADE", n: "SET NULL", d: "SET DEFAULT" };
722
+ function firstColumn(n) {
723
+ if (!n || typeof n !== "object") return void 0;
724
+ if (n.ColumnRef) {
725
+ const last = n.ColumnRef.fields?.at(-1);
726
+ return last?.String ? str(last) : void 0;
727
+ }
728
+ for (const v of Object.values(n)) {
729
+ const found = Array.isArray(v) ? v.map(firstColumn).find(Boolean) : firstColumn(v);
730
+ if (found) return found;
731
+ }
732
+ return void 0;
733
+ }
734
+ function names(list) {
735
+ return (list ?? []).map(str);
736
+ }
737
+ function buildSchema(files, parse) {
738
+ const s = {
739
+ tables: /* @__PURE__ */ new Map(),
740
+ enums: /* @__PURE__ */ new Map(),
741
+ domains: /* @__PURE__ */ new Map(),
742
+ ignored: /* @__PURE__ */ new Map(),
743
+ errors: /* @__PURE__ */ new Map(),
744
+ notes: []
745
+ };
746
+ for (const f of files) {
747
+ let tree;
748
+ try {
749
+ tree = parse(f.sql);
750
+ } catch (e) {
751
+ s.errors.set(f.path, e instanceof Error ? e.message : String(e));
752
+ continue;
753
+ }
754
+ new FileReader(s, f.path, f.sql).run(tree);
755
+ }
756
+ return s;
757
+ }
758
+ var Lines = class {
759
+ bytes;
760
+ breaks = [];
761
+ constructor(sql) {
762
+ this.bytes = new TextEncoder().encode(sql);
763
+ this.bytes.forEach((b, i) => b === 10 && this.breaks.push(i));
764
+ }
765
+ /** The line of a byte offset, after skipping whitespace and comments when `skip` is set */
766
+ lineAt(offset, skip = false) {
767
+ const b = this.bytes;
768
+ let i = Math.max(0, offset);
769
+ while (skip && i < b.length) {
770
+ if (b[i] === 32 || b[i] === 9 || b[i] === 10 || b[i] === 13) i++;
771
+ else if (b[i] === 45 && b[i + 1] === 45) while (i < b.length && b[i] !== 10) i++;
772
+ else if (b[i] === 47 && b[i + 1] === 42) {
773
+ let j = i + 2;
774
+ while (j < b.length && !(b[j] === 42 && b[j + 1] === 47)) j++;
775
+ i = j + 2;
776
+ } else break;
777
+ }
778
+ let lo = 0;
779
+ let hi = this.breaks.length;
780
+ while (lo < hi) {
781
+ const mid = lo + hi >> 1;
782
+ if (this.breaks[mid] < i) lo = mid + 1;
783
+ else hi = mid;
784
+ }
785
+ return lo + 1;
786
+ }
787
+ };
788
+ var FileReader = class {
789
+ constructor(s, file, sql) {
790
+ this.s = s;
791
+ this.file = file;
792
+ this.lines = new Lines(sql);
793
+ this.here = { file, line: 1 };
794
+ }
795
+ searchPath = "public";
796
+ lines;
797
+ /** Where the current statement starts */
798
+ here;
799
+ run(tree) {
800
+ for (const st of tree?.stmts ?? []) {
801
+ const [kind, v] = Object.entries(st.stmt ?? {})[0] ?? [];
802
+ if (!kind) continue;
803
+ this.here = { file: this.file, line: this.lines.lineAt(st.stmt_location ?? 0, true) };
804
+ this.statement(kind, v);
805
+ }
806
+ }
807
+ /** The location of a node inside the current statement (or the statement itself) */
808
+ at(location) {
809
+ return typeof location === "number" && location >= 0 ? { file: this.file, line: this.lines.lineAt(location) } : this.here;
810
+ }
811
+ ignore(what) {
812
+ this.s.ignored.set(what, (this.s.ignored.get(what) ?? 0) + 1);
813
+ }
814
+ note(msg) {
815
+ this.s.notes.push(`${this.file}: ${msg}`);
816
+ }
817
+ rel(r) {
818
+ const schema = r?.schemaname || this.searchPath;
819
+ const name = r?.relname ?? "";
820
+ return { schema, name, key: qualified(schema, name) };
821
+ }
822
+ /** "schema.name" from a list of String nodes (enum / domain names) */
823
+ typeName(list) {
824
+ const n = names(list);
825
+ return n.length > 1 ? n.join(".") : qualified(this.searchPath, n[0] ?? "");
826
+ }
827
+ table(r, what) {
828
+ const { key } = this.rel(r);
829
+ const t = this.s.tables.get(key);
830
+ if (!t) this.note(`${what}: \u30C6\u30FC\u30D6\u30EB ${key} \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`);
831
+ return t;
832
+ }
833
+ statement(kind, v) {
834
+ switch (kind) {
835
+ case "VariableSetStmt":
836
+ if (v.name === "search_path") {
837
+ const first = (v.args ?? []).map((a) => a.A_Const?.sval?.sval).find((x) => x && x !== "$user");
838
+ if (v.kind === "VAR_SET_VALUE" && first) this.searchPath = first;
839
+ if (v.kind === "VAR_RESET" || v.kind === "VAR_SET_DEFAULT") this.searchPath = "public";
840
+ }
841
+ return;
842
+ case "CreateSchemaStmt":
843
+ return;
844
+ case "CreateStmt":
845
+ return this.createTable(v);
846
+ case "AlterTableStmt":
847
+ if (v.objtype === "OBJECT_TABLE" || v.objtype === void 0) return this.alterTable(v);
848
+ return this.ignore(`ALTER ${String(v.objtype).replace("OBJECT_", "")}`);
849
+ case "IndexStmt":
850
+ return this.createIndex(v);
851
+ case "CreateEnumStmt":
852
+ return this.createEnum(v);
853
+ case "AlterEnumStmt":
854
+ return this.alterEnum(v);
855
+ case "CreateDomainStmt":
856
+ return this.createDomain(v);
857
+ case "RenameStmt":
858
+ return this.rename(v);
859
+ case "CommentStmt":
860
+ return this.comment(v);
861
+ default:
862
+ return this.ignore(kind.replace(/Stmt$/, ""));
863
+ }
864
+ }
865
+ // ---- tables
866
+ createTable(v) {
867
+ const { schema, name, key } = this.rel(v.relation);
868
+ if (this.s.tables.has(key)) {
869
+ if (!v.if_not_exists) this.note(`\u30C6\u30FC\u30D6\u30EB ${key} \u304C2\u56DE\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059`);
870
+ return;
871
+ }
872
+ const t = { schema, name, file: this.file, loc: this.here, columns: [], constraints: [], indexes: [] };
873
+ this.s.tables.set(key, t);
874
+ for (const el of v.tableElts ?? []) {
875
+ if (el.ColumnDef) this.addColumn(t, el.ColumnDef);
876
+ else if (el.Constraint) this.addConstraint(t, el.Constraint);
877
+ else this.ignore(`CREATE TABLE \u306E ${Object.keys(el)[0]}`);
878
+ }
879
+ for (const c of t.constraints) if (c.view.kind === "primary") this.setNotNull(t, c.view.columns);
880
+ }
881
+ /** PostgreSQL makes primary key columns NOT NULL even when the SQL doesn't say so. */
882
+ setNotNull(t, columns) {
883
+ for (const c of t.columns) if (columns.includes(c.view.name)) c.view.notNull = true;
884
+ }
885
+ addColumn(t, c) {
886
+ const view = { name: c.colname, type: typeText(c.typeName), notNull: false };
887
+ const col = { view, loc: this.at(c.location), key: { type: typeKey(c.typeName) } };
888
+ t.columns = t.columns.filter((x) => x.view.name !== c.colname);
889
+ t.columns.push(col);
890
+ for (const k of c.constraints ?? []) {
891
+ const con = k.Constraint;
892
+ switch (con?.contype) {
893
+ case "CONSTR_NOTNULL":
894
+ view.notNull = true;
895
+ break;
896
+ case "CONSTR_NULL":
897
+ view.notNull = false;
898
+ break;
899
+ case "CONSTR_DEFAULT":
900
+ view.default = exprText(con.raw_expr);
901
+ col.key.default = nodeKey(con.raw_expr);
902
+ break;
903
+ case "CONSTR_IDENTITY":
904
+ view.identity = con.generated_when === "a" ? "always" : "by default";
905
+ break;
906
+ case "CONSTR_GENERATED":
907
+ view.generated = exprText(con.raw_expr);
908
+ col.key.generated = nodeKey(con.raw_expr);
909
+ break;
910
+ case "CONSTR_PRIMARY":
911
+ case "CONSTR_UNIQUE":
912
+ case "CONSTR_CHECK":
913
+ case "CONSTR_FOREIGN":
914
+ this.addConstraint(t, con, c.colname);
915
+ break;
916
+ default:
917
+ break;
918
+ }
919
+ }
920
+ if (view.identity) view.notNull = true;
921
+ }
922
+ /** PostgreSQL's default name for an unnamed constraint */
923
+ defaultName(t, kind, cols) {
924
+ const suffix = { primary: "pkey", unique: "key", foreign: "fkey", check: "check", exclude: "excl" }[kind];
925
+ const base = kind === "primary" ? `${t.name}_pkey` : [t.name, ...cols.slice(0, 1).concat(kind === "check" ? [] : cols.slice(1)), suffix].join("_");
926
+ let name = base;
927
+ for (let i = 1; t.constraints.some((c) => c.view.name === name); i++) name = `${base}${i}`;
928
+ return name;
929
+ }
930
+ addConstraint(t, c, column2) {
931
+ const kind = {
932
+ CONSTR_PRIMARY: "primary",
933
+ CONSTR_UNIQUE: "unique",
934
+ CONSTR_CHECK: "check",
935
+ CONSTR_FOREIGN: "foreign",
936
+ CONSTR_EXCLUSION: "exclude"
937
+ }[c.contype];
938
+ if (!kind) return;
939
+ let columns;
940
+ let definition;
941
+ let key;
942
+ let references;
943
+ let values2;
944
+ switch (kind) {
945
+ case "primary":
946
+ case "unique": {
947
+ columns = column2 ? [column2] : names(c.keys);
948
+ const include = names(c.including);
949
+ definition = `${kind === "primary" ? "PRIMARY KEY" : "UNIQUE"}${c.nulls_not_distinct ? " NULLS NOT DISTINCT" : ""} (${columns.map(ident).join(", ")})${include.length ? ` INCLUDE (${include.map(ident).join(", ")})` : ""}`;
950
+ key = nodeKey({ kind, columns, include, nnd: c.nulls_not_distinct });
951
+ break;
952
+ }
953
+ case "check": {
954
+ values2 = checkValues(c.raw_expr) ?? void 0;
955
+ const first = firstColumn(c.raw_expr);
956
+ columns = column2 ? [column2] : values2 ? [values2.column] : first ? [first] : [];
957
+ definition = `CHECK (${exprText(c.raw_expr)})${c.skip_validation ? " NOT VALID" : ""}`;
958
+ key = nodeKey({ kind, expr: c.raw_expr });
959
+ break;
960
+ }
961
+ case "foreign": {
962
+ columns = column2 ? [column2] : names(c.fk_attrs);
963
+ const ref = this.rel(c.pktable);
964
+ const refCols = names(c.pk_attrs);
965
+ const onDelete = FK_ACTIONS[c.fk_del_action];
966
+ const onUpdate = FK_ACTIONS[c.fk_upd_action];
967
+ references = { table: ref.key, columns: refCols, ...onDelete && { onDelete }, ...onUpdate && { onUpdate } };
968
+ definition = `FOREIGN KEY (${columns.map(ident).join(", ")}) REFERENCES ${ident(ref.schema)}.${ident(ref.name)}` + (refCols.length ? ` (${refCols.map(ident).join(", ")})` : "") + (onDelete ? ` ON DELETE ${onDelete}` : "") + (onUpdate ? ` ON UPDATE ${onUpdate}` : "") + (c.deferrable ? " DEFERRABLE" : "");
969
+ key = nodeKey({ kind, columns, ref: references, match: c.fk_matchtype, deferrable: c.deferrable, initdeferred: c.initdeferred });
970
+ break;
971
+ }
972
+ case "exclude":
973
+ columns = [];
974
+ definition = `EXCLUDE USING ${c.access_method ?? "gist"} (\u2026)`;
975
+ key = nodeKey({ kind, c: { ...c, conname: void 0 } });
976
+ break;
977
+ }
978
+ const name = c.conname || this.defaultName(t, kind, columns);
979
+ const view = { name, kind, columns, definition, ...references && { references }, ...values2 && { values: values2 } };
980
+ t.constraints = t.constraints.filter((x) => x.view.name !== name);
981
+ t.constraints.push({ view, key, loc: this.at(c.location) });
982
+ if (kind === "primary") this.setNotNull(t, columns);
983
+ }
984
+ alterTable(v) {
985
+ const t = this.table(v.relation, "ALTER TABLE");
986
+ if (!t) return;
987
+ for (const item of v.cmds ?? []) {
988
+ const cmd = item.AlterTableCmd;
989
+ if (!cmd) continue;
990
+ const col = () => t.columns.find((c) => c.view.name === cmd.name);
991
+ switch (cmd.subtype) {
992
+ case "AT_AddColumn":
993
+ if (cmd.def?.ColumnDef) this.addColumn(t, cmd.def.ColumnDef);
994
+ break;
995
+ case "AT_DropColumn":
996
+ t.columns = t.columns.filter((c) => c.view.name !== cmd.name);
997
+ t.constraints = t.constraints.filter((c) => !c.view.columns.includes(cmd.name));
998
+ t.indexes = t.indexes.filter((i) => !i.view.columns.includes(cmd.name));
999
+ break;
1000
+ case "AT_AlterColumnType": {
1001
+ const c = col();
1002
+ const tn = cmd.def?.ColumnDef?.typeName;
1003
+ if (c && tn) {
1004
+ c.view.type = typeText(tn);
1005
+ c.key.type = typeKey(tn);
1006
+ }
1007
+ break;
1008
+ }
1009
+ case "AT_SetNotNull":
1010
+ case "AT_DropNotNull": {
1011
+ const c = col();
1012
+ if (c) c.view.notNull = cmd.subtype === "AT_SetNotNull";
1013
+ break;
1014
+ }
1015
+ case "AT_ColumnDefault": {
1016
+ const c = col();
1017
+ if (!c) break;
1018
+ if (cmd.def) {
1019
+ c.view.default = exprText(cmd.def);
1020
+ c.key.default = nodeKey(cmd.def);
1021
+ } else {
1022
+ delete c.view.default;
1023
+ delete c.key.default;
1024
+ }
1025
+ break;
1026
+ }
1027
+ case "AT_AddConstraint":
1028
+ if (cmd.def?.Constraint) this.addConstraint(t, cmd.def.Constraint);
1029
+ break;
1030
+ case "AT_DropConstraint":
1031
+ t.constraints = t.constraints.filter((c) => c.view.name !== cmd.name);
1032
+ break;
1033
+ default:
1034
+ this.ignore(`ALTER TABLE ${String(cmd.subtype).replace(/^AT_/, "")}`);
1035
+ }
1036
+ }
1037
+ }
1038
+ createIndex(v) {
1039
+ const t = this.table(v.relation, "CREATE INDEX");
1040
+ if (!t) return;
1041
+ const columns = (v.indexParams ?? []).map((p) => {
1042
+ const e = p.IndexElem ?? {};
1043
+ let text = e.name ? ident(e.name) : `(${exprText(e.expr)})`;
1044
+ if (e.expr?.FuncCall) text = exprText(e.expr);
1045
+ if (e.ordering === "SORTBY_DESC") text += " DESC";
1046
+ if (e.nulls_ordering === "SORTBY_NULLS_FIRST") text += " NULLS FIRST";
1047
+ if (e.nulls_ordering === "SORTBY_NULLS_LAST") text += " NULLS LAST";
1048
+ return text;
1049
+ });
1050
+ const include = (v.indexIncludingParams ?? []).map((p) => p.IndexElem?.name ?? "");
1051
+ const name = v.idxname || `${t.name}_${columns.map((c) => c.replace(/\W+/g, "_")).join("_")}_idx`;
1052
+ const view = {
1053
+ name,
1054
+ unique: !!v.unique,
1055
+ ...v.accessMethod && v.accessMethod !== "btree" && { method: v.accessMethod },
1056
+ columns,
1057
+ ...include.length && { include },
1058
+ ...v.whereClause && { where: exprText(v.whereClause) }
1059
+ };
1060
+ const key = nodeKey({
1061
+ unique: v.unique,
1062
+ method: v.accessMethod ?? "btree",
1063
+ params: v.indexParams,
1064
+ include: v.indexIncludingParams,
1065
+ where: v.whereClause,
1066
+ nnd: v.nulls_not_distinct
1067
+ });
1068
+ t.indexes = t.indexes.filter((i) => i.view.name !== name);
1069
+ t.indexes.push({ view, key, loc: this.here });
1070
+ }
1071
+ // ---- types
1072
+ createEnum(v) {
1073
+ const name = this.typeName(v.typeName);
1074
+ this.s.enums.set(name, { view: { name, values: names(v.vals) }, file: this.file, loc: this.here });
1075
+ }
1076
+ alterEnum(v) {
1077
+ const name = this.typeName(v.typeName);
1078
+ const e = this.s.enums.get(name);
1079
+ if (!e) return this.note(`ALTER TYPE: \u578B ${name} \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`);
1080
+ const vals = e.view.values;
1081
+ if (v.oldVal) {
1082
+ const i = vals.indexOf(v.oldVal);
1083
+ if (i >= 0) vals[i] = v.newVal;
1084
+ return;
1085
+ }
1086
+ if (!v.newVal || vals.includes(v.newVal)) return;
1087
+ const at = v.newValNeighbor ? vals.indexOf(v.newValNeighbor) : -1;
1088
+ if (at < 0) vals.push(v.newVal);
1089
+ else vals.splice(v.newValIsAfter ? at + 1 : at, 0, v.newVal);
1090
+ }
1091
+ createDomain(v) {
1092
+ const name = this.typeName(v.domainname);
1093
+ const view = { name, type: typeText(v.typeName), notNull: false, checks: [] };
1094
+ const keyParts = [typeKey(v.typeName)];
1095
+ for (const k of v.constraints ?? []) {
1096
+ const c = k.Constraint;
1097
+ if (c?.contype === "CONSTR_NOTNULL") view.notNull = true;
1098
+ if (c?.contype === "CONSTR_DEFAULT") view.default = exprText(c.raw_expr);
1099
+ if (c?.contype === "CONSTR_CHECK") {
1100
+ const values2 = checkValues(c.raw_expr) ?? void 0;
1101
+ view.checks.push({
1102
+ name: c.conname || `${names(v.domainname).at(-1)}_check`,
1103
+ kind: "check",
1104
+ columns: [],
1105
+ definition: `CHECK (${exprText(c.raw_expr)})`,
1106
+ ...values2 && { values: values2 }
1107
+ });
1108
+ }
1109
+ keyParts.push({ ...c, location: void 0 });
1110
+ }
1111
+ this.s.domains.set(name, { view, file: this.file, loc: this.here, key: nodeKey(keyParts) });
1112
+ }
1113
+ // ---- renames and comments
1114
+ rename(v) {
1115
+ switch (v.renameType) {
1116
+ case "OBJECT_TABLE": {
1117
+ const from = this.rel(v.relation);
1118
+ const t = this.s.tables.get(from.key);
1119
+ if (!t) return this.note(`RENAME: \u30C6\u30FC\u30D6\u30EB ${from.key} \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`);
1120
+ this.s.tables.delete(from.key);
1121
+ t.name = v.newname;
1122
+ this.s.tables.set(qualified(t.schema, t.name), t);
1123
+ return;
1124
+ }
1125
+ case "OBJECT_COLUMN": {
1126
+ const t = this.table(v.relation, "RENAME COLUMN");
1127
+ const c = t?.columns.find((x) => x.view.name === v.subname);
1128
+ if (!t || !c) return;
1129
+ c.view.name = v.newname;
1130
+ for (const k of t.constraints) k.view.columns = k.view.columns.map((x) => x === v.subname ? v.newname : x);
1131
+ return;
1132
+ }
1133
+ case "OBJECT_TABCONSTRAINT": {
1134
+ const t = this.table(v.relation, "RENAME CONSTRAINT");
1135
+ const c = t?.constraints.find((x) => x.view.name === v.subname);
1136
+ if (c) c.view.name = v.newname;
1137
+ return;
1138
+ }
1139
+ default:
1140
+ this.ignore(`RENAME ${String(v.renameType).replace("OBJECT_", "")}`);
1141
+ }
1142
+ }
1143
+ comment(v) {
1144
+ const text = v.comment ?? void 0;
1145
+ if (v.objtype === "OBJECT_TABLE") {
1146
+ const n = names(v.object?.List?.items);
1147
+ const key = n.length > 1 ? n.join(".") : qualified(this.searchPath, n[0] ?? "");
1148
+ const t = this.s.tables.get(key);
1149
+ if (t) t.comment = text;
1150
+ return;
1151
+ }
1152
+ if (v.objtype === "OBJECT_COLUMN") {
1153
+ const n = names(v.object?.List?.items);
1154
+ const colName = n.pop() ?? "";
1155
+ const key = n.length > 1 ? n.join(".") : qualified(this.searchPath, n[0] ?? "");
1156
+ const c = this.s.tables.get(key)?.columns.find((x) => x.view.name === colName);
1157
+ if (c) {
1158
+ if (text === void 0) delete c.view.comment;
1159
+ else c.view.comment = text;
1160
+ }
1161
+ return;
1162
+ }
1163
+ this.ignore(`COMMENT ON ${String(v.objtype).replace("OBJECT_", "")}`);
1164
+ }
1165
+ };
1166
+ function schemaLocations(s) {
1167
+ const out = /* @__PURE__ */ new Map();
1168
+ for (const [key, t] of s.tables) {
1169
+ out.set(key, t.loc);
1170
+ for (const c of t.columns) out.set(`${key}.${c.view.name}`, c.loc);
1171
+ for (const c of t.constraints) out.set(`${key}:${c.view.name}`, c.loc);
1172
+ for (const i of t.indexes) if (!out.has(`${key}:${i.view.name}`)) out.set(`${key}:${i.view.name}`, i.loc);
1173
+ }
1174
+ for (const [key, e] of s.enums) out.set(key, e.loc);
1175
+ for (const [key, d] of s.domains) out.set(key, d.loc);
1176
+ return out;
1177
+ }
1178
+
1179
+ // ../dbshape/src/sources.ts
1180
+ import { posix } from "node:path";
1181
+ var stripComments = (content) => content.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"])(#|\/\/).*$/gm, "$1");
1182
+ function srcPaths(configPath, text) {
1183
+ const dir = posix.dirname(configPath);
1184
+ const out = [];
1185
+ for (const m of text.matchAll(/\bsrc\s*=\s*(\[[^\]]*\]|"[^"]*")/g)) {
1186
+ for (const f of m[1].matchAll(/"file:\/\/([^"]+)"/g)) {
1187
+ const p = posix.normalize(posix.join(dir === "." ? "" : dir, f[1])).replace(/^\.\//, "").replace(/\/$/, "");
1188
+ if (!out.includes(p)) out.push(p);
1189
+ }
1190
+ }
1191
+ return out;
1192
+ }
1193
+ function atlasEnvs(configPath, content) {
1194
+ const text = stripComments(content);
1195
+ const envs = [];
1196
+ let outside = "";
1197
+ let last = 0;
1198
+ for (const m of text.matchAll(/\benv\s*(?:"([^"]*)"\s*)?\{/g)) {
1199
+ const start = m.index;
1200
+ if (start < last) continue;
1201
+ let depth = 0;
1202
+ let end = start + m[0].length - 1;
1203
+ for (; end < text.length; end++) {
1204
+ if (text[end] === "{") depth++;
1205
+ else if (text[end] === "}" && --depth === 0) break;
1206
+ }
1207
+ outside += text.slice(last, start);
1208
+ envs.push({ name: m[1] ?? "", sources: srcPaths(configPath, text.slice(start, end + 1)) });
1209
+ last = end + 1;
1210
+ }
1211
+ outside += text.slice(last);
1212
+ const top = srcPaths(configPath, outside);
1213
+ if (top.length) envs.unshift({ name: "", sources: top });
1214
+ return envs.filter((e) => e.sources.length > 0);
1215
+ }
1216
+ function atlasDatabases(configPath, content, files) {
1217
+ const groups = [];
1218
+ for (const env of atlasEnvs(configPath, content)) {
1219
+ const own = [];
1220
+ for (const src of env.sources) for (const f of expandSource(src, files)) if (!own.includes(f)) own.push(f);
1221
+ if (!own.length) continue;
1222
+ const shared = groups.filter((g) => g.files.some((f) => own.includes(f)));
1223
+ const merged = { envs: [...shared.flatMap((g) => g.envs), env.name], files: [...shared.flatMap((g) => g.files)] };
1224
+ for (const f of own) if (!merged.files.includes(f)) merged.files.push(f);
1225
+ for (const g of shared) groups.splice(groups.indexOf(g), 1);
1226
+ groups.push(merged);
1227
+ }
1228
+ return groups;
1229
+ }
1230
+ function schemaPatterns(patterns) {
1231
+ const out = /* @__PURE__ */ new Map();
1232
+ for (const p of patterns) {
1233
+ const m = /^([\w.-]+)=(.+)$/.exec(p);
1234
+ const [name, glob] = m ? [m[1], m[2]] : ["", p];
1235
+ out.set(name, [...out.get(name) ?? [], glob]);
1236
+ }
1237
+ return out;
1238
+ }
1239
+ function atlasConfigs(files) {
1240
+ return files.filter((f) => {
1241
+ const segs = f.split("/");
1242
+ return segs.at(-1) === "atlas.hcl" && !segs.some((s) => s === "node_modules" || s.startsWith(".") && s.length > 1);
1243
+ });
1244
+ }
1245
+ function expandSource(src, files) {
1246
+ if (files.includes(src)) return src.endsWith(".sql") ? [src] : [];
1247
+ const prefix = `${src}/`;
1248
+ return files.filter((f) => f.startsWith(prefix) && !f.slice(prefix.length).includes("/") && f.endsWith(".sql")).sort();
1249
+ }
1250
+ function globRegex(glob) {
1251
+ let re = "";
1252
+ for (let i = 0; i < glob.length; i++) {
1253
+ const c = glob[i];
1254
+ if (c === "*") {
1255
+ if (glob[i + 1] === "*") {
1256
+ const slash = glob[i + 2] === "/";
1257
+ re += slash ? "(?:.*/)?" : ".*";
1258
+ i += slash ? 2 : 1;
1259
+ } else re += "[^/]*";
1260
+ } else if (c === "?") re += "[^/]";
1261
+ else if (c === "{") {
1262
+ const end = glob.indexOf("}", i);
1263
+ if (end < 0) re += "\\{";
1264
+ else {
1265
+ re += `(?:${glob.slice(i + 1, end).split(",").map((s) => s.replace(/[.+^$()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*")).join("|")})`;
1266
+ i = end;
1267
+ }
1268
+ } else re += c.replace(/[.+^$()|[\]\\]/g, "\\$&");
1269
+ }
1270
+ return new RegExp(`^${re}$`);
1271
+ }
1272
+ function matchGlobs(patterns, files) {
1273
+ const res = patterns.map((p) => globRegex(p.replace(/^\.\//, "")));
1274
+ return files.filter((f) => res.some((r) => r.test(f))).sort();
1275
+ }
1276
+
1277
+ // ../dbshape/src/analyze.ts
1278
+ var dirName = (config) => posix2.dirname(config) === "." ? "(\u30EB\u30FC\u30C8)" : posix2.dirname(config);
1279
+ async function findDatabases(root, source, opts) {
1280
+ const all = await listFiles(root, source);
1281
+ if (opts.schema?.length) {
1282
+ return [...schemaPatterns(opts.schema)].map(([name, globs]) => ({
1283
+ id: `schema:${name}`,
1284
+ name: name || globs.join(" "),
1285
+ files: matchGlobs(globs, all),
1286
+ schemaFrom: { kind: "option", patterns: globs }
1287
+ }));
1288
+ }
1289
+ const configs = atlasConfigs(all);
1290
+ const contents = await readFiles(root, source, configs);
1291
+ const out = [];
1292
+ for (const c of configs) {
1293
+ const groups = atlasDatabases(c, contents.get(c) ?? "", all);
1294
+ for (const g of groups) {
1295
+ const several = groups.length > 1;
1296
+ const envs = g.envs.filter(Boolean);
1297
+ out.push({
1298
+ id: several ? `${c}#${[...g.envs].sort().join(",")}` : c,
1299
+ name: several && envs.length ? `${dirName(c)}\uFF08${envs.join(", ")}\uFF09` : dirName(c),
1300
+ files: g.files,
1301
+ schemaFrom: { kind: "atlas", configs: [c], ...envs.length && { envs } }
1302
+ });
1303
+ }
1304
+ }
1305
+ return out;
1306
+ }
1307
+ async function readSide(root, source, files) {
1308
+ const contents = await readFiles(root, source, files);
1309
+ return files.filter((f) => contents.has(f)).map((f) => ({ path: f, sql: contents.get(f) }));
1310
+ }
1311
+ var loaded;
1312
+ async function parser() {
1313
+ loaded ??= loadModule();
1314
+ await loaded;
1315
+ return parseSync;
1316
+ }
1317
+ function ignoredList(s) {
1318
+ return [...s.ignored].map(([statement, count]) => ({ statement, count })).sort((a, b) => b.count - a.count || a.statement.localeCompare(b.statement));
1319
+ }
1320
+ function locations(before, after) {
1321
+ const out = {};
1322
+ for (const [k, l] of schemaLocations(after)) out[k] = { file: l.file, line: l.line };
1323
+ for (const [k, l] of schemaLocations(before)) if (!(k in out)) out[k] = { file: l.file, line: l.line, base: true };
1324
+ return out;
1325
+ }
1326
+ async function analyzeSources({ root, target, base, targetLabel, baseLabel }, opts = {}) {
1327
+ const [t, b] = await Promise.all([findDatabases(root, target, opts), findDatabases(root, base, opts)]);
1328
+ const ids = [.../* @__PURE__ */ new Set([...t.map((d) => d.id), ...b.map((d) => d.id)])];
1329
+ const pairs = ids.map((id) => {
1330
+ const after = t.find((d) => d.id === id);
1331
+ const before = b.find((d) => d.id === id);
1332
+ const main = after ?? before;
1333
+ const files = [...after?.files ?? [], ...(before?.files ?? []).filter((f) => !after?.files.includes(f))];
1334
+ return { ...main, files };
1335
+ });
1336
+ if (pairs.every((p) => p.files.length === 0)) {
1337
+ throw new Error(
1338
+ opts.schema?.length ? `--schema \u306B\u4E00\u81F4\u3059\u308B SQL \u30D5\u30A1\u30A4\u30EB\u304C\u3042\u308A\u307E\u305B\u3093\uFF08${opts.schema.join(", ")}\uFF09` : "\u30B9\u30AD\u30FC\u30DE\u306E SQL \u30D5\u30A1\u30A4\u30EB\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002atlas.hcl \u306E src \u3092\u8AAD\u3081\u306A\u304B\u3063\u305F\u306E\u3067\u3001--schema 'db/**/*.sql' \u306E\u3088\u3046\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"
1339
+ );
1340
+ }
1341
+ const parse = await parser();
1342
+ const generatedAt = (/* @__PURE__ */ new Date()).toISOString();
1343
+ const databases = await Promise.all(
1344
+ pairs.filter((p) => p.files.length > 0).sort((x, y) => x.name.localeCompare(y.name)).map(async (db) => {
1345
+ const [afterFiles, beforeFiles] = await Promise.all([readSide(root, target, db.files), readSide(root, base, db.files)]);
1346
+ const after = buildSchema(afterFiles, parse);
1347
+ const before = buildSchema(beforeFiles, parse);
1348
+ const diff = diffSchemas(before, after);
1349
+ const warnings = [];
1350
+ for (const [side, s] of [
1351
+ ["\u6BD4\u8F03\u5143", before],
1352
+ ["\u5909\u66F4\u5F8C", after]
1353
+ ]) {
1354
+ for (const [file, err] of s.errors) warnings.push(`${side}\u306E ${file} \u3092\u89E3\u6790\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08\u3053\u306E\u30D5\u30A1\u30A4\u30EB\u306E\u30C6\u30FC\u30D6\u30EB\u306F\u6BD4\u8F03\u304B\u3089\u5916\u3057\u3066\u3044\u307E\u3059\uFF09: ${err}`);
1355
+ }
1356
+ warnings.push(...after.notes.map((n) => `\u5909\u66F4\u5F8C: ${n}`), ...before.notes.map((n) => `\u6BD4\u8F03\u5143: ${n}`));
1357
+ return {
1358
+ database: { id: db.id, name: db.name },
1359
+ repoRoot: root,
1360
+ generatedAt,
1361
+ base: { label: baseLabel, files: beforeFiles.map((f) => f.path) },
1362
+ target: { label: targetLabel, files: afterFiles.map((f) => f.path) },
1363
+ schemaFrom: db.schemaFrom,
1364
+ diff,
1365
+ er: erTables(before, after, diff),
1366
+ locations: locations(before, after),
1367
+ ignored: ignoredList(after),
1368
+ warnings
1369
+ };
1370
+ })
1371
+ );
1372
+ return { repoRoot: root, generatedAt, targetLabel, baseLabel, databases };
1373
+ }
1374
+
1375
+ // ../dbshape/src/names.ts
1376
+ function schemaFromText(f) {
1377
+ if (f.kind === "option") return `--schema ${f.patterns.join(" ")}`;
1378
+ const envs = f.envs?.filter(Boolean) ?? [];
1379
+ return `${f.configs.join(", ")}${envs.length ? `\uFF08env: ${envs.join(", ")}\uFF09` : ""} \u306E src`;
1380
+ }
1381
+
1382
+ // ../dbshape/src/format.ts
1383
+ var ansi = (code) => (s) => `\x1B[${code}m${s}\x1B[0m`;
1384
+ var COLORS = { add: ansi("32"), del: ansi("31"), mod: ansi("33"), dim: ansi("2"), bold: ansi("1") };
1385
+ var PLAIN = { add: (s) => s, del: (s) => s, mod: (s) => s, dim: (s) => s, bold: (s) => s };
1386
+ function column(c) {
1387
+ const parts = [c.type];
1388
+ if (c.notNull) parts.push("NOT NULL");
1389
+ if (c.default !== void 0) parts.push(`DEFAULT ${c.default}`);
1390
+ if (c.identity) parts.push(`GENERATED ${c.identity === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY`);
1391
+ if (c.generated) parts.push(`GENERATED ALWAYS AS (${c.generated}) STORED`);
1392
+ return parts.join(" ");
1393
+ }
1394
+ function indexText(i) {
1395
+ return `${i.unique ? "UNIQUE " : ""}INDEX ${i.method ? `USING ${i.method} ` : ""}(${i.columns.join(", ")})${i.include ? ` INCLUDE (${i.include.join(", ")})` : ""}${i.where ? ` WHERE ${i.where}` : ""}`;
1396
+ }
1397
+ var values = (v) => v.map((x) => `'${x}'`).join(", ");
1398
+ function tableLines(t, c) {
1399
+ const out = [];
1400
+ const mark = { added: c.add("+"), removed: c.del("-"), modified: c.mod("~") };
1401
+ const full = t.status !== "modified";
1402
+ for (const col of t.columns) {
1403
+ if (full) {
1404
+ out.push(` ${col.name} ${c.dim(column(col.after ?? col.before))}`);
1405
+ continue;
1406
+ }
1407
+ if (col.status === "modified") {
1408
+ out.push(` ${mark.modified} ${col.name} ${c.dim(column(col.before))} \u2192 ${column(col.after)}`);
1409
+ } else {
1410
+ out.push(` ${mark[col.status]} ${col.name} ${column(col.after ?? col.before)}`);
1411
+ }
1412
+ }
1413
+ for (const k of t.constraints) {
1414
+ const v = k.after ?? k.before;
1415
+ if (full) out.push(` ${c.dim(`${v.name}: ${v.definition}`)}`);
1416
+ else if (k.status === "modified") out.push(` ${mark.modified} ${k.name} ${c.dim(k.before.definition)} \u2192 ${k.after.definition}`);
1417
+ else out.push(` ${mark[k.status]} ${k.name} ${v.definition}`);
1418
+ }
1419
+ for (const i of t.indexes) {
1420
+ const v = i.after ?? i.before;
1421
+ if (full) out.push(` ${c.dim(`${v.name}: ${indexText(v)}`)}`);
1422
+ else if (i.status === "modified") out.push(` ${mark.modified} ${i.name} ${c.dim(indexText(i.before))} \u2192 ${indexText(i.after)}`);
1423
+ else out.push(` ${mark[i.status]} ${i.name} ${indexText(v)}`);
1424
+ }
1425
+ if (t.comment && !full) out.push(` ${mark.modified} COMMENT ${c.dim(t.comment.before ?? "(\u306A\u3057)")} \u2192 ${t.comment.after ?? "(\u306A\u3057)"}`);
1426
+ return out;
1427
+ }
1428
+ function valueLine(v, c) {
1429
+ const where = v.source === "check" ? `${v.table}.${v.column}` : `${v.type}\uFF08${v.source === "enum" ? "ENUM \u578B" : "DOMAIN"}\uFF09`;
1430
+ const what = v.status === "added" ? `CHECK \u3067\u5024\u3092\u5236\u9650: ${values(v.added)}` : v.status === "removed" ? `\u5024\u306E\u5236\u9650\u304C\u306A\u304F\u306A\u3063\u305F\uFF08${values(v.removed)}\uFF09` : [...v.added.map((x) => c.add(`+'${x}'`)), ...v.removed.map((x) => c.del(`-'${x}'`))].join(" ");
1431
+ const extra = v.source === "check" ? c.dim(` CHECK ${v.constraint}`) : v.usedBy?.length ? c.dim(` \u4F7F\u7528: ${v.usedBy.join(", ")}`) : "";
1432
+ return ` ${where} ${what}${extra}`;
1433
+ }
1434
+ function formatSummary(r, c = PLAIN, opts = {}) {
1435
+ const d = r.diff;
1436
+ const added = d.tables.filter((t) => t.status === "added");
1437
+ const modified = d.tables.filter((t) => t.status === "modified");
1438
+ const removed = d.tables.filter((t) => t.status === "removed");
1439
+ const out = [];
1440
+ if (opts.header !== false) out.push(c.bold(`${r.target.label} vs ${r.base.label}`));
1441
+ out.push(c.dim(`\u30B9\u30AD\u30FC\u30DE: ${r.target.files.length} \u30D5\u30A1\u30A4\u30EB\uFF08${schemaFromText(r.schemaFrom)}\uFF09\u3001\u5909\u66F4\u306E\u306A\u3044\u30C6\u30FC\u30D6\u30EB ${d.unchangedTables}`));
1442
+ out.push("");
1443
+ const section = (title, items, mark) => {
1444
+ out.push(c.bold(`${title} (${items.length})`));
1445
+ for (const t of items) {
1446
+ out.push(` ${mark} ${t.name}${t.status !== "modified" ? c.dim(` ${t.columns.length} \u30AB\u30E9\u30E0 ${t.file}`) : ""}`);
1447
+ out.push(...tableLines(t, c));
1448
+ }
1449
+ out.push("");
1450
+ };
1451
+ section("\u65B0\u898F\u30C6\u30FC\u30D6\u30EB", added, c.add("+"));
1452
+ section("\u5909\u66F4\u3057\u305F\u30C6\u30FC\u30D6\u30EB", modified, c.mod("~"));
1453
+ section("\u524A\u9664\u3057\u305F\u30C6\u30FC\u30D6\u30EB", removed, c.del("-"));
1454
+ out.push(c.bold(`\u5024\u306E\u5909\u5316 (${d.values.length})`));
1455
+ for (const v of d.values) out.push(valueLine(v, c));
1456
+ out.push("");
1457
+ const types = [...d.enums.map((e) => ({ ...e, kind: "ENUM \u578B" })), ...d.domains.map((e) => ({ ...e, kind: "DOMAIN" }))];
1458
+ if (types.length) {
1459
+ out.push(c.bold(`\u578B (${types.length})`));
1460
+ for (const t of types) {
1461
+ const mark = t.status === "added" ? c.add("+") : t.status === "removed" ? c.del("-") : c.mod("~");
1462
+ out.push(` ${mark} ${t.name} ${c.dim(t.kind)}`);
1463
+ }
1464
+ out.push("");
1465
+ }
1466
+ if (r.ignored.length) {
1467
+ out.push(c.dim(`\u6BD4\u8F03\u3057\u3066\u3044\u306A\u3044\u6587: ${r.ignored.map((i) => `${i.statement} ${i.count}`).join(", ")}`));
1468
+ }
1469
+ for (const w of r.warnings) out.push(c.mod(`\u6CE8\u610F: ${w}`));
1470
+ return out.join("\n").replace(/\n+$/, "") + "\n";
1471
+ }
1472
+ function formatRunSummary(run2, c = PLAIN) {
1473
+ if (run2.databases.length === 1) return formatSummary(run2.databases[0], c);
1474
+ const parts = run2.databases.map((d) => `${c.bold(`\u25A0 DB: ${d.database.name}`)}
1475
+ ${formatSummary(d, c, { header: false })}`);
1476
+ return `${c.bold(`${run2.targetLabel} vs ${run2.baseLabel}`)}
1477
+
1478
+ ${parts.join("\n")}`;
1479
+ }
1480
+
1481
+ // ../dbshape/src/index.ts
1482
+ var dbAnalyzer = (opts = {}) => ({ id: "db", analyze: (s) => analyzeSources(s, opts) });
1483
+
1484
+ // ../depshape/src/analyze.ts
1485
+ import { createHash } from "node:crypto";
1486
+ import { posix as posix4 } from "node:path";
1487
+
1488
+ // ../depshape/src/go.ts
1489
+ function parseGoModModulePath(content) {
1490
+ for (const raw of content.split("\n")) {
1491
+ const line = raw.replace(/\/\/.*$/, "").trim();
1492
+ const m = /^module\s+("?)([^\s"]+)\1$/.exec(line);
1493
+ if (m) return m[2];
1494
+ }
1495
+ return null;
1496
+ }
1497
+ function* tokenize(src) {
1498
+ let i = 0;
1499
+ const n = src.length;
1500
+ while (i < n) {
1501
+ const c = src[i];
1502
+ if (c === " " || c === " " || c === "\r" || c === "\n") {
1503
+ i++;
1504
+ continue;
1505
+ }
1506
+ if (c === "/" && src[i + 1] === "/") {
1507
+ const end = src.indexOf("\n", i);
1508
+ i = end === -1 ? n : end + 1;
1509
+ continue;
1510
+ }
1511
+ if (c === "/" && src[i + 1] === "*") {
1512
+ const end = src.indexOf("*/", i + 2);
1513
+ i = end === -1 ? n : end + 2;
1514
+ continue;
1515
+ }
1516
+ if (c === '"') {
1517
+ let j = i + 1;
1518
+ let value = "";
1519
+ while (j < n && src[j] !== '"' && src[j] !== "\n") {
1520
+ if (src[j] === "\\") {
1521
+ value += src[j + 1] ?? "";
1522
+ j += 2;
1523
+ } else {
1524
+ value += src[j];
1525
+ j++;
1526
+ }
1527
+ }
1528
+ i = j + 1;
1529
+ yield { kind: "string", value };
1530
+ continue;
1531
+ }
1532
+ if (c === "`") {
1533
+ const end = src.indexOf("`", i + 1);
1534
+ const value = src.slice(i + 1, end === -1 ? n : end);
1535
+ i = end === -1 ? n : end + 1;
1536
+ yield { kind: "string", value };
1537
+ continue;
1538
+ }
1539
+ if (/[A-Za-z_\u0080-￿]/.test(c)) {
1540
+ let j = i + 1;
1541
+ while (j < n && /[A-Za-z0-9_\u0080-￿]/.test(src[j])) j++;
1542
+ yield { kind: "ident", value: src.slice(i, j) };
1543
+ i = j;
1544
+ continue;
1545
+ }
1546
+ yield { kind: "punct", value: c };
1547
+ i++;
1548
+ }
1549
+ }
1550
+ function parseGoImports(src) {
1551
+ const tokens = tokenize(src);
1552
+ const next = () => {
1553
+ const r = tokens.next();
1554
+ return r.done ? null : r.value;
1555
+ };
1556
+ let t = next();
1557
+ if (!t || t.kind !== "ident" || t.value !== "package") return [];
1558
+ t = next();
1559
+ if (!t) return [];
1560
+ const imports = [];
1561
+ t = next();
1562
+ while (t) {
1563
+ if (t.kind === "punct" && t.value === ";") {
1564
+ t = next();
1565
+ continue;
1566
+ }
1567
+ if (!(t.kind === "ident" && t.value === "import")) break;
1568
+ t = next();
1569
+ if (!t) break;
1570
+ if (t.kind === "punct" && t.value === "(") {
1571
+ t = next();
1572
+ while (t && !(t.kind === "punct" && t.value === ")")) {
1573
+ if (t.kind === "string") imports.push(t.value);
1574
+ t = next();
1575
+ }
1576
+ t = next();
1577
+ continue;
1578
+ }
1579
+ if (t.kind !== "string") t = next();
1580
+ if (t && t.kind === "string") imports.push(t.value);
1581
+ t = next();
1582
+ }
1583
+ return imports;
1584
+ }
1585
+ function isStdlib(importPath) {
1586
+ const first = importPath.split("/")[0];
1587
+ return !first.includes(".");
1588
+ }
1589
+
1590
+ // ../depshape/src/ts.ts
1591
+ import { builtinModules } from "node:module";
1592
+ import { posix as posix3 } from "node:path";
1593
+ var TS_EXTS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
1594
+ function isTsFile(path) {
1595
+ return TS_EXTS.some((e) => path.endsWith(e)) && !path.endsWith(".min.js");
1596
+ }
1597
+ function isTsTest(path) {
1598
+ return /\.(test|spec)\.[cm]?[jt]sx?$/.test(path);
1599
+ }
1600
+ var REGEX_AFTER_KEYWORD = /* @__PURE__ */ new Set([
1601
+ "return",
1602
+ "typeof",
1603
+ "instanceof",
1604
+ "in",
1605
+ "of",
1606
+ "new",
1607
+ "delete",
1608
+ "void",
1609
+ "throw",
1610
+ "case",
1611
+ "do",
1612
+ "else",
1613
+ "yield",
1614
+ "await"
1615
+ ]);
1616
+ function* tokenize2(src) {
1617
+ let i = 0;
1618
+ const n = src.length;
1619
+ let prev = null;
1620
+ const tpl = [];
1621
+ let depth = 0;
1622
+ const OPERAND_END = /* @__PURE__ */ new Set([")", "]", "}", "num", "regex", "`"]);
1623
+ const regexAllowed = () => prev === null || prev.t === "p" && !OPERAND_END.has(prev.v) || prev.t === "id" && REGEX_AFTER_KEYWORD.has(prev.v);
1624
+ const readTemplate = () => {
1625
+ while (i < n) {
1626
+ const c = src[i];
1627
+ if (c === "\\") {
1628
+ i += 2;
1629
+ } else if (c === "`") {
1630
+ i++;
1631
+ return;
1632
+ } else if (c === "$" && src[i + 1] === "{") {
1633
+ i += 2;
1634
+ tpl.push(depth);
1635
+ depth++;
1636
+ return;
1637
+ } else i++;
1638
+ }
1639
+ };
1640
+ while (i < n) {
1641
+ const c = src[i];
1642
+ if (c === " " || c === " " || c === "\n" || c === "\r" || c === "\f" || c === "\v" || c === "\uFEFF") {
1643
+ i++;
1644
+ continue;
1645
+ }
1646
+ if (c === "/" && src[i + 1] === "/") {
1647
+ while (i < n && src[i] !== "\n") i++;
1648
+ continue;
1649
+ }
1650
+ if (c === "/" && src[i + 1] === "*") {
1651
+ const end = src.indexOf("*/", i + 2);
1652
+ i = end === -1 ? n : end + 2;
1653
+ continue;
1654
+ }
1655
+ if (c === "'" || c === '"') {
1656
+ let j = i + 1;
1657
+ let v = "";
1658
+ while (j < n && src[j] !== c && src[j] !== "\n") {
1659
+ if (src[j] === "\\") {
1660
+ v += src[j + 1] ?? "";
1661
+ j += 2;
1662
+ } else v += src[j++];
1663
+ }
1664
+ i = j + 1;
1665
+ yield prev = { t: "str", v };
1666
+ continue;
1667
+ }
1668
+ if (c === "`") {
1669
+ i++;
1670
+ readTemplate();
1671
+ yield prev = { t: "p", v: "`" };
1672
+ continue;
1673
+ }
1674
+ if (c === "/" && regexAllowed()) {
1675
+ let j = i + 1;
1676
+ let cls = false;
1677
+ while (j < n && src[j] !== "\n") {
1678
+ const d = src[j];
1679
+ if (d === "\\") j += 2;
1680
+ else if (d === "[") cls = true, j++;
1681
+ else if (d === "]") cls = false, j++;
1682
+ else if (d === "/" && !cls) break;
1683
+ else j++;
1684
+ }
1685
+ i = j + 1;
1686
+ while (i < n && /[a-z]/i.test(src[i])) i++;
1687
+ yield prev = { t: "p", v: "regex" };
1688
+ continue;
1689
+ }
1690
+ if (/[A-Za-z_$]/.test(c) || c.charCodeAt(0) > 127) {
1691
+ let j = i + 1;
1692
+ while (j < n && (/[A-Za-z0-9_$]/.test(src[j]) || src.charCodeAt(j) > 127)) j++;
1693
+ yield prev = { t: "id", v: src.slice(i, j) };
1694
+ i = j;
1695
+ continue;
1696
+ }
1697
+ if (/[0-9]/.test(c)) {
1698
+ let j = i + 1;
1699
+ while (j < n && /[0-9a-zA-Z_.]/.test(src[j])) j++;
1700
+ i = j;
1701
+ yield prev = { t: "p", v: "num" };
1702
+ continue;
1703
+ }
1704
+ if (c === "{") depth++;
1705
+ if (c === "}") {
1706
+ if (tpl.length && tpl[tpl.length - 1] === depth - 1) {
1707
+ tpl.pop();
1708
+ depth--;
1709
+ i++;
1710
+ readTemplate();
1711
+ yield prev = { t: "p", v: "`" };
1712
+ continue;
1713
+ }
1714
+ depth--;
1715
+ }
1716
+ i++;
1717
+ yield prev = { t: "p", v: c };
1718
+ }
1719
+ }
1720
+ function parseTsImports(src) {
1721
+ const toks = [...tokenize2(src)];
1722
+ const out = [];
1723
+ const at = (k) => toks[k];
1724
+ const isP = (k, v) => at(k)?.t === "p" && at(k).v === v;
1725
+ const isId = (k, v) => at(k)?.t === "id" && at(k).v === v;
1726
+ const afterDot = (k) => isP(k - 1, ".");
1727
+ const findFrom = (k) => {
1728
+ let braces = 0;
1729
+ for (let j = k; j < toks.length && j < k + 400; j++) {
1730
+ const tk = toks[j];
1731
+ if (braces === 0 && j > k && tk.t === "id" && (tk.v === "import" || tk.v === "export") && !isP(j - 1, ".")) return null;
1732
+ if (tk.t === "p") {
1733
+ if (tk.v === "{") braces++;
1734
+ else if (tk.v === "}") braces--;
1735
+ else if (braces === 0 && (tk.v === ";" || tk.v === "(" || tk.v === "=" || tk.v === "`")) return null;
1736
+ }
1737
+ if (braces === 0 && tk.t === "id" && tk.v === "from" && at(j + 1)?.t === "str") return { spec: at(j + 1).v, end: j + 1 };
1738
+ }
1739
+ return null;
1740
+ };
1741
+ for (let k = 0; k < toks.length; k++) {
1742
+ const tk = toks[k];
1743
+ if (tk.t !== "id" || afterDot(k)) continue;
1744
+ if (tk.v === "import") {
1745
+ if (isP(k + 1, ".")) continue;
1746
+ if (isP(k + 1, "(")) {
1747
+ if (at(k + 2)?.t === "str") out.push({ spec: at(k + 2).v, typeOnly: false });
1748
+ continue;
1749
+ }
1750
+ if (at(k + 1)?.t === "str") {
1751
+ out.push({ spec: at(k + 1).v, typeOnly: false });
1752
+ continue;
1753
+ }
1754
+ const typeOnly = isId(k + 1, "type") && !isP(k + 2, ",") && !isId(k + 2, "from");
1755
+ const f = findFrom(k + 1);
1756
+ if (f) {
1757
+ out.push({ spec: f.spec, typeOnly });
1758
+ k = f.end;
1759
+ }
1760
+ continue;
1761
+ }
1762
+ if (tk.v === "export") {
1763
+ const typeOnly = isId(k + 1, "type") && (isP(k + 2, "{") || isP(k + 2, "*"));
1764
+ if (!(isP(k + 1, "{") || isP(k + 1, "*") || typeOnly)) continue;
1765
+ const f = findFrom(k + 1);
1766
+ if (f) {
1767
+ out.push({ spec: f.spec, typeOnly });
1768
+ k = f.end;
1769
+ }
1770
+ continue;
1771
+ }
1772
+ if (tk.v === "require" && isP(k + 1, "(") && at(k + 2)?.t === "str" && isP(k + 3, ")")) {
1773
+ out.push({ spec: at(k + 2).v, typeOnly: false });
1774
+ continue;
1775
+ }
1776
+ }
1777
+ return out;
1778
+ }
1779
+ function parseJsonc(text) {
1780
+ let out = "";
1781
+ let i = 0;
1782
+ const n = text.length;
1783
+ while (i < n) {
1784
+ const c = text[i];
1785
+ if (c === '"') {
1786
+ let j = i + 1;
1787
+ while (j < n && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
1788
+ out += text.slice(i, j + 1);
1789
+ i = j + 1;
1790
+ } else if (c === "/" && text[i + 1] === "/") {
1791
+ while (i < n && text[i] !== "\n") i++;
1792
+ } else if (c === "/" && text[i + 1] === "*") {
1793
+ const end = text.indexOf("*/", i + 2);
1794
+ i = end === -1 ? n : end + 2;
1795
+ } else {
1796
+ out += c;
1797
+ i++;
1798
+ }
1799
+ }
1800
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"));
1801
+ }
1802
+ var BUILTINS = new Set(builtinModules.flatMap((m) => [m, m.replace(/^node:/, "")]));
1803
+ function buildTsProject(files, configTexts, packageTexts) {
1804
+ const raw = /* @__PURE__ */ new Map();
1805
+ for (const [p, text] of configTexts) {
1806
+ try {
1807
+ const v = parseJsonc(text);
1808
+ if (v && typeof v === "object") raw.set(p, v);
1809
+ } catch {
1810
+ }
1811
+ }
1812
+ const effective = (p, seen = /* @__PURE__ */ new Set()) => {
1813
+ if (seen.has(p)) return {};
1814
+ seen.add(p);
1815
+ const c = raw.get(p);
1816
+ if (!c) return {};
1817
+ let inherited = {};
1818
+ const ext = c.extends;
1819
+ for (const e of Array.isArray(ext) ? ext : ext ? [ext] : []) {
1820
+ if (typeof e !== "string" || !e.startsWith(".")) continue;
1821
+ let target = posix3.normalize(posix3.join(posix3.dirname(p), e));
1822
+ if (!target.endsWith(".json")) target += ".json";
1823
+ const parent = effective(target, seen);
1824
+ inherited = { ...inherited, ...Object.fromEntries(Object.entries(parent).filter(([, v]) => v !== void 0)) };
1825
+ }
1826
+ const co = c.compilerOptions ?? {};
1827
+ const dir = dirOf(p);
1828
+ const res = { ...inherited };
1829
+ if (typeof co.baseUrl === "string") res.baseUrl = [dir, co.baseUrl];
1830
+ if (co.paths && typeof co.paths === "object") res.paths = [dir, co.paths];
1831
+ return res;
1832
+ };
1833
+ const configs = [];
1834
+ for (const p of raw.keys()) {
1835
+ const name = posix3.basename(p);
1836
+ if (name !== "tsconfig.json" && name !== "jsconfig.json") continue;
1837
+ const e = effective(p);
1838
+ const baseUrl = e.baseUrl ? posix3.normalize(posix3.join(e.baseUrl[0], e.baseUrl[1])) : null;
1839
+ const pathsBase = e.paths ? baseUrl ?? e.paths[0] : null;
1840
+ configs.push({
1841
+ dir: dirOf(p),
1842
+ baseUrl: baseUrl === "." ? "" : baseUrl,
1843
+ pathsBase: pathsBase === "." ? "" : pathsBase,
1844
+ paths: e.paths ? Object.entries(e.paths[1]).filter(([, v]) => Array.isArray(v)) : []
1845
+ });
1846
+ }
1847
+ configs.sort((a, b) => b.dir.length - a.dir.length);
1848
+ const packages = /* @__PURE__ */ new Map();
1849
+ for (const [p, text] of packageTexts) {
1850
+ try {
1851
+ const pkg = JSON.parse(text);
1852
+ if (typeof pkg.name !== "string") continue;
1853
+ const entries = [];
1854
+ const exp = pkg.exports;
1855
+ const pick = (v) => {
1856
+ if (typeof v === "string") return v;
1857
+ if (v && typeof v === "object") {
1858
+ const o = v;
1859
+ return pick(o["."]) ?? pick(o.types) ?? pick(o.import) ?? pick(o.default) ?? pick(o.require);
1860
+ }
1861
+ return void 0;
1862
+ };
1863
+ for (const v of [pick(exp), pkg.types, pkg.typings, pkg.module, pkg.main, pkg.source]) if (typeof v === "string") entries.push(v);
1864
+ entries.push("src/index", "index");
1865
+ packages.set(pkg.name, { dir: dirOf(p), entries });
1866
+ } catch {
1867
+ }
1868
+ }
1869
+ return { files, configs, packages };
1870
+ }
1871
+ function dirOf(p) {
1872
+ const d = posix3.dirname(p);
1873
+ return d === "." ? "" : d;
1874
+ }
1875
+ var JS_TO_TS = {
1876
+ ".js": [".ts", ".tsx"],
1877
+ ".jsx": [".tsx"],
1878
+ ".mjs": [".mts"],
1879
+ ".cjs": [".cts"]
1880
+ };
1881
+ var TRY_EXTS = [".ts", ".tsx", ".d.ts", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
1882
+ function resolveFile(files, base) {
1883
+ const p = posix3.normalize(base).replace(/^\.\//, "").replace(/\/$/, "");
1884
+ if (p.startsWith("..")) return null;
1885
+ if (files.has(p)) return p;
1886
+ const ext = posix3.extname(p);
1887
+ for (const alt of JS_TO_TS[ext] ?? []) {
1888
+ const cand = p.slice(0, -ext.length) + alt;
1889
+ if (files.has(cand)) return cand;
1890
+ }
1891
+ for (const e of TRY_EXTS) if (files.has(p + e)) return p + e;
1892
+ for (const e of TRY_EXTS) if (files.has(`${p}/index${e}`)) return `${p}/index${e}`;
1893
+ return null;
1894
+ }
1895
+ function packageName(spec) {
1896
+ const parts = spec.split("/");
1897
+ return spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
1898
+ }
1899
+ function resolveTsImport(project, fromFile, spec) {
1900
+ if (spec.startsWith("node:")) return { kind: "builtin" };
1901
+ const clean = spec.replace(/[?#].*$/, "");
1902
+ if (clean === "") return { kind: "unresolved" };
1903
+ if (clean.startsWith(".") || clean.startsWith("/")) {
1904
+ const target = clean.startsWith("/") ? clean.slice(1) : posix3.join(dirOf(fromFile), clean);
1905
+ const f = resolveFile(project.files, target);
1906
+ return f ? { kind: "file", path: f } : { kind: "unresolved" };
1907
+ }
1908
+ const cfg = project.configs.find((c) => c.dir === "" || fromFile.startsWith(c.dir + "/"));
1909
+ if (cfg && cfg.pathsBase !== null) {
1910
+ let best = null;
1911
+ for (const [pattern, targets] of cfg.paths) {
1912
+ const star = pattern.indexOf("*");
1913
+ if (star === -1) {
1914
+ if (pattern === clean && (!best || pattern.length > best.prefixLen)) best = { prefixLen: pattern.length, targets, star: "" };
1915
+ } else {
1916
+ const pre = pattern.slice(0, star);
1917
+ const suf = pattern.slice(star + 1);
1918
+ if (clean.startsWith(pre) && clean.endsWith(suf) && clean.length >= pre.length + suf.length && (!best || pre.length > best.prefixLen)) {
1919
+ best = { prefixLen: pre.length, targets, star: clean.slice(pre.length, clean.length - suf.length) };
1920
+ }
1921
+ }
1922
+ }
1923
+ if (best) {
1924
+ for (const t of best.targets) {
1925
+ const f = resolveFile(project.files, posix3.join(cfg.pathsBase, t.replace("*", best.star)));
1926
+ if (f) return { kind: "file", path: f };
1927
+ }
1928
+ }
1929
+ }
1930
+ if (cfg && cfg.baseUrl !== null) {
1931
+ const f = resolveFile(project.files, posix3.join(cfg.baseUrl, clean));
1932
+ if (f) return { kind: "file", path: f };
1933
+ }
1934
+ if (BUILTINS.has(clean) || BUILTINS.has(clean.split("/")[0])) return { kind: "builtin" };
1935
+ const name = packageName(clean);
1936
+ const pkg = project.packages.get(name);
1937
+ if (pkg) {
1938
+ const sub = clean.slice(name.length).replace(/^\//, "");
1939
+ if (sub) {
1940
+ const f = resolveFile(project.files, posix3.join(pkg.dir, sub)) ?? resolveFile(project.files, posix3.join(pkg.dir, "src", sub));
1941
+ if (f) return { kind: "file", path: f };
1942
+ } else {
1943
+ for (const e of pkg.entries) {
1944
+ const f = resolveFile(project.files, posix3.join(pkg.dir, e));
1945
+ if (f) return { kind: "file", path: f };
1946
+ }
1947
+ }
1948
+ }
1949
+ return { kind: "external", name };
1950
+ }
1951
+
1952
+ // ../depshape/src/analyze.ts
1953
+ function fileKind(path) {
1954
+ const segs = path.split("/");
1955
+ const name = segs[segs.length - 1];
1956
+ const hidden = segs.some((s) => s === "node_modules" || s.startsWith(".") && s.length > 1);
1957
+ if (hidden) return null;
1958
+ if (name === "go.mod" || name.endsWith(".go")) {
1959
+ if (segs.some((s) => s === "vendor" || s === "testdata" || s.startsWith("_"))) return null;
1960
+ return name === "go.mod" ? "gomod" : "go";
1961
+ }
1962
+ if (/^(tsconfig[^/]*|jsconfig)\.json$/.test(name)) return "tsconfig";
1963
+ if (name === "package.json") return "package";
1964
+ if (isTsFile(name)) return "ts";
1965
+ return null;
1966
+ }
1967
+ function countLines(c) {
1968
+ return c.length === 0 ? 0 : c.split("\n").length - (c.endsWith("\n") ? 1 : 0);
1969
+ }
1970
+ async function loadSnapshot(root, source) {
1971
+ const kinds = /* @__PURE__ */ new Map();
1972
+ for (const p of await listFiles(root, source)) {
1973
+ const k = fileKind(p);
1974
+ if (k) kinds.set(p, k);
1975
+ }
1976
+ const contents = await readFiles(root, source, [...kinds.keys()]);
1977
+ for (const p of [...kinds.keys()]) if (!contents.has(p)) kinds.delete(p);
1978
+ const modules = [];
1979
+ for (const [p, c] of contents) {
1980
+ if (posix4.basename(p) !== "go.mod") continue;
1981
+ const modPath = parseGoModModulePath(c);
1982
+ if (modPath) modules.push({ dir: dirOf2(p), path: modPath });
1983
+ }
1984
+ modules.sort((a, b) => b.path.length - a.path.length);
1985
+ const files = /* @__PURE__ */ new Map();
1986
+ for (const [p, c] of contents) {
1987
+ if (!p.endsWith(".go")) continue;
1988
+ const imports = [];
1989
+ const seen = /* @__PURE__ */ new Set();
1990
+ for (const imp of parseGoImports(c)) {
1991
+ if (isStdlib(imp)) continue;
1992
+ const local = resolveLocal(modules, imp);
1993
+ const to = local ?? imp;
1994
+ if (seen.has(to)) continue;
1995
+ seen.add(to);
1996
+ imports.push({ to, external: local === null });
1997
+ }
1998
+ files.set(p, { hash: createHash("sha1").update(c).digest("hex"), lines: countLines(c), imports });
1999
+ }
2000
+ const tsFiles = new Set([...kinds].filter(([, k]) => k === "ts").map(([p]) => p));
2001
+ if (tsFiles.size > 0) {
2002
+ const pick = (kind) => new Map([...kinds].filter(([, k]) => k === kind).map(([p]) => [p, contents.get(p)]));
2003
+ const project = buildTsProject(tsFiles, pick("tsconfig"), pick("package"));
2004
+ for (const p of tsFiles) {
2005
+ const c = contents.get(p);
2006
+ const byTo = /* @__PURE__ */ new Map();
2007
+ for (const imp of parseTsImports(c)) {
2008
+ const res = resolveTsImport(project, p, imp.spec);
2009
+ if (res.kind === "builtin" || res.kind === "unresolved") continue;
2010
+ const to = res.kind === "file" ? dirOf2(res.path) : res.name;
2011
+ let entry = byTo.get(to);
2012
+ if (!entry) byTo.set(to, entry = { external: res.kind === "external", typeOnly: true, files: /* @__PURE__ */ new Map() });
2013
+ entry.typeOnly &&= imp.typeOnly;
2014
+ if (res.kind === "file" && res.path !== p) entry.files.set(res.path, (entry.files.get(res.path) ?? true) && imp.typeOnly);
2015
+ }
2016
+ const imports = [];
2017
+ for (const [to, e] of byTo) {
2018
+ if (!e.external && e.files.size === 0) continue;
2019
+ if (e.external) {
2020
+ imports.push({ to, external: true, typeOnly: e.typeOnly });
2021
+ continue;
2022
+ }
2023
+ const typeOnlyFiles = [...e.files].filter(([, t]) => t).map(([f]) => f);
2024
+ imports.push({ to, external: false, typeOnly: e.typeOnly, files: [...e.files.keys()].sort(), ...typeOnlyFiles.length ? { typeOnlyFiles } : {} });
2025
+ }
2026
+ files.set(p, { hash: createHash("sha1").update(c).digest("hex"), lines: countLines(c), imports });
2027
+ }
2028
+ }
2029
+ return { modules, files };
2030
+ }
2031
+ function dirOf2(p) {
2032
+ const d = posix4.dirname(p);
2033
+ return d === "." ? "" : d;
2034
+ }
2035
+ function resolveLocal(modules, importPath) {
2036
+ for (const m of modules) {
2037
+ if (importPath === m.path) return m.dir;
2038
+ if (importPath.startsWith(m.path + "/")) {
2039
+ return posix4.join(m.dir, importPath.slice(m.path.length + 1));
2040
+ }
2041
+ }
2042
+ return null;
2043
+ }
2044
+ function diffSnapshots(before, after) {
2045
+ const files = [];
2046
+ const edges = [];
2047
+ const all = /* @__PURE__ */ new Set([...before.files.keys(), ...after.files.keys()]);
2048
+ for (const path of [...all].sort()) {
2049
+ const b = before.files.get(path);
2050
+ const a = after.files.get(path);
2051
+ const status = !b ? "added" : !a ? "removed" : a.hash === b.hash ? "unchanged" : "modified";
2052
+ files.push({
2053
+ path,
2054
+ dir: dirOf2(path),
2055
+ status,
2056
+ linesBefore: b?.lines ?? null,
2057
+ linesAfter: a?.lines ?? null,
2058
+ isTest: path.endsWith("_test.go") || isTsFile(path) && isTsTest(path)
2059
+ });
2060
+ const bImports = new Map((b?.imports ?? []).map((i) => [i.to, i]));
2061
+ const aImports = new Map((a?.imports ?? []).map((i) => [i.to, i]));
2062
+ for (const to of /* @__PURE__ */ new Set([...bImports.keys(), ...aImports.keys()])) {
2063
+ const ai = aImports.get(to);
2064
+ const bi = bImports.get(to);
2065
+ const edge = {
2066
+ from: path,
2067
+ to,
2068
+ external: (ai ?? bi).external,
2069
+ status: ai && bi ? "unchanged" : ai ? "added" : "removed"
2070
+ };
2071
+ const typeOnly = (ai ?? bi).typeOnly;
2072
+ if (typeOnly !== void 0) edge.typeOnly = typeOnly;
2073
+ if (ai?.files || bi?.files) {
2074
+ const bf = new Set(bi?.files ?? []);
2075
+ const af = new Set(ai?.files ?? []);
2076
+ const typeOnlyAfter = new Set(ai?.typeOnlyFiles ?? []);
2077
+ const typeOnlyBefore = new Set(bi?.typeOnlyFiles ?? []);
2078
+ edge.files = [.../* @__PURE__ */ new Set([...bf, ...af])].sort().map((f) => {
2079
+ const status2 = af.has(f) && bf.has(f) ? "unchanged" : af.has(f) ? "added" : "removed";
2080
+ const typeOnly2 = af.has(f) ? typeOnlyAfter.has(f) : typeOnlyBefore.has(f);
2081
+ return typeOnly2 ? { path: f, status: status2, typeOnly: typeOnly2 } : { path: f, status: status2 };
2082
+ });
2083
+ }
2084
+ edges.push(edge);
2085
+ }
2086
+ }
2087
+ const modules = /* @__PURE__ */ new Map();
2088
+ for (const m of [...before.modules, ...after.modules]) modules.set(m.dir, m);
2089
+ return { files, edges, modules: [...modules.values()].sort((x, y) => x.dir.localeCompare(y.dir)) };
2090
+ }
2091
+ async function analyzeSources2({ root, target, base, targetLabel, baseLabel }) {
2092
+ const [before, after] = await Promise.all([loadSnapshot(root, base), loadSnapshot(root, target)]);
2093
+ const { files, edges, modules } = diffSnapshots(before, after);
2094
+ return {
2095
+ repoRoot: root,
2096
+ targetLabel,
2097
+ baseLabel,
2098
+ modules,
2099
+ files,
2100
+ edges,
2101
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
2102
+ };
2103
+ }
2104
+
2105
+ // ../depshape/src/index.ts
2106
+ var depAnalyzer = { id: "dep", analyze: analyzeSources2 };
2107
+
2108
+ // src/app.ts
2109
+ var message = (e) => (e instanceof Error ? e.stderr || e.message : String(e)).trim();
2110
+ var App = class {
2111
+ constructor(cwd, opts, analyzers) {
2112
+ this.cwd = cwd;
2113
+ this.opts = opts;
2114
+ this.analyzers = analyzers;
2115
+ }
2116
+ sources;
2117
+ results = /* @__PURE__ */ new Map();
2118
+ /** Resolves the comparison (errors like an unknown revision are thrown) and starts every module */
2119
+ async refresh() {
2120
+ this.sources = await resolveSources(this.cwd, this.opts);
2121
+ for (const a of this.analyzers) {
2122
+ this.results.set(
2123
+ a.id,
2124
+ a.analyze(this.sources).then(
2125
+ (data) => ({ data }),
2126
+ (e) => ({ error: message(e) })
2127
+ )
2128
+ );
2129
+ }
2130
+ return this.info();
2131
+ }
2132
+ info() {
2133
+ const { root, targetLabel, baseLabel } = this.sources;
2134
+ return { repoRoot: root, targetLabel, baseLabel, modules: this.analyzers.map((a) => a.id) };
2135
+ }
2136
+ result(id) {
2137
+ return this.results.get(id) ?? Promise.resolve({ error: `unknown module: ${id}` });
2138
+ }
2139
+ };
2140
+
2141
+ // src/server.ts
2142
+ import { fileURLToPath } from "node:url";
2143
+ var UI_DIR = fileURLToPath(new URL("./ui/", import.meta.url));
2144
+ function startServer2(app, host, port) {
2145
+ const api = {
2146
+ "/api/info": async (url) => url.searchParams.get("refresh") === "1" ? app.refresh() : app.info()
2147
+ };
2148
+ for (const a of app.analyzers) api[`/api/module/${a.id}`] = () => app.result(a.id);
2149
+ return startServer({ uiDir: UI_DIR, host, port, api });
2150
+ }
2151
+
2152
+ // src/cli.ts
2153
+ var TARGETS = `target:
2154
+ . \u4F5C\u696D\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\uFF08\u672A\u30B3\u30DF\u30C3\u30C8\u306E\u5909\u66F4\u3059\u3079\u3066\uFF09 \u203B\u30C7\u30D5\u30A9\u30EB\u30C8
2155
+ staged \u30B9\u30C6\u30FC\u30B8\u6E08\u307F\u306E\u5909\u66F4
2156
+ working \u672A\u30B9\u30C6\u30FC\u30B8\u306E\u5909\u66F4\u306E\u307F\uFF08\u6BD4\u8F03\u5143\u306F\u30B9\u30C6\u30FC\u30B8\u6E08\u307F\u306E\u72B6\u614B\uFF09
2157
+ <rev> \u30B3\u30DF\u30C3\u30C8 / \u30D6\u30E9\u30F3\u30C1\uFF08@ \u306F HEAD\uFF09
2158
+
2159
+ compare-with:
2160
+ \u6BD4\u8F03\u5143\u306E\u30EA\u30D3\u30B8\u30E7\u30F3\u3002\u7701\u7565\u6642\u306F target \u304C . / staged \u306A\u3089 HEAD\u3001<rev> \u306A\u3089 <rev>^`;
2161
+ var COMMON = ` --merge-base compare-with \u3068 target \u306E\u5206\u5C90\u70B9\u3092\u6BD4\u8F03\u5143\u306B\u3059\u308B\uFF08GitHub \u306E PR \u3068\u540C\u3058\u898B\u3048\u65B9\uFF09
2162
+ --port <n> \u30DD\u30FC\u30C8\u756A\u53F7\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8 4977\u3001\u4F7F\u7528\u4E2D\u306A\u3089 +1\uFF09
2163
+ --host <host> \u5F85\u3061\u53D7\u3051\u30DB\u30B9\u30C8\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8 127.0.0.1\u30020.0.0.0 \u306A\u3069\u306B\u3059\u308B\u3068\u540C\u3058\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u304B\u3089
2164
+ \u30EA\u30DD\u30B8\u30C8\u30EA\u306E\u69CB\u6210\u304C\u898B\u3048\u308B\u306E\u3067\u6CE8\u610F\uFF09
2165
+ --no-open \u30D6\u30E9\u30A6\u30B6\u3092\u81EA\u52D5\u3067\u958B\u304B\u306A\u3044`;
2166
+ var SCHEMA = ` --schema <glob> \u30B9\u30AD\u30FC\u30DE\u306E SQL \u30D5\u30A1\u30A4\u30EB\uFF08\u8907\u6570\u6307\u5B9A\u53EF\uFF09\u3002\u7701\u7565\u6642\u306F\u30EA\u30DD\u30B8\u30C8\u30EA\u5185\u306E\u3059\u3079\u3066\u306E atlas.hcl \u306E src \u3092\u8AAD\u3080
2167
+ DB \u304C\u8907\u6570\u3042\u308B\u3068\u304D\u306F --schema billing=services/billing/**/*.sql \u306E\u3088\u3046\u306B\u540D\u524D\u3092\u4ED8\u3051\u308B`;
2168
+ var HELP = {
2169
+ all: `diffshape - git \u306E\u5DEE\u5206\u3092\u3001\u30B3\u30FC\u30C9\u306E\u4F9D\u5B58\u95A2\u4FC2\uFF08depshape\uFF09\u3068 DB \u30B9\u30AD\u30FC\u30DE\uFF08dbshape\uFF09\u306E\u5F62\u3067\u898B\u305B\u307E\u3059
2170
+
2171
+ \u4F7F\u3044\u65B9:
2172
+ diffshape [target] [compare-with] [options]
2173
+
2174
+ ${TARGETS}
2175
+
2176
+ options:
2177
+ ${COMMON}
2178
+ ${SCHEMA}
2179
+ --only <dep|db> \u7247\u65B9\u306E\u30E2\u30B8\u30E5\u30FC\u30EB\u3060\u3051\u3092\u8868\u793A\u3059\u308B\uFF08depshape / dbshape \u30B3\u30DE\u30F3\u30C9\u3068\u540C\u3058\uFF09
2180
+ -h, --help \u3053\u306E\u30D8\u30EB\u30D7\u3092\u8868\u793A
2181
+
2182
+ \u4F8B:
2183
+ diffshape \u672A\u30B3\u30DF\u30C3\u30C8\u306E\u5909\u66F4 vs HEAD
2184
+ diffshape . main --merge-base \u672A\u30B3\u30DF\u30C3\u30C8\u306E\u5909\u66F4\u3092\u542B\u3080\u73FE\u5728\u306E\u72B6\u614B vs main \u304B\u3089\u306E\u5206\u5C90\u70B9
2185
+ diffshape @ abc1234 HEAD vs \u7279\u5B9A\u306E\u30B3\u30DF\u30C3\u30C8
2186
+ `,
2187
+ dep: `depshape - git \u306E\u5DEE\u5206\u306B\u3088\u308B\u4F9D\u5B58\u95A2\u4FC2\u306E\u5909\u5316\u3092\u3001\u65E2\u5B58\u306E\u69CB\u9020\u3068\u4E26\u3079\u3066\u53EF\u8996\u5316\u3057\u307E\u3059\uFF08Go / TypeScript / JavaScript \u5BFE\u5FDC\uFF09
2188
+ \uFF08diffshape \u306E\u4F9D\u5B58\u30E2\u30B8\u30E5\u30FC\u30EB\u3060\u3051\u3092\u958B\u304D\u307E\u3059\uFF09
2189
+
2190
+ \u4F7F\u3044\u65B9:
2191
+ depshape [target] [compare-with] [options]
2192
+
2193
+ ${TARGETS}
2194
+
2195
+ options:
2196
+ ${COMMON}
2197
+ --json \u30B5\u30FC\u30D0\u30FC\u3092\u8D77\u52D5\u305B\u305A\u3001\u89E3\u6790\u7D50\u679C\u306E JSON \u3092\u6A19\u6E96\u51FA\u529B\u306B\u51FA\u3059
2198
+ -h, --help \u3053\u306E\u30D8\u30EB\u30D7\u3092\u8868\u793A
2199
+ `,
2200
+ db: `dbshape - git \u306E\u5DEE\u5206\u3067 PostgreSQL \u306E\u30B9\u30AD\u30FC\u30DE\uFF08\u30C6\u30FC\u30D6\u30EB\u30FB\u30AB\u30E9\u30E0\u30FB\u5236\u7D04\u30FB\u5916\u90E8\u30AD\u30FC\u30FBCHECK \u306E\u5024\uFF09\u304C\u3069\u3046\u5909\u308F\u3063\u305F\u304B\u3092\u898B\u305B\u307E\u3059
2201
+ \uFF08diffshape \u306E DB \u30E2\u30B8\u30E5\u30FC\u30EB\u3060\u3051\u3092\u958B\u304D\u307E\u3059\uFF09
2202
+
2203
+ \u4F7F\u3044\u65B9:
2204
+ dbshape [target] [compare-with] [options]
2205
+
2206
+ ${TARGETS}
2207
+
2208
+ options:
2209
+ ${COMMON}
2210
+ ${SCHEMA}
2211
+ --text \u30B5\u30FC\u30D0\u30FC\u3092\u8D77\u52D5\u305B\u305A\u3001\u5DEE\u5206\u306E\u8981\u7D04\u3092\u30BF\u30FC\u30DF\u30CA\u30EB\u306B\u51FA\u3059
2212
+ --json \u30B5\u30FC\u30D0\u30FC\u3092\u8D77\u52D5\u305B\u305A\u3001\u5DEE\u5206\u3092 JSON \u3067\u6A19\u6E96\u51FA\u529B\u306B\u51FA\u3059
2213
+ --no-color --text \u306E\u51FA\u529B\u306B\u8272\u3092\u4ED8\u3051\u306A\u3044
2214
+ -h, --help \u3053\u306E\u30D8\u30EB\u30D7\u3092\u8868\u793A
2215
+ `
2216
+ };
2217
+ function parseArgs(argv, command) {
2218
+ const fixed = command === "depshape" ? "dep" : command === "dbshape" ? "db" : void 0;
2219
+ const fail = (msg) => {
2220
+ throw new UsageError(msg);
2221
+ };
2222
+ const args = { port: 4977, host: "127.0.0.1", open: true, json: false, text: false, color: !!process.stdout.isTTY && !process.env.NO_COLOR, schema: [], only: fixed };
2223
+ const positional = [];
2224
+ const allowed = (opt, ok) => ok || fail(`\u4E0D\u660E\u306A\u30AA\u30D7\u30B7\u30E7\u30F3: ${opt}`);
2225
+ for (let i = 0; i < argv.length; i++) {
2226
+ const a = argv[i];
2227
+ switch (a) {
2228
+ case "-h":
2229
+ case "--help":
2230
+ process.stdout.write(HELP[fixed ?? "all"]);
2231
+ process.exit(0);
2232
+ case "--merge-base":
2233
+ args.mergeBase = true;
2234
+ break;
2235
+ case "--port":
2236
+ args.port = Number(argv[++i]);
2237
+ if (!Number.isInteger(args.port)) fail("--port \u306B\u306F\u6570\u5024\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
2238
+ break;
2239
+ case "--host":
2240
+ args.host = argv[++i] ?? fail("--host \u306B\u306F\u5024\u304C\u5FC5\u8981\u3067\u3059");
2241
+ break;
2242
+ case "--no-open":
2243
+ args.open = false;
2244
+ break;
2245
+ case "--schema":
2246
+ allowed(a, fixed !== "dep");
2247
+ args.schema.push(argv[++i] ?? fail("--schema \u306B\u306F glob \u304C\u5FC5\u8981\u3067\u3059"));
2248
+ break;
2249
+ case "--only": {
2250
+ allowed(a, !fixed);
2251
+ const v = argv[++i];
2252
+ if (v !== "dep" && v !== "db") fail("--only \u306B\u306F dep \u304B db \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
2253
+ args.only = v;
2254
+ break;
2255
+ }
2256
+ case "--json":
2257
+ allowed(a, !!fixed);
2258
+ args.json = true;
2259
+ break;
2260
+ case "--text":
2261
+ allowed(a, fixed === "db");
2262
+ args.text = true;
2263
+ break;
2264
+ case "--no-color":
2265
+ allowed(a, fixed === "db");
2266
+ args.color = false;
2267
+ break;
2268
+ default:
2269
+ if (a.startsWith("-") && a !== "-") fail(`\u4E0D\u660E\u306A\u30AA\u30D7\u30B7\u30E7\u30F3: ${a}`);
2270
+ positional.push(a);
2271
+ }
2272
+ }
2273
+ if (positional.length > 2) fail("\u5F15\u6570\u304C\u591A\u3059\u304E\u307E\u3059\uFF08target \u3068 compare-with \u306E2\u3064\u307E\u3067\uFF09");
2274
+ [args.target, args.base] = positional;
2275
+ if (args.mergeBase && !args.base) fail(`--merge-base \u306B\u306F compare-with \u306E\u6307\u5B9A\u304C\u5FC5\u8981\u3067\u3059\uFF08\u4F8B: ${command} . main --merge-base\uFF09`);
2276
+ return args;
2277
+ }
2278
+ var UsageError = class extends Error {
2279
+ };
2280
+ async function run(command, argv) {
2281
+ const fail = (msg) => {
2282
+ process.stderr.write(`${command}: ${msg}
2283
+ `);
2284
+ process.exit(1);
2285
+ };
2286
+ let args;
2287
+ try {
2288
+ args = parseArgs(argv, command);
2289
+ } catch (e) {
2290
+ return fail(e.message);
2291
+ }
2292
+ const all = [depAnalyzer, dbAnalyzer({ schema: args.schema })];
2293
+ const analyzers = args.only ? all.filter((a) => a.id === args.only) : all;
2294
+ const app = new App(process.cwd(), args, analyzers);
2295
+ try {
2296
+ await app.refresh();
2297
+ if (args.json || args.text) {
2298
+ const r = await app.result(analyzers[0].id);
2299
+ if ("error" in r) return fail(r.error);
2300
+ if (args.text) process.stdout.write(formatRunSummary(r.data, args.color ? COLORS : PLAIN));
2301
+ else process.stdout.write(JSON.stringify(r.data, null, 2) + "\n");
2302
+ return;
2303
+ }
2304
+ const { url } = await startServer2(app, args.host, args.port);
2305
+ process.stdout.write(`${command}: ${url} \u3067\u8868\u793A\u4E2D\uFF08Ctrl+C \u3067\u7D42\u4E86\uFF09
2306
+ `);
2307
+ if (args.open) openBrowser(url);
2308
+ } catch (e) {
2309
+ const msg = e instanceof Error ? e.stderr || e.message : String(e);
2310
+ fail(msg.trim());
2311
+ }
2312
+ }
2313
+
2314
+ export {
2315
+ run
2316
+ };