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
9 changes: 8 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@

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

## Unreleased
## 0.1.2

### Added

- **Deadlines for `latest` calls: `f.within(ms)(...args)`.** A call that has not settled `ms` milliseconds after it started aborts its `AbortSignal` and resolves to `Timeout` (`{ ok: false, error: { kind: "timeout", ms } }`), or to `Stale` if a newer call started meanwhile. It shares the line with plain calls, on a function and on a fork. Before, a deadline meant a `setTimeout` race written by hand, which neither aborted the request nor kept the latest-wins guarantee. Found by an app whose server calls an AI with a 2-second budget (CS Pro's chat widget).
- **SEAM1403: a `fetch` in a latest function that does not take the function's signal.** Such a request keeps running after the call is superseded, cancelled or out of time, so the server keeps working (and paying) for an answer nobody reads. The quick fix passes `signal`. An init object that is not a literal, or that spreads another object, is left alone.
- **`poll(read, { every, maxEvery?, onResult })`** in `@seamscript/runtime`: reads one at a time, `every` ms apart after each read ends, doubles the wait after failures up to `maxEvery`, starts no read while the page is hidden (and reads at once when it is shown if one fell due), and stops for good on `stop()`, aborting a read in flight. For state a page must notice changing on the server, such as a switch that turns a feature off.


### Fixed

Expand Down
9 changes: 9 additions & 0 deletions DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ In development builds the compiler doesn't import `@seamscript/core`, so during
| SEAM1301 | A Text other than `Text<NFC>` / `Text<NFD>` |
| SEAM1401 | A latest function can't be a generator |
| SEAM1402 | The type of a latest function's AbortSignal parameter isn't written as `AbortSignal` |
| SEAM1403 | A `fetch` in a latest function doesn't take the function's signal |
| SEAM2001 | Unknown flows to an exit other than decode |
| SEAM2002 | A call that takes Unknown and returns any / unknown |
| SEAM2003 | A source method is referenced without being called |
Expand Down Expand Up @@ -357,6 +358,14 @@ The goal was to let the frontend of a real-time voice interpretation app be writ
- **`file.readJson` rejects malformed JSON with a SyntaxError naming only the path**: `JSON.parse`'s own message quotes the text. To get malformed JSON back as a DecodeError, `decode T from json await file.readText(path)`.
- **Found on the way: spreading Unknown into an object literal or JSX props is SEAM2001 everywhere.** The copy's type has only the brand's symbol key, which TypeScript lets pass as `Record<string, string>` and the like, so `{ ...JSON.parse(s) }` let the fields out unchecked. An object spread can never keep data Unknown, so it is always reported (an array spread is still allowed where the destination keeps Unknown).

## Deadlines, polling and fetch signals (0.1.2)

Found by the first production app (CS Pro's chat widget), which asks a server that asks an AI, with a 2-second budget: it raced `fetch` against a `setTimeout` by hand, so a late request kept running on the client and, through the server, at the AI, and a reply arriving after the user had moved on could still be shown. Three small additions, each the least that removes that class of bug:

- **`within(ms)` on a latest line, not a new keyword.** A deadline is a property of one call site (the same function is called with 2 s from a text box and 10 s from a chat), so it is a method that returns a call, not part of the declaration. It shares the generation line: a newer call still makes it `Stale`, which wins over `Timeout`, so a screen never shows a timeout for a question the user has already replaced. On expiry it aborts only its own signal, never a newer call's. `Timeout` is a separate `Err` kind rather than `Stale`, because the caller acts on it (falls back), whereas `Stale` is to be ignored. The TLA+ model is unchanged: a timeout is one more way for the current call to settle, delivered under the same generation check.
- **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.

## Open questions

### From the demonstration
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.1"
"@seamscript/runtime": "0.1.2"
},
"devDependencies": {
"@seamscript/compiler": "0.1.1",
"@seamscript/compiler": "0.1.2",
"typescript": "5.9.3",
"vite": "8.3.4",
"vitest": "5.0.3"
Expand Down
3 changes: 2 additions & 1 deletion packages/compiler/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ A declared method that returns a promise gives `Promise<Unknown>`. `seamc`, the
| SEAM1302 | `Pcm` / `Planar` with arguments they don't take (`Pcm<Int24, 16000, 1>`, a rate that isn't a positive whole number, `Planar<Int16, 1>`) |
| SEAM1401 | A latest function can't be a generator |
| SEAM1402 | The type of a latest function's AbortSignal parameter isn't written as `AbortSignal` |
| SEAM1403 | A `fetch` in a latest function doesn't take the function's signal |
| SEAM2001 | Unknown flows to an exit other than decode (`as`, assignment to `unknown` or `any`, templates, `+`, `in`, `throw`, and so on) |
| SEAM2002 | A call that takes Unknown and returns any / unknown |
| SEAM2003 | A method that is a source of outside data is referenced without being called |
Expand All @@ -80,7 +81,7 @@ A declared method that returns a promise gives `Promise<Unknown>`. `seamc`, the
| SEAM2201 | A value containing a bigint is passed to `JSON.stringify` (pass `Order.encode(o)` instead) |
| SEAM9001 | Editor plugin only, a warning: the editor's TypeScript is not the version `seamc` checks with (5.9), so the type errors it shows can differ from `seamc check` |

Every message says how to fix the problem. In the editor, the mechanical fixes are quick fixes: SEAM2001, SEAM2005 and TypeScript's assignment errors on a typed variable (`const o: Order = JSON.parse(s)` becomes `const o = decode Order from JSON.parse(s)`), SEAM2101 (`Text.length(t)`, `Text.at(t, i)`), SEAM2201 (`Order.encode(o)`, `orders.map(Order.encode)`) and SEAM1402 (write `AbortSignal`).
Every message says how to fix the problem. In the editor, the mechanical fixes are quick fixes: SEAM2001, SEAM2005 and TypeScript's assignment errors on a typed variable (`const o: Order = JSON.parse(s)` becomes `const o = decode Order from JSON.parse(s)`), SEAM2101 (`Text.length(t)`, `Text.at(t, i)`), SEAM2201 (`Order.encode(o)`, `orders.map(Order.encode)`) SEAM1402 (write `AbortSignal`) and SEAM1403 (pass `signal`).

## Bundlers

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.1",
"version": "0.1.2",
"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.1",
"@seamscript/parser": "0.1.2",
"magic-string": "1.4.3",
"typescript": "5.9.3",
"unplugin": "3.4.0"
},
"devDependencies": {
"@seamscript/runtime": "0.1.1",
"@seamscript/runtime": "0.1.2",
"@types/node": "24.19.2",
"rollup": "4.64.6",
"vite": "8.3.4",
Expand Down
51 changes: 50 additions & 1 deletion packages/compiler/src/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,52 @@ export function createChecker(ts: typeof import("typescript"), options: CheckerO
}
};

