Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@

All `@seamscript/*` packages and `create-seamscript` are released together, with one version number. Releases are on GitHub: https://github.com/Shogo256/SeamScript/releases

## 0.1.3

### Added

- **`Decoder<T>` needs no import**, like `SeamResponse`. A boundary is a value of this type, and `decode b from json text` already took one in place of a type name, so a single `get<T>(b: Decoder<T>, url)` can fetch and check any boundary; but the type had to be imported from `@seamscript/runtime`, and the README never showed it. Found by an app that wrote the same fetch-and-decode function once per boundary.
- **`Unknown.of(value)`** marks a value as outside data, for tests: `decode Order from Unknown.of({ ... })` is checked exactly like a response body. Before, tests needed `as unknown as Unknown`. It is an identity function at run time and is allowed everywhere, as marking a value Unknown only takes uses away.

### Changed

- **SEAM2001 says which value holds the Unknown data and where it came from.** ``Unknown data in `text` (from `res.text()`, line 12) cannot flow into string here``; for a value that holds Unknown inside it, the place: ``Unknown data in `res.json()` (`res` is SeamResponse) cannot flow into ...``. The origin follows `const` declarations in the same file. Before, the message only said "Unknown data", which was confusing when the value was a `SeamResponse`, not Unknown itself.

### Fixed

- **The hint to type a variable `SeamResponse` was missing for `Response | undefined`**, the usual type of a variable declared before a `try`. It now shows whenever the destination's type includes the lib's `Response`, and says what to write instead of telling the reader to decode.

## 0.1.2

### Added
Expand Down
9 changes: 9 additions & 0 deletions DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,15 @@ Found by the first production app (CS Pro's chat widget), which asks a server th
- **SEAM1403 checks only what it can see.** A `fetch` in a latest function's body (including nested callbacks) with no init, or with an object-literal init without `signal`, is reported. An init in a variable, or a literal with a spread, is not: the checker can't tell what is in it, and a false error would teach people to silence the check. Any `signal` property counts (`AbortSignal.any([signal, ...])` is legitimate).
- **`poll` is a runtime function, not language.** Polling has no data that needs the compiler: the reads are ordinary (decode, Result). It runs one read at a time instead of on a fixed timer, so a slow server is never hit by overlapping reads; backs off only on failure; and pauses while the page is hidden, because a background tab polling every few minutes, in every tab a user keeps open, is load nobody sees. Long polling, SSE and debounce stay out: no app here needs them yet.

## Passing boundaries and outside data around (0.1.3)

Raised by a user's list of language proposals. Of the five, two already worked and only needed to be shown (a boundary as a `Decoder<T>` argument; Unknown in fields, arrays and parameters typed Unknown), one was already the design (`SeamResponse` passes freely; only the lib's `Response` is refused), and two were new:

- **No `Boundary<T>` type or new syntax for generic decoding.** A boundary's constant is already a `Decoder<T>`, and `decode b from ...` already accepts a value there (the transform emits `__decode(b, v)` for any expression). Making `Decoder` ambient was enough.
- **The line stays at "losing the mark", not "carrying it".** Carrying Unknown in places typed Unknown was always allowed (the outflow allowlist); what is refused is any place that would let it be read without decode. The lib's `Response` is one: its `json()` is `any`.
- **`Unknown.of` is not restricted to tests.** Going from a value to Unknown can only remove uses, so it opens no hole; a warning outside tests would need a notion of "test file" the compiler does not have, for no safety gain. It is easy to find by name.
- **SEAM2001's origin is followed through `const` declarations in the same file only.** A `let` may have been reassigned, and a parameter's origin is at each call site; naming a wrong origin would be worse than naming none. The line is filled in by the caller (`withOriginLine`), as only `seamc` and the editor plugin can map positions in the transformed file back to the source. The path into a value that holds Unknown (`res.json()`, `box.inner[i]`) is found by the same walk as `mentionsUnknown`, through unions, awaited types, array elements, properties and call results.

## Open questions

### From the demonstration
Expand Down
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,32 @@ The common web APIs are sources already. Declare your own in `tsconfig.json`, as

With `"externalAny": "unknown"`, a value whose declared type is `any` in a package's type declarations (`axios`'s `response.data`, for example) is reported where it is used, with a quick fix that decodes it.

### Passing boundaries and outside data around

A boundary is also a value, of type `Decoder<T>`, so one function can fetch and check any of them. `decode` takes it in place of a type name, and `Decoder` needs no import:

```ts
async function get<T>(b: Decoder<T>, url: string): Promise<Result<T, DecodeError>> {
const res = await fetch(url);
return decode b from json await res.text();
}

const order = await get(Order, `/orders/${id}`);
```

