suppa-mcp-2 1.44.5 → 1.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -30,7 +30,7 @@ No API key needed to start — the server authenticates interactively via the `s
30
30
 
31
31
  ## The `suppa` command
32
32
 
33
- The same 106 operations the MCP server exposes are available as a command, for
33
+ The same 108 operations the MCP server exposes are available as a command, for
34
34
  shells, scripts and CI:
35
35
 
36
36
  ```bash
@@ -59,11 +59,16 @@ refused or not fully done (`passed: false`, `created: false`, a non-zero
59
59
  For an endpoint no command covers there is `suppa api <METHOD> <path>` — the raw
60
60
  call, with the CLI's session and tenant resolution. It exists only in the CLI,
61
61
  never as an MCP tool, and it is gated because it skips every check the commands
62
- make. Reads (GET, and POST to `…/select`, `…/search`, `…/query`, `…/count`) are
63
- sent at once. Anything else prints the request and sends nothing. With
64
- `--confirm` it is sent, but only to a tenant named by `--tenant`, never to the
65
- remembered one. The permanent delete stays refused. `suppa help api` has the
66
- flags. In Git Bash, leave off the path's leading slash (`core/schema`): MSYS
62
+ make. Every call names its tenant with `--tenant` — reads too: on Windows,
63
+ `suppa.cmd` runs through cmd.exe, which ends the command at an `&`, so a flag after
64
+ a `?a=1&b=2` path never arrived and the read went to the remembered tenant. Query
65
+ parameters go as `--query key=value`, or the whole call as `--args-file`
66
+ {method, path, query, body, tenant}. Reads (GET, and POST to `…/select`,
67
+ `…/search`, `…/query`, `…/count`, and the register reads `registers/<name>/balance`,
68
+ `turnovers`, `balance-and-turnovers`, `movements`, `slice-last`, `slice-first`,
69
+ `registers/recorders/status`) are sent at once; what was sent is said on stderr.
70
+ Anything else prints the request and sends nothing until `--confirm`. The permanent
71
+ delete stays refused. `suppa help api` has the flags. In Git Bash, leave off the path's leading slash (`core/schema`): MSYS
67
72
  rewrites an argument that starts with `/` into a Windows path, and the command
68
73
  refuses that path and says why.
69
74
 
@@ -414,7 +419,7 @@ extension table is created outside that check and is not subject to it.
414
419
 
415
420
  ## Available tools
416
421
 
417
- 106 tools across the areas below.
422
+ 108 tools across the areas below.
418
423
 
419
424
  ### Session & identity
420
425
 
@@ -547,7 +552,7 @@ Of the seven above, `suppa_get_form` reads both generations: since 1.43.3 a 2.x
547
552
  the builder reads it (schema, variables, localizations, the Code Form's files). The other six are
548
553
  **Suppa 1.0** forms: they read and write `data.formShema` (the platform's misspelling) and the v1
549
554
  field types. A **Suppa 2.0** entity-builder form is a different product —
550
- the `schema` column on the row since 2.1, 57 component types — and is served by the six below plus the bundled
555
+ the `schema` column on the row since 2.1, 57 component types — and is served by the eight below plus the bundled
551
556
  `skills/suppa-form-v2` skill. The first two touch no tenant: they read files inside the package.
552
557
 
553
558
  | Tool | Description |
@@ -557,6 +562,8 @@ the `schema` column on the row since 2.1, 57 component types — and is served b
557
562
  | `suppa_write_form_draft` | Save a checked draft through the builder's own save (`PUT /core/forms/:id/schema`) — gated first against the live form (what the form already has does not block), guarded by the form's revision, recorded in History; saves the widget renders the gate compiled, never a hand-written one; `variables` only when the draft lists some. It never publishes |
558
563
  | `suppa_create_form_v2` | Create a 2.0 form (create / update / custom) with its draft in one transaction — the routing flag and default variable the builder adds, optionally filed into a folder (confirm-gated) |
559
564
  | `suppa_form_versions` | A form's published versions, the component diff between two of them, and a summary of recent draft saves (read-only) |
565
+ | `suppa_form_code` | A form's Code Form (TypeScript against `formAPI`) without a browser tab: the rules, `pull` (the draft's code into a workspace folder with the SDK and the form's own typings), `api` (an element's, a type's or `formAPI`'s members, events and docs, read by the checker), `check` (tsc as the builder's code editor runs it, the import rule, invented events, the agent's deny list) |
566
+ | `suppa_push_form_code` | Save the workspace's code changes to the DRAFT — only `code`, guarded by the revision; re-checked first, conflicts with someone else's save handed back to merge, `@shared` files read-only; the server's build result reported (a failed build keeps the previous one running). Confirm-gated, never publishes |
560
567
  | `suppa_form_lifecycle` | Publish, roll back (restore + publish), discard (unrecoverable) or promote — gated on the form gate (a stored widget with an empty render is refused) and on the version belonging to the form (confirm-gated) |
561
568
 
562
569
  ### Migration (Suppa 1.0 → 2.0) & workspace
package/dist/bin.js CHANGED
@@ -41,10 +41,41 @@ process.on("uncaughtException", (err) => {
41
41
  * process at once, since no answer can arrive anyway.
42
42
  */
43
43
  const DRAIN_MS = 30_000;
44
+ /**
45
+ * How long after its last answer the process waits before it is ended even though something still
46
+ * holds the event loop (the reason this exit exists: a Windows npx parent that never lets go).
47
+ */
48
+ const EXIT_GRACE_MS = 1_000;
49
+ /**
50
+ * End the process — never with a process.exit() in the same breath as a fetch. On Windows,
51
+ * process.exit() right after a fetch aborts Node with 0xC0000409 (STATUS_STACK_BUFFER_OVERRUN, libuv's
52
+ * assert on an async handle undici is still closing). Measured 2026-11-16, Node 26, ten children each,
53
+ * two fetches then exit: at 0 ms 10/10 crashed, at 50 ms 9/10, at 250 ms 0/10, at 1000 ms 0/10; a
54
+ * natural exit 0/10. A user reported the crash ("the suppa processes die with 0xC0000409"), and the
55
+ * in-flight test hit it as soon as one call made two requests. So: the exit code is set and stdin let go,
56
+ * the event loop ends the process when nothing holds it, and the hard exit — unref'd, so it never keeps
57
+ * the process alive itself — comes only after the grace.
58
+ */
59
+ function endProcess() {
60
+ process.exitCode = 0;
61
+ try {
62
+ process.stdin.destroy();
63
+ }
64
+ catch {
65
+ /* already gone */
66
+ }
67
+ setTimeout(() => process.exit(0), EXIT_GRACE_MS).unref();
68
+ }
44
69
  function exitWhenClientIsGone(transport) {
45
70
  const inFlight = new Set();
46
71
  let leaving = false;
47
- const done = () => process.exit(0);
72
+ let ended = false;
73
+ const done = () => {
74
+ if (ended)
75
+ return;
76
+ ended = true;
77
+ endProcess();
78
+ };
48
79
  const deliver = transport.onmessage;
49
80
  transport.onmessage = (message, extra) => {
50
81
  if (message && message.method !== undefined && message.id !== undefined)
package/dist/cli/api.js CHANGED
@@ -8,11 +8,15 @@
8
8
  * there). So the user's decision (2026-09-29) is the gate:
9
9
  *
10
10
  * - CLI only. There is no MCP tool for it.
11
- * - Reads run at once: GET, and a POST whose last segment is select / search / query / count.
12
- * `resolve` is NOT one — `/forms/:id/inheritance-issues/:id/resolve` writes.
13
- * - Anything else prints the request and sends nothing. With `--confirm` it is sent — and only
14
- * to a tenant named by `--tenant`, never to the remembered one: the tenant a CLI remembers can
15
- * be production, and one forgotten flag must not put a raw write there.
11
+ * - Reads run at once: GET, a POST whose last segment is select / search / query / count, and the
12
+ * register reads listed in READ_POST_PATHS. `resolve` is NOT one —
13
+ * `/forms/:id/inheritance-issues/:id/resolve` writes.
14
+ * - Anything else prints the request and sends nothing. With `--confirm` it is sent.
15
+ * - EVERY call names its tenant (`--tenant`, or `tenant` in --args-file) — since 2026-11-16, reads
16
+ * too. A Windows shell cuts a command at an `&`: through `suppa.cmd` (cmd.exe), PowerShell's
17
+ * `suppa api GET "core/x?a=1&b=2" --tenant t` arrives as `api GET core/x?a=1` — the `--tenant` is
18
+ * gone and the read went to the remembered tenant without a word (reported 2026-11-16). A call
19
+ * that must name its tenant is refused instead, and the refusal says why.
16
20
  * - The platform's permanent delete is refused whatever is passed (the same block the HTTP
17
21
  * client enforces on every request, checked here first so it is never offered as a preview).
18
22
  */
@@ -22,32 +26,57 @@ import { pointAtTenant } from "./tenantPoint.js";
22
26
  import { readOnlyProblem } from "../tools/query.js";
23
27
  export const API_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
24
28
  export const READ_POST_SUFFIXES = ["select", "search", "query", "count"];
25
- /** A read is sent at once; a write is shown first. Decided from the method and the last segment. */
29
+ /**
30
+ * POST endpoints that only read, by their exact shape — read in entity-builder (develop, 2026-11-16)
31
+ * registers.controller.ts: `recorders/status` (RegisterRecorderService.statuses) and the register
32
+ * reads `:name/balance | turnovers | balance-and-turnovers | movements | slice-last | slice-first`
33
+ * (RegisterQueryService — SELECTs through engineRead). NOT here, because they write or start work:
34
+ * `:name/balance/job` (a background job), `recorders/:e/:id/repost`, `repost`, `:name/check`,
35
+ * `:name/totals/rebuild`, `:name/held/release`, `violations/:id/resolve`, the jobs' pause / resume / cancel.
36
+ */
37
+ export const READ_POST_PATHS = [
38
+ /^\/api\/core\/registers\/recorders\/status$/,
39
+ /^\/api\/core\/registers\/[^/]+\/(balance|turnovers|balance-and-turnovers|movements|slice-last|slice-first)$/,
40
+ ];
41
+ /** A read is sent at once; a write is shown first. Decided from the method and the path. */
26
42
  export function classify(method, path) {
27
43
  const m = method.toUpperCase();
28
44
  if (m === "GET")
29
45
  return "read";
30
46
  if (m !== "POST")
31
47
  return "write";
32
- const last = path.split("?")[0].split("/").filter(Boolean).pop() ?? "";
48
+ const bare = path.split("?")[0];
49
+ if (READ_POST_PATHS.some((re) => re.test(bare)))
50
+ return "read";
51
+ const last = bare.split("/").filter(Boolean).pop() ?? "";
33
52
  return READ_POST_SUFFIXES.includes(last) ? "read" : "write";
34
53
  }
54
+ /** What the refusal says when no tenant arrived — the `&` cut is the likely reason, so it is named. */
55
+ export const NO_TENANT_REFUSAL = "a raw call names its tenant: add --tenant <alias> (or `tenant` in --args-file). If you DID pass " +
56
+ "--tenant, the shell cut the command before it: through suppa.cmd (cmd.exe — PowerShell runs it too) " +
57
+ "an `&` ends the command, so `core/x?a=1&b=2 --tenant t` arrives as `core/x?a=1`. Pass parameters with " +
58
+ "--query key=value, or the whole call with --args-file.";
35
59
  export const API_HELP = "suppa api <METHOD> <path> — a raw call to the platform API, with this CLI's session and tenant.\n\n" +
36
60
  " METHOD GET POST PUT PATCH DELETE\n" +
37
61
  " path /api/core/… or /core/… (a ?query in it is moved into --query); the\n" +
38
62
  " leading slash is optional — in Git Bash leave it off (core/schema)\n" +
39
- " --query <k=v> a query parameter; repeat the flag per parameter\n" +
63
+ " --tenant <alias> the tenant for this call — REQUIRED, reads included\n" +
64
+ " --query <k=v> a query parameter; repeat the flag per parameter — never `&` in the path\n" +
65
+ " on Windows: cmd.exe (suppa.cmd) cuts the command there\n" +
40
66
  " --body-file <json> the request body, from a file\n" +
41
67
  " --body-stdin the request body, from standard input\n" +
68
+ " --args-file <json> the call as one JSON object {method, path, query, body, tenant} — the way\n" +
69
+ " past a shell that cuts at `&` or garbles non-ASCII; flags win over it\n" +
42
70
  " --confirm send a write (see below)\n" +
43
- " --tenant <alias> the tenant for this call — REQUIRED to send a write\n" +
44
71
  " --pretty re-indent the JSON answer\n\n" +
45
- "Reads — GET, and POST to …/select, …/search, …/query, …/count — are sent at once.\n" +
46
- "Anything else is a write: without --confirm it prints the request and sends nothing; with\n" +
47
- "--confirm it goes only to the tenant --tenant names, never to the remembered one. A raw call\n" +
72
+ "Reads — GET, POST to …/select, …/search, …/query, …/count, and the register reads (registers/\n" +
73
+ "recorders/status, registers/<name>/balance | turnovers | balance-and-turnovers | movements |\n" +
74
+ "slice-last | slice-first) — are sent at once. Anything else is a write: without --confirm it\n" +
75
+ "prints the request and sends nothing. What was sent is said on stderr (→ METHOD url). A raw call\n" +
48
76
  "skips every check the operation commands make — prefer one when it exists (suppa help <group>).\n" +
49
77
  "The platform's permanent delete (/core/data/<entity>/delete) is refused always; /remove is the\n" +
50
78
  "reversible delete.\n";
79
+ const ARGS_FILE_KEYS = ["method", "path", "query", "body", "tenant"];
51
80
  export async function runApi(argv, io) {
52
81
  const { out, err, stdin } = io;
53
82
  const refuse = (...lines) => {
@@ -59,6 +88,7 @@ export async function runApi(argv, io) {
59
88
  const query = {};
60
89
  let bodyFile = null;
61
90
  let bodyStdin = false;
91
+ let argsFile = null;
62
92
  let confirm = false;
63
93
  let tenant = null;
64
94
  let pretty = false;
@@ -110,6 +140,9 @@ export async function runApi(argv, io) {
110
140
  case "--body-stdin":
111
141
  bodyStdin = bare();
112
142
  break;
143
+ case "--args-file":
144
+ argsFile = value();
145
+ break;
113
146
  case "--confirm":
114
147
  confirm = bare();
115
148
  break;
@@ -120,14 +153,55 @@ export async function runApi(argv, io) {
120
153
  pretty = bare();
121
154
  break;
122
155
  default:
123
- problems.push(`unknown flag ${flag} — this command takes --query, --body-file, --body-stdin, --confirm, --tenant, --pretty`);
156
+ problems.push(`unknown flag ${flag} — this command takes --tenant, --query, --body-file, --body-stdin, --args-file, --confirm, --pretty`);
124
157
  }
125
158
  }
126
159
  if (problems.length)
127
160
  return refuse(...problems);
161
+ // ---- --args-file: the whole call as JSON, for what a shell cannot carry -------------------
162
+ // Command-line values win, as in every other command: the file fills only what the line left out.
163
+ let fileBody = undefined;
164
+ if (argsFile !== null) {
165
+ let parsed;
166
+ try {
167
+ const text = readFileSync(argsFile, "utf-8");
168
+ parsed = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
169
+ }
170
+ catch (e) {
171
+ return refuse(`--args-file ${argsFile}: ${e instanceof Error ? e.message : String(e)}`);
172
+ }
173
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
174
+ return refuse(`--args-file ${argsFile} must hold a JSON object: {"method": "GET", "path": "core/…", "tenant": "…"}`);
175
+ }
176
+ const obj = parsed;
177
+ const unknown = Object.keys(obj).filter((k) => !ARGS_FILE_KEYS.includes(k));
178
+ if (unknown.length) {
179
+ return refuse(`unknown key${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} in --args-file — it takes ${ARGS_FILE_KEYS.join(", ")}; --confirm stays on the command line`);
180
+ }
181
+ for (const k of ["method", "path", "tenant"]) {
182
+ if (obj[k] !== undefined && typeof obj[k] !== "string")
183
+ return refuse(`--args-file: "${k}" must be a string`);
184
+ }
185
+ if (obj.query !== undefined) {
186
+ if (!obj.query || typeof obj.query !== "object" || Array.isArray(obj.query))
187
+ return refuse('--args-file: "query" must be an object of key → value');
188
+ for (const [k, v] of Object.entries(obj.query)) {
189
+ if (!(k in query))
190
+ query[k] = typeof v === "string" ? v : JSON.stringify(v);
191
+ }
192
+ }
193
+ if (positional.length === 0 && typeof obj.method === "string")
194
+ positional.push(obj.method);
195
+ if (positional.length === 1 && typeof obj.path === "string")
196
+ positional.push(obj.path);
197
+ if (tenant === null && typeof obj.tenant === "string")
198
+ tenant = obj.tenant;
199
+ if (obj.body !== undefined)
200
+ fileBody = obj.body;
201
+ }
128
202
  const [rawMethod, rawPath, ...extra] = positional;
129
203
  if (!rawMethod || !rawPath)
130
- return refuse("give a METHOD and a path: suppa api GET /core/schema");
204
+ return refuse("give a METHOD and a path: suppa api GET core/schema --tenant <alias>");
131
205
  if (extra.length)
132
206
  return refuse(`unexpected argument${extra.length > 1 ? "s" : ""}: ${extra.join(" ")}`);
133
207
  const method = rawMethod.toUpperCase();
@@ -186,14 +260,21 @@ export async function runApi(argv, io) {
186
260
  return refuse(`the body is not valid JSON: ${e instanceof Error ? e.message : String(e)}`);
187
261
  }
188
262
  }
263
+ else if (fileBody !== undefined) {
264
+ if (method === "GET")
265
+ return refuse("a GET carries no body — put it in \"query\" in --args-file, or use POST");
266
+ body = fileBody;
267
+ }
189
268
  // ---- the tenant, and the gate -----------------------------------------
269
+ if (tenant === null)
270
+ return refuse(NO_TENANT_REFUSAL);
190
271
  const point = await pointAtTenant(tenant, err);
191
272
  if (!point.ok)
192
273
  return 2;
193
274
  let kind = classify(method, path);
194
275
  // `…/query` is a read only for what suppa_query itself would send. The engine is SELECT-only,
195
- // but "read" here means "sent at once, to the remembered tenant" — so a statement suppa_query
196
- // would refuse is shown and gated like any write instead.
276
+ // but "read" here means "sent at once" — so a statement suppa_query would refuse is shown and
277
+ // gated like any write instead.
197
278
  let readRefusedBecause = null;
198
279
  if (kind === "read" && path === "/api/core/data/query") {
199
280
  const statement = body && typeof body === "object" ? body.query : undefined;
@@ -214,17 +295,17 @@ export async function runApi(argv, io) {
214
295
  out(JSON.stringify({
215
296
  status: "confirmation_required",
216
297
  message: "NOT sent. A raw write skips every check the operation commands make. Show this request to " +
217
- "the user; to send it, re-run with --confirm --tenant <alias> — a write never goes to the " +
218
- "remembered tenant by default.",
298
+ "the user; to send it, re-run with --confirm.",
219
299
  would_send: request,
220
300
  ...(readRefusedBecause ? { read_refused_because: readRefusedBecause } : {}),
221
301
  }, null, pretty ? 2 : undefined) + "\n");
222
302
  return 0;
223
303
  }
224
- if (kind === "write" && !point.explicit) {
225
- return refuse(`a raw write names its tenant: add --tenant <alias>. Without it this would go to the remembered tenant, ${point.host}.`);
226
- }
227
304
  // ---- send -------------------------------------------------------------
305
+ // Said on stderr, so it never mixes into the JSON answer: the tenant and the query that really
306
+ // went — a parameter a shell cut off is visible here rather than as a silently shorter answer.
307
+ const qs = Object.keys(query).length ? `?${new URLSearchParams(query).toString()}` : "";
308
+ err(`→ ${method} https://${point.host}${path}${qs}\n`);
228
309
  let answer;
229
310
  try {
230
311
  answer = await makeRequest(method, path, body, { raw: true, ...(Object.keys(query).length ? { query } : {}) });
package/dist/cli/run.js CHANGED
@@ -106,10 +106,13 @@ function parseArgsObject(text, source) {
106
106
  * (migrate: 2 done, 3 failed used to exit 0). A nested `error` is NOT a
107
107
  * refusal: create_entity answers {entity, title_field: {error}} when the
108
108
  * entity exists and only a sub-step failed. {status: "confirmation_required"}
109
- * exits 0 deliberately — it is a prompt, not a failure.
109
+ * exits 0 deliberately — it is a prompt, not a failure. An `error` that is null, false or "" is the
110
+ * ABSENCE of one: set_title_field answers `error: null` on success, and the key alone made a done call
111
+ * exit 1 (reported 2026-11-16).
110
112
  */
111
113
  export function answerFailed(answer) {
112
- if ("error" in answer)
114
+ const e = answer.error;
115
+ if (e !== undefined && e !== null && e !== false && e !== "")
113
116
  return true;
114
117
  for (const key of ["passed", "created", "applied", "ok", "success"]) {
115
118
  if (answer[key] === false)
@@ -0,0 +1,150 @@
1
+ import { createWorkspaceProgram, eventNames, loadTs, toDiagnostic } from "./typecheck.js";
2
+ /** A `formAPI…` property path — no calls, no computed expressions: the probe is type-checked, never run, but it is still the agent's text going into a source file. */
3
+ const PATH_RE = /^formAPI(?:\.[A-Za-z_$][\w$]*|\[(?:'[^'\\\n]+'|"[^"\\\n]+")\])*$/;
4
+ const TYPE_RE = /^[A-Za-z][\w.-]*$/;
5
+ const PROBE_PATH = ".suppa-code/api-probe.ts";
6
+ const PROBE = "__suppaCodeProbe";
7
+ export function probeSource(subject) {
8
+ if (subject.type !== undefined) {
9
+ if (!TYPE_RE.test(subject.type))
10
+ throw new Error(`"${subject.type}" is not an element type`);
11
+ return `import type { ElementApiFor } from '@suppa/frontend-sdk';\ndeclare const ${PROBE}: ElementApiFor<'${subject.type}'>;\nexport {};\n`;
12
+ }
13
+ const path = subject.path ?? "formAPI";
14
+ if (!PATH_RE.test(path))
15
+ throw new Error(`"${path}" is not a formAPI path — write it like formAPI.elements.title or formAPI.services.ui`);
16
+ return `const ${PROBE} = ${path};\nexport {};\n`;
17
+ }
18
+ function find(ts, file, test) {
19
+ let found = null;
20
+ const visit = (node) => {
21
+ if (found)
22
+ return;
23
+ if (test(node))
24
+ found = node;
25
+ else
26
+ ts.forEachChild(node, visit);
27
+ };
28
+ visit(file);
29
+ return found;
30
+ }
31
+ function originOf(ts, symbol) {
32
+ const owner = symbol.getDeclarations()?.[0]?.parent;
33
+ return owner && (ts.isClassDeclaration(owner) || ts.isInterfaceDeclaration(owner)) && owner.name ? owner.name.text : null;
34
+ }
35
+ /** The named class or interface the subject is. The form's own `CurrentFormAPI` is an intersection, which has no symbol of its own — its first named part is what it is. */
36
+ function ownerName(type) {
37
+ for (const part of type.isIntersection() ? type.types : [type]) {
38
+ const name = part.getSymbol()?.getName();
39
+ if (name && !name.startsWith("__"))
40
+ return name;
41
+ }
42
+ return null;
43
+ }
44
+ function isHidden(ts, symbol) {
45
+ if (symbol.getName().startsWith("_") || symbol.getName().startsWith("#"))
46
+ return true;
47
+ const hidden = ts.ModifierFlags.Private | ts.ModifierFlags.Protected;
48
+ return (symbol.getDeclarations() ?? []).some((d) => (ts.getCombinedModifierFlags(d) & hidden) !== 0);
49
+ }
50
+ function isReadonly(ts, symbol) {
51
+ const declarations = symbol.getDeclarations() ?? [];
52
+ if (declarations.some((d) => ts.isGetAccessorDeclaration(d)) && !declarations.some((d) => ts.isSetAccessorDeclaration(d)))
53
+ return true;
54
+ return declarations.some((d) => (ts.getCombinedModifierFlags(d) & ts.ModifierFlags.Readonly) !== 0);
55
+ }
56
+ export async function describeApi(dir, subject) {
57
+ const ts = await loadTs();
58
+ const text = probeSource(subject);
59
+ const { root, program } = createWorkspaceProgram(ts, dir, { path: PROBE_PATH, text });
60
+ const file = program.getSourceFiles().find((s) => s.fileName.replace(/\\/g, "/").endsWith(PROBE_PATH));
61
+ if (!file)
62
+ throw new Error("the API probe did not compile");
63
+ const problems = [...program.getSyntacticDiagnostics(file), ...program.getSemanticDiagnostics(file)].filter((d) => d.category === ts.DiagnosticCategory.Error);
64
+ if (problems.length)
65
+ throw new Error(problems.map((d) => toDiagnostic(ts, root, d).message).join("\n"));
66
+ const checker = program.getTypeChecker();
67
+ const probe = find(ts, file, (n) => ts.isVariableDeclaration(n) && n.name.getText() === PROBE);
68
+ if (!probe)
69
+ throw new Error("the API probe has no subject");
70
+ const type = checker.getNonNullableType(checker.getTypeAtLocation(probe.name));
71
+ const format = ts.TypeFormatFlags.NoTruncation;
72
+ const members = checker
73
+ .getPropertiesOfType(type)
74
+ .filter((s) => !isHidden(ts, s))
75
+ .map((symbol) => {
76
+ const memberType = checker.getTypeOfSymbolAtLocation(symbol, probe);
77
+ const calls = memberType.getCallSignatures();
78
+ // A method is deprecated only when every overload is — `on` carries one retired overload beside the live ones.
79
+ const deprecatedCall = (sig) => sig.getJsDocTags().some((t) => t.name === "deprecated");
80
+ const tag = symbol.getJsDocTags(checker).find((t) => t.name === "deprecated");
81
+ const deprecated = tag && (!calls.length || calls.every(deprecatedCall)) ? tag : undefined;
82
+ return {
83
+ name: symbol.getName(),
84
+ kind: calls.length ? "method" : "property",
85
+ readonly: isReadonly(ts, symbol),
86
+ signatures: calls.length
87
+ ? calls.map((sig) => `${symbol.getName()}${checker.signatureToString(sig, undefined, format)}${deprecatedCall(sig) && !deprecated ? " [deprecated overload]" : ""}`)
88
+ : [checker.typeToString(memberType, undefined, format)],
89
+ doc: ts.displayPartsToString(symbol.getDocumentationComment(checker)).trim(),
90
+ deprecated: deprecated ? ts.displayPartsToString(deprecated.text).trim() || "deprecated" : null,
91
+ origin: originOf(ts, symbol),
92
+ };
93
+ });
94
+ const typeName = checker.typeToString(type);
95
+ return {
96
+ subject: subject.type !== undefined ? `ElementApiFor<'${subject.type}'>` : subject.path ?? "formAPI",
97
+ type: typeName,
98
+ ownName: ownerName(type) ?? typeName.replace(/<.*$/, ""),
99
+ events: eventNames(ts, checker, type, probe),
100
+ members: members.sort((a, b) => a.name.localeCompare(b.name)),
101
+ };
102
+ }
103
+ const SUMMARY_CHARS = 140;
104
+ const HEAD_CHARS = 200;
105
+ /** The first sentence of a doc comment, for the one-line listing. */
106
+ export function summaryOf(doc) {
107
+ const flat = doc.replace(/\s+/g, " ").trim();
108
+ const sentence = /^(.+?[.!?])(\s|$)/.exec(flat)?.[1] ?? flat;
109
+ return sentence.length > SUMMARY_CHARS ? `${sentence.slice(0, SUMMARY_CHARS - 1)}…` : sentence;
110
+ }
111
+ function memberHead(m, full = false) {
112
+ const head = m.kind === "method" ? m.signatures[0] : `${m.readonly ? "readonly " : ""}${m.name}: ${m.signatures[0]}`;
113
+ const more = m.signatures.length > 1 ? ` (+${m.signatures.length - 1} overload${m.signatures.length === 2 ? "" : "s"})` : "";
114
+ return full || head.length <= HEAD_CHARS ? `${head}${more}` : `${head.slice(0, HEAD_CHARS - 1)}…${more}`;
115
+ }
116
+ export const DEFAULT_API_LINES = 60;
117
+ /** The subject's own members one line each (signature + the first sentence of its doc), inherited ones by name only, and the events. */
118
+ export function formatApi(api, options = {}) {
119
+ if (options.member) {
120
+ const found = api.members.find((m) => m.name === options.member);
121
+ if (!found)
122
+ return `${api.subject} has no public member "${options.member}" — members: ${api.members.map((m) => m.name).join(", ")}`;
123
+ return [
124
+ `${api.subject}.${found.name}${found.origin ? ` (declared in ${found.origin})` : ""}${found.deprecated ? ` — DEPRECATED: ${found.deprecated}` : ""}`,
125
+ ...(found.kind === "method" ? found.signatures : [memberHead(found, true)]),
126
+ found.doc || "(no documentation)",
127
+ ].join("\n");
128
+ }
129
+ const needle = options.filter?.toLowerCase();
130
+ const matches = (m) => !needle || m.name.toLowerCase().includes(needle) || m.doc.toLowerCase().includes(needle);
131
+ const own = api.members.filter((m) => (!m.origin || m.origin === api.ownName) && matches(m));
132
+ const inherited = api.members.filter((m) => m.origin && m.origin !== api.ownName && matches(m));
133
+ const limit = options.maxLines ?? DEFAULT_API_LINES;
134
+ const lines = [`${api.subject}: ${api.type}${needle ? ` — members matching "${options.filter}"` : ""}`];
135
+ if (api.events && !needle)
136
+ lines.push(`events — on(name, handler): ${api.events.join(", ")}`);
137
+ for (const m of own.slice(0, limit))
138
+ lines.push(` ${memberHead(m)}${m.deprecated ? " [deprecated]" : ""}${m.doc ? ` — ${summaryOf(m.doc)}` : ""}`);
139
+ if (own.length > limit)
140
+ lines.push(` … ${own.length - limit} more of its own — narrow with filter: "<word>"`);
141
+ const byOrigin = new Map();
142
+ for (const m of inherited)
143
+ byOrigin.set(m.origin, [...(byOrigin.get(m.origin) ?? []), m.name]);
144
+ for (const [origin, names] of byOrigin)
145
+ lines.push(`inherited from ${origin}: ${names.join(", ")}`);
146
+ if (!own.length && !inherited.length)
147
+ lines.push(" (no public member matches)");
148
+ lines.push('one member in full: the same call with member: "<name>"');
149
+ return lines.join("\n");
150
+ }