// A latest function hands each call an AbortSignal and aborts it when the call is
// superseded, cancelled (fork().cancel()) or out of time (within(ms)). A fetch in its body
// that does not take the signal keeps running after the call is dropped: the server keeps
// working, and pays, for an answer nobody reads.
const fetchChecked = new Set<ts.Node>();
const isFetch = (callee: ts.Expression): boolean => {
if (!ts.isIdentifier(callee) || callee.text !== "fetch") return false;
let symbol = checker.getSymbolAtLocation(callee);
if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol);
return (symbol?.declarations ?? []).some((d) => program.isSourceFileDefaultLibrary(d.getSourceFile()) || runtime?.isRuntimeDeclaration(d) === true);
};
const checkLatestFetch = (call: ts.CallExpression) => {
if (call.arguments.length !== 2 || !ts.isIdentifier(call.expression) || call.expression.text !== "__latestFor") return;
const target = call.arguments[0]!;
const name = ts.isExpressionWithTypeArguments(target) ? target.expression : target;
const decl = checker.getSymbolAtLocation(name)?.valueDeclaration;
if (decl === undefined || !ts.isFunctionDeclaration(decl) || decl.body === undefined || fetchChecked.has(decl)) return;
fetchChecked.add(decl);
const signal = decl.parameters.at(-1)?.name;
if (signal === undefined || !ts.isIdentifier(signal)) return;
const walk = (node: ts.Node): void => {
if (ts.isCallExpression(node) && isFetch(node.expression)) {
const init = node.arguments[1];
const missing =
init === undefined
? true
: ts.isObjectLiteralExpression(init) &&
!init.properties.some((p) => ts.isSpreadAssignment(p) || (p.name !== undefined && ts.isIdentifier(p.name) && p.name.text === "signal"));
if (missing) {
const edits =
init === undefined
? [{ pos: node.arguments[0]!.getEnd(), end: node.arguments[0]!.getEnd(), text: `, { signal: ${signal.text} }` }]
: [{ pos: (init as ts.ObjectLiteralExpression).getStart(file) + 1, end: (init as ts.ObjectLiteralExpression).getStart(file) + 1, text: ` signal: ${signal.text},` }];
report(
node,
Codes.latestFetchSignal,
`This fetch is in a latest function but does not take its signal, so it keeps running after the call is superseded, cancelled or out of time: pass \`signal: ${signal.text}\`.`,
{ description: `Pass the latest function's signal (${signal.text})`, edits },
);
}
}
ts.forEachChild(node, walk);
};
ts.forEachChild(decl.body, walk);
};