Unknown can be carried anywhere its type says `Unknown`: a field (`{ body: Unknown; at: number }`), an array (`Unknown[]`), a parameter (`(raw: Unknown) => ...`) or a return value. What is stopped is losing the mark (`unknown`, `any`, `as`, a template string, ...), not carrying the value. `fetch`'s result is a `SeamResponse`, which can be passed and returned like any value; only a place typed with the lib's `Response` is an error, because its `json()` would hand the data out as `any`.

In tests, `Unknown.of(value)` marks a value as outside data, so it is checked exactly as a response body would be, without a cast:

```ts
const r = decode Order from Unknown.of({ id: "1", status: "paid" }); // checked like a response body
expect(r.ok).toBe(false); // id must be an Int64, total is missing, ...
```

`Unknown.of` changes nothing at run time. It is allowed in any file: marking a value Unknown only takes uses away from it.

When Unknown data goes somewhere it may not, SEAM2001 says which value holds it and where it came from: ``Unknown data in `text` (from `res.text()`, line 12) cannot flow into string here``, or, for a value that holds Unknown inside it, ``Unknown data in `res.json()` (`res` is SeamResponse) cannot flow into Response | undefined here``.

### Value constraints

A boundary field's type can be followed by constraints, checked when the value is decoded (and by `encode`, which throws `EncodeRangeError` for a value that would not decode again):
Expand Down
4 changes: 2 additions & 2 deletions demo/seamscript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
"test": "vitest run"
},
"dependencies": {
"@seamscript/runtime": "0.1.2"
"@seamscript/runtime": "0.1.3"
},
"devDependencies": {
"@seamscript/compiler": "0.1.2",
"@seamscript/compiler": "0.1.3",
"typescript": "5.9.3",
"vite": "8.3.4",
"vitest": "5.0.3"
Expand Down
6 changes: 3 additions & 3 deletions packages/compiler/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@seamscript/compiler",
"version": "0.1.2",
"version": "0.1.3",
"description": "SeamScript compiler: expands .seam.ts into plain TypeScript and checks boundaries",
"keywords": [
"seamscript",
Expand Down Expand Up @@ -69,13 +69,13 @@
"dependencies": {
"@babel/types": "8.0.6",
"@jridgewell/trace-mapping": "0.3.31",
"@seamscript/parser": "0.1.2",
"@seamscript/parser": "0.1.3",
"magic-string": "1.4.3",
"typescript": "5.9.3",
"unplugin": "3.4.0"
},
"devDependencies": {
"@seamscript/runtime": "0.1.2",
"@seamscript/runtime": "0.1.3",
"@types/node": "24.19.2",
"rollup": "4.64.6",
"vite": "8.3.4",
Expand Down
123 changes: 115 additions & 8 deletions packages/compiler/src/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ export interface Finding {
fix?: Fix;
/** Not a diagnostic: a fix for TypeScript's own error `code` over this span. */
fixOnly?: boolean;
/**
* Where the Unknown data in a SEAM2001 came from, in the transformed file. Its
* line in the source goes where `message` holds ORIGIN_LINE (see `withOriginLine`).
*/
origin?: number;
}

/** Stands in a finding's message for ", line N" of its `origin`, which only the caller can map to the source. */
export const ORIGIN_LINE = "\u0000origin-line\u0000";

/** A finding's message with its origin's 1-based source line filled in (or left out when unknown). */
export function withOriginLine(message: string, line: number | undefined): string {
return message.replace(ORIGIN_LINE, line === undefined ? "" : `, line ${line}`);
}

/** Edits in the transformed file's positions, all within text kept from the source. */
Expand Down Expand Up @@ -395,13 +408,14 @@ export function createChecker(ts: typeof import("typescript"), options: CheckerO
const ENV_HINT =
" To check one variable, decode it: `const port = decode Int64 from process.env.PORT`, then `port.ok`; a variable that isn't set fails to decode (actual: \"undefined\").";

const report = (node: ts.Node, code: string, message: string, fix?: Fix) =>
const report = (node: ts.Node, code: string, message: string, fix?: Fix, origin?: number) =>
findings.push({
pos: node.getStart(file),
end: node.getEnd(),
code,
message: code === Codes.unknownFlow && isWholeProcessEnv(node) ? message + ENV_HINT : message,
...(fix ? { fix } : {}),
...(origin !== undefined ? { origin } : {}),
});

// ---- Fixes -------------------------------------------------------------------------
Expand Down Expand Up @@ -577,7 +591,94 @@ export function createChecker(ts: typeof import("typescript"), options: CheckerO
const hasUnknown = (node: ts.Expression) => containsUnknown(typeOf(node)) || narrowedUnknown(node);
const narrowedMessage = "Unknown data stays Unknown after a type guard such as `typeof`; decode it instead (`decode T from ...`).";

const exitMessage = (what: string) => `Unknown data cannot be ${what}; decode it first (\`decode T from ...\`).`;
// ---- Where the Unknown data is, for messages ---------------------------------------

/** Source text on one line, shortened: messages quote it. */
const quote = (node: ts.Node, max = 40): string => {
const text = node.getText(file).replace(/\s+/g, " ");
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
};

/** The value itself, without parentheses, `await`, `!` or the compiler's Unknown marker. */
const bare = (e: ts.Expression): ts.Expression => {
for (;;) {
if (ts.isParenthesizedExpression(e) || ts.isAwaitExpression(e) || ts.isNonNullExpression(e)) e = e.expression;
else if (ts.isCallExpression(e) && ts.isIdentifier(e.expression) && e.expression.text.startsWith("__unknown") && e.arguments[0]) e = e.arguments[0];
else return e;
}
};

/** The expression a `const` got its value from, followed through other consts: `text` in `const text = await res.text()` → `res.text()`. */
const originOf = (expr: ts.Expression): ts.Expression | undefined => {
let origin: ts.Expression | undefined;
let e = bare(expr);
for (let i = 0; i < 8 && ts.isIdentifier(e); i++) {
const decl = checker.getSymbolAtLocation(e)?.valueDeclaration;
if (decl === undefined || !ts.isVariableDeclaration(decl) || !ts.isIdentifier(decl.name) || decl.initializer === undefined) break;
if (decl.getSourceFile() !== file || !(ts.getCombinedNodeFlags(decl) & ts.NodeFlags.Const)) break;
e = origin = bare(decl.initializer);
}
return origin;
};

/** Where in a value of type `t` its Unknown is, as an access: "" (it is Unknown), ".json()", "[i].body"; undefined if not found. */
const unknownPath = (t: ts.Type, depth = 0): string | undefined => {
if (depth > 6 || !containsUnknown(t)) return undefined;
if (brandOf(t) === "Unknown") return "";
if (t.isUnionOrIntersection()) {
for (const m of t.types) {
const p = unknownPath(m, depth + 1);
if (p !== undefined) return p;
}
return undefined;
}
if (!(t.flags & ts.TypeFlags.Object)) return undefined;
const awaited = checker.getAwaitedType(t);
if (awaited !== undefined && awaited !== t) return unknownPath(awaited, depth + 1);
if (checker.isArrayLikeType(t)) {
const element = checker.getIndexTypeOfType(t, ts.IndexKind.Number);
const p = element && unknownPath(element, depth + 1);
return p === undefined ? undefined : `[i]${p}`;
}
for (const prop of checker.getPropertiesOfType(t)) {
if (typeof prop.escapedName === "string" && prop.escapedName.startsWith("__")) continue;
const p = unknownPath(checker.getTypeOfSymbol(prop), depth + 1);
if (p !== undefined) return `.${prop.name}${p}`;
}
for (const sig of t.getCallSignatures()) {
const p = unknownPath(sig.getReturnType(), depth + 1);
if (p !== undefined) return `()${p}`;
}
return undefined;
};

/**
* Which value holds the Unknown data and where it came from, for a message:
* " in `text` (from `res.text()`, line 12)", " from `e.data`",
* " in `res.json()` (`res` is SeamResponse)".
*/
const placeOf = (expr: ts.Expression): { text: string; origin?: number } => {
const e = bare(expr);
const name = quote(e);
const type = typeOf(expr);
const path = unknownPath(type);
if (path === "") {
const origin = originOf(expr);
if (origin !== undefined) return { text: ` in \`${name}\` (from \`${quote(origin)}\`${ORIGIN_LINE})`, origin: origin.getStart(file) };
return { text: ts.isIdentifier(e) ? ` in \`${name}\`` : ` from \`${name}\`` };
}
const shown = show(type);
const typeText = shown.length > 60 ? `${shown.slice(0, 59)}…` : shown;
if (path === undefined) return { text: ` in \`${name}\` (${typeText})` };
return { text: ` in \`${name.length > 30 ? "…" : name}${path}\` (\`${name}\` is ${typeText})` };
};

const exitMessage = (what: string, place = "") => `Unknown data${place} cannot be ${what}; decode it first (\`decode T from ...\`).`;
/** Reports `node` for letting out the Unknown data in `expr` (by default, `node` itself). */
const reportExit = (node: ts.Node, what: string, expr: ts.Expression) => {
const place = placeOf(expr);
report(node, Codes.unknownFlow, exitMessage(what, place.text), undefined, place.origin);
};

/**
* A value flowing into the place its contextual type describes. Returns whether
Expand Down Expand Up @@ -611,8 +712,13 @@ export function createChecker(ts: typeof import("typescript"), options: CheckerO
if (!absorbs(source, target)) return false;
// The lib's Response would let json() escape as any: the usual cause is a
// variable typed for fetch's result, so say what to write instead.
const responseHint = show(target) === "Response" ? " `fetch` returns a SeamResponse, whose json() stays Unknown: type the variable `SeamResponse`." : "";
if (assignable) report(expr, Codes.unknownFlow, `Unknown data cannot flow into ${show(target)} here; decode it first (\`decode T from ...\`).${responseHint}`, decodeFix(expr));
const response = (target.isUnion() ? target.types : [target]).some((t) => show(t) === "Response");
const advice = response
? "`fetch` returns a SeamResponse, whose json() stays Unknown: type it `SeamResponse` instead of `Response`."
: "decode it first (`decode T from ...`).";
if (!assignable) return true;
const place = placeOf(expr);
report(expr, Codes.unknownFlow, `Unknown data${place.text} cannot flow into ${show(target)} here; ${advice}`, decodeFix(expr), place.origin);
return true;
};

Expand Down Expand Up @@ -841,7 +947,7 @@ export function createChecker(ts: typeof import("typescript"), options: CheckerO
// An object spread copies the fields out from under the brand: the copy's
// type has only the brand's symbol key, which TypeScript lets pass as
// `Record<string, string>` and the like. It never keeps the data Unknown.
if (hasUnknown(node.expression)) report(node, Codes.unknownFlow, exitMessage(ts.isJsxSpreadAttribute(node) ? "spread into JSX props" : "spread into an object"));
if (hasUnknown(node.expression)) reportExit(node, ts.isJsxSpreadAttribute(node) ? "spread into JSX props" : "spread into an object", node.expression);
else checkValue(node.expression);
} else if (ts.isJsxExpression(node)) {
checkValue(node.expression);
Expand All @@ -851,12 +957,13 @@ export function createChecker(ts: typeof import("typescript"), options: CheckerO
if (narrowedUnknown(node.expression)) {
report(node, Codes.unknownFlow, narrowedMessage);
} else if (containsUnknown(source) && (!containsUnknown(target) || absorbs(source, target))) {
report(node, Codes.unknownFlow, "Unknown data cannot be asserted with `as`; decode it instead (`decode T from ...`).");
const place = placeOf(node.expression);
report(node, Codes.unknownFlow, `Unknown data${place.text} cannot be asserted with \`as\`; decode it instead (\`decode T from ...\`).`, undefined, place.origin);
}
} else if (ts.isTemplateSpan(node)) {
if (hasUnknown(node.expression)) report(node.expression, Codes.unknownFlow, exitMessage("interpolated into a template"));
if (hasUnknown(node.expression)) reportExit(node.expression, "interpolated into a template", node.expression);
} else if (ts.isThrowStatement(node)) {
if (hasUnknown(node.expression)) report(node.expression, Codes.unknownFlow, exitMessage("thrown"));
if (hasUnknown(node.expression)) reportExit(node.expression, "thrown", node.expression);
}

if (options.externalAny !== "allow" && (ts.isPropertyAccessExpression(node) || ts.isCallExpression(node) || (ts.isIdentifier(node) && isBareReference(node)))) {
Expand Down
9 changes: 7 additions & 2 deletions packages/compiler/src/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { decodedMappings, originalPositionFor, TraceMap } from "@jridgewell/trac
// Loaded with require: importing TypeScript's CommonJS API as ESM makes Node
// scan all of it for export names first, about 100 ms on every run.
import ts = require("typescript");
import { type CheckerOptions, createChecker, type Finding } from "./checker.js";
import { type CheckerOptions, createChecker, type Finding, withOriginLine } from "./checker.js";
import type { Diagnostic } from "./diagnostics.js";
import { isSeamFile, RUNTIME_MODULE, type TransformResult, transform, type UnknownWrap } from "./transform.js";

Expand Down Expand Up @@ -217,7 +217,12 @@ export function createSeamProgram(

function fromFinding(f: Finding, fileName: string, sf: ts.SourceFile, map: TraceMap): Diagnostic {
const pos = sf.getLineAndCharacterOfPosition(f.pos);
return { file: fileName, ...originalPosition(map, pos.line, pos.character), code: f.code, message: f.message, category: "error" };
let originLine: number | undefined;
if (f.origin !== undefined) {
const o = sf.getLineAndCharacterOfPosition(f.origin);
originLine = originalPosition(map, o.line, o.character).line;
}
return { file: fileName, ...originalPosition(map, pos.line, pos.character), code: f.code, message: withOriginLine(f.message, originLine), category: "error" };
}

function fromTs(d: ts.Diagnostic, map: TraceMap | undefined): Diagnostic {
Expand Down
Loading
Loading