@nanobpm/urban 0.77.1 → 0.77.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,14 @@ export interface SchedulerDeps {
4
4
  clearTimer: (handle: unknown) => void;
5
5
  /** Current wall-clock time in ms since epoch. */
6
6
  now: () => number;
7
+ /** Optional shutdown signal. When it aborts, a pending {@link schedulerClock} `wait()` clears its
8
+ * armed timer and rejects, so a handler parked on the (virtual) clock unwinds at teardown instead
9
+ * of wedging whoever awaits it. Under the test kit this is the engine's shutdown signal: a worker
10
+ * handler parked on `app.wait()` sits on a virtual timer that no `advanceTime` will fire during
11
+ * `engine.close()`, so without this its promise never settles and `close()` hangs (the issue #446
12
+ * follow-up — the virtual-timer sibling of the real-time use-after-free). Absent on the live
13
+ * scheduler, where real timers always fire on wall-clock time, so `wait()` never rejects there. */
14
+ readonly signal?: AbortSignal;
7
15
  }
8
16
  /** Max delay a single `setTimeout` honours before its 32-bit signed overflow (~24.8 days). */
9
17
  export declare const MAX_TIMER_DELAY_MS = 2147483647;
@@ -3,6 +3,13 @@
3
3
  // worker handlers. Keeping one definition here — rather than a copy per module — means a
4
4
  // test's fake scheduler drives them all the same way, and the "clamp a far-future delay to
5
5
  // setTimeout's 32-bit range" rule has a single home.
6
+ /** The rejection surfaced to a `wait()` cancelled by a shutdown {@link SchedulerDeps.signal}: the
7
+ * signal's `reason` when it is an {@link Error}, else a generic teardown error. Reusing the reason
8
+ * keeps a caller's fail-loud message (e.g. "WasmEngineClient closing") intact. */
9
+ function schedulerAbortError(signal) {
10
+ const reason = signal.reason;
11
+ return reason instanceof Error ? reason : new Error("app.wait aborted: scheduler shutting down");
12
+ }
6
13
  /** Max delay a single `setTimeout` honours before its 32-bit signed overflow (~24.8 days). */
7
14
  export const MAX_TIMER_DELAY_MS = 2_147_483_647;