/** Whether a type written in a declaration is `any`, or a type parameter that defaults to `any` (`AxiosResponse<T = any>`). */
const declaredAny = (type: ts.TypeNode | undefined): boolean => {
if (type === undefined) return false;
Expand Down Expand Up @@ -719,7 +765,10 @@ export function createChecker(ts: typeof import("typescript"), options: CheckerO
};

const visit = (node: ts.Node): void => {
if (ts.isCallExpression(node)) checkLatestSignal(node);
if (ts.isCallExpression(node)) {
checkLatestSignal(node);
checkLatestFetch(node);
}
if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
const args = node.arguments ?? ts.factory.createNodeArray();
const unknownArgs = args.map((arg) => (ts.isSpreadElement(arg) ? arg.expression : arg)).filter((value) => !PRIMITIVE_EXPRESSIONS.has(value.kind) && hasUnknown(value));
Expand Down
1 change: 1 addition & 0 deletions packages/compiler/src/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export const Codes = {
audioType: "SEAM1302",
latestShape: "SEAM1401",
latestSignal: "SEAM1402",
latestFetchSignal: "SEAM1403",
unknownFlow: "SEAM2001",
unknownLaunder: "SEAM2002",
sourceReference: "SEAM2003",
Expand Down
5 changes: 3 additions & 2 deletions packages/compiler/src/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,8 +313,9 @@ export function transform(source: string, fileName: string, options: TransformOp
`}\n` +
// A fork of a generic function fixes its type arguments: f.fork<T>().
(tp
? `${name}.fork = function ${typeParams}() { return __latestFor(${implRef}${options}).fork(); };\n`
: `${name}.fork = () => __latestFor(${impl}${options}).fork();\n`) +
? `${name}.fork = function ${typeParams}() { return __latestFor(${implRef}${options}).fork(); };\n` +
`${name}.within = function ${typeParams}(ms: number) { return __latestFor(${implRef}${options}).within(ms); };\n`
: `${name}.fork = () => __latestFor(${impl}${options}).fork();\n` + `${name}.within = (ms: number) => __latestFor(${impl}${options}).within(ms);\n`) +
`async function ${impl}`,
);
helpers.add("__latestFor");
Expand Down
30 changes: 30 additions & 0 deletions packages/compiler/test/checker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,4 +255,34 @@ export latest async function optional(q: string, signal?: Sig | undefined): Prom
[8, "SEAM1402"],
]);
});

