@simetrajs/designer 0.2.0 → 0.3.0-next.2

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.
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { a as invoke, c as summarizeData, d as writeChanges, f as checkEnvName, h as databaseResource, i as renderPlan, m as parseDataLaunch, n as renderApply, p as dataResource, r as renderDiff, s as toolByName, t as formatDiagnostics, u as isMetadataFile } from "./report-DV4deFdu.js";
2
+ import { a as toolByName, c as writeChanges, d as parseDataLaunch, f as databaseResource, i as structureOf, l as checkEnvName, o as formatDiagnostics, r as presentation, s as isMetadataFile, t as invoke, u as dataResource } from "./invoke-DLCOtVpB.js";
3
3
  import { i as DEFAULT_DATABASE_URL_ENV, n as trimSlash, p as UsageError, t as DEFAULT_DIR } from "./default-dir-DerxTbci.js";
4
4
  import { defineCommand } from "citty";
5
5
  import { mkdtemp, readdir, rm, stat } from "node:fs/promises";
6
6
  import { basename, dirname, join, resolve } from "node:path";
7
7
  import { ATTRIBUTE_CASES, DATABASE_PROVIDERS, METADATA_KINDS } from "simetra/model";
8
8
  import { DEFAULT_APPLY_TIMEOUTS, renderDesiredState } from "simetra/schema";
9
- import { buildRuntimeCatalog, canonicalSnapshot, emitEntityTypes } from "simetra/compiler";
9
+ import { buildClientCatalog, buildRuntimeCatalog, canonicalSnapshot, emitEntityTypes } from "simetra/compiler";
10
10
  import { spawn } from "node:child_process";
11
11
  import { tmpdir } from "node:os";
12
12
  // src/tools/artifacts.ts
@@ -15,6 +15,7 @@ import { tmpdir } from "node:os";
15
15
  * адаптер (`compile --out`), тут лише вміст.
16
16
  */