8
15
  function isTimerHandle(handle) {
@@ -32,9 +39,48 @@ export function defaultScheduler() {
32
39
  export function schedulerClock(sched) {
33
40
  return {
34
41
  now: () => sched.now(),
35
- wait: (ms) => new Promise((resolve) => {
42
+ wait: (ms) => new Promise((resolve, reject) => {
43
+ const signal = sched.signal;
44
+ // Already shutting down: reject immediately rather than arm a timer that would outlive the
45
+ // teardown (and, under the virtual clock, never fire).
46
+ if (signal?.aborted) {
47
+ reject(schedulerAbortError(signal));
48
+ return;
49
+ }
36
50
  const delay = Number.isFinite(ms) && ms > 0 ? Math.min(ms, MAX_TIMER_DELAY_MS) : 0;
37
- sched.setTimer(() => resolve(), delay);
51
+ let settled = false;
52
+ let onAbort;
53
+ const handle = sched.setTimer(() => {
54
+ settled = true;
55
+ if (onAbort && signal)
56
+ signal.removeEventListener("abort", onAbort);
57
+ resolve();
58
+ }, delay);
59
+ // When a shutdown signal is present, a mid-wait abort disarms the timer and rejects, so a
60
+ // handler parked here unwinds at teardown instead of wedging its awaiter. Inert (no listener,
61
+ // no behaviour change) on the live scheduler, which supplies no signal.
62
+ //
63
+ // `settled` guards the synchronous-timer case: this seam permits `setTimer` to invoke its
64
+ // callback synchronously (the test `capturingScheduler` does exactly that), which resolves
65
+ // the wait *before* we get here. Installing an abort listener on that already-settled promise
66
+ // would leak its closure until the signal fires (and have shutdown clear an already-fired
67
+ // handle), so skip it entirely when the callback already ran.
68
+ if (signal && !settled) {
69
+ onAbort = () => {
70
+ sched.clearTimer(handle);
71
+ reject(schedulerAbortError(signal));
72
+ };
73
+ signal.addEventListener("abort", onAbort, { once: true });
74
+ // Re-entrant seam: `setTimer` above is injectable and may abort `signal` *synchronously*
75
+ // without firing the timer callback (so `settled` is still false). An abort event is not
76
+ // replayed to a listener added after the fact, so the listener just registered would never
77
+ // run and the wait would hang until the runner timeout. Re-check and drive the abort path
78
+ // by hand — removing the (now-inert) listener first so it cannot also fire and double-reject.
79
+ if (signal.aborted && !settled) {
80
+ signal.removeEventListener("abort", onAbort);
81
+ onAbort();
82
+ }
83
+ }
38
84
  }),
39
85
  };
40
86
  }
@@ -17,6 +17,48 @@ export const API_BINDINGS_TS = "operations.ts";
17
17
  * `tsc` (ADR 0059). The runtime dispatches through this map instead of per-op path imports. */
18
18
  export const API_CONTROLLER_TS = "controller.ts";
19
19
  export { DEFAULT_OPERATIONS_DIR };
20
+ /** Order two import source specifiers the way Biome's `organizeImports` assist does, so the
21
+ * controller emits its delegate imports in Biome's canonical order and the generated file passes
22
+ * `biome check` without a post-generation import sort. Biome's collation is, per character:
23
+ * digit-runs compared numerically (`item2` before `item10`), letters compared case-insensitively
24
+ * as the primary key, and — when two characters are the same letter differing only in case — the
25
+ * uppercase one sorts first as an immediate tiebreak (`getAgentInstructions` before
26
+ * `getAgenticRegistry` before `getAgentSkill`). */
27
+ function naturalCompare(a, b) {
28
+ const tokens = (s) => s.match(/\d+|\D/g) ?? [];
29
+ const isDigitRun = (t) => t.charCodeAt(0) >= 48 && t.charCodeAt(0) <= 57;
30
+ const ax = tokens(a);
31
+ const bx = tokens(b);
32
+ const n = Math.min(ax.length, bx.length);
33
+ for (let i = 0; i < n; i++) {
34
+ const ca = ax[i];
35
+ const cb = bx[i];
36
+ if (ca === undefined || cb === undefined)
37
+ break;
38
+ if (isDigitRun(ca) && isDigitRun(cb)) {
39
+ // Compare digit runs by numeric value *without* floating-point loss: strip leading zeros,
40
+ // then a longer run is the larger number, else compare the equal-length digits lexically.
41
+ // (`Number(ca) - Number(cb)` collapses 17+-digit runs to the same IEEE-754 value and yields
42
+ // `NaN` beyond `Number.MAX_SAFE_INTEGER`, both of which break the total order `sort` needs.)
43
+ const na = ca.replace(/^0+/, "");
44
+ const nb = cb.replace(/^0+/, "");
45
+ if (na.length !== nb.length)
46
+ return na.length < nb.length ? -1 : 1;
47
+ if (na !== nb)
48
+ return na < nb ? -1 : 1;
49
+ if (ca !== cb)
50
+ return ca < cb ? -1 : 1; // equal value, differing leading zeros
51
+ }
52
+ else if (ca !== cb) {
53
+ const la = ca.toLowerCase();
54
+ const lb = cb.toLowerCase();
55
+ if (la !== lb)
56
+ return la < lb ? -1 : 1; // case-insensitive primary key
57
+ return ca < cb ? -1 : 1; // same letter, different case → uppercase (lower code point) first
58
+ }
59
+ }
60
+ return ax.length - bx.length;
61
+ }
20
62
  /** A TS identifier form of an operationId (used for the per-op type names). */
21
63
  function typeStem(operationId) {
22
64
  const cleaned = operationId.replace(/[^A-Za-z0-9]+/g, " ").trim();
@@ -139,7 +181,7 @@ function objectToTs(schema, depth) {
139
181
  function paramsTs(op, where, ejected) {
140
182
  const ps = op.parameters.filter((p) => p.in === where);
141
183
  if (ps.length === 0)
142
- return "{}";
184
+ return "Record<string, never>";
143
185
  const rawWire = where === "query" ? "string | string[]" : "string";
144
186
  const fields = ps.map((p) => {
145
187
  // Coerced to the schema type (number/boolean/array/enum/…); optionality is carried by the `?`
@@ -188,8 +230,7 @@ export function emitApiBindings(doc, surfaceEject = false) {
188
230
  "// The endpoint type map: each operationId maps to its typed request (coerced path/query params\n" +
189
231
  "// + JSON body) and response (a union of every documented JSON response body), derived from the\n" +
190
232
  "// spec. Do not edit — regenerated from\n" +
191
- "// the spec; erased to plain JS at compile.\n" +
192
- "// eslint-disable\n\n";
233
+ "// the spec; erased to plain JS at compile.\n\n";
193
234
  const componentDecls = Object.entries(components)
194
235
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
195
236
  .map(([name, schema]) => `export type ${typeStem(name)} = ${schemaToTs(schema)};`)
@@ -242,13 +283,19 @@ export function emitApiBindings(doc, surfaceEject = false) {
242
283
  return ` ${JSON.stringify(op.operationId)}: { request: ${stem}Request; response: ${stem}Response };`;
243
284
  })
244
285
  .join("\n");
286
+ // With generated `.ts` now linted in the scaffold, an empty operation set must NOT emit an empty
287
+ // `interface ApiOperations {}` (`suspicious/noEmptyInterface`); fall back to the same non-empty-safe
288
+ // `Record<never, never>` used elsewhere (its `keyof` is `never`, matching `ApiOperationId = never`).
289
+ const apiOperations = ops.length > 0
290
+ ? `export interface ApiOperations {\n${mapEntries}\n}\n`
291
+ : `export type ApiOperations = Record<never, never>;\n`;
245
292
  return (header +
246
293
  (componentDecls ? `${componentDecls}\n\n` : "") +
247
294
  (opDecls ? `${opDecls}\n\n` : "") +
248
295
  `/** Every declared operationId (ADR 0058): the delegate key set. */\n` +
249
296
  `export type ApiOperationId = ${idUnion};\n\n` +
250
297
  `/** Request/response contract per operationId. */\n` +
251
- `export interface ApiOperations {\n${mapEntries}\n}\n`);
298
+ apiOperations);
252
299
  }
253
300
  /** Emit `operations.ts`: the typed `defineOperation` wrapper, keyed by operationId (mirrors the
254
301
  * generated typed `defineWorker`). Written verbatim (it never changes with the spec) — it only
@@ -257,10 +304,9 @@ export function emitApiBindingsRuntime() {
257
304
  return ("// AUTO-GENERATED by @nanobpm/urban (ADR 0058): the typed `defineOperation`.\n" +
258
305
  "// Re-exports the operation SDK and overrides `defineOperation` with an operationId-keyed\n" +
259
306
  "// signature (the delegate's validated request + result typed from the spec). Erased to a\n" +
260
- "// pass-through at runtime. Do not edit.\n" +
261
- "// eslint-disable\n\n" +
262
- `import { defineOperation as defineOperationRaw } from "@nanobpm/urban";\n` +
307
+ "// pass-through at runtime. Do not edit.\n\n" +
263
308
  `import type { OperationHandler } from "@nanobpm/urban";\n` +
309
+ `import { defineOperation as defineOperationRaw } from "@nanobpm/urban";\n` +
264
310
  `import type { ApiOperationId, ApiOperations } from "./${API_BINDINGS_DTS}";\n\n` +
265
311
  `type ReqFor<K extends ApiOperationId> = ApiOperations[K]["request"];\n` +
266
312
  `type ResFor<K extends ApiOperationId> = ApiOperations[K]["response"];\n\n` +
@@ -303,17 +349,22 @@ export function emitApiController(doc, operationsDir = DEFAULT_OPERATIONS_DIR) {
303
349
  "// registry. Statically imports every operation delegate and asserts the complete, correctly-\n" +
304
350
  "// typed set via `satisfies` — a missing, mismatched, or orphan delegate fails `tsc`. The\n" +
305
351
  "// runtime dispatches through this map, so endpoints cannot drift from the spec. Do not edit —\n" +
306
- "// regenerated from the spec.\n" +
307
- "// eslint-disable\n\n";
308
- const typeImports = `import type { OperationHandler } from "@nanobpm/urban";\n` +
309
- `import type { ApiOperationId, ApiOperations } from "./${API_BINDINGS_DTS}";\n`;
352
+ "// regenerated from the spec.\n\n";
353
+ // Emit imports in Biome's canonical `organizeImports` order so the generated file is lint-clean
354
+ // without a post-gen fixup: the bare package import first, then the delegate imports sorted by
355
+ // source specifier (Biome's natural, numeric-aware collation), then the relative `./api-io.d.ts`
356
+ // type import last. Alias bindings (`op<i>`) stay tied to the original index so the `operations`
357
+ // map below still resolves each operationId to its delegate regardless of import line order.
310
358
  const delegateImports = ops
311
- .map((op, i) => `import op${i} from ${JSON.stringify(`../${dir}/${op.operationId}.ts`)};`)
359
+ .map((op, i) => ({ i, spec: `../${dir}/${op.operationId}.ts` }))
360
+ .sort((a, b) => naturalCompare(a.spec, b.spec))
361
+ .map(({ i, spec }) => `import op${i} from ${JSON.stringify(spec)};`)
312
362
  .join("\n");
313
363
  const mapEntries = ops.map((op, i) => ` ${JSON.stringify(op.operationId)}: op${i},`).join("\n");
314
364
  return (header +
315
- typeImports +
365
+ `import type { OperationHandler } from "@nanobpm/urban";\n` +
316
366
  (delegateImports ? `${delegateImports}\n` : "") +
367
+ `import type { ApiOperationId, ApiOperations } from "./${API_BINDINGS_DTS}";\n` +
317
368
  `\n` +
318
369
  `type ReqFor<K extends ApiOperationId> = ApiOperations[K]["request"];\n` +
319
370
  `type ResFor<K extends ApiOperationId> = ApiOperations[K]["response"];\n\n` +
@@ -83,10 +83,9 @@ function tableInterface(t) {
83
83
  */
84
84
  export function emitDomainDts(tables) {
85
85
  const header = "// AUTO-GENERATED by nanobpmn from the datasource schema (ADR 0029 §4.1).\n" +
86
- "// Do not edit — regenerated from the live tables. Erased at `deno compile`.\n" +
87
- "// eslint-disable\n";
86
+ "// Do not edit — regenerated from the live tables. Erased at `deno compile`.\n";
88
87
  if (tables.length === 0) {
89
- return `${header}\nexport interface DomainTables {}\n`;
88
+ return `${header}\nexport type DomainTables = Record<never, never>;\n`;
90
89
  }
91
90
  const interfaces = tables.map(tableInterface).join("\n\n");
92
91
  const map = tables
@@ -113,15 +112,14 @@ export function emitDomainDtsForSources(sources, defaultSource) {
113
112
  return emitDomainDts(sources[0]?.tables ?? []);
114
113
  }
115
114
  const header = "// AUTO-GENERATED by nanobpmn from the datasource schemas (ADR 0029 §4.1/§6).\n" +
116
- "// Do not edit — regenerated from the live tables. Erased at `deno compile`.\n" +
117
- "// eslint-disable\n";
115
+ "// Do not edit — regenerated from the live tables. Erased at `deno compile`.\n";
118
116
  const interfaces = sources
119
117
  .flatMap((s) => s.tables.map((t) => tableInterfaceNamed(prefixedInterfaceName(s.source, t.name), t)))
120
118
  .join("\n\n");
121
119
  const sourceMap = sources
122
120
  .map((s) => {
123
121
  if (s.tables.length === 0)
124
- return ` ${JSON.stringify(s.source)}: {};`;
122
+ return ` ${JSON.stringify(s.source)}: Record<never, never>;`;
125
123
  const tableMap = s.tables
126
124
  .map((t) => ` ${JSON.stringify(t.name)}: ${prefixedInterfaceName(s.source, t.name)};`)
127
125
  .join("\n");
@@ -181,7 +179,7 @@ export function emitDomainTypeRegistry(types) {
181
179
  return ` ${key}${opt}: ${fieldTsType(field, ids)};`;
182
180
  })
183
181
  .join("\n");
184
- const body = fields.length > 0 ? `{\n${fields}\n }` : "{}";
182
+ const body = fields.length > 0 ? `{\n${fields}\n }` : "Record<never, never>";
185
183
  return ` ${JSON.stringify(id)}: ${body};`;
186
184
  })
187
185
  .join("\n");
@@ -233,8 +231,7 @@ export function emitDomainBindings(sources, defaultSource) {
233
231
  const header = "// AUTO-GENERATED by nanobpmn from the datasource schema (ADR 0029 §4.1/§6).\n" +
234
232
  "// The typed data-object layer: `openDomain()` → one `Table<T>` per table, so\n" +
235
233
  "// workers manipulate typed rows instead of hand-writing SQL. Do not edit —\n" +
236
- "// regenerated from the live tables. Erased to plain JS at `deno compile`.\n" +
237
- "// eslint-disable\n";
234
+ "// regenerated from the live tables. Erased to plain JS at `deno compile`.\n";
238
235
  const multi = sources.length > 1;
239
236
  const def = defaultSource && sources.some((s) => s.source === defaultSource)
240
237
  ? defaultSource
@@ -279,7 +276,7 @@ export function emitDomainBindings(sources, defaultSource) {
279
276
  (binds ? `${binds}\n` : "") +
280
277
  ` close: () => raw.close(),\n };\n}`;
281
278
  return `${header}\n` +
282
- `import { openDataSource, type DataSource, type Table } from "./data-sdk.ts";\n` +
279
+ `import { type DataSource, openDataSource, type Table } from "./data-sdk.ts";\n` +
283
280
  importTypes +
284
281
  `\n${domainIface}\n\n${openFn}\n\nexport type { Table };\n`;
285
282
  }
@@ -323,13 +320,14 @@ function emitKeyedDomainBindings(header, sources, def) {
323
320
  `export async function openDomain<K extends DomainSource = ${JSON.stringify(def)}>(\n` +
324
321
  ` source?: K,\n` +
325
322
  `): Promise<Domain<DomainSources[K]>> {\n` +
326
- ` const key = (source ?? DEFAULT_SOURCE) as string;\n` +
323
+ ` const key = source ?? DEFAULT_SOURCE;\n` +
327
324
  ` const raw = await openDataSource(key);\n` +
328
325
  ` const db: Record<string, unknown> = { raw, close: () => raw.close() };\n` +
329
326
  ` for (const t of DOMAIN_TABLES[key] ?? []) db[t.name] = raw.table(t.name, t.pk);\n` +
327
+ ` // biome-ignore lint/plugin: the per-source table set is bound dynamically from DOMAIN_TABLES; the Domain<M> shape can't be expressed statically over the runtime loop.\n` +
330
328
  ` return db as Domain<DomainSources[K]>;\n}`;
331
329
  return `${header}\n` +
332
- `import { openDataSource, type DataSource, type Table } from "./data-sdk.ts";\n` +
330
+ `import { type DataSource, openDataSource, type Table } from "./data-sdk.ts";\n` +
333
331
  `import type { DomainSources } from "./${DOMAIN_DTS}";\n\n` +
334
332
  `${runtimeMap}\n\n${types}\n\n${openFn}\n\nexport type { Table };\n`;
335
333
  }
@@ -79,15 +79,14 @@ export function emitMessageBindings(messages, declaredTypeIds) {
79
79
  "// The bridge from a `bpmn:message`'s data envelope to the message type system:\n" +
80
80
  "// each named message maps to the TS type of its payload, so the typed\n" +
81
81
  "// `publishMessage` types a call by its message name. Do not edit — regenerated\n" +
82
- "// from the model. Erased to plain JS at compile.\n" +
83
- "// eslint-disable\n";
82
+ "// from the model. Erased to plain JS at compile.\n";
84
83
  const needsRegistry = payloads.length > 0;
85
84
  const importTypes = needsRegistry
86
85
  ? `import type { DomainTypes } from "./${DOMAIN_DTS}";\n`
87
86
  : "";
88
87
  const payloadsIface = payloads.length > 0
89
88
  ? `export interface MessagePayloads {\n${payloads.join("\n")}\n}\n`
90
- : `export interface MessagePayloads {}\n`;
89
+ : `export type MessagePayloads = Record<never, never>;\n`;
91
90
  return `${header}\n` +
92
91
  importTypes +
93
92
  `\n/** Untyped fallback payload for a message that declares no envelope type. */\n` +
@@ -149,11 +148,10 @@ export function emitMessageBindingsRuntime() {
149
148
  return "// AUTO-GENERATED by nanobpmn (ADR 0040 slice 2): the typed `publishMessage`.\n" +
150
149
  "// Re-exports the worker SDK's `publishMessage` and overrides it with a\n" +
151
150
  "// messageName-keyed typed signature (variables typed from the message's declared\n" +
152
- "// envelope). Erased to a pass-through at runtime. Do not edit.\n" +
153
- "// eslint-disable\n\n" +
154
- `import { publishMessage as publishMessageRaw } from "./worker-sdk.ts";\n` +
151
+ "// envelope). Erased to a pass-through at runtime. Do not edit.\n\n" +
152
+ `import type { MessageName, MessagePayloads, MessageVars } from "./${MESSAGE_BINDINGS_DTS}";\n` +
155
153
  `import type { PublishMessageOptions, PublishMessageResult } from "./worker-sdk.ts";\n` +
156
- `import type { MessageName, MessagePayloads, MessageVars } from "./${MESSAGE_BINDINGS_DTS}";\n\n` +
154
+ `import { publishMessage as publishMessageRaw } from "./worker-sdk.ts";\n\n` +
157
155
  `export type { PublishMessageOptions, PublishMessageResult } from "./worker-sdk.ts";\n\n` +
158
156
  `type PayloadFor<K extends MessageName> = K extends keyof MessagePayloads ? MessagePayloads[K] : MessageVars;\n\n` +
159
157
  `/**\n` +
@@ -166,6 +164,7 @@ export function emitMessageBindingsRuntime() {
166
164
  ` name: K,\n` +
167
165
  ` opts?: PublishMessageOptions<PayloadFor<K> & object>,\n` +
168
166
  `): Promise<PublishMessageResult> {\n` +
167
+ ` // biome-ignore lint/plugin: generic-to-raw erasure at the message-SDK boundary; the wire stays untyped JSON (ADR 0040 slice 2).\n` +
169
168
  ` return publishMessageRaw(name, opts as unknown as PublishMessageOptions);\n` +
170
169
  `}\n`;
171
170
  }
@@ -67,23 +67,25 @@ export function emitMeta(metas) {
67
67
  const header = "// AUTO-GENERATED by nanobpmn from the process model (ADR 0040 §5): the typed\n" +
68
68
  "// model-metadata accessor. Each `nano:meta` key/value the models declare becomes\n" +
69
69
  "// a checked `AppMeta` property, so `meta(key)` is typed and app-wide queryable\n" +
70
- "// without a second store. Do not edit — regenerated from the model.\n" +
71
- "// eslint-disable\n\n";
70
+ "// without a second store. Do not edit — regenerated from the model.\n\n";
72
71
  const iface = keys.length > 0
73
72
  ? `export interface AppMeta {\n${keys.map((k) => ` ${propKey(k)}: string;`).join("\n")}\n}\n`
74
- : `export interface AppMeta {}\n`;
73
+ : `export type AppMeta = Record<never, never>;\n`;
74
+ // Dot-access satisfies Biome's `useLiteralKeys`, but `__proto__` must stay a computed key: dot
75
+ // access would trip `noProto` and (off a null-prototype dict) change semantics.
76
+ const assignTarget = (k) => isIdent(k) && k !== "__proto__" ? `m.${k}` : `m[${JSON.stringify(k)}]`;
75
77
  const constDecl = keys.length > 0
76
78
  ? `export const appMeta: AppMeta = (() => {\n` +
77
- ` const m: Record<string, string> = Object.create(null);\n` +
78
- keys.map((k) => ` m[${JSON.stringify(k)}] = ${JSON.stringify(folded[k])};`).join("\n") +
79
- `\n return m as AppMeta;\n})();\n`
80
- : `export const appMeta: AppMeta = Object.create(null) as AppMeta;\n`;
79
+ ` const m: AppMeta = Object.create(null);\n` +
80
+ keys.map((k) => ` ${assignTarget(k)} = ${JSON.stringify(folded[k])};`).join("\n") +
81
+ `\n return m;\n})();\n`
82
+ : `export const appMeta: AppMeta = Object.create(null);\n`;
81
83
  const accessor = `\n/** Read a model-level metadata value. A declared key is typed; a dynamic key\n` +
82
84
  ` * returns \`string | undefined\`. */\n` +
83
85
  `export function meta<K extends keyof AppMeta>(key: K): AppMeta[K];\n` +
84
86
  `export function meta(key: string): string | undefined;\n` +
85
87
  `export function meta(key: string): string | undefined {\n` +
86
- ` return (appMeta as Record<string, string>)[key];\n` +
88
+ ` return Reflect.get(appMeta, key);\n` +
87
89
  `}\n`;
88
90
  return `${header}/** Every model-level metadata key the App's models declare (ADR 0040 §5). */\n` +
89
91
  iface + "\n" + constDecl + accessor;
@@ -143,21 +143,20 @@ export function emitWorkerBindings(workers, declaredTypeIds) {
143
143
  "// The bridge from the process model to the worker type system: each declared\n" +
144
144
  "// worker's `taskType` maps to the TS type of its input payload (`job.variables`)\n" +
145
145
  "// and result, so the typed `defineWorker` types a handler by its job type. Do\n" +
146
- "// not edit — regenerated from the manifest. Erased to plain JS at compile.\n" +
147
- "// eslint-disable\n";
146
+ "// not edit — regenerated from the manifest. Erased to plain JS at compile.\n";
148
147
  const needsRegistry = inputs.length > 0 || outputs.length > 0;
149
148
  const importTypes = needsRegistry
150
149
  ? `import type { DomainTypes } from "./${DOMAIN_DTS}";\n`
151
150
  : "";
152
151
  const inputsIface = inputs.length > 0
153
152
  ? `export interface WorkerInputs {\n${inputs.join("\n")}\n}\n`
154
- : `export interface WorkerInputs {}\n`;
153
+ : `export type WorkerInputs = Record<never, never>;\n`;
155
154
  const outputsIface = outputs.length > 0
156
155
  ? `export interface WorkerOutputs {\n${outputs.join("\n")}\n}\n`
157
- : `export interface WorkerOutputs {}\n`;
156
+ : `export type WorkerOutputs = Record<never, never>;\n`;
158
157
  const headersIface = headers.length > 0
159
158
  ? `export interface WorkerHeaders {\n${headers.join("\n")}\n}\n`
160
- : `export interface WorkerHeaders {}\n`;
159
+ : `export type WorkerHeaders = Record<never, never>;\n`;
161
160
  return `${header}\n` +
162
161
  importTypes +
163
162
  `\n/** Untyped fallback for a job whose worker declares no input/output type. */\n` +
@@ -315,11 +314,10 @@ export function emitWorkerBindingsRuntime() {
315
314
  "// Re-exports the worker SDK and overrides `defineWorker` with a taskType-keyed\n" +
316
315
  "// typed signature (job.variables, job.customHeaders + result typed from the\n" +
317
316
  "// worker's declared input/output/header contract). Erased to a pass-through at\n" +
318
- "// runtime. Do not edit.\n" +
319
- "// eslint-disable\n\n" +
320
- `import { defineWorker as defineWorkerRaw } from "./worker-sdk.ts";\n` +
317
+ "// runtime. Do not edit.\n\n" +
318
+ `import type { WorkerHdrs, WorkerHeaders, WorkerInputs, WorkerOutputs, WorkerTaskType, WorkerVars } from "./${WORKER_BINDINGS_DTS}";\n` +
321
319
  `import type { WorkerOptions } from "./worker-sdk.ts";\n` +
322
- `import type { WorkerInputs, WorkerOutputs, WorkerHeaders, WorkerTaskType, WorkerVars, WorkerHdrs } from "./${WORKER_BINDINGS_DTS}";\n\n` +
320
+ `import { defineWorker as defineWorkerRaw } from "./worker-sdk.ts";\n\n` +
323
321
  `export * from "./worker-sdk.ts";\n\n` +
324
322
  `type InFor<K extends WorkerTaskType> = K extends keyof WorkerInputs ? WorkerInputs[K] : WorkerVars;\n` +
325
323
  `type OutFor<K extends WorkerTaskType> = K extends keyof WorkerOutputs ? WorkerOutputs[K] : WorkerVars;\n` +
@@ -334,6 +332,7 @@ export function emitWorkerBindingsRuntime() {
334
332
  `export function defineWorker<K extends WorkerTaskType>(\n` +
335
333
  ` opts: { type: K } & WorkerOptions<InFor<K> & object, OutFor<K> & object, HdrFor<K> & object>,\n` +
336
334
  `): void {\n` +
335
+ ` // biome-ignore lint/plugin: generic-to-raw erasure at the worker-SDK boundary; the wire stays untyped JSON (ADR 0033 §3).\n` +
337
336
  ` defineWorkerRaw(opts as unknown as WorkerOptions);\n` +
338
337
  `}\n`;
339
338
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nanobpm/urban",
3
- "version": "0.77.1",
3
+ "version": "0.77.3",
4
4
  "description": "Urban: build and run code-first apps on Nano — runtime, derivation toolkit, and CLI in one. Author durable processes with @nanobpm/workflow (defineFlow), a typed datasource, forms, triggers and surfaces from a nano.app.json manifest, on Node or Deno.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -103,7 +103,7 @@
103
103
  "@nanobpm/nano-sdk": "^1.2.5",
104
104
  "@nanobpm/workflow": "^0.14.0",
105
105
  "bpmn-auto-layout": "^2.0.0-alpha.2",
106
- "create-urban-app": "^0.15.0",
106
+ "create-urban-app": "^0.15.1",
107
107
  "yaml": "^2.9.0"
108
108
  },
109
109
  "devDependencies": {
@@ -42,3 +42,108 @@ test("schedulerClock.wait clamps non-positive / non-finite delays to the current
42
42
  await schedulerClock(sched).wait(Number.POSITIVE_INFINITY);
43
43
  assert.deepEqual(sched.delays, [0, 0, 0]);
44
44
  });
45
+
46
+ // Regression (issue #446 follow-up): a handler parked on `app.wait()` sits on a (virtual) timer that
47
+ // no clock advance fires during teardown, so whoever awaits it — the test kit's `engine.close()` —
48
+ // hangs forever. `schedulerClock().wait()` now honours an optional shutdown `signal`: a mid-wait
49
+ // abort disarms the armed timer and rejects, so the parked handler unwinds at teardown. The live
50
+ // scheduler supplies no signal, so this is wholly inert in production.
51
+ test("schedulerClock.wait disarms its timer and rejects when the shutdown signal aborts mid-wait", async () => {
52
+ const controller = new AbortController();
53
+ const cleared: unknown[] = [];
54
+ let armed: (() => void) | undefined;
55
+ const sched: SchedulerDeps = {
56
+ now: () => 0,
57
+ signal: controller.signal,
58
+ setTimer: (fn) => {
59
+ armed = fn;
60
+ return 42;
61
+ },
62
+ clearTimer: (h) => cleared.push(h),
63
+ };
64
+ const waiting = schedulerClock(sched).wait(10_000);
65
+ assert.equal(typeof armed, "function", "wait must arm a timer while not aborted");
66
+ controller.abort(new Error("engine shutting down"));
67
+ await assert.rejects(waiting, /engine shutting down/, "an aborted wait must reject with the signal's reason");
68
+ assert.deepEqual(cleared, [42], "the armed timer must be cleared on abort so it cannot fire later");
69
+ });
70
+
71
+ test("schedulerClock.wait rejects immediately (arming no timer) when the signal is already aborted", async () => {
72
+ const controller = new AbortController();
73
+ controller.abort(new Error("already shutting down"));
74
+ let armedCount = 0;
75
+ const sched: SchedulerDeps = {
76
+ now: () => 0,
77
+ signal: controller.signal,
78
+ setTimer: () => {
79
+ armedCount += 1;
80
+ return 0;
81
+ },
82
+ clearTimer: () => {},
83
+ };
84
+ await assert.rejects(schedulerClock(sched).wait(1000), /already shutting down/);
85
+ assert.equal(armedCount, 0, "an already-aborted signal must reject without arming a timer");
86
+ });
87
+
88
+ // Regression (PR #447 review, scheduler.ts): this seam permits `setTimer` to fire its callback
89
+ // SYNCHRONOUSLY (the `capturingScheduler` above does). When it does — and a shutdown `signal` is
90
+ // present — the wait resolves before we would install the abort listener, so we must NOT install
91
+ // one: attaching a listener to an already-settled promise leaks its closure until the signal fires
92
+ // and later has shutdown clear an already-fired timer handle. A synchronously-resolved wait must
93
+ // leave zero listeners on the signal and must not clear its (already-fired) handle on a later abort.
94
+ test("schedulerClock.wait installs no abort listener when a signalled wait resolves synchronously", async () => {
95
+ const controller = new AbortController();
96
+ const cleared: unknown[] = [];
97
+ const sched: SchedulerDeps = {
98
+ now: () => 0,
99
+ signal: controller.signal,
100
+ setTimer: (fn) => {
101
+ fn(); // fire synchronously — the wait resolves before any listener could be installed
102
+ return 7;
103
+ },
104
+ clearTimer: (h) => cleared.push(h),
105
+ };
106
+ await schedulerClock(sched).wait(0);
107
+ // A leaked listener would fire here and clear the stale handle; the fix installs none.
108
+ controller.abort(new Error("shutting down"));
109
+ assert.deepEqual(cleared, [], "a synchronously-resolved wait must not install an abort listener");
110
+ });
111
+ // The abort reason is attacker/caller-controlled: guard the case where it is a bare value rather
112
+ // than an Error so `wait()` still rejects with a generic teardown error instead of leaking it.
113
+ test("schedulerClock.wait rejects with a generic teardown error when the abort reason is not an Error", async () => {
114
+ const controller = new AbortController();
115
+ const sched: SchedulerDeps = {
116
+ now: () => 0,
117
+ signal: controller.signal,
118
+ setTimer: () => 0,
119
+ clearTimer: () => {},
120
+ };
121
+ const waiting = schedulerClock(sched).wait(1000);
122
+ controller.abort("not-an-error");
123
+ await assert.rejects(waiting, /scheduler shutting down/);
124
+ });
125
+
126
+ // Regression (PR #447 review, scheduler.ts:108): `setTimer` is an injectable seam that may abort the
127
+ // shutdown `signal` SYNCHRONOUSLY while arming, WITHOUT firing its callback (a re-entrant scheduler).
128
+ // An abort event is not replayed to a listener added after the fact, so a wait that merely installed
129
+ // its listener would hang forever — never rejecting, never clearing the armed timer. `wait()` must
130
+ // re-check `signal.aborted` after installing the listener and drive the abort path by hand.
131
+ test("schedulerClock.wait rejects (and clears its timer) when setTimer aborts the signal synchronously", async () => {
132
+ const controller = new AbortController();
133
+ const cleared: unknown[] = [];
134
+ const sched: SchedulerDeps = {
135
+ now: () => 0,
136
+ signal: controller.signal,
137
+ setTimer: () => {
138
+ controller.abort(new Error("aborted during setTimer"));
139
+ return 99;
140
+ },
141
+ clearTimer: (h) => cleared.push(h),
142
+ };
143
+ await assert.rejects(
144
+ schedulerClock(sched).wait(1000),
145
+ /aborted during setTimer/,
146
+ "a synchronous mid-arm abort must reject the wait, not leave it hanging",
147
+ );
148
+ assert.deepEqual(cleared, [99], "the armed timer must be cleared when the synchronous abort is handled");
149
+ });
@@ -10,6 +10,22 @@ export interface SchedulerDeps {
10
10
  clearTimer: (handle: unknown) => void;
11
11
  /** Current wall-clock time in ms since epoch. */
12
12
  now: () => number;
13
+ /** Optional shutdown signal. When it aborts, a pending {@link schedulerClock} `wait()` clears its
14
+ * armed timer and rejects, so a handler parked on the (virtual) clock unwinds at teardown instead
15
+ * of wedging whoever awaits it. Under the test kit this is the engine's shutdown signal: a worker
16
+ * handler parked on `app.wait()` sits on a virtual timer that no `advanceTime` will fire during
17
+ * `engine.close()`, so without this its promise never settles and `close()` hangs (the issue #446
18
+ * follow-up — the virtual-timer sibling of the real-time use-after-free). Absent on the live
19
+ * scheduler, where real timers always fire on wall-clock time, so `wait()` never rejects there. */
20
+ readonly signal?: AbortSignal;
21
+ }
22
+
23
+ /** The rejection surfaced to a `wait()` cancelled by a shutdown {@link SchedulerDeps.signal}: the
24
+ * signal's `reason` when it is an {@link Error}, else a generic teardown error. Reusing the reason
25
+ * keeps a caller's fail-loud message (e.g. "WasmEngineClient closing") intact. */
26
+ function schedulerAbortError(signal: AbortSignal): Error {
27
+ const reason: unknown = signal.reason;
28
+ return reason instanceof Error ? reason : new Error("app.wait aborted: scheduler shutting down");
13
29
  }
14
30
 
15
31
  /** Max delay a single `setTimeout` honours before its 32-bit signed overflow (~24.8 days). */
@@ -58,9 +74,47 @@ export function schedulerClock(sched: SchedulerDeps): AppClock {
58
74
  return {
59
75
  now: () => sched.now(),
60
76
  wait: (ms) =>
61
- new Promise<void>((resolve) => {
77
+ new Promise<void>((resolve, reject) => {
78
+ const signal = sched.signal;
79
+ // Already shutting down: reject immediately rather than arm a timer that would outlive the
80
+ // teardown (and, under the virtual clock, never fire).
81
+ if (signal?.aborted) {
82
+ reject(schedulerAbortError(signal));
83
+ return;
84
+ }
62
85
  const delay = Number.isFinite(ms) && ms > 0 ? Math.min(ms, MAX_TIMER_DELAY_MS) : 0;
63
- sched.setTimer(() => resolve(), delay);
86
+ let settled = false;
87
+ let onAbort: (() => void) | undefined;
88
+ const handle = sched.setTimer(() => {
89
+ settled = true;
90
+ if (onAbort && signal) signal.removeEventListener("abort", onAbort);
91
+ resolve();
92
+ }, delay);
93
+ // When a shutdown signal is present, a mid-wait abort disarms the timer and rejects, so a
94
+ // handler parked here unwinds at teardown instead of wedging its awaiter. Inert (no listener,
95
+ // no behaviour change) on the live scheduler, which supplies no signal.
96
+ //
97
+ // `settled` guards the synchronous-timer case: this seam permits `setTimer` to invoke its
98
+ // callback synchronously (the test `capturingScheduler` does exactly that), which resolves
99
+ // the wait *before* we get here. Installing an abort listener on that already-settled promise
100
+ // would leak its closure until the signal fires (and have shutdown clear an already-fired
101
+ // handle), so skip it entirely when the callback already ran.
102
+ if (signal && !settled) {
103
+ onAbort = () => {
104
+ sched.clearTimer(handle);
105
+ reject(schedulerAbortError(signal));
106
+ };
107
+ signal.addEventListener("abort", onAbort, { once: true });
108
+ // Re-entrant seam: `setTimer` above is injectable and may abort `signal` *synchronously*
109
+ // without firing the timer callback (so `settled` is still false). An abort event is not
110
+ // replayed to a listener added after the fact, so the listener just registered would never
111
+ // run and the wait would hang until the runner timeout. Re-check and drive the abort path
112
+ // by hand — removing the (now-inert) listener first so it cannot also fire and double-reject.
113
+ if (signal.aborted && !settled) {
114
+ signal.removeEventListener("abort", onAbort);
115
+ onAbort();
116
+ }
117
+ }
64
118
  }),
65
119
  };
66
120
  }