it("reports a fetch in a latest function that does not take the function's signal", () => {
const source = `export latest async function search(q: string, signal: AbortSignal): Promise<Result<string, string>> {
await fetch("/a");
await fetch("/b", { method: "POST" });
await fetch("/c", { signal });
await fetch("/d", { method: "POST", signal: AbortSignal.any([signal]) });
const init = { signal };
await fetch("/e", init);
await fetch("/f", { ...init });
const inner = async () => fetch("/g");
await inner();
return { ok: true, value: q };
}
export latest async function noSignal(q: string): Promise<Result<string, string>> {
await fetch("/h");
return { ok: true, value: q };
}
export async function notLatest(q: string) {
await fetch("/i");
return q;
}
search.within(1000)("x");
`;
expect(codesByLine(source)).toEqual([
[2, "SEAM1403"],
[3, "SEAM1403"],
[9, "SEAM1403"],
]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export function withAlias(...args: __LatestArgs<typeof withAlias__impl, false>):
return __latestFor(withAlias__impl).apply(undefined, args);
}
withAlias.fork = () => __latestFor(withAlias__impl).fork();
withAlias.within = (ms: number) => __latestFor(withAlias__impl).within(ms);
async function withAlias__impl(q: string, signal: Signal) {
void signal;
return ok(q);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export function search(...args: __LatestArgs<typeof search__impl, true>): __Late
return __latestFor(search__impl, { signal: 1 }).apply(undefined, args);
}
search.fork = () => __latestFor(search__impl, { signal: 1 }).fork();
search.within = (ms: number) => __latestFor(search__impl, { signal: 1 }).within(ms);
async function search__impl(q: Text<"NFC">, signal: AbortSignal) {
const res = await fetch(`/search?q=${encodeURIComponent(q)}`, { signal });
return __decode(__b.array(Order), await res.json());
Expand All @@ -16,6 +17,7 @@ export function count(...args: __LatestArgs<typeof count__impl, false>): __Lates
return __latestFor(count__impl).apply(undefined, args);
}
count.fork = () => __latestFor(count__impl).fork();
count.within = (ms: number) => __latestFor(count__impl).within(ms);
async function count__impl(n: number) {
return ok(n + 1);
}
Expand All @@ -24,6 +26,7 @@ export function get<T extends object>(...args: __LatestArgs<typeof get__impl<T>,
return __latestFor(get__impl<T>, { signal: 1 }).apply(undefined, args);
}
get.fork = function <T extends object>() { return __latestFor(get__impl<T>, { signal: 1 }).fork(); };
get.within = function <T extends object>(ms: number) { return __latestFor(get__impl<T>, { signal: 1 }).within(ms); };
async function get__impl<T extends object>(key: string, signal: AbortSignal): Promise<Result<T | null, DecodeError>> {
void key;
void signal;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ function search(...args: __LatestArgs<typeof search__impl, false>): __LatestRetu
return __latestFor(search__impl).apply(undefined, args);
}
search.fork = () => __latestFor(search__impl).fork();
search.within = (ms: number) => __latestFor(search__impl).within(ms);
async function search__impl(query: string) {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
return __decode(SearchResult, await res.json());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ function loadSnapshot(...args: __LatestArgs<typeof loadSnapshot__impl, true>): _
return __latestFor(loadSnapshot__impl, { signal: 0 }).apply(undefined, args);
}
loadSnapshot.fork = () => __latestFor(loadSnapshot__impl, { signal: 0 }).fork();
loadSnapshot.within = (ms: number) => __latestFor(loadSnapshot__impl, { signal: 0 }).within(ms);
async function loadSnapshot__impl(signal: AbortSignal) {
const r = await getJson("/api/snapshot", signal);
if (!r.ok) return r;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export function searchInstruments(...args: __LatestArgs<typeof searchInstruments
return __latestFor(searchInstruments__impl, { signal: 1 }).apply(undefined, args);
}
searchInstruments.fork = () => __latestFor(searchInstruments__impl, { signal: 1 }).fork();
searchInstruments.within = (ms: number) => __latestFor(searchInstruments__impl, { signal: 1 }).within(ms);
async function searchInstruments__impl(query: Text<"NFC">, signal: AbortSignal) {
const r = await getJson(`/api/instruments?q=${encodeURIComponent(query)}`, signal);
if (!r.ok) return r;
Expand All @@ -20,6 +21,7 @@ export function loadOrderDetail(...args: __LatestArgs<typeof loadOrderDetail__im
return __latestFor(loadOrderDetail__impl, { signal: 1 }).apply(undefined, args);
}
loadOrderDetail.fork = () => __latestFor(loadOrderDetail__impl, { signal: 1 }).fork();
loadOrderDetail.within = (ms: number) => __latestFor(loadOrderDetail__impl, { signal: 1 }).within(ms);
async function loadOrderDetail__impl(id: Int64, signal: AbortSignal) {
const r = await getJson(`/api/orders/${id}`, signal);
if (!r.ok) return r;
Expand Down
2 changes: 2 additions & 0 deletions packages/compiler/test/transform.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ describe("latest", () => {
" return __latestFor(search__impl).apply(undefined, args);\n" +
"}\n" +
"search.fork = () => __latestFor(search__impl).fork();\n" +
"search.within = (ms: number) => __latestFor(search__impl).within(ms);\n" +
"async function search__impl(q: string) {\n return ok(q);\n}",
);
});
Expand Down Expand Up @@ -292,6 +293,7 @@ describe("latest", () => {
" return __latestFor(get__impl<T, K>, { signal: 1 }).apply(undefined, args);\n" +
"}\n" +
"get.fork = function <T extends object, const K = string>() { return __latestFor(get__impl<T, K>, { signal: 1 }).fork(); };\n" +
"get.within = function <T extends object, const K = string>(ms: number) { return __latestFor(get__impl<T, K>, { signal: 1 }).within(ms); };\n" +
"async function get__impl<T extends object, const K = string>(key: K, signal: AbortSignal): Promise<Result<T, Text<\"NFC\">>> {}",
);
expect(out).toContain("type Stale as __Stale");
Expand Down
6 changes: 3 additions & 3 deletions packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@seamscript/core",
"version": "0.1.1",
"version": "0.1.2",
"description": "WASM core for SeamScript's Text: grapheme segmentation and normalization at a pinned Unicode version",
"keywords": [
"seamscript",
Expand Down Expand Up @@ -43,15 +43,15 @@
"access": "public"
},
"devDependencies": {
"@seamscript/runtime": "0.1.1",
"@seamscript/runtime": "0.1.2",
"@types/node": "24.19.2",
"fast-check": "4.10.2",
"typescript": "5.9.3",
"vite": "8.3.4",
"vitest": "5.0.3"
},
"peerDependencies": {
"@seamscript/runtime": "0.1.1"
"@seamscript/runtime": "0.1.2"
},
"engines": {
"node": ">=20"
Expand Down
2 changes: 1 addition & 1 deletion packages/create-seamscript/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "create-seamscript",
"version": "0.1.1",
"version": "0.1.2",
"description": "Start a SeamScript app: `npm create seamscript my-app` sets up Vite, seamc check, the WASM core and editor support",
"keywords": [
"seamscript",
Expand Down
2 changes: 1 addition & 1 deletion packages/parser/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@seamscript/parser",
"version": "0.1.1",
"version": "0.1.2",
"description": "Fork of @babel/parser 8.0.7 that adds SeamScript syntax: boundary, decode … from, latest",
"keywords": [
"seamscript",
Expand Down
Loading
Loading