17
17
  function compileArtifacts(model) {
18
+ const runtime = buildRuntimeCatalog(model);
18
19
  return [
19
20
  {
20
21
  path: "snapshot.json",
@@ -30,7 +31,11 @@ function compileArtifacts(model) {
30
31
  },
31
32
  {
32
33
  path: "runtime-catalog.json",
33
- content: `${JSON.stringify(buildRuntimeCatalog(model), null, 2)}\n`
34
+ content: `${JSON.stringify(runtime, null, 2)}\n`
35
+ },
36
+ {
37
+ path: "client-catalog.json",
38
+ content: `${JSON.stringify(buildClientCatalog(runtime), null, 2)}\n`
34
39
  }
35
40
  ];
36
41
  }
@@ -246,12 +251,17 @@ async function cliInput(tool, args, stdin) {
246
251
  if (tool.name === "explain") {
247
252
  const target = positional[0] ?? "";
248
253
  const dot = target.indexOf(".");
249
- if (dot <= 0 || dot === target.length - 1) throw new UsageError(`Invalid target "${target}". Expected <Kind>.<Name>, e.g. Document.ServiceAccrual (kinds: ${METADATA_KINDS.join(", ")}).`);
254
+ if (dot <= 0 || dot === target.length - 1) throw new UsageError(`Invalid target "${target}". Expected <Kind>.<Name>, e.g. Document.ServiceAccrual (kinds: ${METADATA_KINDS.join(", ")}), or <schema>.<function>, e.g. public.post_order.`);
255
+ const head = target.slice(0, dot);
256
+ const tail = target.slice(dot + 1);
250
257
  return {
251
- input: {
252
- kind: target.slice(0, dot),
253
- name: target.slice(dot + 1)
254
- },
258
+ input: METADATA_KINDS.includes(head) ? {
259
+ kind: head,
260
+ name: tail
261
+ } : { function: {
262
+ schema: head,
263
+ name: tail
264
+ } },
255
265
  dirs: [trimSlash(positional[1] ?? "./metadata")]
256
266
  };
257
267
  }
@@ -280,10 +290,14 @@ async function cliInput(tool, args, stdin) {
280
290
  input: args.tables === void 0 ? {} : { tables: list("tables", args.tables) },
281
291
  dirs: [trimSlash(positional[0] ?? "./metadata")]
282
292
  };
283
- if (tool.name === "plan" || tool.name === "roles") return {
293
+ if (tool.name === "plan") return {
284
294
  input: {},
285
295
  dirs: [trimSlash(positional[0] ?? "./metadata")]
286
296
  };
297
+ if (tool.name === "roles") return {
298
+ input: args["dev-passwords"] === true ? { devPasswords: true } : {},
299
+ dirs: [trimSlash(positional[0] ?? "./metadata")]
300
+ };
287
301
  if (tool.name === "apply") {
288
302
  const plan = positional[0];
289
303
  if (plan === void 0) throw new UsageError("apply needs the plan file: simetra apply <plans/….plan.json> [dir] --plan-hash <hex> --yes.");
@@ -318,135 +332,44 @@ async function cliInput(tool, args, stdin) {
318
332
  };
319
333
  }
320
334
  // src/cli/render.ts
321
- /** Текст пояснення об'єкта для терміналу; JSON-вигляд друкується як є. */
322
- function renderExplanation(e) {
323
- const lines = [`${e.object.kind} ${e.object.name} (${e.object.file})`];
324
- if (e.object.scopeKind !== void 0) lines.push(`scope: ${e.object.scopeKind}`);
325
- for (const t of e.tables) {
326
- lines.push("", `table ${t.schema}.${t.name}${t.part ? ` [${t.part}]` : ""}`);
327
- for (const c of t.columns) {
328
- const tags = [
329
- c.notNull ? "not null" : void 0,
330
- c.logical === void 0 ? void 0 : `logical: ${c.logical}`,
331
- c.standard === void 0 ? void 0 : `standard: ${c.standard}`,
332
- c.scope === true ? "scope" : void 0
333
- ].filter((x) => x !== void 0);
334
- lines.push(` ${c.name} ${c.type}${tags.length > 0 ? ` (${tags.join(", ")})` : ""}`);
335
- }
336
- if (t.primaryKey !== void 0) lines.push(` primary key (${t.primaryKey.join(", ")})`);
337
- for (const u of t.uniques) lines.push(` unique (${u.join(", ")})`);
338
- for (const f of t.foreignKeys) lines.push(` foreign key (${f.columns.join(", ")}) -> ${f.references}`);
339
- }
340
- for (const q of e.movementQueries) lines.push("", `movement query ${q.identity}`, q.sql);
341
- for (const u of e.generatedUnits) lines.push("", `generated ${u.identity}`, u.sql);
342
- if (e.contracts.length > 0) lines.push("", "contracts:", JSON.stringify(e.contracts, null, 2));
343
- if (e.referencedBy.length > 0) {
344
- lines.push("", "referenced by:");
345
- for (const r of e.referencedBy) lines.push(` ${r.file}#${r.pointer} (${r.role})`);
346
- }
347
- return `${lines.join("\n")}\n`;
348
- }
349
- /**
350
- * Підсумок запису промоції для терміналу: що на що перетворилось і що
351
- * лишається плану бази. Повний запис — у `--format json`.
352
- */
353
- function renderPromotion(r, written) {
354
- const lines = [`${written ? "promoted" : "would promote"} ${r.objectId} into ${r.kind}`];
355
- for (const t of r.tables) lines.push(` table ${t.schema}.${t.from} -> ${t.to}`);
356
- const counts = [
357
- ["columns renamed or moved", r.columns.length],
358
- ["type changes", r.typeChanges.length],
359
- ["data steps", r.dataSteps.length],
360
- ["columns retired", r.retired.length],
361
- ["constraints relaxed", r.relaxed.length],
362
- ["constraints tightened", r.tightened.length],
363
- ["row level security changes", r.rowLevelSecurity.length],
364
- ["delete semantics changes", r.deleteSemantics.length],
365
- ["conversions", r.conversions.length],
366
- ["units moved", r.movedUnits.length],
367
- ["units rewritten", r.rewrittenUnits.length],
368
- ["contract changes", r.contractChanges.length]
369
- ];
370
- for (const [label, n] of counts) if (n > 0) lines.push(` ${label}: ${n}`);
371
- return lines.join("\n");
372
- }
373
335
  /** Кінцевий результат одного виклику в тексті/JSON для терміналу. */
374
336
  function renderResult(tool, r, o) {
375
337
  const report = formatDiagnostics(r.diagnostics, o);
376
- if (tool.name === "compile") return o.format === "json" ? {
338
+ const present = tool.present;
339
+ if (present?.diagnosticsOnly === true) return o.format === "json" ? {
377
340
  stdout: "",
378
341
  json: JSON.parse(report)
379
342
  } : { stdout: report };
380
- if (tool.name === "explain" && r.ok && r.data !== void 0) {
381
- const explanation = r.data;
382
- return { stdout: o.format === "json" ? JSON.stringify(explanation, null, 2) : renderExplanation(explanation).trimEnd() };
383
- }
384
- if (tool.name === "diff" && r.data !== void 0) {
385
- const data = r.data;
386
- return { stdout: o.format === "json" ? JSON.stringify({
387
- ok: r.ok,
388
- empty: data.empty,
389
- plan: data.plan,
390
- differences: data.differences,
391
- diagnostics: JSON.parse(report)
392
- }, null, 2) : renderDiff(data, report) };
393
- }
394
- if (tool.name === "plan" || tool.name === "apply") {
395
- if (o.format === "json") return { stdout: JSON.stringify({
396
- ok: r.ok,
397
- written: r.written,
398
- artifacts: r.artifacts ?? [],
399
- ...r.data,
400
- diagnostics: JSON.parse(report)
401
- }, null, 2) };
402
- return { stdout: tool.name === "plan" ? renderPlan(r.data, report, {
403
- ok: r.ok,
404
- written: r.written
405
- }) : renderApply(r.data, r.diagnostics, report) };
406
- }
407
- if (tool.name === "roles" && r.data !== void 0) {
408
- const { roles, skipped } = r.data;
409
- return { stdout: o.format === "json" ? JSON.stringify({
410
- ok: r.ok,
411
- roles,
412
- skipped,
413
- diagnostics: JSON.parse(report)
414
- }, null, 2) : [
415
- ...roles.map((x) => `${x.server}: ${x.name} ${x.outcome}`),
416
- ...skipped.map((x) => `target: ${x.name} skipped: the directory has no project.meta.json, so database.provider is unknown; run roles in a metadata directory with a project file to create it`),
417
- ...r.diagnostics.length > 0 ? [report] : []
418
- ].join("\n") };
419
- }
420
- if (tool.name === "rights-maintenance" && r.data !== void 0) {
421
- const done = r.data;
422
- return { stdout: o.format === "json" ? JSON.stringify({
423
- ok: r.ok,
424
- ...done,
425
- diagnostics: JSON.parse(report)
426
- }, null, 2) : `assigned ${done.assignment}${done.member === void 0 ? "" : ` to member ${done.member}`}` };
427
- }
428
- if ((tool.name === "data-read" || tool.name === "data-command") && r.data !== void 0) {
429
- const data = r.data;
430
- return { stdout: o.format === "json" ? JSON.stringify({
431
- ok: r.ok,
432
- ...data
433
- }, null, 2) : summarizeData(tool.name, data) };
343
+ const view = {
344
+ channel: "cli",
345
+ ok: r.ok,
346
+ written: r.written,
347
+ diagnostics: r.diagnostics,
348
+ report
349
+ };
350
+ const { shown: shows, data } = presentation(tool, r);
351
+ if (shows && present?.bare === true && o.format === "json") return { stdout: JSON.stringify(r.data, null, 2) };
352
+ if (shows && o.format === "text") {
353
+ const text = present?.text?.(r.data, view);
354
+ if (text !== void 0) return { stdout: text };
434
355
  }
435
- if (tool.files === "read") return { stdout: report };
356
+ if (!shows && tool.files === "read") return { stdout: report };
436
357
  const changed = r.changes.map((c) => c.path);
437
358
  if (o.format === "json") return { stdout: JSON.stringify({
438
359
  ok: r.ok,
439
360
  written: r.written,
361
+ ...r.wouldWrite === true ? { wouldWrite: true } : {},
440
362
  changed,
441
- diagnostics: JSON.parse(report),
442
- ...tool.name === "promote" && r.data !== void 0 ? { record: r.data } : {}
363
+ ...tool.files === "artifact" ? { artifacts: r.artifacts ?? [] } : {},
364
+ ...data !== void 0 ? structureOf(tool, data) : {},
365
+ diagnostics: JSON.parse(report)
443
366
  }, null, 2) };
444
367
  const verb = (deleted) => r.written ? deleted ? "deleted" : "written" : deleted ? "would delete" : "would write";
445
368
  return { stdout: [
446
369
  ...r.changes.map((c) => `${verb(c.deleted)} ${o.dir}/${c.path}`),
447
- ...r.ok ? [] : ["nothing written: the result has errors"],
370
+ ...r.ok ? [] : r.written ? ["written: the result keeps only repair-class errors the directory already had"] : r.wouldWrite === true ? ["would write: the result keeps only repair-class errors the directory already had"] : ["nothing written: the result has errors"],
448
371
  report,
449
- ...tool.name === "promote" && r.data !== void 0 ? [renderPromotion(r.data, r.written)] : []
372
+ ...data !== void 0 && present?.appendix !== void 0 ? [present.appendix(data, view)] : []
450
373
  ].join("\n") };
451
374
  }
452
375
  // src/cli/command.ts
@@ -546,6 +469,7 @@ async function runTool(tool, argv, stdin = readStdin, cwd = process.cwd(), env =
546
469
  channel: "cli",
547
470
  database,
548
471
  databaseEnv,
472
+ env,
549
473
  ...baseline === void 0 ? {} : { baseline }
550
474
  });
551
475
  if (result.refusal !== void 0) return fail(result.refusal.message);
@@ -594,12 +518,12 @@ function argsFor(tool) {
594
518
  };
595
519
  args.out = {
596
520
  type: "string",
597
- description: "Write snapshot.json, desired-state.sql, entities.d.ts, runtime-catalog.json here"
521
+ description: "Write snapshot.json, desired-state.sql, entities.d.ts, runtime-catalog.json, client-catalog.json here"
598
522
  };
599
523
  } else if (tool.name === "explain") {
600
524
  args.target = {
601
525
  type: "positional",
602
- description: "<Kind>.<Name>, e.g. Document.ServiceAccrual",
526
+ description: "<Kind>.<Name>, e.g. Document.ServiceAccrual, or <schema>.<function>, e.g. public.post_order (a schema named like a kind, or containing a dot, needs the JSON input of MCP)",
603
527
  required: true
604
528
  };
605
529
  args.dir = {
@@ -655,7 +579,7 @@ function argsFor(tool) {
655
579
  args["database-provider"] = {
656
580
  type: "enum",
657
581
  options: [...DATABASE_PROVIDERS],
658
- description: "Database provider of a new project (default \"supabase\")"
582
+ description: "Database provider of a new project: supabase | postgres (default \"supabase\")"
659
583
  };
660
584
  }
661
585
  if (tool.name === "diff") args.tables = {
@@ -685,6 +609,11 @@ function argsFor(tool) {
685
609
  description: `statement_timeout of the apply transaction (default ${DEFAULT_APPLY_TIMEOUTS.statementTimeoutMs})`
686
610
  };
687
611
  }
612
+ if (tool.name === "roles") args["dev-passwords"] = {
613
+ type: "boolean",
614
+ default: false,
615
+ description: "Postgres provider, a database on this machine only: set the passwords of the login roles this run creates from SIMETRA_OWNER_DEV_PASSWORD, SIMETRA_AUTH_DEV_PASSWORD, SIMETRA_RUNTIME_DEV_PASSWORD and SIMETRA_SIGNALS_DEV_PASSWORD"
616
+ };
688
617
  if (tool.database !== "none") {
689
618
  args["database-url-env"] = {
690
619
  type: "string",
@@ -761,6 +690,7 @@ function toCliArgs(args) {
761
690
  "plan-hash": str(args["plan-hash"]),
762
691
  allow: str(args.allow),
763
692
  rehearse: args.rehearse === true,
693
+ "dev-passwords": args["dev-passwords"] === true,
764
694
  "lock-timeout-ms": str(args["lock-timeout-ms"]),
765
695
  "statement-timeout-ms": str(args["statement-timeout-ms"]),
766
696
  "data-url-env": str(args["data-url-env"]),
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ // src/schema-engine/errors.ts
3
+ /** Тінь на сервері іншої мажорної версії: каталоги двох версій не порівнюються. */
4
+ var ShadowServerMismatchError = class extends Error {
5
+ name = "ShadowServerMismatchError";
6
+ };
7
+ /** Роль підключення не має `CREATEDB` на сервері, де мала б з'явитися тінь. */
8
+ var ShadowCreateRefusedError = class extends Error {
9
+ onShadowBase;
10
+ name = "ShadowCreateRefusedError";
11
+ constructor(onShadowBase) {
12
+ super("the connecting role lacks CREATEDB");
13
+ this.onShadowBase = onShadowBase;
14
+ }
15
+ };
16
+ /**
17
+ * Збій створення тіні чи підключення до неї з причиною, якої адаптер не
18
+ * розпізнав: причина — у `cause`. Межа описує її адресою сервера, де мала
19
+ * з'явитися тінь, і називає вимогу тіні до режиму з'єднання (спека designer
20
+ * §3.2).
21
+ */
22
+ var ShadowServerError = class extends Error {
23
+ onShadowBase;
24
+ shadowDrop;
25
+ name = "ShadowServerError";
26
+ constructor(cause, onShadowBase, shadowDrop) {
27
+ super("the shadow could not be created or reached", { cause });
28
+ this.onShadowBase = onShadowBase;
29
+ this.shadowDrop = shadowDrop;
30
+ }
31
+ };
32
+ /**
33
+ * Збій видалення тіні на шляху винятку: виняток лишається тим самим (його
34
+ * клас розпізнає межа), а попередження `engine.shadow-drop-failed` стає його
35
+ * полем `shadowDrop`. Значення, що не є `Error`, поля не несе.
36
+ */
37
+ function withShadowDrop(error, drop) {
38
+ if (error instanceof Error) Object.assign(error, { shadowDrop: drop });
39
+ return error;
40
+ }
41
+ /** Попередження про невидалену тінь, яке несе виняток, якщо несе. */
42
+ function shadowDropOf(error) {
43
+ if (!(error instanceof Error)) return void 0;
44
+ return error.shadowDrop;
45
+ }
46
+ /** Шаблон тіні профілю відсутній або не запечатаний суперкористувачем: його готує `simetra roles`. */
47
+ var ShadowTemplateMissingError = class extends Error {
48
+ template;
49
+ name = "ShadowTemplateMissingError";
50
+ constructor(template) {
51
+ super(`the shadow template database "${template}" is missing or not sealed`);
52
+ this.template = template;
53
+ }
54
+ };
55
+ /** Профіль `postgres` будує тіні з шаблону кластера цілі й окремого сервера тіней не має. */
56
+ var ShadowBaseUnsupportedError = class extends Error {
57
+ name = "ShadowBaseUnsupportedError";
58
+ constructor() {
59
+ super("a separate shadow server is not supported with the postgres profile");
60
+ }
61
+ };
62
+ export { ShadowTemplateMissingError as a, ShadowServerMismatchError as i, ShadowCreateRefusedError as n, shadowDropOf as o, ShadowServerError as r, withShadowDrop as s, ShadowBaseUnsupportedError as t };