diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 4ee702d3374..6ee11de2671 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8698,7 +8698,7 @@ API request and response schemas: [createWorkflowFromSource](/api-reference/work ### sim workflows source check -Compile a workflow source directory locally, without the server +Compile and type-check a workflow source directory locally, without the server ```bash sim workflows source check [options] @@ -8713,11 +8713,12 @@ sim workflows source check [options] | `--dir ` | No | Source directory: workflow.ts, functions/* and .sim/. Defaults to `.`. | | `--strict` | No | Fail on the warnings listed below in every block, not only new ones. | | `--no-strict` | No | Never fail on a warning an apply saves. | +| `--no-types` | No | Skip the type check (TypeScript 7.0.2 over tsconfig.json) that runs after the compile. | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | -Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so tsc type-checks a block the edit added; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts, so tsc types each workflow's inputs as its files declare them. +Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code; one on a line the compile already reports an error on, or in a file still as the last get or apply wrote it, is left out. The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. @@ -10080,7 +10081,7 @@ API request and response schemas: [applyWorkspaceSource](/api-reference/workflow ### sim workspaces source check -Compile every workflow of a workspace source directory locally, without the server +Compile and type-check every workflow of a workspace source directory locally, without the server ```bash sim workspaces source check [options] @@ -10095,11 +10096,12 @@ sim workspaces source check [options] | `--dir ` | No | Workspace source directory: the kind folders and .sim/base.json. Defaults to `.`. | | `--strict` | No | Fail on the warnings listed below in every block, not only new ones. | | `--no-strict` | No | Never fail on a warning an apply saves. | +| `--no-types` | No | Skip the type check (TypeScript 7.0.2 over tsconfig.json) that runs after the compile. | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | -Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so tsc types a key added since the get, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. +Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code; one on a line the compile already reports an error on, or in a file still as the last get or apply wrote it, is left out. The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials). With --output json, stdout is one document that also lists every finding under diagnostics. diff --git a/apps/docs/content/docs/cli/scripting.mdx b/apps/docs/content/docs/cli/scripting.mdx index f14a6f229df..921d08d70b4 100644 --- a/apps/docs/content/docs/cli/scripting.mdx +++ b/apps/docs/content/docs/cli/scripting.mdx @@ -112,11 +112,11 @@ Run the next command only when the cursor is non-null. `--limit` applies to each Results go to stdout; diagnostics go to stderr. JSON/YAML modes serialize API errors as `{error:{code,message,details?}}`. Display formats use `Error:` plus any supplied code/details. Configuration and argument-parser errors, run-wait outcome messages, and unexpected stack traces can remain text. Do not assume every stderr stream is a single JSON document. -`sim workflows source check`, `sim workspaces source check` and both `source apply` commands (dry run or not) print their findings on stderr as `file:line:column` with the code frame. In JSON output (the [default](/cli/output)) or `--output yaml`, stdout is one document holding the counts and every finding as well: +`sim workflows source check`, `sim workspaces source check` and both `source apply` commands (dry run or not) print their findings on stderr as `file:line:column` with the code frame. A check's `checked` lists what ran: `compile`, and `types` unless `--no-types` or an offline first run (`W_TYPES_UNCHECKED`) skipped the type check. In JSON output (the [default](/cli/output)) or `--output yaml`, stdout is one document holding the counts and every finding as well: ```json { - "checked": "compile", + "checked": ["compile", "types"], "errors": 1, "warnings": 0, "diagnostics": [ diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index ed4df922b58..67558d48f85 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1492,7 +1492,7 @@ sim workflows source catalog [options] API request and response schemas: [getSourceCatalog](/api-reference/catalog/getSourceCatalog). -### Compile a workflow source directory locally, without the server +### Compile and type-check a workflow source directory locally, without the server ```bash sim workflows source check [options] @@ -1507,11 +1507,12 @@ sim workflows source check [options] | `--dir ` | No | Source directory: workflow.ts, functions/* and .sim/. Defaults to `.`. | | `--strict` | No | Fail on the warnings listed below in every block, not only new ones. | | `--no-strict` | No | Never fail on a warning an apply saves. | +| `--no-types` | No | Skip the type check (TypeScript 7.0.2 over tsconfig.json) that runs after the compile. | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | -Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so tsc type-checks a block the edit added; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts, so tsc types each workflow's inputs as its files declare them. +Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code; one on a line the compile already reports an error on, or in a file still as the last get or apply wrote it, is left out. The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index ccaae1e1758..7f50eb3c1f1 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -768,7 +768,7 @@ Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printe API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). -### Compile every workflow of a workspace source directory locally, without the server +### Compile and type-check every workflow of a workspace source directory locally, without the server ```bash sim workspaces source check [options] @@ -783,11 +783,12 @@ sim workspaces source check [options] | `--dir ` | No | Workspace source directory: the kind folders and .sim/base.json. Defaults to `.`. | | `--strict` | No | Fail on the warnings listed below in every block, not only new ones. | | `--no-strict` | No | Never fail on a warning an apply saves. | +| `--no-types` | No | Skip the type check (TypeScript 7.0.2 over tsconfig.json) that runs after the compile. | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | -Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so tsc types a key added since the get, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. +Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code; one on a line the compile already reports an error on, or in a file still as the last get or apply wrote it, is left out. The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials). With --output json, stdout is one document that also lists every finding under diagnostics. diff --git a/apps/docs/content/docs/workflows/code/ci.mdx b/apps/docs/content/docs/workflows/code/ci.mdx index 21c0d41f0f6..4b96da36834 100644 --- a/apps/docs/content/docs/workflows/code/ci.mdx +++ b/apps/docs/content/docs/workflows/code/ci.mdx @@ -75,7 +75,6 @@ jobs: - uses: oven-sh/setup-bun@v2 - run: bun add -g sim - run: sim workspaces source check --dir workspace - - run: bunx -p typescript@7.0.2 tsc -p workspace - run: sim workspaces source apply --dir workspace --dry-run - if: github.event_name == 'push' run: sim workspaces source apply --dir workspace --yes @@ -89,7 +88,7 @@ jobs: fi ``` -`check` runs first because it is offline and fast, and it regenerates `.sim/sdk/workspace.d.ts`, so the `tsc` step after it types resources the pull request adds. Apply rewrites files under the directory (each `.sim/base.json`, ids it allocated, values the server normalized), and the next apply compares with them, so the last step commits them back to the branch; `[skip ci]` keeps that commit from running the job again. That step runs even when the apply failed (`!cancelled()`), because an apply can fail having written part of its plan: exit `15` means it held back changes that use a secret with no value or a credential nothing binds to and applied the rest, and exit `8` means it stopped part-way. Either way the directory records what was written, so committing it keeps the next run from being refused as stale (exit `5`) for resources this run wrote; the job still fails, so set the secret, connect the credential or fix the failure, and push again. Where the branch is protected, run `sim workspaces source get --dir workspace` on a new branch instead and open a pull request. +`check` runs first because it needs no server and is fast: it compiles every workflow and type-checks the directory after regenerating `.sim/sdk/workspace.d.ts`, so resources the pull request adds are typed. Each finding is also a GitHub annotation at its line. Apply rewrites files under the directory (each `.sim/base.json`, ids it allocated, values the server normalized), and the next apply compares with them, so the last step commits them back to the branch; `[skip ci]` keeps that commit from running the job again. That step runs even when the apply failed (`!cancelled()`), because an apply can fail having written part of its plan: exit `15` means it held back changes that use a secret with no value or a credential nothing binds to and applied the rest, and exit `8` means it stopped part-way. Either way the directory records what was written, so committing it keeps the next run from being refused as stale (exit `5`) for resources this run wrote; the job still fails, so set the secret, connect the credential or fix the failure, and push again. Where the branch is protected, run `sim workspaces source get --dir workspace` on a new branch instead and open a pull request. After merging two branches that each applied, a dry run with no changes means the files match the workspace. Exit `5` means a resource changed since this branch's base: get the workspace into a fresh directory and carry the edit over. Exit `10` means another apply is writing the workspace (or another command is using the directory), so retry; the `concurrency` key keeps two runs of this job from overlapping. Pull requests from forks do not receive repository secrets, so the dry run needs a branch in the same repository. diff --git a/apps/docs/content/docs/workflows/code/coding-agents.mdx b/apps/docs/content/docs/workflows/code/coding-agents.mdx index 91cfe685573..42ec35a8469 100644 --- a/apps/docs/content/docs/workflows/code/coding-agents.mdx +++ b/apps/docs/content/docs/workflows/code/coding-agents.mdx @@ -24,7 +24,7 @@ Point the agent at `.sim/AGENTS.md` before it edits. sim workflows source check --dir && sim workflows source apply --dir --yes && sim workflows run --manual --input '{...}' ``` - A non-zero exit code stops the chain at the first failure. `apply` compiles the source and compares it with the saved draft again, so an agent can skip `--dry-run`. People and CI use `apply --dry-run` to review the plan, and `status` shows what changed and what to run next. Add `bunx -p typescript@7.0.2 tsc -p ` after `check` to catch type errors. + A non-zero exit code stops the chain at the first failure. `apply` compiles the source and compares it with the saved draft again, so an agent can skip `--dry-run`. `check` also type-checks the directory, so the chain needs no separate `tsc`. People and CI use `apply --dry-run` to review the plan, and `status` shows what changed and what to run next. For a whole workspace, use `sim workspaces source` with the same steps; see [Manage a workspace as code](/workflows/code/workspace). diff --git a/apps/docs/content/docs/workflows/code/diagnostics.mdx b/apps/docs/content/docs/workflows/code/diagnostics.mdx index c9b8bbf92c0..8d9c4159afe 100644 --- a/apps/docs/content/docs/workflows/code/diagnostics.mdx +++ b/apps/docs/content/docs/workflows/code/diagnostics.mdx @@ -190,6 +190,15 @@ Saving the workflow draft. | `E_APPLY_INVALID_SCHEDULE` | An added or changed schedule whose cron, timezone or interval deploy would refuse. | | `W_TABLE_UNKNOWN_COLUMN` | A table row write whose data names a key that is not a column of the table; the run drops it. The hint names the nearest column. | +#### Type check + +`sim workflows source check` and `sim workspaces source check` type-checking the directory with TypeScript after the compile. The server never reports these. + +| Code | Meaning | +| --- | --- | +| `E_TYPE` | TypeScript (the release the declarations are built for) reported an error; the message starts with its `TS` code. A type error on a line the compile already reports an error on, or in a file still as the last get or apply wrote it, is left out. | +| `W_TYPES_UNCHECKED` | The type check did not run: TypeScript could not be installed (offline, or no `npm`) or did not start. The other findings stand; pass `--no-types` to skip it. | + ### Workspace source Workspace source reports every workflow code above for the files of `workflows//`, with that path as the file, and these codes for the rest of the directory. diff --git a/apps/docs/content/docs/workflows/code/edit.mdx b/apps/docs/content/docs/workflows/code/edit.mdx index 7aa8d8c57dd..346615110a9 100644 --- a/apps/docs/content/docs/workflows/code/edit.mdx +++ b/apps/docs/content/docs/workflows/code/edit.mdx @@ -29,15 +29,9 @@ Edit `workflow.ts`, then compile it on your machine with Sim's compiler: sim workflows source check --dir ./support-triage ``` -`check` makes no request. It needs the block catalog the last `get` cached in `~/.sim/cache/source-catalog/`; with none cached it exits `1` and tells you to run `get` once. It exits `1` on an error, and on the warnings `sim workflows source check --help` lists (a missing required field, an unknown option, an unwired condition or router branch, a literal secret and more) in a block you added since the get. `--strict` fails on these in every block, except an unwired branch on a block the get printed; `--no-strict` never fails on a warning. It also adds the blocks the workflow now uses to `tsconfig.json`. +`check` makes no request. It needs the block catalog the last `get` cached in `~/.sim/cache/source-catalog/`; with none cached it exits `1` and tells you to run `get` once. It exits `1` on an error, and on the warnings `sim workflows source check --help` lists (a missing required field, an unknown option, an unwired condition or router branch, a literal secret and more) in a block you added since the get. `--strict` fails on these in every block, except an unwired branch on a block the get printed; `--no-strict` never fails on a warning. -Your editor type-checks the file against the generated declarations, and this checks it from the command line with the TypeScript release the declarations are built for: - -```bash -bunx -p typescript@7.0.2 tsc -p ./support-triage -``` - -Use `-p ./support-triage/tsconfig.full.json` to type-check against every block. +Then it adds the blocks the workflow now uses to `tsconfig.json` and type-checks the directory with it, using the TypeScript release the generated declarations are built for, as your editor does. Each type error is an `E_TYPE` error at its line, with TypeScript's own code (`TS2339: …`) at the start of the message. A type error is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it, where the dry run decides. The first check installs that release with `npm` into `~/.sim/cache/typescript/`, once; offline before then, `check` warns `W_TYPES_UNCHECKED` and passes or fails on the compile alone. `--no-types` skips the type check. `tsconfig.full.json` includes every block, for an editor. ## 3. See what changed diff --git a/apps/docs/content/docs/workflows/code/get-started.mdx b/apps/docs/content/docs/workflows/code/get-started.mdx index 0e592f79b55..6bbdeedd29d 100644 --- a/apps/docs/content/docs/workflows/code/get-started.mdx +++ b/apps/docs/content/docs/workflows/code/get-started.mdx @@ -33,10 +33,9 @@ Open `workflow.ts` and change one value, such as an agent's `model` or a message ```bash sim workflows source check --dir ./support-triage -bunx -p typescript@7.0.2 tsc -p ./support-triage ``` -`check` compiles the file on your machine, and `tsc` type-checks it. Each problem prints with its line, the code around it, and a hint. +`check` compiles the file on your machine and type-checks it. Each problem prints with its line, the code around it, and a hint. The first check installs the TypeScript release the declarations are built for, once. ## 5. See what changed diff --git a/apps/docs/content/docs/workflows/code/how-it-works.mdx b/apps/docs/content/docs/workflows/code/how-it-works.mdx index 9da6506e437..da27f0d19f0 100644 --- a/apps/docs/content/docs/workflows/code/how-it-works.mdx +++ b/apps/docs/content/docs/workflows/code/how-it-works.mdx @@ -9,7 +9,7 @@ A source file is a declaration, not a program. Sim reads it, compares it with th `workflow.ts` is TypeScript so that your editor can complete and type-check it, but no command executes it. Sim parses the file and reads each `const x = builder('Name', {…})` as one block, each `.to()` as one connection, and each param as one setting. That is why the file holds declarations only: a helper function, a loop that creates blocks, or an import from anything but `@sim/workflow-sdk` has no value Sim could read without running it, so it is refused with `E_UNSUPPORTED_SYNTAX` and a hint. -`check` runs this compiler on your machine, the same one the server runs, against the block catalog the last `get` cached. Function code under `functions/` is not run either: it is stored as the Function block's code and runs in Sim, like code typed into the workflow builder. +`check` runs this compiler on your machine, the same one the server runs, against the block catalog the last `get` cached, then type-checks the directory with the TypeScript release the generated declarations are built for. Function code under `functions/` is not run either: it is stored as the Function block's code and runs in Sim, like code typed into the workflow builder. ## From a file to a saved draft diff --git a/apps/docs/content/docs/workflows/code/troubleshooting.mdx b/apps/docs/content/docs/workflows/code/troubleshooting.mdx index b93ba36e084..5fd2eacde6c 100644 --- a/apps/docs/content/docs/workflows/code/troubleshooting.mdx +++ b/apps/docs/content/docs/workflows/code/troubleshooting.mdx @@ -96,6 +96,10 @@ The file holds a form Sim cannot read without running it, such as a helper funct A builder or param name the block catalog does not have. The hint suggests the closest name. `sim workflows source params ` prints a builder's params and outputs, and a namespace such as `gmail` lists its builders. +### `E_TYPE` and `W_TYPES_UNCHECKED` [#e-type] + +`E_TYPE` is a type error `check` found after the compile; its message starts with TypeScript's own code, such as `TS2339: Property 'emial' does not exist`. Fix it at the line it names: it usually reads an output or input the block does not declare, or passes a value of the wrong type. `W_TYPES_UNCHECKED` means the type check did not run, most often because the first `check` on this machine could not install TypeScript offline. The compile's findings still stand; run `check` once with network access, or pass `--no-types`. + ### `W_REQUIRED_MISSING` [#w-required-missing] A required field is empty, or holds `todo()`. Fill it in, or use `env.NAME` for a value you keep in an environment variable. diff --git a/apps/docs/content/docs/workflows/code/workspace.mdx b/apps/docs/content/docs/workflows/code/workspace.mdx index 09c356241ed..3a525475ee7 100644 --- a/apps/docs/content/docs/workflows/code/workspace.mdx +++ b/apps/docs/content/docs/workflows/code/workspace.mdx @@ -46,7 +46,7 @@ sim workspaces source apply --dir ./my-workspace --yes `check` compiles every workflow on your machine against what the directory declares: an unknown table, credential, knowledge base, skill, custom tool, MCP server or workflow key, a table row write naming a column the table does not declare, and a child workflow call whose `inputMapping` names an input the child's Start trigger does not declare, are reported, and an env name `secrets.ts` lacks is a warning. It checks each `tables/.rows.jsonl` line against its table the way an apply writes it (a required cell, a unique value, a column's type and select options), so the dry run's `E_TABLE_ROWS` shows up offline at its line. It exits 1 on errors and, as `sim workflows source check` does, on a broken block you added. -Unlike a workflow directory's `check`, it needs the block catalog but fetches it for you: on a fresh clone with none cached it downloads the catalog once with the profile's credentials, and without credentials it exits `1` and tells you to run `get`. It also regenerates `.sim/sdk/workspace.d.ts` from the declarations, so run `bunx -p typescript@7.0.2 tsc -p ./my-workspace` after it to type-check every file, keys added since the get included. Run in a `workflows/` folder, `sim workflows source check --dir .` checks that one workflow the same way. +Unlike a workflow directory's `check`, it needs the block catalog but fetches it for you: on a fresh clone with none cached it downloads the catalog once with the profile's credentials, and without credentials it exits `1` and tells you to run `get`. It also regenerates `.sim/sdk/workspace.d.ts` from the declarations and then type-checks every file, so a table, workflow or other key the directory declares since the get is typed in the same check. Run in a `workflows/` folder, `sim workflows source check --dir .` checks that one workflow the same way. The dry run prints the plan (`+` create, `~` update, `=` adopt an existing resource with the same name, `-` delete) and every error with its file and line. `--only tables,workflows` limits a get or an apply to some kinds. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 9e23599839a..1ee288774cb 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -19401,7 +19401,9 @@ "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `W_CANON_UNRESOLVED_ID`." }, @@ -19876,7 +19878,9 @@ "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `E_UNKNOWN_PARAM` or `E_APPLY_LOCKED_BLOCK`." }, @@ -20841,7 +20845,9 @@ "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `E_UNKNOWN_PARAM` or `E_APPLY_LOCKED_BLOCK`." }, @@ -21782,7 +21788,9 @@ "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `E_UNKNOWN_PARAM` or `E_APPLY_LOCKED_BLOCK`." }, @@ -26828,7 +26836,9 @@ "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." }, @@ -27412,7 +27422,9 @@ "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code." }, @@ -27826,7 +27838,9 @@ "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." }, @@ -28690,7 +28704,9 @@ "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code." }, @@ -29104,7 +29120,9 @@ "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." }, diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index 2a4f4f63954..ffcc9397ea8 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -14256,8 +14256,8 @@ { "lang": "json", "meta": null, - "sha256": "a19ec054796bc74549f7dbe83949c9eb6c5ae1f54cda5b5c9f8a7e1db5f99d80", - "bytes": 349, + "sha256": "bf4d32315fcc01d909ecff9703177bc1b53ca17a1c30c875a4824d68e2899fae", + "bytes": 360, "line": 117 }, { diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index 5e00732c2a9..636a60d0332 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -48,6 +48,7 @@ import { type LocalDeclarations, refreshTsconfigs, } from './source-tree' +import type { TypeCheck } from './source-types' import { type Diagnostic, findingsOutput } from './source-ui' import { blockDigest, readStoredBlockDigests, readStoredEdges } from './stored-edges' import { lockRecoveryHint, readSourceFiles } from './workflow-dir' @@ -765,7 +766,8 @@ interface UnlistedCounts { } /** - * Prints a check's findings and result, and exits 1 on any error. The findings are bounded as the + * Prints a check's findings and result, and exits 1 on any error. `checked` lists what ran: the + * compile, and the type check unless it was skipped or could not run. The findings are bounded as the * server bounds an answer of the same source (`bound`, the workflow answer's by default), while * `errors` and `warnings` count every one. `verbose` keeps info findings in a machine result. */ @@ -779,8 +781,11 @@ export function reportCheck( unlisted?: UnlistedCounts /** The source directory, which GitHub Actions annotations resolve finding files under. */ dir?: string + /** The type check that ran after the compile, whose findings join the compile's. */ + types?: TypeCheck } = {} ): void { + findings = [...findings, ...(options.types?.findings ?? [])] const shown = findingsOutput(output, options.verbose, options.dir) const listed = boundAnswerFindings(findings, options.bound) shown.print(listed) @@ -788,7 +793,7 @@ export function reportCheck( const errors = findings.filter((finding) => finding.severity === 'error').length + unlisted.errors if (errors > 0) setSoftExitCode(1) printProtocolResult(output, { - checked: 'compile', + checked: options.types?.checked ? ['compile', 'types'] : ['compile'], errors, warnings: findings.filter((finding) => finding.severity === 'warning').length + unlisted.warnings, diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index dfad37b24fd..f1ddf2d5e8e 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -2,7 +2,6 @@ * The group help of `sim workflows source` and `sim workspaces source`: the edit loop and the * flags it needs, so a reader of the group needs no command's own `--help` to start. */ -import { typecheckCommand } from '@sim/workflow-sdk/codegen' import { SOURCE_DRIFT_EXIT_CODE, SOURCE_LOCAL_CHANGES_EXIT_CODE } from '../../exit-codes' import { SOURCE_AGENTS_FILE } from './source-dir' @@ -35,13 +34,13 @@ The loop: ${loopRows([ ['sim workflows source get --dir ./wf', 'write workflow.ts, functions/* and .sim/'], ['edit ./wf/workflow.ts', 'every file first, then the one command below'], - ['sim workflows source check --dir ./wf', 'offline: each error as file:line:column'], + ['sim workflows source check --dir ./wf', 'compile + types: each error as file:line:column'], [' && sim workflows source apply --dir ./wf --yes', 'save the draft (it re-checks)'], [' && sim workflows run --manual', 'test the saved draft'], ])} Run those three as one chained command: a non-zero exit stops it at the first failure, and the next -step fixes what it reported. For review, \`apply --dry-run\` prints the plan and writes nothing; -\`${typecheckCommand('./wf')}\` adds type errors. +step fixes what it reported. Check also type-checks with TypeScript (installed once, on its first +run; --no-types skips it). For review, \`apply --dry-run\` prints the plan and writes nothing. A new workflow: \`sim workflows source create --dir ./new --workspace \` writes a starter that records its workspace; edit and check it, then \`create --dir ./new --yes\` creates the workflow there, and the loop above goes on from there. @@ -59,12 +58,12 @@ The loop: ${loopRows([ ['sim workspaces source get --dir ./ws', 'write tables/, workflows//, … and .sim/'], ['edit the files', 'every file first; a new workflow: workflows//workflow.ts'], - ['sim workspaces source check --dir ./ws', 'offline: each error as file:line:column'], + ['sim workspaces source check --dir ./ws', 'compile + types: each error as file:line:column'], [' && sim workspaces source apply --dir ./ws --yes', 'write it to the workspace (it re-checks)'], ])} Run those two as one chained command: a non-zero exit stops it at the first failure, and the next -step fixes what it reported. For review, \`apply --dry-run\` prints the plan and writes nothing; -\`${typecheckCommand('./ws')}\` adds type errors. +step fixes what it reported. Check also type-checks with TypeScript (installed once, on its first +run; --no-types skips it). For review, \`apply --dry-run\` prints the plan and writes nothing. Promote dev to prod: \`sim workspaces source apply --dir ./ws --to --dry-run\`, then --yes. ${WORKSPACE_LINE} diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 759c1782421..8fea762be25 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -11,7 +11,6 @@ import { describeBuilder, referencedBuilders, SDK_MAJOR, - typecheckCommand, } from '@sim/workflow-sdk/codegen' import { RATE_LIMITED_EXIT_CODE, @@ -55,7 +54,7 @@ const WORKFLOW_PRIMER = `# Sim workflow source: primer \`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it statically and nothing in it runs. Commands read the workflow id from \`${SOURCE_BASE_FILE}\`; run them from this directory. -**Edit loop**: write every file, then run one chained command and fix what it reports next: \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --manual --input '{…}'\`. A non-zero exit stops the chain. Apply re-checks the source and its base, so \`apply --dry-run\` is only the review for people and CI. Add \`${typecheckCommand()}\` after \`check\` for type errors. Apply saves the draft in canonical form: read \`${SOURCE_ENTRY_FILE}\` again before the next edit. +**Edit loop**: write every file, then run one chained command and fix what it reports next: \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --manual --input '{…}'\`. A non-zero exit stops the chain. \`check\` compiles and type-checks (no separate \`tsc\`). Apply re-checks the source and its base, so \`apply --dry-run\` is only the review for people and CI. Apply saves the draft in canonical form: read \`${SOURCE_ENTRY_FILE}\` again before the next edit. - **Deletes**: removing a block or a variable needs \`apply --allow-delete\` (\`E_APPLY_BLOCK_DELETE\` / \`E_APPLY_VARIABLE_DELETE\`). - **Deploy**: apply saves a draft; \`apply --deploy\` also deploys it, or \`sim workflows deploy \` publishes the saved draft later. @@ -70,7 +69,7 @@ const WORKSPACE_PRIMER = `# Sim workspace source: primer This directory is a Sim workspace as files (\`tables/\`, \`workflows//workflow.ts\`, …); nothing in it runs. Commands read the workspace id from \`${SOURCE_BASE_FILE}\`; run them from this directory. Every \`.ts\` file, \`deployments/\` too, starts with \`// @sim-sdk ${SDK_MAJOR}\`. -**Edit loop**: write every file, then run one chained command and fix what it reports next: \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\` (add a \`sim workflows run\` to test). A non-zero exit stops the chain. Apply re-checks the source and its base, so \`apply --dry-run\` is only the review for people and CI. Add \`${typecheckCommand()}\` after \`check\` for type errors. Apply rewrites the directory: read a file again before the next edit. +**Edit loop**: write every file, then run one chained command and fix what it reports next: \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\` (add a \`sim workflows run\` to test). A non-zero exit stops the chain. \`check\` compiles and type-checks (no separate \`tsc\`). Apply re-checks the source and its base, so \`apply --dry-run\` is only the review for people and CI. Apply rewrites the directory: read a file again before the next edit. - **Deletes**: a file or folder missing from a kind's folder, or a removed table column, workflow block or variable, is a delete: refused without \`apply --allow-delete\`, and it cannot be undone. - **Deploy**: \`deployments/.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys that workflow on apply; without one, apply never deploys. diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index 7e47cffaf73..77a1043f3d6 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -375,24 +375,31 @@ export async function loadWorkspaceTypes( /** * Regenerates `workspace.d.ts` from the stored manifest the last get kept beside it and what the - * directory declares now (`local`), so `tsc` types a key added since without a request. A - * directory with no kept manifest (no get has written its types) is left as it is. + * directory declares now (`local`), so a check types a key added since without a request. Without + * a kept manifest (the get could not list the workspace's resources), it types what the directory + * declares, as that get did, and removes the file when it declares nothing. A manifest that does + * not parse leaves the file as it is. */ export async function refreshWorkspaceTypes(dir: string, local: LocalDeclarations): Promise { const [manifest, current] = await Promise.all([ readSourceText(dir, WORKSPACE_MANIFEST_FILE), readSourceText(dir, WORKSPACE_TYPES_FILE), ]) - if (manifest === null) return - let stored: unknown - try { - stored = JSON.parse(manifest) - } catch { - return + let stored: WorkspaceManifest | null = null + if (manifest !== null) { + let parsed: unknown + try { + parsed = JSON.parse(manifest) + } catch { + return + } + if (!isRecordLike(parsed)) return + stored = parsed } - if (!isRecordLike(stored)) return const types = workspaceTypesFrom(stored, local) - if (types && types.text !== current) { + if (types === null) { + if (current !== null) await updateSourceDir(dir, { write: [], remove: [WORKSPACE_TYPES_FILE] }) + } else if (types.text !== current) { await updateSourceDir(dir, { write: [[WORKSPACE_TYPES_FILE, types.text]] }) } } diff --git a/packages/sim-cli/src/commands/protocol/source-types.ts b/packages/sim-cli/src/commands/protocol/source-types.ts new file mode 100644 index 00000000000..e83b0977469 --- /dev/null +++ b/packages/sim-cli/src/commands/protocol/source-types.ts @@ -0,0 +1,370 @@ +/** + * The type check `sim workflows source check` and `sim workspaces source check` run after the + * compile: the pinned TypeScript release (`SOURCE_TYPESCRIPT_VERSION`, the one the generated + * declarations are built for) over the directory's `tsconfig.json`, each error a finding. + * + * A source directory has no `package.json`, so the release is installed once with `npm` into the + * CLI's cache and reused from there. When it cannot be installed (offline, no `npm`) or does not + * start, the check reports `W_TYPES_UNCHECKED` and the compile's findings still decide the exit. + */ +import { spawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import { mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { mapWithConcurrency } from '@sim/utils/concurrency' +import { getErrorMessage } from '@sim/utils/errors' +import { codeFrame } from '@sim/workflow-code' +import { SOURCE_TYPESCRIPT_VERSION } from '@sim/workflow-sdk/codegen' +import type { Command } from 'commander' +import { configDir } from '../../config/paths' +import { embedStore } from '../../embed-context' +import { childProcessEnv } from '../../environment' +import { printError } from '../../output/io' +import { digest, FILE_CONCURRENCY, readSourceText, readWritten } from './source-dir' +import type { Diagnostic } from './source-ui' + +/** The `--types` / `--no-types` pair: absent runs the type check. */ +export interface TypesOptions { + types?: boolean +} + +/** What both check commands' help says of the type check. */ +export const TYPES_HELP = `Then it type-checks the directory with TypeScript ${SOURCE_TYPESCRIPT_VERSION} (the release the +declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message +starting with TypeScript's code; one on a line the compile already reports an error on, or in a +file still as the last get or apply wrote it, is left out. The first check installs that release +with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns +W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check.` + +/** Adds `--no-types` to a check command. */ +export function typesFlag(command: Command): Command { + return command.option( + '--no-types', + `Skip the type check (TypeScript ${SOURCE_TYPESCRIPT_VERSION} over tsconfig.json) that runs after the compile` + ) +} + +/** Why the type check could not run: the `W_TYPES_UNCHECKED` message and hint. */ +class TypesUnavailable extends Error { + constructor( + message: string, + readonly hint = 'Pass --no-types to skip the type check.' + ) { + super(message) + } +} + +/** Neither process should take this long; a hung one (a stalled registry) is cut off. */ +const PROCESS_TIMEOUT_MS = 5 * 60_000 + +/** At most this much of a process's output is kept: tsc's findings, npm's error lines. */ +const MAX_OUTPUT_BYTES = 1024 * 1024 + +/** Where the pinned release is installed: cache, safe to delete, so it follows `SIM_CONFIG_DIR`. */ +function typescriptRoot(): string { + return join(configDir(), 'cache', 'typescript', SOURCE_TYPESCRIPT_VERSION) +} + +function tscPath(root: string): string { + return join(root, 'node_modules', 'typescript', 'bin', 'tsc') +} + +interface Finished { + code: number | null + signal: NodeJS.Signals | null + stdout: string + stderr: string + /** Whether stdout passed {@link MAX_OUTPUT_BYTES} and the rest was left out. */ + stdoutCut: boolean +} + +/** + * Runs `command` (`label` names it) to its end, keeping the start of its output (`stdout: false` + * discards it). Neither child gets the Sim API key. A failure to start is a {@link TypesUnavailable}. + */ +function run( + label: string, + command: string, + args: readonly string[], + options: { cwd: string; shell?: boolean; stdout?: boolean } +): Promise { + return new Promise((resolve, reject) => { + const child = spawn(command, args, { + cwd: options.cwd, + env: childProcessEnv(['sim_api_key']), + shell: options.shell ?? false, + stdio: ['ignore', options.stdout === false ? 'ignore' : 'pipe', 'pipe'], + timeout: PROCESS_TIMEOUT_MS, + killSignal: 'SIGKILL', + windowsHide: true, + }) + const output = { stdout: '', stderr: '', stdoutCut: false } + for (const stream of ['stdout', 'stderr'] as const) { + child[stream]?.setEncoding('utf8').on('data', (chunk: string) => { + if (output[stream].length < MAX_OUTPUT_BYTES) output[stream] += chunk + else if (stream === 'stdout') output.stdoutCut = true + }) + } + child.once('error', (error) => + reject(new TypesUnavailable(`${label} could not start (${getErrorMessage(error)}).`)) + ) + child.once('close', (code, signal) => resolve({ code, signal, ...output })) + }) +} + +/** + * What npm said went wrong: its first `npm error` line that is not a bare field (`code`, `errno`, + * `syscall`) or the pointer to its debug log, such as `request to … failed, reason: getaddrinfo + * ENOTFOUND registry.npmjs.org`. + */ +function npmReason(stderr: string): string { + const said = stderr + .split('\n') + .map((line) => /^npm (?:error|ERR!) (.*)$/.exec(line.trim())?.[1]?.trim() ?? '') + .find( + (line) => + line !== '' && + !/^(?:code|errno|syscall) \S+$/.test(line) && + !line.startsWith('A complete log') + ) + return said?.replace(/^(?:network |FetchError: )/, '') ?? 'npm printed no reason' +} + +/** + * The pinned release's `tsc`, installed on first use: into a fresh folder beside its place, then + * renamed there, so a check interrupted mid-install or two checks installing at once never leave + * a partial install behind. The install reads the person's npm configuration (registry, proxy). + */ +async function installedTsc(): Promise { + const root = typescriptRoot() + const tsc = tscPath(root) + if (existsSync(tsc)) return tsc + try { + await installTypescript(root) + } catch (error) { + if (error instanceof TypesUnavailable) throw error + // The cache folder could not be written (permissions, a full disk). + throw new TypesUnavailable( + `TypeScript could not be installed into ${root} (${getErrorMessage(error)}).` + ) + } + return tsc +} + +/** Installs the pinned release into `root` (see {@link installedTsc}). */ +async function installTypescript(root: string): Promise { + const tsc = tscPath(root) + const parent = dirname(root) + await mkdir(parent, { recursive: true }) + const staging = await mkdtemp(join(parent, `.${SOURCE_TYPESCRIPT_VERSION}-`)) + const offline = `Run the check once with network access (TypeScript is kept in ${root}), or pass --no-types.` + try { + // A package.json makes the staging folder npm's prefix, so no path is passed on the command + // line, which a Windows shell would split at a space. + await writeFile(join(staging, 'package.json'), '{ "private": true }\n') + printError(`Installing TypeScript ${SOURCE_TYPESCRIPT_VERSION} for the type check, once.`) + const finished = await run( + 'npm', + 'npm', + [ + 'install', + '--no-save', + '--no-package-lock', + '--ignore-scripts', + '--no-audit', + '--no-fund', + '--update-notifier=false', + '--prefer-offline', + '--fetch-retries=0', + '--fetch-timeout=30000', + '--loglevel=error', + `typescript@${SOURCE_TYPESCRIPT_VERSION}`, + ], + // npm is a `.cmd` launcher on Windows; every argument above is fixed. + { cwd: staging, shell: process.platform === 'win32', stdout: false } + ).catch((error: unknown) => { + throw error instanceof TypesUnavailable ? new TypesUnavailable(error.message, offline) : error + }) + if (finished.code !== 0) { + throw new TypesUnavailable( + `npm could not install typescript@${SOURCE_TYPESCRIPT_VERSION}: ${npmReason(finished.stderr)}.`, + offline + ) + } + if (!existsSync(tscPath(staging))) { + throw new TypesUnavailable( + `npm installed typescript@${SOURCE_TYPESCRIPT_VERSION} without tsc.` + ) + } + try { + await rename(staging, root) + } catch (error) { + // Another check installed it first. + if (!existsSync(tsc)) throw error + } + } finally { + await rm(staging, { recursive: true, force: true }) + } +} + +/** An error tsc printed at a file position. */ +interface LocatedTscError { + file: string + line: number + column: number + message: string +} + +const LOCATED_ERROR = /^(.+)\((\d+),(\d+)\): error (TS\d+): (.*)$/ +const PROJECT_ERROR = /^error (TS\d+): (.*)$/ + +/** + * The errors of `tsc --pretty false`, at a file position or about the project (`tsconfig.json`): + * one line each, with the indented lines of a message chain (`Types of property 'a' are + * incompatible.`) joined onto it. + */ +function parseTscOutput(stdout: string): { located: LocatedTscError[]; project: string[] } { + const located: LocatedTscError[] = [] + const project: Array<{ message: string }> = [] + let last: { message: string } | undefined + for (const line of stdout.split(/\r?\n/)) { + const at = LOCATED_ERROR.exec(line) + const global = at ? null : PROJECT_ERROR.exec(line) + if (at) { + const error: LocatedTscError = { + file: at[1], + line: Number(at[2]), + column: Number(at[3]), + message: `${at[4]}: ${at[5]}`, + } + located.push(error) + last = error + } else if (global) { + last = { message: `${global[1]}: ${global[2]}` } + project.push(last) + } else if (last && /^\s/.test(line) && line.trim()) { + last.message += ` ${line.trim()}` + } + } + return { located, project: project.map(({ message }) => message) } +} + +/** The type check's outcome: whether it ran, and its findings. */ +export interface TypeCheck { + checked: boolean + findings: Diagnostic[] +} + +/** + * Runs the pinned tsc over `root`'s `tsconfig.json` and returns its errors; a {@link + * TypesUnavailable} when it cannot be installed, does not start, or stops without saying why. + */ +async function tscErrors(root: string): Promise> { + const tsc = await installedTsc() + const finished = await run( + 'TypeScript', + process.execPath, + // --noEmit: a tsconfig.json the person wrote may emit, and a check writes nothing. + [tsc, '-p', '.', '--pretty', 'false', '--noEmit'], + { + cwd: root, + } + ) + // Output past the cap ends mid-line: parse whole lines only, and say what was left out, as an + // error no filter drops, so a cut list never reads as a clean check. + const errors = parseTscOutput( + finished.stdoutCut + ? finished.stdout.slice(0, finished.stdout.lastIndexOf('\n')) + : finished.stdout + ) + if (finished.stdoutCut) { + errors.project.push( + 'TypeScript reported more errors than a check lists; fix these and check again to see the rest.' + ) + } + if (finished.code !== 0 && errors.located.length === 0 && errors.project.length === 0) { + const said = (finished.stderr || finished.stdout).trim().split('\n')[0] ?? '' + throw new TypesUnavailable( + `TypeScript stopped (${finished.signal ?? `exit ${finished.code}`})${said ? `: ${said}` : '.'}` + ) + } + return errors +} + +/** + * Type-checks the source directory `root` with its `tsconfig.json`, unless `enabled` is false + * (`--no-types`). `scope` (a folder under `root`, such as `workflows//`) keeps only that + * folder's errors, with files relative to it, as a check of one workflow folder of a workspace + * reports them. Two kinds of type error are left out: one on a line where `compiled` (the + * compile's findings) already has an error, the same mistake, which the compile says better; and + * one in a file still as the last get or apply wrote it (`.sim/written.json`), printed source the + * server accepted, where the declarations can lag (a block the workspace's catalog withholds from + * the caller while a stored workflow holds it). An embedded run reads files through its host, + * which no subprocess can, so it does not type-check. + */ +export async function typeCheck( + root: string, + options: { enabled: boolean; scope?: string; compiled: readonly Diagnostic[] } +): Promise { + if (!options.enabled || embedStore.getStore()) return { checked: false, findings: [] } + let errors: Awaited> + try { + errors = await tscErrors(root) + } catch (error) { + if (!(error instanceof TypesUnavailable)) throw error + return { + checked: false, + findings: [ + { + code: 'W_TYPES_UNCHECKED', + severity: 'warning', + message: `Types were not checked: ${error.message}`, + hint: error.hint, + }, + ], + } + } + const { scope = '' } = options + const compiledErrorLines = new Set( + options.compiled + .filter((finding) => finding.severity === 'error' && finding.file !== undefined) + .map((finding) => `${finding.file}:${finding.line}`) + ) + const located = errors.located.filter( + ({ file, line }) => + file.startsWith(scope) && !compiledErrorLines.has(`${file.slice(scope.length)}:${line}`) + ) + const files = [...new Set(located.map(({ file }) => file))] + const [written, texts] = await Promise.all([ + located.length > 0 ? readWritten(root) : null, + mapWithConcurrency(files, FILE_CONCURRENCY, (file) => readSourceText(root, file)), + ]) + const sources = new Map( + files.map((file, index) => { + const text = texts[index] + const printed = text !== null && written?.digests[file] === digest(text) + return [file, { text, printed }] as const + }) + ) + const findings: Diagnostic[] = errors.project.map((message) => ({ + code: 'E_TYPE', + severity: 'error', + message, + })) + for (const { file, line, column, message } of located) { + const source = sources.get(file) + if (source?.printed) continue + findings.push({ + code: 'E_TYPE', + severity: 'error', + message, + file: file.slice(scope.length), + line, + column, + ...(source && source.text !== null + ? { frame: codeFrame(source.text, { line, column }) } + : {}), + }) + } + return { checked: true, findings } +} diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 65726eb842f..6e286410b31 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -14,11 +14,7 @@ import { SOURCE_ENTRY_FILE, SOURCE_LOCK_FILE, } from '@sim/workflow-code/limits' -import { - SDK_GUIDE_FILE, - SOURCE_COMPILER_OPTIONS, - typecheckCommand, -} from '@sim/workflow-sdk/codegen' +import { SDK_GUIDE_FILE, SOURCE_COMPILER_OPTIONS } from '@sim/workflow-sdk/codegen' import { SOURCE_PLANNED_EXIT_CODE, SOURCE_STALE_EXIT_CODE } from '../../exit-codes' import type { ApplyWorkflowSourceBody, GetWorkflowSourceResponse } from '../../generated/v2-api' import type { OperationClient } from '../../runtime/called-operations' @@ -48,7 +44,6 @@ import { type SourceTree, type SourceTreeProfile, sourceTreeChange, - TSCONFIG_FULL_FILE, TSCONFIG_MARKER, WORKSPACE_TYPES_FILE, type WorkspaceTypes, @@ -192,7 +187,7 @@ const SOURCE_DOCS_URL = 'https://docs.sim.ai/workflows/code' type WorkflowSource = GetWorkflowSourceResponse['data'] /** - * A `tsconfig.json` that lets an editor or `tsc -p` resolve `@sim/workflow-sdk` to the written + * A `tsconfig.json` that lets an editor or `source check` resolve `@sim/workflow-sdk` to the written * declarations and type-checks `workflow.ts` with the SDK files `sdkFiles`. */ function workflowTsconfig(sdkFiles: readonly string[]): string { @@ -221,20 +216,19 @@ The primer above is enough to edit; read a section here when a step needs it. ## Edit loop in detail -Batch it: write every file first, then run steps 2 and 5 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --manual --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Steps 3, 4 and the dry run in step 5 are for a person, CI, or a change you want reviewed first. +Batch it: write every file first, then run steps 2 and 4 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --manual --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 and the dry run in step 4 are for a person, CI, or a change you want reviewed first. 1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`. -2. \`sim workflows source check --dir .\`: compiles offline with the server's compiler, in milliseconds. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It also adds the blocks the source now uses to \`tsconfig.json\`. -3. \`${typecheckCommand()}\` (chain it after step 2): about a second; catches what step 2 and the dry run do not (such as a reference to a start input the trigger does not declare). It runs the TypeScript release the declarations are built for (the directory has no \`package.json\`; plain \`bunx tsc\` would run whatever version it finds). \`tsconfig.json\` includes only the blocks the source used at the last check, get or apply: a builder from another block fails with \`has no exported member\` until you run step 2 (or use \`${typecheckCommand(TSCONFIG_FULL_FILE)}\`, every current block). The dry run is the authority: a printed line you did not edit that \`tsc\` flags and the dry run accepts is fine. -4. \`sim workflows source status --dir .\`: the files you changed (\`sim workflows source diff --dir .\` shows the edits), whether the workflow changed on the server since the get, and the command to run next (\`--offline\`: skip the server). Then \`sim workflows source apply --dir . --dry-run\` until it exits 0. -5. \`sim workflows source apply --dir . --yes\`: saves the draft, refusing errors, block deletions without \`--allow-delete\` and a stale directory, so it needs no separate dry run (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}). \`--deploy\` also deploys it; without it, a deployed workflow's next \`sim workflows deploy --expected-draft-fingerprint \` is printed, which deploys only the draft this apply saved. It then rewrites \`${SOURCE_ENTRY_FILE}\` in canonical form (order, quoting, defaults left out). -6. Exit ${SOURCE_STALE_EXIT_CODE} (\`SOURCE_STALE\`, HTTP 409, or \`E_APPLY_STALE\` on a dry run): the workflow changed and nothing was saved. Run \`sim workflows source get --dir \`, reapply your edit there, dry-run, apply. A get into this directory refuses to overwrite your unapplied edits unless you pass \`--force\`. Exit ${SOURCE_STALE_EXIT_CODE} right after an apply that ended without an answer (a timeout, a dropped connection) means the draft changed, by that apply or by someone else: get into a fresh directory and compare. Only when it holds your edit, run \`sim workflows source get --dir . --force\`; otherwise reapply your edit in the fresh directory. +2. \`sim workflows source check --dir .\`: compiles with the server's compiler, in milliseconds and without a request. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It then adds the blocks the source now uses to \`tsconfig.json\` and type-checks with it, using the TypeScript release the declarations are built for (installed once into the CLI's cache, on the first check; \`E_TYPE\` findings). That catches what the compile and the dry run do not, such as a reference to a start input the trigger does not declare. Offline before that install, it warns \`W_TYPES_UNCHECKED\` and passes on the compile alone; \`--no-types\` skips it. The dry run is the authority: a type error on a printed line you did not edit that the dry run accepts can be skipped with \`--no-types\`. +3. \`sim workflows source status --dir .\`: the files you changed (\`sim workflows source diff --dir .\` shows the edits), whether the workflow changed on the server since the get, and the command to run next (\`--offline\`: skip the server). Then \`sim workflows source apply --dir . --dry-run\` until it exits 0. +4. \`sim workflows source apply --dir . --yes\`: saves the draft, refusing errors, block deletions without \`--allow-delete\` and a stale directory, so it needs no separate dry run (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}). \`--deploy\` also deploys it; without it, a deployed workflow's next \`sim workflows deploy --expected-draft-fingerprint \` is printed, which deploys only the draft this apply saved. It then rewrites \`${SOURCE_ENTRY_FILE}\` in canonical form (order, quoting, defaults left out). +5. Exit ${SOURCE_STALE_EXIT_CODE} (\`SOURCE_STALE\`, HTTP 409, or \`E_APPLY_STALE\` on a dry run): the workflow changed and nothing was saved. Run \`sim workflows source get --dir \`, reapply your edit there, dry-run, apply. A get into this directory refuses to overwrite your unapplied edits unless you pass \`--force\`. Exit ${SOURCE_STALE_EXIT_CODE} right after an apply that ended without an answer (a timeout, a dropped connection) means the draft changed, by that apply or by someone else: get into a fresh directory and compare. Only when it holds your edit, run \`sim workflows source get --dir . --force\`; otherwise reapply your edit in the fresh directory. Editing the \`workflow('…')\` name or description renames or redescribes the workflow; a name another workflow in its folder holds is refused with \`E_NAME_TAKEN\`. Lines starting \`note:\` explain something the write did differently than the source says; read them. ## A new workflow, or a fork -\`sim workflows source create --dir --workspace \` (without \`--dry-run\` or \`--yes\`) on a directory without \`${SOURCE_ENTRY_FILE}\` writes a starter \`${SOURCE_ENTRY_FILE}\`, the types of that workspace, \`tsconfig.json\` and this guide, records the workspace in \`${SOURCE_STARTER_FILE}\`, and creates nothing. Until the workflow exists there is no \`${SOURCE_BASE_FILE}\`, so \`status\`, \`diff\` and \`apply\` refuse the directory: edit the starter, check and type-check it, then \`sim workflows source create --dir --workspace --dry-run\` and the same with \`--yes\` (the starter prints both with its workspace filled in): it prints the new workflow id and writes the lock files. A create goes to the starter's workspace whatever the profile's default, unless \`--workspace\` names another. Exit 1 with \`SOURCE_NAME_TAKEN\` means another workflow has that name: pass \`--name\`. To fork a workflow, copy its directory, delete the copy's \`.sim/\` and run \`sim workflows source create --dir --workspace --name --yes\`. +\`sim workflows source create --dir --workspace \` (without \`--dry-run\` or \`--yes\`) on a directory without \`${SOURCE_ENTRY_FILE}\` writes a starter \`${SOURCE_ENTRY_FILE}\`, the types of that workspace, \`tsconfig.json\` and this guide, records the workspace in \`${SOURCE_STARTER_FILE}\`, and creates nothing. Until the workflow exists there is no \`${SOURCE_BASE_FILE}\`, so \`status\`, \`diff\` and \`apply\` refuse the directory: edit the starter, check it, then \`sim workflows source create --dir --workspace --dry-run\` and the same with \`--yes\` (the starter prints both with its workspace filled in): it prints the new workflow id and writes the lock files. A create goes to the starter's workspace whatever the profile's default, unless \`--workspace\` names another. Exit 1 with \`SOURCE_NAME_TAKEN\` means another workflow has that name: pass \`--name\`. To fork a workflow, copy its directory, delete the copy's \`.sim/\` and run \`sim workflows source create --dir --workspace --name --yes\`. ## File shape diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts index ba073a04761..a2d1c646a8d 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts @@ -32,7 +32,7 @@ async function check(): Promise { const source = new Command('source') attachWorkflowSourceCheck(source) source.commands.forEach((command) => command.exitOverride()) - await source.parseAsync(['node', 'source', 'check', '--dir', dir]) + await source.parseAsync(['node', 'source', 'check', '--dir', dir, '--no-types']) } function cacheCatalog(): void { @@ -159,7 +159,7 @@ async function checkIn(folder: string, ...flags: string[]): Promise { const source = new Command('source') attachWorkflowSourceCheck(source) source.commands.forEach((command) => command.exitOverride()) - await source.parseAsync(['node', 'source', 'check', '--dir', folder, ...flags]) + await source.parseAsync(['node', 'source', 'check', '--dir', folder, '--no-types', ...flags]) } /** `CLEAN` plus an API block with an unknown method: `W_UNKNOWN_OPTION` on block `call`. */ @@ -266,7 +266,7 @@ describe('sim workflows source check', () => { await check() - expect(result()).toMatchObject({ checked: 'compile', errors: 0, warnings: 0 }) + expect(result()).toMatchObject({ checked: ['compile'], errors: 0, warnings: 0 }) expect(process.exitCode).toBeUndefined() expect(contextMockFns.mockRequest).not.toHaveBeenCalled() }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts index d9076d5c57a..062deea4b05 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -1,5 +1,6 @@ import { toRecord } from '@sim/utils/object' import { SOURCE_BASE_FILE } from '@sim/workflow-code/limits' +import { KIND_DIRS } from '@sim/workspace-code' import type { Command } from 'commander' import { profileFrom } from '../../context' import { CliUsageError } from './local-errors' @@ -29,19 +30,21 @@ import { refreshTsconfigs, refreshWorkspaceTypes, } from './source-tree' +import { TYPES_HELP, type TypesOptions, typeCheck, typesFlag } from './source-types' import { verboseFlag } from './source-ui' import { requireEntry, WORKFLOW_TREE } from './workflow-dir' const CHECK_HELP = ` Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run -does. No request is made. It covers the source itself (syntax, builders, params, references, +does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the -CLI's tsconfig.json, so tsc type-checks a block the edit added; in a workspace directory it also -regenerates .sim/sdk/workspace.d.ts, so tsc types each workflow's inputs as its files declare them. +CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also +regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. +${TYPES_HELP} ${strictHelp('no cached catalog (run the get once)')}` @@ -52,19 +55,24 @@ ${strictHelp('no cached catalog (run the get once)')}` */ export function attachWorkflowSourceCheck(source: Command): void { verboseFlag( - strictFlags( - absoluteDirOption(source.command('check')).option( - '--dir ', - 'Source directory: workflow.ts, functions/* and .sim/', - '.' + typesFlag( + strictFlags( + absoluteDirOption(source.command('check')).option( + '--dir ', + 'Source directory: workflow.ts, functions/* and .sim/', + '.' + ) ) ) ) .allowExcessArguments(false) - .description('Compile a workflow source directory locally, without the server') + .description('Compile and type-check a workflow source directory locally, without the server') .addHelpText('after', CHECK_HELP) .action( - async (options: { dir: string; verbose?: boolean } & StrictOptions, command: Command) => { + async ( + options: { dir: string; verbose?: boolean } & StrictOptions & TypesOptions, + command: Command + ) => { const profile = profileFrom(command) await assertSourceDirKind(options.dir, 'workflow') const base = toRecord(await readSourceJson(options.dir, SOURCE_BASE_FILE)) @@ -117,6 +125,11 @@ export function attachWorkflowSourceCheck(source: Command): void { { incremental: true } ) } + const types = await typeCheck(workspace ? workspace.root : options.dir, { + enabled: options.types !== false, + ...(workspace ? { scope: `${KIND_DIRS.workflow}/${workspace.key}/` } : {}), + compiled: findings, + }) reportCheck( profile.output, findings, @@ -125,6 +138,7 @@ export function attachWorkflowSourceCheck(source: Command): void { verbose: options.verbose === true, unlisted, dir: options.dir, + types, } ) } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts index 20c2b886019..dcc9e6b8df9 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts @@ -17,6 +17,7 @@ import { SimApiError } from '../../http/client' import { buildProgram } from '../../program' import { buildGeneratedCommands } from '../../runtime/build' import { contextMockFns, contextMockState, mockedProfile } from '../../test/context-mock' +import { provideTypescript } from '../../test/typescript' import { digest } from './source-dir' import { AGENTS_POINTER_MARKER, @@ -154,6 +155,7 @@ beforeEach(() => { rootDir = mkdtempSync(join(tmpdir(), 'sim-source-')) outDir = join(rootDir, 'out') vi.stubEnv('SIM_CONFIG_DIR', join(rootDir, 'config')) + provideTypescript(join(rootDir, 'config')) vi.spyOn(console, 'log').mockImplementation(() => {}) }) @@ -318,6 +320,52 @@ describe('sim workflows source get --dir', () => { expect(typecheck('tsconfig.json')).toMatch(unknownParam) }) + it('type-checks the directory in the check, with the blocks the edit added', async () => { + const workflow = [ + '// @sim-sdk 1', + "import { trigger, workflow } from '@sim/workflow-sdk'", + '', + "export default workflow('W', {}, () => {", + " const start = trigger.start('Start', {})", + '})', + '', + ].join('\n') + serve({ [SOURCE_PATH]: () => source({ 'workflow.ts': workflow }, []) }) + await get('--dir', outDir) + writeFileSync( + join(outDir, 'workflow.ts'), + workflow + .replace('{ trigger, workflow }', '{ gmail, trigger, workflow }') + .replace( + " const start = trigger.start('Start', {})\n", + " const start = trigger.start('Start', {})\n const mail = gmail.sendEmail('Mail', {\n to: 'a@b.c',\n subject: 's',\n body: start.missing,\n })\n start.to(mail)\n" + ) + ) + contextMockFns.mockProfileFrom.mockReturnValue({ + ...mockedProfile(), + workspaceId: WORKSPACE_ID, + output: 'json', + }) + const check = new Command('source') + attachWorkflowSourceCheck(check) + check.commands.forEach((command) => command.exitOverride()) + await check.parseAsync(['node', 'source', 'check', '--dir', outDir]) + + expect(process.exitCode).toBe(1) + process.exitCode = undefined + const printed = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') + expect(printed.checked).toEqual(['compile', 'types']) + expect( + (printed.diagnostics as Array<{ code: string }>).filter(({ code }) => code === 'E_TYPE') + ).toEqual([ + expect.objectContaining({ + file: 'workflow.ts', + line: 9, + message: expect.stringMatching(/^TS2339: Property 'missing' does not exist/), + }), + ]) + }) + it('writes the example workflows beside the guide, outside what the tsconfig files type-check', async () => { serve() diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts index 5c7d6238dab..66a75d3d802 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts @@ -986,7 +986,8 @@ const EVERY_WITHHELD_BUILDER = [ '', ].join('\n') -const check = (...flags: string[]) => sim('workflows', 'source', 'check', '--dir', dir, ...flags) +const check = (...flags: string[]) => + sim('workflows', 'source', 'check', '--dir', dir, '--no-types', ...flags) function checked(): { errors: number; warnings: number; diagnostics: unknown[] } { return JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') @@ -1126,7 +1127,8 @@ describe('checking wiring between blocks the lock binds', () => { process.exitCode = undefined }) - const check = (...flags: string[]) => sim('workflows', 'source', 'check', '--dir', dir, ...flags) + const check = (...flags: string[]) => + sim('workflows', 'source', 'check', '--dir', dir, '--no-types', ...flags) function codes(): string[] { const printed = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts index 7aa7b5e0441..4c217702ea1 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts @@ -35,7 +35,7 @@ async function check(...flags: string[]): Promise { const source = new Command('source') attachWorkspaceSourceCheck(source) source.commands.forEach((command) => command.exitOverride()) - await source.parseAsync(['node', 'source', 'check', '--dir', dir, ...flags]) + await source.parseAsync(['node', 'source', 'check', '--dir', dir, '--no-types', ...flags]) } function writeFile(path: string, text: string): void { @@ -109,7 +109,7 @@ describe('sim workspaces source check', () => { await check() - expect(result()).toMatchObject({ checked: 'compile', errors: 0, warnings: 0, workflows: 2 }) + expect(result()).toMatchObject({ checked: ['compile'], errors: 0, warnings: 0, workflows: 2 }) expect(process.exitCode).toBeUndefined() expect(contextMockFns.mockRequest).not.toHaveBeenCalled() }) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts index d93d2509e73..f9f4b97ca01 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts @@ -29,6 +29,7 @@ import { } from './source-dir' import { credentialRefused, unreachableReason } from './source-status' import { cachedCatalog, loadCatalog, refreshWorkspaceTypes } from './source-tree' +import { TYPES_HELP, type TypesOptions, typeCheck, typesFlag } from './source-types' import { verboseFlag } from './source-ui' import { assertWorkspaceDir } from './workspace-source-dir' @@ -36,7 +37,7 @@ const CHECK_HELP = ` Compiles every workflows//workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other -request is made. It checks, against what the directory declares: +request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a @@ -50,8 +51,9 @@ request is made. It checks, against what the directory declares: - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates -.sim/sdk/workspace.d.ts from the declarations (so tsc types a key added since the get, and each +.sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. +${TYPES_HELP} ${strictHelp("no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials)")}` @@ -93,21 +95,26 @@ export function attachWorkspaceSourceCheck(source: Command): void { const [command, connect] = apiCommand(source, 'check', ['getSourceCatalog']) absoluteDirOption(command) verboseFlag( - strictFlags( - command.option( - '--dir ', - `Workspace source directory: the kind folders and ${WORKSPACE_BASE_FILE}`, - '.' + typesFlag( + strictFlags( + command.option( + '--dir ', + `Workspace source directory: the kind folders and ${WORKSPACE_BASE_FILE}`, + '.' + ) ) ) ) .allowExcessArguments(false) .description( - 'Compile every workflow of a workspace source directory locally, without the server' + 'Compile and type-check every workflow of a workspace source directory locally, without the server' ) .addHelpText('after', `${CHECK_HELP}\n${SOURCE_DIR_BUSY_HELP}`) .action( - async (options: { dir: string; verbose?: boolean } & StrictOptions, command: Command) => { + async ( + options: { dir: string; verbose?: boolean } & StrictOptions & TypesOptions, + command: Command + ) => { const profile = profileFrom(command) const base = toRecord(await readSourceJson(options.dir, WORKSPACE_BASE_FILE)) await assertWorkspaceDir(options.dir) @@ -167,6 +174,10 @@ export function attachWorkspaceSourceCheck(source: Command): void { withWorkflowInputs(declarations.local, declarations.workflowInputs) ) await refreshWorkspaceTsconfigs(options.dir, workspaceId) + const types = await typeCheck(options.dir, { + enabled: options.types !== false, + compiled: findings, + }) reportCheck( profile.output, findings, @@ -176,6 +187,7 @@ export function attachWorkspaceSourceCheck(source: Command): void { bound: WORKSPACE_ANSWER_BOUND, unlisted, dir: options.dir, + types, } ) }) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts index 123e1c93d6c..7aa25517a77 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -12,7 +12,6 @@ import { SOURCE_CODE_DIR, SOURCE_ENTRY_FILE, SOURCE_LOCK_FILE } from '@sim/workf import { SDK_MAJOR, SOURCE_COMPILER_OPTIONS, - typecheckCommand, WORKSPACE_COOKBOOK, WORKSPACE_SDK_DTS, } from '@sim/workflow-sdk/codegen' @@ -141,19 +140,18 @@ Every \`.ts\` file below, a deployment included, starts with the line \`// @sim- ${APPLY_ORDER.map((kind) => `- ${WORKSPACE_KIND_SPECS[kind].guide}`).join('\n')} -One apply creates resources before the workflows that use them, so a workflow may name a key this directory declares before it exists. \`.sim/sdk/workspace.d.ts\` types the keys the server held at the last get and the ones this directory declares, with each workflow's inputs: \`sim workspaces source check\` (or \`sim workflows source check\` in a workflow folder) regenerates it from the files, so run it before \`tsc\` after adding a resource or a workflow input. The dry run is the authority. +One apply creates resources before the workflows that use them, so a workflow may name a key this directory declares before it exists. \`.sim/sdk/workspace.d.ts\` types the keys the server held at the last get and the ones this directory declares, with each workflow's inputs: \`sim workspaces source check\` (or \`sim workflows source check\` in a workflow folder) regenerates it from the files before it type-checks them. The dry run is the authority. Secrets never appear in source: a workflow reads an environment variable as \`env.NAME\` and tool code as \`$env.NAME\`, both by name, and a saved credential is \`credential('')\`. Declare the ones workflows use in \`${KIND_DIRS.secret}\` and \`${KIND_DIRS.credential}\`: a workflow using a declared secret the workspace has no value for, or a declared credential key nothing binds to, is held back, with the command that fixes it, while the rest of the apply is written (exit ${SOURCE_HELD_EXIT_CODE}; exit 1 when nothing else was). The same directory applied to another workspace binds each credential key to that workspace's own credential. ## Edit loop in detail -Batch it: write every file first, then run steps 2 and 5 (and any test run) as one chained command, \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Steps 3 and 4, and the dry run, are for a person, CI, or a change you want reviewed first. +Batch it: write every file first, then run steps 2 and 4 (and any test run) as one chained command, \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3, and the dry run, are for a person, CI, or a change you want reviewed first. 1. Edit the files. -2. \`sim workspaces source check --dir .\`: compiles every workflow offline with the server's compiler, against what this directory declares: an unknown resource key (skills included) or table column, a child workflow's inputs, and an env name \`${KIND_DIRS.secret}\` lacks (a warning); and checks each \`${KIND_DIRS.table}/.rows.jsonl\` line against its table as the apply would. It fails (exit 1) on errors and on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block), regenerates \`.sim/sdk/workspace.d.ts\` and adds the blocks the workflows now use to \`tsconfig.json\`. In a workflow folder, \`sim workflows source check --dir .\` checks that one workflow the same way. Fix and rerun until it exits 0. -3. Run \`${typecheckCommand()}\` after step 2 (chain it) and fix what it reports: it takes about a second and catches what step 2 and the dry run do not (such as a reference to a start input the trigger does not declare). It type-checks the files with the TypeScript release the declarations are built for. \`tsconfig.json\` includes only the blocks the workflows used at the last check or get, which keeps it fast: a builder from another block fails with \`has no exported member\` until you run step 2 (or check with \`${typecheckCommand(TSCONFIG_FULL_FILE)}\`, every current block). \`sim workflows source params \` prints one builder's params and outputs; do not read the declarations whole. The dry run is the authority: a printed file you did not edit that \`tsc\` flags and the dry run accepts is fine, so leave it as it is. -4. \`sim workspaces source status --dir .\` before applying: your changes by resource (\`sim workspaces source diff --dir .\` shows the edits), what changed on the server since the get (a workflow edited in the editor included), the conflicts, and the command to run next. Exit 0 nothing changed, ${SOURCE_LOCAL_CHANGES_EXIT_CODE} only your edits, ${SOURCE_DRIFT_EXIT_CODE} the server changed since (\`--offline\`: skip the server). Then \`sim workspaces source apply --dir . --dry-run\`: shows the plan (\`+\` create, \`~\` update, \`=\` adopt an existing resource of the same name, \`-\` delete) and every error; fix and rerun until it exits 0. -5. \`sim workspaces source apply --dir . --yes\`: writes it and rewrites this directory from what was stored; it prints the plan it applied (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}, writing nothing). +2. \`sim workspaces source check --dir .\`: compiles every workflow offline with the server's compiler, against what this directory declares: an unknown resource key (skills included) or table column, a child workflow's inputs, and an env name \`${KIND_DIRS.secret}\` lacks (a warning); and checks each \`${KIND_DIRS.table}/.rows.jsonl\` line against its table as the apply would. It fails (exit 1) on errors and on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block), regenerates \`.sim/sdk/workspace.d.ts\` from the files (so a resource or workflow input added since the get is typed) and adds the blocks the workflows now use to \`tsconfig.json\`, then type-checks every file with it, using the TypeScript release the declarations are built for (installed once into the CLI's cache, on the first check; \`E_TYPE\` findings): that catches what the compile and the dry run do not, such as a reference to a start input the trigger does not declare. Offline before that install, it warns \`W_TYPES_UNCHECKED\` and passes on the compile alone; \`--no-types\` skips it. In a workflow folder, \`sim workflows source check --dir .\` checks that one workflow the same way. Fix and rerun until it exits 0. +3. \`sim workspaces source status --dir .\` before applying: your changes by resource (\`sim workspaces source diff --dir .\` shows the edits), what changed on the server since the get (a workflow edited in the editor included), the conflicts, and the command to run next. Exit 0 nothing changed, ${SOURCE_LOCAL_CHANGES_EXIT_CODE} only your edits, ${SOURCE_DRIFT_EXIT_CODE} the server changed since (\`--offline\`: skip the server). Then \`sim workspaces source apply --dir . --dry-run\`: shows the plan (\`+\` create, \`~\` update, \`=\` adopt an existing resource of the same name, \`-\` delete) and every error; fix and rerun until it exits 0. +4. \`sim workspaces source apply --dir . --yes\`: writes it and rewrites this directory from what was stored; it prints the plan it applied (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}, writing nothing). ## Good to know diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts index bb42350a716..03d8adc4522 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts @@ -19,6 +19,7 @@ import { knowledgeCodec } from '@sim/workspace-code/kinds/knowledge' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { SimApiError } from '../../http/client' import { contextMockFns, contextMockState, mockedProfile } from '../../test/context-mock' +import { provideTscPrinting, provideTypescript } from '../../test/typescript' import { runWorkflowSourceCheck, runWorkspaceSource } from '../../test/workspace-source-command' import { blobBytes, blobDigests } from './workspace-source-blobs' import { kindFolders } from './workspace-source-dir' @@ -98,6 +99,7 @@ beforeEach(() => { rootDir = mkdtempSync(join(tmpdir(), 'sim-workspace-get-')) dir = join(rootDir, 'out') vi.stubEnv('SIM_CONFIG_DIR', join(rootDir, 'config')) + provideTypescript(join(rootDir, 'config')) vi.spyOn(console, 'log').mockImplementation(() => {}) vi.spyOn(console, 'error').mockImplementation(() => {}) }) @@ -1130,3 +1132,319 @@ describe('workspaces source check after a get', () => { expect(process.exitCode).toBe(1) }) }) + +describe('the type check of workspaces source check', () => { + afterEach(() => { + process.exitCode = undefined + }) + + /** A workflow inserting a row into table `key`; `extra` is one more statement in its body. */ + function writeInserting(key: string, extra = ''): void { + mkdirSync(join(dir, 'workflows/save'), { recursive: true }) + writeFileSync( + join(dir, 'workflows/save/workflow.ts'), + [ + '// @sim-sdk 1', + "import { response, table, trigger, workflow } from '@sim/workflow-sdk'", + "export default workflow('Save', {}, () => {", + " const start = trigger.start('Start', { inputFormat: { email: 'string' } })", + ` const save = table.insertRow('Save', { tableId: table('${key}'), data: {} })`, + ' start.to(save)', + ...(extra ? [extra] : []), + '})', + '', + ].join('\n') + ) + } + + function result(): { + checked: string[] + errors: number + diagnostics: Array> + } { + return JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') + } + + it.each([ + ['the resources listed', true], + ['no resource listing (the listing route not found)', false], + ])( + 'types a table a new tables/.ts declares, in the same check, with %s', + async (_, listed) => { + serve( + { 'tables/leads.ts': LEADS }, + listed + ? { + manifest: { + workspaceId: 'ws_local', + tables: [{ key: 'leads', id: 'tbl-1', name: 'leads', columns: [] }], + knowledgeBases: [], + credentials: [], + workflows: [], + skills: [], + customTools: [], + mcpServers: [], + env: [], + truncated: false, + }, + } + : {} + ) + await get() + expect(existsSync(join(dir, '.sim/sdk/workspace.d.ts'))).toBe(true) + writeFileSync( + join(dir, 'tables/daily_totals.ts'), + "// @sim-sdk 1\nimport { defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({ name: 'daily_totals', columns: {} })\n" + ) + writeInserting('daily_totals') + + await runWorkspaceSource('check', dir) + + expect(result()).toMatchObject({ checked: ['compile', 'types'], errors: 0, diagnostics: [] }) + expect(process.exitCode).toBeUndefined() + } + ) + + it('removes workspace.d.ts when a directory with no resource listing stops declaring anything', async () => { + serve({ 'tables/leads.ts': LEADS }) + await get() + expect(existsSync(join(dir, '.sim/sdk/workspace.d.ts'))).toBe(true) + rmSync(join(dir, 'tables/leads.ts')) + + await runWorkspaceSource('check', dir) + + expect(existsSync(join(dir, '.sim/sdk/workspace.d.ts'))).toBe(false) + expect(result()).toMatchObject({ checked: ['compile', 'types'], errors: 0 }) + }) + + it('fails on a type error the compile only warns about, at its file and line, annotated in CI', async () => { + serve({ 'tables/leads.ts': LEADS }) + await get() + writeInserting( + 'leads', + " const done = response('Done', { body: { email: start.emial } })\n save.to(done)" + ) + vi.stubEnv('GITHUB_ACTIONS', 'true') + + await runWorkspaceSource('check', dir) + + expect(result()).toMatchObject({ + checked: ['compile', 'types'], + errors: 1, + diagnostics: expect.arrayContaining([ + expect.objectContaining({ code: 'W_OUTPUT_PATH_UNDECLARED', severity: 'warning', line: 7 }), + expect.objectContaining({ + code: 'E_TYPE', + severity: 'error', + file: 'workflows/save/workflow.ts', + line: 7, + message: expect.stringMatching(/^TS2551: Property 'emial' does not exist/), + }), + ]), + }) + expect(process.exitCode).toBe(1) + const annotations = vi + .mocked(console.error) + .mock.calls.map(([line]) => String(line)) + .filter((line) => line.startsWith('::error')) + expect(annotations).toEqual([ + expect.stringMatching( + new RegExp( + `^::error file=${join(dir, 'workflows/save/workflow.ts').replaceAll('/', '\\/')},line=7,col=\\d+,title=E_TYPE::TS2551: ` + ) + ), + ]) + }) + + it('leaves out a type error on a line the compile already reports an error on', async () => { + serve({ 'tables/leads.ts': LEADS }) + await get() + writeInserting( + 'leads', + " const extra = table.insertRow('Extra', { tableId: table('leads'), bogus: 1 })" + ) + + await runWorkspaceSource('check', dir) + + expect(result().checked).toEqual(['compile', 'types']) + const codes = result().diagnostics.map(({ code, line }) => `${code}:${line}`) + expect(codes).toContain('E_UNKNOWN_PARAM:7') + expect(codes).not.toContain('E_TYPE:7') + }) + + it('reports only its own folder from a workflow folder, files relative to it', async () => { + serve({ 'tables/leads.ts': LEADS }) + await get() + writeInserting( + 'leads', + " const done = response('Done', { body: { email: start.emial } })\n save.to(done)" + ) + mkdirSync(join(dir, 'workflows/other'), { recursive: true }) + writeFileSync( + join(dir, 'workflows/other/workflow.ts'), + [ + '// @sim-sdk 1', + "import { response, trigger, workflow } from '@sim/workflow-sdk'", + "export default workflow('Other', {}, () => {", + " const start = trigger.start('Start', {})", + " const done = response('Done', { body: { flag: start.flag } })", + ' start.to(done)', + '})', + '', + ].join('\n') + ) + + await runWorkflowSourceCheck(join(dir, 'workflows/other')) + + expect(result().checked).toEqual(['compile', 'types']) + expect(result().diagnostics.filter(({ code }) => code === 'E_TYPE')).toEqual([ + expect.objectContaining({ file: 'workflow.ts', line: 5 }), + ]) + }) + + it('warns and passes on the compile alone when TypeScript cannot be installed', async () => { + serve({ 'tables/leads.ts': LEADS }) + await get() + writeInserting( + 'leads', + " const done = response('Done', { body: { email: start.emial } })\n save.to(done)" + ) + rmSync(join(rootDir, 'config/cache/typescript'), { recursive: true }) + vi.stubEnv('npm_config_registry', 'http://127.0.0.1:9/') + vi.stubEnv('npm_config_cache', join(rootDir, 'npm-cache')) + + await runWorkspaceSource('check', dir) + + expect(result()).toMatchObject({ checked: ['compile'], errors: 0 }) + expect(result().diagnostics.filter(({ code }) => code === 'W_TYPES_UNCHECKED')).toEqual([ + expect.objectContaining({ + severity: 'warning', + message: expect.stringMatching(/npm could not install typescript@.*ECONNREFUSED/), + }), + ]) + expect(process.exitCode).toBeUndefined() + expect(existsSync(join(rootDir, 'config/cache/typescript'))).toBe(true) + expect(readdirSync(join(rootDir, 'config/cache/typescript'))).toEqual([]) + }) + + it('runs npm without the Sim API key', async () => { + serve({ 'tables/leads.ts': LEADS }) + await get() + rmSync(join(rootDir, 'config/cache/typescript'), { recursive: true }) + const bin = join(rootDir, 'bin') + mkdirSync(bin) + writeFileSync( + join(bin, 'npm'), + `#!/bin/sh\nenv > "${join(rootDir, 'npm-env')}"\necho "npm error offline" >&2\nexit 1\n`, + { mode: 0o755 } + ) + vi.stubEnv('PATH', `${bin}:${process.env.PATH}`) + vi.stubEnv('SIM_API_KEY', 'sk-sim-secret') + + await runWorkspaceSource('check', dir) + + expect(result().diagnostics).toContainEqual( + expect.objectContaining({ + code: 'W_TYPES_UNCHECKED', + message: expect.stringContaining('offline'), + }) + ) + const env = readFileSync(join(rootDir, 'npm-env'), 'utf8') + expect(env).toContain(`PATH=${bin}`) + expect(env).not.toContain('sk-sim-secret') + }) + + it('warns and passes on the compile alone when the TypeScript cache cannot be written', async () => { + serve({ 'tables/leads.ts': LEADS }) + await get() + rmSync(join(rootDir, 'config/cache/typescript'), { recursive: true }) + writeFileSync(join(rootDir, 'config/cache/typescript'), 'not a folder') + + await runWorkspaceSource('check', dir) + + expect(result()).toMatchObject({ checked: ['compile'], errors: 0 }) + expect(result().diagnostics).toContainEqual( + expect.objectContaining({ + code: 'W_TYPES_UNCHECKED', + message: expect.stringContaining('TypeScript could not be installed into'), + }) + ) + }) + + it('fails rather than passing when TypeScript prints more than a check keeps', async () => { + serve({ 'tables/leads.ts': LEADS }) + await get() + rmSync(join(rootDir, 'config/cache/typescript'), { recursive: true }) + const flood = + "tables/leads.ts(2,1): error TS2322: Type 'string' is not assignable to type 'number'.\n" + provideTscPrinting( + join(rootDir, 'config'), + flood.repeat(Math.ceil((1.2 * 1024 * 1024) / flood.length)) + ) + + await runWorkspaceSource('check', dir) + + expect(result()).toMatchObject({ checked: ['compile', 'types'], errors: 1 }) + expect(result().diagnostics).toEqual([ + expect.objectContaining({ + code: 'E_TYPE', + message: expect.stringContaining('more errors than a check lists'), + }), + ]) + expect(process.exitCode).toBe(1) + }) + + it('keeps the whole message chain of a project error', async () => { + serve({ 'tables/leads.ts': LEADS }) + await get() + rmSync(join(rootDir, 'config/cache/typescript'), { recursive: true }) + provideTscPrinting( + join(rootDir, 'config'), + "error TS5110: Option 'module' must be set.\n Set it in tsconfig.json.\n" + ) + + await runWorkspaceSource('check', dir) + + expect(result().diagnostics).toEqual([ + expect.objectContaining({ + code: 'E_TYPE', + message: "TS5110: Option 'module' must be set. Set it in tsconfig.json.", + }), + ]) + }) + + it('writes no build output under a tsconfig.json of its own that emits', async () => { + serve({ 'tables/leads.ts': LEADS }) + await get() + writeInserting('leads') + const tsconfig = JSON.parse( + readFileSync(join(dir, 'tsconfig.json'), 'utf8').replace(/^\/\/.*\n/, '') + ) + writeFileSync( + join(dir, 'tsconfig.json'), + JSON.stringify({ + ...tsconfig, + compilerOptions: { ...tsconfig.compilerOptions, noEmit: false }, + }) + ) + + await runWorkspaceSource('check', dir) + + expect(result().checked).toEqual(['compile', 'types']) + expect(existsSync(join(dir, 'workflows/save/workflow.js'))).toBe(false) + }) + + it('skips the type check with --no-types', async () => { + serve({ 'tables/leads.ts': LEADS }) + await get() + writeInserting( + 'leads', + " const done = response('Done', { body: { email: start.emial } })\n save.to(done)" + ) + + await runWorkspaceSource('check', dir, '--no-types') + + expect(result()).toMatchObject({ checked: ['compile'], errors: 0 }) + expect(result().diagnostics.map(({ code }) => code)).not.toContain('E_TYPE') + }) +}) diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 3bc9f3f8a53..1b9cc195655 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -981,6 +981,8 @@ export type ApplyWorkflowSourceResponse = { | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' + | 'E_TYPE' + | 'W_TYPES_UNCHECKED' severity: 'error' | 'warning' | 'info' message: string hint?: string @@ -1482,6 +1484,8 @@ export type ApplyWorkspaceSourceResponse = { | 'E_APPLY_BLOCK_DELETE' | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' + | 'E_TYPE' + | 'W_TYPES_UNCHECKED' message: string } needBlobs: Array @@ -1777,6 +1781,8 @@ export type ApplyWorkspaceSourceResponse = { | 'E_APPLY_BLOCK_DELETE' | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' + | 'E_TYPE' + | 'W_TYPES_UNCHECKED' severity: 'error' | 'warning' | 'info' message: string hint?: string @@ -5454,6 +5460,8 @@ export type CreateWorkflowFromSourceResponse = { | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' + | 'E_TYPE' + | 'W_TYPES_UNCHECKED' severity: 'error' | 'warning' | 'info' message: string hint?: string @@ -10591,6 +10599,8 @@ export type GetWorkflowSourceResponse = { | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' + | 'E_TYPE' + | 'W_TYPES_UNCHECKED' severity: 'error' | 'warning' | 'info' message: string hint?: string @@ -11285,6 +11295,8 @@ export type GetWorkspaceSourceResponse = { | 'E_APPLY_BLOCK_DELETE' | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' + | 'E_TYPE' + | 'W_TYPES_UNCHECKED' severity: 'error' | 'warning' | 'info' message: string hint?: string @@ -14618,6 +14630,8 @@ export type PlanWorkflowSourceResponse = { | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' + | 'E_TYPE' + | 'W_TYPES_UNCHECKED' severity: 'error' | 'warning' | 'info' message: string hint?: string @@ -15074,6 +15088,8 @@ export type PlanWorkspaceSourceResponse = { | 'E_APPLY_BLOCK_DELETE' | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' + | 'E_TYPE' + | 'W_TYPES_UNCHECKED' message: string } needBlobs: Array @@ -15369,6 +15385,8 @@ export type PlanWorkspaceSourceResponse = { | 'E_APPLY_BLOCK_DELETE' | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' + | 'E_TYPE' + | 'W_TYPES_UNCHECKED' severity: 'error' | 'warning' | 'info' message: string hint?: string diff --git a/packages/sim-cli/src/test/typescript.ts b/packages/sim-cli/src/test/typescript.ts new file mode 100644 index 00000000000..8818cd02cf2 --- /dev/null +++ b/packages/sim-cli/src/test/typescript.ts @@ -0,0 +1,34 @@ +import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { SOURCE_TYPESCRIPT_VERSION } from '@sim/workflow-sdk/codegen' + +/** The repository's own TypeScript, the release `SOURCE_TYPESCRIPT_VERSION` pins. */ +const REPO_TYPESCRIPT = join(__dirname, '../../../../node_modules/typescript') + +/** + * Installs the pinned TypeScript into config directory `configDir` as a check's first run does, + * by linking the repository's copy, so a check type-checks without reaching npm. + */ +export function provideTypescript(configDir: string): void { + const installed = installedPath(configDir) + mkdirSync(dirname(installed), { recursive: true }) + symlinkSync(REPO_TYPESCRIPT, installed, 'dir') +} + +function installedPath(configDir: string): string { + return join(configDir, 'cache/typescript', SOURCE_TYPESCRIPT_VERSION, 'node_modules/typescript') +} + +/** + * Installs, in place of the pinned TypeScript, a `tsc` that prints `stdout` and exits 2, as tsc + * does on errors: for output real sources rarely produce (a cut-off flood, a project error chain). + */ +export function provideTscPrinting(configDir: string, stdout: string): void { + const installed = installedPath(configDir) + mkdirSync(join(installed, 'bin'), { recursive: true }) + writeFileSync(join(installed, 'output.txt'), stdout) + writeFileSync( + join(installed, 'bin/tsc'), + "const { readFileSync } = require('node:fs')\nprocess.stdout.write(readFileSync(require('node:path').join(__dirname, '../output.txt'), 'utf8'), () => process.exit(2))\n" + ) +} diff --git a/packages/workflow-code/DESIGN.md b/packages/workflow-code/DESIGN.md index 4637f9c8a4b..39e4eb807d4 100644 --- a/packages/workflow-code/DESIGN.md +++ b/packages/workflow-code/DESIGN.md @@ -629,7 +629,8 @@ failures in `workflow_source_applied`, `workflow_source_dry_run` and `workspace_ - Function code is one verbatim file per block: no imports, no shared modules, and `$ref`/`$env` are untyped globals in JavaScript. Source has no loops or helpers that generate blocks; the compiler accepts only the printed grammar. -- Nothing runs locally. Checks happen on apply (or `--dry-run`); `tsc -p .` checks types only. +- Nothing in the source runs. `source check` compiles and type-checks it offline; the server's + checks happen on apply (or `--dry-run`). - A comment inside an expression is hoisted to its enclosing anchor (`W_COMMENT_MOVED`). - Chat in the product does not write through source yet. diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index 1f1f16353e8..eb7b02d2241 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -543,3 +543,10 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `E_WORKFLOW_META_INVALID` | The `workflow('…')` name is empty or over 255 characters, or its description is over 50,000 characters: limits the workflow API holds every workflow to. | | `E_APPLY_INVALID_SCHEDULE` | An added or changed schedule whose cron, timezone or interval deploy would refuse. | | `W_TABLE_UNKNOWN_COLUMN` | A table row write whose data names a key that is not a column of the table; the run drops it. The hint names the nearest column. | + +**Type check** (`source check` only) + +| Code | Meaning | +|---|---| +| `E_TYPE` | TypeScript (the release the declarations are built for) reported an error; the message starts with its `TS` code. A type error on a line the compile already reports an error on, or in a file still as the last get or apply wrote it, is left out. | +| `W_TYPES_UNCHECKED` | The type check did not run: TypeScript could not be installed (offline, or no `npm`) or did not start. The other findings stand; pass `--no-types` to skip it. | diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index 4a222f03af0..79190d5b749 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -562,6 +562,21 @@ const APPLY_DIAGNOSTIC_CODES = [ ] as const export type ApplyDiagnosticCode = (typeof APPLY_DIAGNOSTIC_CODES)[number] +/** + * The type check `sim workflows source check` and `sim workspaces source check` run after the + * compile: the pinned TypeScript release over the directory's `tsconfig.json`. The server never + * reports them. + */ +const TYPE_CHECK_CODES = [ + /** TypeScript reported an error; the message starts with its `TS` code (`TS2322: …`). */ + 'E_TYPE', + /** + * The type check did not run: the pinned TypeScript release could not be installed (offline, or + * no `npm`) or did not start. The compile's findings still stand. + */ + 'W_TYPES_UNCHECKED', +] as const + /** * Every code, as a value: the wire contracts' enum, so a client matching on a code is checked * against the vocabulary. @@ -573,6 +588,7 @@ export const DIAGNOSTIC_CODES = [ ...CANONICALIZE_DIAGNOSTIC_CODES, ...MATERIALIZE_DIAGNOSTIC_CODES, ...APPLY_DIAGNOSTIC_CODES, + ...TYPE_CHECK_CODES, ] as const /** Whether a tuple of codes lists one of them twice. */ diff --git a/packages/workflow-sdk/src/codegen/index.ts b/packages/workflow-sdk/src/codegen/index.ts index fdc2aef763a..30b7f99a658 100644 --- a/packages/workflow-sdk/src/codegen/index.ts +++ b/packages/workflow-sdk/src/codegen/index.ts @@ -29,7 +29,7 @@ export { renderBuilderReference, renderCompactBuilder, } from './reference' -export { SOURCE_COMPILER_OPTIONS, typecheckCommand } from './tsconfig' +export { SOURCE_COMPILER_OPTIONS, SOURCE_TYPESCRIPT_VERSION } from './tsconfig' export { type GenerateWorkspaceTypesFn, generateWorkspaceTypes, diff --git a/packages/workflow-sdk/src/codegen/tsconfig.test.ts b/packages/workflow-sdk/src/codegen/tsconfig.test.ts index fde04fda69e..66cfec767d6 100644 --- a/packages/workflow-sdk/src/codegen/tsconfig.test.ts +++ b/packages/workflow-sdk/src/codegen/tsconfig.test.ts @@ -1,10 +1,10 @@ import { createRequire } from 'node:module' import { describe, expect, it } from 'vitest' -import { typecheckCommand } from './tsconfig' +import { SOURCE_TYPESCRIPT_VERSION } from './tsconfig' -describe('typecheckCommand', () => { - it('runs the TypeScript release this repository type-checks the generated declarations with', () => { +describe('SOURCE_TYPESCRIPT_VERSION', () => { + it('is the TypeScript release this repository type-checks the generated declarations with', () => { const { version } = createRequire(import.meta.url)('typescript/package.json') - expect(typecheckCommand()).toBe(`bunx -p typescript@${version} tsc -p .`) + expect(SOURCE_TYPESCRIPT_VERSION).toBe(version) }) }) diff --git a/packages/workflow-sdk/src/codegen/tsconfig.ts b/packages/workflow-sdk/src/codegen/tsconfig.ts index 8e1a3f1bb75..a627faf4c39 100644 --- a/packages/workflow-sdk/src/codegen/tsconfig.ts +++ b/packages/workflow-sdk/src/codegen/tsconfig.ts @@ -16,12 +16,7 @@ export const SOURCE_COMPILER_OPTIONS = { /** * The TypeScript release a source directory is type-checked with: the one this repository checks - * the generated declarations against. A directory has no `package.json`, so the command fetches - * exactly this release instead of whatever `tsc` resolves to. + * the generated declarations against. A directory has no `package.json`, so `source check` installs + * exactly this release instead of running whatever `tsc` resolves to. */ -const SOURCE_TYPESCRIPT_VERSION = '7.0.2' - -/** The command that type-checks a source directory with `project` (a tsconfig path). */ -export function typecheckCommand(project = '.'): string { - return `bunx -p typescript@${SOURCE_TYPESCRIPT_VERSION} tsc -p ${project}` -} +export const SOURCE_TYPESCRIPT_VERSION = '7.0.2' diff --git a/scripts/sync-workflow-code-docs.ts b/scripts/sync-workflow-code-docs.ts index e00a15f69fb..4c8f21f9e2a 100644 --- a/scripts/sync-workflow-code-docs.ts +++ b/scripts/sync-workflow-code-docs.ts @@ -34,7 +34,7 @@ import { } from '../packages/sim-cli/src/commands/protocol/source-exit-codes' import { DIAGNOSTIC_CODES } from '../packages/workflow-code/src/diagnostics/codes' import { SOURCE_LIMITS } from '../packages/workflow-code/src/limits' -import { typecheckCommand } from '../packages/workflow-sdk/src/codegen/tsconfig' +import { SOURCE_TYPESCRIPT_VERSION } from '../packages/workflow-sdk/src/codegen/tsconfig' import { WORKSPACE_DIAGNOSTIC_CODES } from '../packages/workspace-code/src/diagnostics/codes' import { APPLY_ORDER } from '../packages/workspace-code/src/kind' import { WORKSPACE_SOURCE_LIMITS } from '../packages/workspace-code/src/limits' @@ -254,6 +254,8 @@ const WORKFLOW_GROUP_LEAD: Record = { Canonicalize: 'Reading the stored workflow in a get.', Materialize: 'Matching the compiled file to the stored blocks.', Apply: 'Saving the workflow draft.', + 'Type check': + '`sim workflows source check` and `sim workspaces source check` type-checking the directory with TypeScript after the compile. The server never reports these.', } /** One error per code `documented` names that `exported` does not hold, and per code it lacks. */ @@ -477,11 +479,7 @@ function checkProse(errors: string[]): void { if (!known.has(match[1])) errors.push(`${rel} names ${match[1]}, which no engine emits`) } } - const pinned = /typescript@(\d+\.\d+\.\d+)/.exec(typecheckCommand())?.[1] - if (!pinned) { - errors.push('typecheckCommand() no longer names a typescript@x.y.z release') - return - } + const pinned = SOURCE_TYPESCRIPT_VERSION for (const file of walkMdx(DOCS_DIR)) { for (const match of fs.readFileSync(file, 'utf8').matchAll(/typescript@(\d+\.\d+\.\d+)/g)) { if (match[1] !== pinned) {