From 8eaf637fd94692e14f2d8aec4b7782a359746dbb Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 16:06:41 +0900 Subject: [PATCH 01/13] Follow helper-returned delivery arrays Track arrays of delivery promises returned by synchronous local helpers at their call sites, so awaiting an array cannot hide unfinished delivery. Keep mixed and unsupported return shapes quiet without losing independent completion-promise warnings. Cover helper chains, aggregation, callback positions, and diagnostic locations, and document the conservative analysis boundaries. Closes https://github.com/fedify-dev/fedify/issues/1070 Assisted-by: OpenCode:gpt-6.1-sol Assisted-by: OpenCode:kimi-k3.1-pro Assisted-by: OpenCode:gpt-6-astra Assisted-by: OpenCode:gemini-4-argon --- CHANGES.md | 7 + changes.d/lint/helper-delivery-arrays.md | 10 + docs/manual/lint.md | 16 +- .../outbox-listener-delivery-not-awaited.ts | 293 ++++++++++++++- ...tbox-listener-delivery-not-awaited.test.ts | 341 +++++++++++++++++- .../outbox-listener-delivery-rules.test.ts | 11 + 6 files changed, 651 insertions(+), 27 deletions(-) create mode 100644 changes.d/lint/helper-delivery-arrays.md diff --git a/CHANGES.md b/CHANGES.md index 99da4b268..fa4f5dea8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -443,17 +443,24 @@ To be released. failures, and in Oxlint, where it has to be enabled by name. It is not registered in Deno Lint, which reports every plugin rule as an error. [[#1401], [#1443]] + - Changed `outbox-listener-delivery-not-awaited` to follow arrays of delivery + promises returned by synchronous local helpers. Awaiting or discarding + such an array now produces a warning; use `Promise.all()` to wait for its + deliveries. Mixed or unknown helper returns remain unreported. + [[#1070], [#1446]] - Extended `raw-property-iri-invalid` to check `withRawProperty()` and static record and tuple keys passed to `withRawProperties()`. The rule reports invalid property IRIs and compact prefixes such as `as:content` across Deno Lint, ESLint, and Oxlint. [[#1355], [#1420]] +[#1070]: https://github.com/fedify-dev/fedify/issues/1070 [#1272]: https://github.com/fedify-dev/fedify/issues/1272 [#1355]: https://github.com/fedify-dev/fedify/issues/1355 [#1356]: https://github.com/fedify-dev/fedify/pull/1356 [#1401]: https://github.com/fedify-dev/fedify/issues/1401 [#1420]: https://github.com/fedify-dev/fedify/pull/1420 [#1443]: https://github.com/fedify-dev/fedify/pull/1443 +[#1446]: https://github.com/fedify-dev/fedify/pull/1446 ### @fedify/mysql diff --git a/changes.d/lint/helper-delivery-arrays.md b/changes.d/lint/helper-delivery-arrays.md new file mode 100644 index 000000000..5eb7ab730 --- /dev/null +++ b/changes.d/lint/helper-delivery-arrays.md @@ -0,0 +1,10 @@ +--- +links: + '#1070': https://github.com/fedify-dev/fedify/issues/1070 + '#1446': https://github.com/fedify-dev/fedify/pull/1446 +--- + - Changed `outbox-listener-delivery-not-awaited` to follow arrays of delivery + promises returned by synchronous local helpers. Awaiting or discarding + such an array now produces a warning; use `Promise.all()` to wait for its + deliveries. Mixed or unknown helper returns remain unreported. + [[#1070], [#1446]] diff --git a/docs/manual/lint.md b/docs/manual/lint.md index 3b4d688a4..d2d1546fe 100644 --- a/docs/manual/lint.md +++ b/docs/manual/lint.md @@ -1017,13 +1017,15 @@ When it cannot tell where a promise goes, the rule stays quiet. In practice: reported. A callback that is invoked immediately, or given to `map()` or `then()`, is only as safe as the result of that call. The same holds for a function passed by name, as in `inboxes.forEach(deliver)`. - - A local helper that delivers is judged by how it is called: `deliver();` is - reported when `deliver()` awaits or returns a delivery, and - `await deliver();` is not. An array of promises, or an object holding one, - that a helper returns is not followed to where the helper is called, since - the caller may pass it to `Promise.all()`. So `await deliverAll();` and a - bare `deliverAll();` are not reported when `deliverAll()` returns the - result of `map()`. + - For a local helper that awaits or returns a delivery, the rule reports a + bare `deliver();` call but not `await deliver();`. A synchronous helper + that consistently returns an array of delivery promises is followed to its + call sites, including through other local helpers. `await deliverAll();`, + a bare `deliverAll();`, and returning that array from the listener are + reported; use `await Promise.all(deliverAll())` to wait for the deliveries. + Mixed or unclassifiable returns stay quiet. The rule does not follow + arrays returned by `async` helpers, recursive return chains, arrays + returned through stored variables, or objects returned by helpers. - A promise passed to a function the rule does not know, such as `queue.push(...)` or `setTimeout(...)`, is left alone, since the rule cannot tell what that function does with it. diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 0378f5105..ba96f89a7 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -35,7 +35,11 @@ type Fate = "dropped" | "awaited" | "returned" | "handled"; * or a `return`: the function that now carries the promise on to its own * callers. */ -type Outcome = { fate: Fate; owner: FunctionLikeNode | null }; +type Outcome = { + fate: Fate; + owner: FunctionLikeNode | null; + shape?: Shape; +}; const HANDLED: Outcome = { fate: "handled", owner: null }; const DROPPED: Outcome = { fate: "dropped", owner: null }; @@ -248,7 +252,11 @@ type Analysis = { * Where the value a callback returns goes, judged by the call that receives * the callback. */ -function callbackResultOutcome(call: Node, analysis: Analysis): Outcome { +function callbackResultOutcome( + call: Node, + analysis: Analysis, + callback: Node, +): Outcome { const callee = unwrap(asNode(get(call, "callee")) ?? call); const name = memberName(callee); // `forEach()` discards what its callback returns, which is the one callback @@ -256,6 +264,8 @@ function callbackResultOutcome(call: Node, analysis: Analysis): Outcome { // `setTimeout()`, may well keep it. if (name === "forEach") return DROPPED; if (name === "map" || name === "flatMap") { + // The optional second argument is thisArg, not another callback. + if ((get(call, "arguments") as Node[])[0] !== callback) return HANDLED; return fateOf(call, analysis, "promises"); } if (name != null && PROMISE_CHAIN_METHODS.has(name)) { @@ -278,7 +288,7 @@ function returnedOutcome( return fateOf(parent, analysis, "promise"); } if ((get(parent, "arguments") as unknown[]).includes(fn)) { - return callbackResultOutcome(parent, analysis); + return callbackResultOutcome(parent, analysis, fn); } } // A function declared or held under a name hands the promise to its @@ -295,8 +305,12 @@ function returnedOutcome( function returnedContainerOutcome( fn: FunctionLikeNode | null, analysis: Analysis, + shape: Shape, ): Outcome { - return fn === analysis.listener ? DROPPED : HANDLED; + if (fn === analysis.listener) return DROPPED; + return fn != null && shape === "promises" + ? { fate: "returned", owner: fn, shape } + : HANDLED; } /** Follows the value of `expression` up through its parents to where it ends up. */ @@ -327,13 +341,21 @@ function fateOf( case "ReturnStatement": return currentShape === "promise" ? returnedOutcome(enclosingFunction(parent), analysis) - : returnedContainerOutcome(enclosingFunction(parent), analysis); + : returnedContainerOutcome( + enclosingFunction(parent), + analysis, + currentShape, + ); case "ArrowFunctionExpression": if (get(parent, "body") !== current) return HANDLED; return currentShape === "promise" ? returnedOutcome(parent as FunctionLikeNode, analysis) - : returnedContainerOutcome(parent as FunctionLikeNode, analysis); + : returnedContainerOutcome( + parent as FunctionLikeNode, + analysis, + currentShape, + ); case "ExpressionStatement": return DROPPED; @@ -482,6 +504,193 @@ function fateOf( } } +/** A small proof of no normal fallthrough, not a general control-flow graph. */ +function exitsFunction(node: Node): boolean { + switch (node.type) { + case "ReturnStatement": + case "ThrowStatement": + return true; + case "BlockStatement": + return (get(node, "body") as Node[]).some(exitsFunction); + case "IfStatement": { + const test = asNode(get(node, "test")); + const consequent = asNode(get(node, "consequent")); + const alternate = asNode(get(node, "alternate")); + if (test?.type === "Literal") { + const branch = test.value ? consequent : alternate; + return branch != null && exitsFunction(branch); + } + return ( + consequent != null && + alternate != null && + exitsFunction(consequent) && + exitsFunction(alternate) + ); + } + default: + return false; + } +} + +/** + * Classifies the container a helper returns independently of whether it + * contains a delivery. The carrying walk supplies that evidence separately. + * Unknown dependencies and recursive cycles never certify an array. + */ +function helperReturnShapes( + scopes: readonly UsedScope[], + isDeliveryCall: (call: CallExpression) => boolean, +): { + shapes: ReadonlyMap; + arrayInvolved: ReadonlySet; +} { + const returns = new Map(); + const scopesByFunction = new Map(); + for (const scope of scopes) { + const fn = scope.fn; + if (fn == null) continue; + scopesByFunction.set(fn, scope); + const body = fn.body as Node; + returns.set( + fn, + body.type !== "BlockStatement" + ? [body] + : [ + ...scope.statements + .filter((node) => node.type === "ReturnStatement") + .map((node) => asNode(get(node, "argument"))), + ...(exitsFunction(body) ? [] : [null]), + ], + ); + } + + const helpersOf = (node: Node, scope: UsedScope): FunctionLikeNode[] => { + const callee = unwrap(asNode(get(node, "callee")) ?? node); + return callee.type === "Identifier" + ? (scope.functionsByName.get(callee.name) ?? []) + : []; + }; + // Keep array provenance even when a mixed or unsupported return has no + // shape. Otherwise legacy promise propagation could revive that helper. + const arrayInvolved = new Set(); + const involvesArray = (node: Node | null, scope: UsedScope): boolean => { + if (node == null) return false; + node = unwrap(node); + switch (node.type) { + case "ArrayExpression": + return true; + case "CallExpression": { + const name = memberName(unwrap(asNode(get(node, "callee")) ?? node)); + return ( + name === "map" || + name === "flatMap" || + helpersOf(node, scope).some( + (fn) => get(fn, "async") !== true && arrayInvolved.has(fn), + ) + ); + } + case "ConditionalExpression": + return ( + involvesArray(asNode(get(node, "consequent")), scope) || + involvesArray(asNode(get(node, "alternate")), scope) + ); + case "LogicalExpression": + return ( + involvesArray(asNode(get(node, "left")), scope) || + involvesArray(asNode(get(node, "right")), scope) + ); + case "SequenceExpression": + return involvesArray( + (get(node, "expressions") as Node[]).at(-1) ?? null, + scope, + ); + case "AwaitExpression": + return involvesArray(asNode(get(node, "argument")), scope); + default: + return false; + } + }; + for (let changed = true; changed;) { + changed = false; + for (const [fn, expressions] of returns) { + if ( + !arrayInvolved.has(fn) && + expressions.some((node) => + involvesArray(node, scopesByFunction.get(fn)!), + ) + ) { + arrayInvolved.add(fn); + changed = true; + } + } + } + + const shapes = new Map(); + const active = new Set(); + const agree = (values: (Shape | null)[]): Shape | null => + values.length > 0 && + values[0] != null && + values.every((value) => value === values[0]) + ? values[0] + : null; + const expressionShape = ( + node: Node | null, + scope: UsedScope, + ): Shape | null => { + if (node == null) return null; + node = unwrap(node); + switch (node.type) { + case "ArrayExpression": + return "promises"; + case "ConditionalExpression": + return agree([ + expressionShape(asNode(get(node, "consequent")), scope), + expressionShape(asNode(get(node, "alternate")), scope), + ]); + case "SequenceExpression": + return expressionShape( + (get(node, "expressions") as Node[]).at(-1) ?? null, + scope, + ); + case "CallExpression": { + if (isDeliveryCall(node as CallExpression)) return "promise"; + const callee = unwrap(asNode(get(node, "callee")) ?? node); + const name = memberName(callee); + if (name === "map" || name === "flatMap") return "promises"; + const object = asNode(get(callee, "object")); + if ( + object != null && + unwrap(object).type === "Identifier" && + get(unwrap(object), "name") === "Promise" && + name != null && + PROMISE_COMBINATORS.has(name) + ) + return "promise"; + return agree(helpersOf(node, scope).map(functionShape)); + } + default: + return null; + } + }; + const functionShape = (fn: FunctionLikeNode): Shape | null => { + if (shapes.has(fn)) return shapes.get(fn)!; + if (active.has(fn)) return null; + const scope = scopesByFunction.get(fn); + if (scope == null || get(fn, "generator") === true) return null; + active.add(fn); + let shape = agree( + (returns.get(fn) ?? []).map((node) => expressionShape(node, scope)), + ); + active.delete(fn); + // An async array return is Promise, not a completion promise. + if (shape === "promises" && get(fn, "async") === true) shape = null; + shapes.set(fn, shape); + return shape; + }; + for (const fn of returns.keys()) functionShape(fn); + return { shapes, arrayInvolved }; +} + /** Reports every place in `listener` where a delivery promise is dropped. */ function checkListener( listener: FunctionLikeNode, @@ -509,6 +718,7 @@ function checkListener( const mentioned = new Set(); collectReferencedNames(listener.body, mentioned, true); const analysis: Analysis = { listener, mentioned }; + const { shapes, arrayInvolved } = helperReturnShapes(scopes, isDeliveryCall); const callsByScope = scopes.map((scope) => { const calls: CallExpression[] = []; @@ -523,16 +733,46 @@ function checkListener( // inside a `map()` callback lands in whatever function awaits or returns // the `Promise.all()` around it. const carrying = new Map(); - const carriesDelivery = (call: CallExpression, scope: UsedScope): boolean => { - if (isDeliveryCall(call)) return true; + const carryingArrays = new Set(); + const carriesCompletion = (helpers: readonly FunctionLikeNode[]): boolean => + helpers.some((fn) => carrying.has(fn)) && + helpers.every((fn) => !arrayInvolved.has(fn) || get(fn, "async") === true); + const deliveryShape = ( + call: CallExpression, + scope: UsedScope, + ): Shape | null => { + if (isDeliveryCall(call)) return "promise"; const callee = unwrap(call.callee as Node); - if (callee.type !== "Identifier") return false; + if (callee.type !== "Identifier") return null; const helpers = scope.functionsByName.get(callee.name); - return helpers?.some((helper) => carrying.has(helper)) ?? false; + if (helpers == null || helpers.length === 0) return null; + if (carriesCompletion(helpers)) return "promise"; + if (helpers.some((fn) => arrayInvolved.has(fn))) { + if (!helpers.every((fn) => shapes.get(fn) === "promises")) return null; + return helpers.some((fn) => carryingArrays.has(fn)) ? "promises" : null; + } + return null; }; - const noteCarrying = ({ fate, owner }: Outcome): boolean => { + const noteCarrying = ({ + fate, + owner, + shape = "promise", + }: Outcome): boolean => { if (owner == null || owner === listener) return false; if (fate !== "awaited" && fate !== "returned") return false; + // An independently awaited delivery still makes an async helper's own + // completion promise significant, even if it later returns an array. + if ( + arrayInvolved.has(owner) && + !(fate === "awaited" && get(owner, "async") === true) + ) { + if (shape !== "promises" || shapes.get(owner) !== "promises") + return false; + if (carryingArrays.has(owner)) return false; + carryingArrays.add(owner); + return true; + } + if (shape !== "promise") return false; const known = carrying.get(owner); if (known === "awaited" || known === fate) return false; carrying.set(owner, fate); @@ -542,14 +782,28 @@ function checkListener( changed = false; for (const [index, scope] of scopes.entries()) { for (const call of callsByScope[index]) { - if ( - carriesDelivery(call, scope) && - noteCarrying(fateOf(call, analysis)) - ) { + const shape = deliveryShape(call, scope); + if (shape != null && noteCarrying(fateOf(call, analysis, shape))) { changed = true; } + for (const arg of call.arguments as Node[]) { + if (arg.type !== "Identifier") continue; + const helpers = scope.functionsByName.get(arg.name); + if (helpers == null || !carriesCompletion(helpers)) continue; + const outcome = callbackResultOutcome(call, analysis, arg); + if (outcome.shape === "promises" && noteCarrying(outcome)) { + changed = true; + } + } } } + // An inline async map callback carries delivery through its own promise + // into the returned array, without a named call to seed that array. + for (const [fn, kind] of carrying) { + if (kind !== "awaited") continue; + const outcome = returnedOutcome(fn, analysis); + if (outcome.shape === "promises" && noteCarrying(outcome)) changed = true; + } } const reported = new Set(); @@ -563,8 +817,9 @@ function checkListener( // dropped. for (const [index, scope] of scopes.entries()) { for (const call of callsByScope[index]) { - if (!carriesDelivery(call, scope)) continue; - if (fateOf(call, analysis).fate === "dropped") flag(call); + const shape = deliveryShape(call, scope); + if (shape == null) continue; + if (fateOf(call, analysis, shape).fate === "dropped") flag(call); } } @@ -588,8 +843,8 @@ function checkListener( for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; const held = scope.functionsByName.get(arg.name); - if (held == null || !held.some((fn) => carrying.has(fn))) continue; - if (callbackResultOutcome(call, analysis).fate === "dropped") { + if (held == null || !carriesCompletion(held)) continue; + if (callbackResultOutcome(call, analysis, arg).fate === "dropped") { flag(arg); } } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index c2fd671f1..b01277ec3 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -1,10 +1,349 @@ +import * as tsParser from "@typescript-eslint/parser"; +import { Linter } from "eslint"; +import { deepStrictEqual } from "node:assert/strict"; import { test } from "node:test"; -import { RULE_IDS } from "../lib/const.ts"; +import { FEDERATION_SETUP, RULE_IDS } from "../lib/const.ts"; import lintTest from "../lib/test.ts"; import * as rule from "../rules/outbox-listener-delivery-not-awaited.ts"; const ruleName = RULE_IDS.outboxListenerDeliveryNotAwaited; +const arrayHelperDelivery = "ctx.sendActivity(sender, inbox, activity)"; +const arrayHelperMap = `inboxes.map((inbox) => ${arrayHelperDelivery})`; + +for (const [producer, definition] of [ + ["map", `const deliverAll = () => ${arrayHelperMap};`], + [ + "async map callback", + `const deliverAll = () => inboxes.map(async () => { await ${arrayHelperDelivery}; });`, + ], + [ + "named map callback", + `const deliverOne = () => ${arrayHelperDelivery}; const deliverAll = () => inboxes.map(deliverOne);`, + ], + [ + "named async map callback", + `const deliverOne = async () => { await ${arrayHelperDelivery}; }; const deliverAll = () => inboxes.map(deliverOne);`, + ], + [ + "flatMap", + `const deliverAll = () => inboxes.flatMap(() => ${arrayHelperDelivery});`, + ], + ["literal", `const deliverAll = () => [${arrayHelperDelivery}];`], + ["block", `function deliverAll() { return ${arrayHelperMap}; }`], + ["wrapper", `const deliverAll = () => ([${arrayHelperDelivery}] as const)!;`], + [ + "conditional", + `const deliverAll = () => condition ? [${arrayHelperDelivery}] : ${arrayHelperMap};`, + ], + [ + "branches", + `function deliverAll() { if (condition) return [${arrayHelperDelivery}]; else return ${arrayHelperMap}; }`, + ], + [ + "chain", + `const deliverAll = () => inner(); const inner = () => [${arrayHelperDelivery}];`, + ], + [ + "reverse chain", + `const inner = () => [${arrayHelperDelivery}]; const deliverAll = () => inner();`, + ], + [ + "spread", + `const inner = () => [${arrayHelperDelivery}]; const deliverAll = () => [...inner()];`, + ], + ["sequence", `const deliverAll = () => (log(), [${arrayHelperDelivery}]);`], + [ + "empty branch", + `const deliverAll = () => condition ? [] : [${arrayHelperDelivery}];`, + ], +] as const) { + for (const [consumer, code, dropped] of [ + ["bare", "deliverAll();", true], + ["await", "await deliverAll();", true], + ["return", "return deliverAll();", true], + ["forgotten", "const pending = deliverAll();", true], + ["dropped combinator", "Promise.all(deliverAll());", true], + [ + "stored", + "const pending = deliverAll(); await Promise.all(pending);", + false, + ], + ["void", "void deliverAll();", false], + ["unknown consumer", "own(deliverAll());", false], + ...["all", "allSettled", "race", "any"].map( + (method) => + [method, `await Promise.${method}(deliverAll());`, false] as const, + ), + ] as const) { + test( + `${ruleName}: array helper ${producer}, ${consumer}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const sender = { identifier: ctx.identifier }; + const inbox = new URL("https://example.com/inbox"); + ${definition} + ${code} + }); +`, + rule, + ruleName, + ...(dropped ? { expectedError: "Delivery is not awaited" } : {}), + }), + ); + } +} + +for (const [scenario, definition] of [ + [ + "mixed array first", + `function deliverAll() { if (condition) return [${arrayHelperDelivery}]; return ${arrayHelperDelivery}; }`, + ], + [ + "mixed promise first", + `function deliverAll() { if (condition) return ${arrayHelperDelivery}; return [${arrayHelperDelivery}]; }`, + ], + [ + "mixed conditional", + `const deliverAll = () => condition ? [${arrayHelperDelivery}] : ${arrayHelperDelivery};`, + ], + [ + "unknown first", + `function deliverAll() { if (condition) return unknown(); return [${arrayHelperDelivery}]; }`, + ], + [ + "unknown last", + `function deliverAll() { if (condition) return [${arrayHelperDelivery}]; return unknown(); }`, + ], + [ + "bare return", + `function deliverAll() { if (condition) return; return [${arrayHelperDelivery}]; }`, + ], + [ + "fallthrough", + `function deliverAll() { if (condition) return [${arrayHelperDelivery}]; }`, + ], + ["async array", `const deliverAll = async () => [${arrayHelperDelivery}];`], + ["object", `const deliverAll = () => ({ pending: ${arrayHelperMap} });`], + [ + "stored identifier", + `const deliverAll = () => { const pending = [${arrayHelperDelivery}]; return pending; };`, + ], + [ + "named thisArg", + `const deliverOne = () => ${arrayHelperDelivery}; const deliverAll = () => inboxes.map((inbox) => inbox, deliverOne);`, + ], + [ + "inline async thisArg", + `const deliverAll = () => inboxes.map((inbox) => inbox, async () => { await ${arrayHelperDelivery}; });`, + ], + [ + "inline returning thisArg", + `const deliverAll = () => inboxes.flatMap((inbox) => inbox, () => ${arrayHelperDelivery});`, + ], + [ + "self recursion", + `const deliverAll = () => condition ? [${arrayHelperDelivery}] : deliverAll();`, + ], + [ + "mutual recursion", + `const deliverAll = () => inner(); const inner = () => condition ? [${arrayHelperDelivery}] : deliverAll();`, + ], + [ + "conflicting bindings", + `let deliverAll = () => [${arrayHelperDelivery}]; deliverAll = () => ${arrayHelperDelivery};`, + ], +] as const) { + test( + `${ruleName}: opaque array helper ${scenario} stays quiet through callers and callbacks`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + ${definition} + const outer = () => deliverAll(); + await deliverAll(); + deliverAll(); + outer(); + inboxes.forEach(deliverAll); + inboxes.forEach(outer); + await Promise.all(await deliverAll()); + }); +`, + rule, + ruleName, + }), + ); +} + +for (const [scenario, definition, consumer, dropped] of [ + [ + "async array and returned completion bindings", + `let deliver = async () => []; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, + "deliver();", + true, + ], + [ + "async array and returned completion callback", + `let deliver = async () => []; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, + "inboxes.forEach(deliver);", + true, + ], + [ + "awaited async array and returned completion", + `let deliver = async () => []; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, + "await deliver();", + false, + ], + [ + "mixed sync and async completion bindings", + `let deliver = async () => { await ${arrayHelperDelivery}; return []; }; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, + "deliver();", + true, + ], + [ + "mixed completion callback bindings", + `let deliver = async () => { await ${arrayHelperDelivery}; return []; }; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, + "inboxes.forEach(deliver);", + true, + ], + [ + "awaited mixed completion bindings", + `let deliver = async () => { await ${arrayHelperDelivery}; return []; }; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, + "await deliver();", + false, + ], + [ + "async helper independently awaits delivery", + `const deliver = async () => { await ${arrayHelperDelivery}; return []; };`, + "deliver();", + true, + ], + [ + "async completion through a sync helper", + `const inner = async () => { await ${arrayHelperDelivery}; return []; }; const deliver = () => inner();`, + "deliver();", + true, + ], + [ + "awaited async helper independently awaits delivery", + `const deliver = async () => { await ${arrayHelperDelivery}; return []; };`, + "await deliver();", + false, + ], + [ + "async callback independently awaits delivery", + `const deliver = async () => { await ${arrayHelperDelivery}; return []; };`, + "inboxes.forEach(deliver);", + true, + ], + [ + "returned aggregate", + `const deliver = () => Promise.all(deliverAll());`, + "await deliver();", + false, + ], + [ + "dropped returned aggregate", + `const deliver = () => Promise.all(deliverAll());`, + "deliver();", + true, + ], + [ + "awaited aggregate", + `const deliver = async () => { await Promise.all(deliverAll()); };`, + "await deliver();", + false, + ], + [ + "dropped awaited aggregate", + `const deliver = async () => { await Promise.all(deliverAll()); };`, + "deliver();", + true, + ], + [ + "dead unknown return", + `function deliver() { return deliverAll(); return unknown(); }`, + "await deliver();", + true, + ], + [ + "dead branch", + `function deliver() { if (false) return unknown(); return deliverAll(); }`, + "await deliver();", + true, + ], + ["unused helper", "", "", false], + ["dead call", "", "if (false) deliverAll();", false], + [ + "named array callback", + "", + "await Promise.all(inboxes.map(deliverAll));", + false, + ], + [ + "promise chain callback", + "", + "await Promise.resolve().then(deliverAll);", + false, + ], +] as const) { + test( + `${ruleName}: array helper ${scenario}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const deliverAll = () => [${arrayHelperDelivery}]; + ${definition} + ${consumer} + }); +`, + rule, + ruleName, + ...(dropped ? { expectedError: "Delivery is not awaited" } : {}), + }), + ); +} + +test(`${ruleName}: array helper diagnostics identify only discarded call sites`, () => { + const code = `import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const deliverAll = () => [ctx.sendActivity(sender, inbox, activity)]; + await Promise.all(deliverAll()); + deliverAll(); + await deliverAll(); + Promise.all(deliverAll()); + return deliverAll(); + });`; + const messages = new Linter().verify( + `${FEDERATION_SETUP}\n\n${code}`, + [ + { + files: ["**/*.ts"], + languageOptions: { parser: tsParser }, + plugins: { fedify: { rules: { [ruleName]: rule.eslint } } }, + rules: { [`fedify/${ruleName}`]: "error" }, + }, + ], + "listener.ts", + ); + deepStrictEqual( + messages.map(({ ruleId, line, column }) => [ruleId, line, column]), + [6, 7, 8, 9].map((line) => [ + `fedify/${ruleName}`, + line + FEDERATION_SETUP.split("\n").length + 1, + line === 7 ? 11 : line === 8 ? 17 : line === 9 ? 12 : 5, + ]), + ); +}); + test( `${ruleName}: ✅ Good - awaited sendActivity call`, lintTest({ diff --git a/packages/lint/src/tests/outbox-listener-delivery-rules.test.ts b/packages/lint/src/tests/outbox-listener-delivery-rules.test.ts index b166415cc..8e910ad7a 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-rules.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-rules.test.ts @@ -15,6 +15,17 @@ const NOT_AWAITED_MESSAGE = "Delivery is not awaited"; // Every listener the not-awaited rule reports has a delivery call. const UNAWAITED: [title: string, code: string][] = [ + [ + "awaiting a local helper's delivery array", + ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const deliverAll = () => [ctx.sendActivity(sender, inbox, activity)]; + await deliverAll(); + }); +`, + ], [ "bare sendActivity call", ` From 32b6161291c4c0c7001237b2fe25452e41f7481a Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 16:51:09 +0900 Subject: [PATCH 02/13] Follow delivery arrays through intermediate awaits Await preserves an array value rather than waiting for its elements. Keep following that value so a later combinator or stored reference can handle delivery without a false diagnostic. Bare awaits still report when the resulting array is discarded. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596660985 Assisted-by: OpenCode:gpt-6.1-sol --- docs/manual/lint.md | 9 ++++++--- .../rules/outbox-listener-delivery-not-awaited.ts | 13 ++++++++++--- .../outbox-listener-delivery-not-awaited.test.ts | 6 ++++++ 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/docs/manual/lint.md b/docs/manual/lint.md index d2d1546fe..a72764588 100644 --- a/docs/manual/lint.md +++ b/docs/manual/lint.md @@ -1023,9 +1023,12 @@ When it cannot tell where a promise goes, the rule stays quiet. In practice: call sites, including through other local helpers. `await deliverAll();`, a bare `deliverAll();`, and returning that array from the listener are reported; use `await Promise.all(deliverAll())` to wait for the deliveries. - Mixed or unclassifiable returns stay quiet. The rule does not follow - arrays returned by `async` helpers, recursive return chains, arrays - returned through stored variables, or objects returned by helpers. + An intermediate `await` preserves the array: + `await Promise.all(await deliverAll())` and storing `await deliverAll()` + for later aggregation are accepted. Mixed or unclassifiable returns stay + quiet. The rule does not follow arrays returned by `async` helpers, + recursive return chains, arrays returned through stored variables, or + objects returned by helpers. - A promise passed to a function the rule does not know, such as `queue.push(...)` or `setTimeout(...)`, is left alone, since the rule cannot tell what that function does with it. diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index ba96f89a7..7e42981e1 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -334,9 +334,16 @@ function fateOf( // Awaiting an array of promises, or an object holding one, waits for // none of them. case "AwaitExpression": - return currentShape === "promise" - ? { fate: "awaited", owner: enclosingFunction(parent) } - : DROPPED; + if (currentShape === "promise") { + return { fate: "awaited", owner: enclosingFunction(parent) }; + } + // Await preserves an array value; its eventual consumer may still + // aggregate the deliveries, store the array, or discard it. + if (currentShape === "promises") { + current = parent; + continue; + } + return DROPPED; case "ReturnStatement": return currentShape === "promise" diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index b01277ec3..131dd2621 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -61,6 +61,12 @@ for (const [producer, definition] of [ for (const [consumer, code, dropped] of [ ["bare", "deliverAll();", true], ["await", "await deliverAll();", true], + ["intermediate await", "await Promise.all(await deliverAll());", false], + [ + "stored intermediate await", + "const pending = await deliverAll(); await Promise.all(pending);", + false, + ], ["return", "return deliverAll();", true], ["forgotten", "const pending = deliverAll();", true], ["dropped combinator", "Promise.all(deliverAll());", true], From da40789bed83f6d8fde24dc8cd1ce3d2672a4d33 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 16:53:04 +0900 Subject: [PATCH 03/13] Keep array helper inference inside lexical regions Do not certify calls from merged helper candidates whose lexical declaration region does not contain the reference. Block-local helpers must not classify calls to unrelated module helpers outside that block. Keep ambiguous candidates quiet without changing shared reachability. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596660995 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 52 +++++++++++++++---- ...tbox-listener-delivery-not-awaited.test.ts | 45 ++++++++++++++++ 2 files changed, 88 insertions(+), 9 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 7e42981e1..6b786984a 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -156,6 +156,42 @@ function enclosingFunction(node: Node): FunctionLikeNode | null { return null; } +/** + * The shared reachability map merges block-local functions. Do not use a + * candidate outside its lexical declaration region: another binding may be + * visible there, including one outside the listener that this rule ignores. + * Ambiguous merged candidates remain unclassified rather than filtered down + * to a possibly incomplete set. + */ +function helpersAt(node: Node, scope: UsedScope): FunctionLikeNode[] { + if (node.type !== "Identifier") return []; + const helpers = scope.functionsByName.get(node.name) ?? []; + for (const fn of helpers) { + let declaration: Node = fn; + while ( + parentOf(declaration) != null && + TRANSPARENT_WRAPPERS.has(parentOf(declaration)!.type) + ) { + declaration = parentOf(declaration)!; + } + const declarator = parentOf(declaration); + const variable = + declarator?.type === "VariableDeclarator" ? parentOf(declarator) : null; + const region = + fn.type === "FunctionDeclaration" + ? parentOf(fn) + : variable?.type === "VariableDeclaration" && + get(variable, "kind") !== "var" + ? parentOf(variable) + : null; + if (region == null) continue; + let current: Node | null = node; + while (current != null && current !== region) current = parentOf(current); + if (current == null) return []; + } + return helpers; +} + /** The names an object pattern binds the delivery methods to. */ function deliveryAliasesOf(pattern: Node, out: Set): void { if (pattern.type !== "ObjectPattern") return; @@ -573,9 +609,7 @@ function helperReturnShapes( const helpersOf = (node: Node, scope: UsedScope): FunctionLikeNode[] => { const callee = unwrap(asNode(get(node, "callee")) ?? node); - return callee.type === "Identifier" - ? (scope.functionsByName.get(callee.name) ?? []) - : []; + return helpersAt(callee, scope); }; // Keep array provenance even when a mixed or unsupported return has no // shape. Otherwise legacy promise propagation could revive that helper. @@ -751,8 +785,8 @@ function checkListener( if (isDeliveryCall(call)) return "promise"; const callee = unwrap(call.callee as Node); if (callee.type !== "Identifier") return null; - const helpers = scope.functionsByName.get(callee.name); - if (helpers == null || helpers.length === 0) return null; + const helpers = helpersAt(callee, scope); + if (helpers.length === 0) return null; if (carriesCompletion(helpers)) return "promise"; if (helpers.some((fn) => arrayInvolved.has(fn))) { if (!helpers.every((fn) => shapes.get(fn) === "promises")) return null; @@ -795,8 +829,8 @@ function checkListener( } for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; - const helpers = scope.functionsByName.get(arg.name); - if (helpers == null || !carriesCompletion(helpers)) continue; + const helpers = helpersAt(arg, scope); + if (!carriesCompletion(helpers)) continue; const outcome = callbackResultOutcome(call, analysis, arg); if (outcome.shape === "promises" && noteCarrying(outcome)) { changed = true; @@ -849,8 +883,8 @@ function checkListener( for (const call of callsByScope[index]) { for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; - const held = scope.functionsByName.get(arg.name); - if (held == null || !carriesCompletion(held)) continue; + const held = helpersAt(arg, scope); + if (!carriesCompletion(held)) continue; if (callbackResultOutcome(call, analysis, arg).fate === "dropped") { flag(arg); } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 131dd2621..c4762163e 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -317,6 +317,51 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const declaration of [ + "const deliverAll = () => [ctx.sendActivity(sender, inbox, activity)];", + "function deliverAll() { return [ctx.sendActivity(sender, inbox, activity)]; }", +]) { + for (const outside of [ + "await deliverAll(ctx, activity);", + "inboxes.forEach(deliverAll);", + "const outer = () => deliverAll(ctx, activity); await outer();", + ]) { + test( + `${ruleName}: block-local array does not classify ${outside} (${declaration})`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +async function deliverAll(ctx, activity) { await ctx.sendActivity(sender, inbox, activity); } +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + { ${declaration} await Promise.all(deliverAll()); } + ${outside} + }); +`, + rule, + ruleName, + }), + ); + } +} + +test( + `${ruleName}: block-local array helper still reports its own dropped call`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + { const deliverAll = () => [ctx.sendActivity(sender, inbox, activity)]; + await deliverAll(); } + }); +`, + rule, + ruleName, + expectedError: "Delivery is not awaited", + }), +); + test(`${ruleName}: array helper diagnostics identify only discarded call sites`, () => { const code = `import { Activity } from "@fedify/vocab"; federation.setOutboxListeners("/users/{identifier}/outbox") From 313ee349e9ef6f71ff345af88980083d297c5ae2 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 16:57:53 +0900 Subject: [PATCH 04/13] Follow delivery arrays through callback consumers Propagate synchronous array-returning callbacks through flatMap, for both inline and named functions, and report arrays discarded by forEach. Keep nested map arrays and async array returns conservative, and exclude thisArg positions from callback handling. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596600131 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596600136 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596600142 Assisted-by: OpenCode:gpt-6.1-sol --- docs/manual/lint.md | 6 +- .../outbox-listener-delivery-not-awaited.ts | 47 +++++++++++---- ...tbox-listener-delivery-not-awaited.test.ts | 58 +++++++++++++++++++ 3 files changed, 100 insertions(+), 11 deletions(-) diff --git a/docs/manual/lint.md b/docs/manual/lint.md index a72764588..c9298e856 100644 --- a/docs/manual/lint.md +++ b/docs/manual/lint.md @@ -1025,7 +1025,11 @@ When it cannot tell where a promise goes, the rule stays quiet. In practice: reported; use `await Promise.all(deliverAll())` to wait for the deliveries. An intermediate `await` preserves the array: `await Promise.all(await deliverAll())` and storing `await deliverAll()` - for later aggregation are accepted. Mixed or unclassifiable returns stay + for later aggregation are accepted. Arrays returned by synchronous + `flatMap()` callbacks are followed through the flattened result. A named + `forEach()` callback returning a delivery array is reported because + `forEach()` discards it; a helper passed as `thisArg` is not invoked. + Mixed or unclassifiable returns stay quiet. The rule does not follow arrays returned by `async` helpers, recursive return chains, arrays returned through stored variables, or objects returned by helpers. diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 6b786984a..c68783f9f 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -292,16 +292,22 @@ function callbackResultOutcome( call: Node, analysis: Analysis, callback: Node, + shape: Shape = "promise", ): Outcome { const callee = unwrap(asNode(get(call, "callee")) ?? call); const name = memberName(callee); // `forEach()` discards what its callback returns, which is the one callback // consumer the rule knows for certain. An unknown one, such as // `setTimeout()`, may well keep it. - if (name === "forEach") return DROPPED; - if (name === "map" || name === "flatMap") { + if (name === "forEach" || name === "map" || name === "flatMap") { // The optional second argument is thisArg, not another callback. if ((get(call, "arguments") as Node[])[0] !== callback) return HANDLED; + } + if (name === "forEach") return DROPPED; + // Only flatMap flattens returned arrays; map and promise callbacks would + // need nested-array or Promise tracking, which remains unsupported. + if (shape === "promises" && name !== "flatMap") return HANDLED; + if (name === "map" || name === "flatMap") { return fateOf(call, analysis, "promises"); } if (name != null && PROMISE_CHAIN_METHODS.has(name)) { @@ -344,6 +350,15 @@ function returnedContainerOutcome( shape: Shape, ): Outcome { if (fn === analysis.listener) return DROPPED; + if (fn != null && shape === "promises" && get(fn, "async") !== true) { + const parent = parentOf(fn); + if ( + parent?.type === "CallExpression" && + (get(parent, "arguments") as Node[]).includes(fn) + ) { + return callbackResultOutcome(parent, analysis, fn, shape); + } + } return fn != null && shape === "promises" ? { fate: "returned", owner: fn, shape } : HANDLED; @@ -778,6 +793,9 @@ function checkListener( const carriesCompletion = (helpers: readonly FunctionLikeNode[]): boolean => helpers.some((fn) => carrying.has(fn)) && helpers.every((fn) => !arrayInvolved.has(fn) || get(fn, "async") === true); + const carriesArray = (helpers: readonly FunctionLikeNode[]): boolean => + helpers.some((fn) => carryingArrays.has(fn)) && + helpers.every((fn) => shapes.get(fn) === "promises"); const deliveryShape = ( call: CallExpression, scope: UsedScope, @@ -788,10 +806,7 @@ function checkListener( const helpers = helpersAt(callee, scope); if (helpers.length === 0) return null; if (carriesCompletion(helpers)) return "promise"; - if (helpers.some((fn) => arrayInvolved.has(fn))) { - if (!helpers.every((fn) => shapes.get(fn) === "promises")) return null; - return helpers.some((fn) => carryingArrays.has(fn)) ? "promises" : null; - } + if (carriesArray(helpers)) return "promises"; return null; }; const noteCarrying = ({ @@ -830,8 +845,13 @@ function checkListener( for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; const helpers = helpersAt(arg, scope); - if (!carriesCompletion(helpers)) continue; - const outcome = callbackResultOutcome(call, analysis, arg); + const shape = carriesCompletion(helpers) + ? "promise" + : carriesArray(helpers) + ? "promises" + : null; + if (shape == null) continue; + const outcome = callbackResultOutcome(call, analysis, arg, shape); if (outcome.shape === "promises" && noteCarrying(outcome)) { changed = true; } @@ -884,8 +904,15 @@ function checkListener( for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; const held = helpersAt(arg, scope); - if (!carriesCompletion(held)) continue; - if (callbackResultOutcome(call, analysis, arg).fate === "dropped") { + const shape = carriesCompletion(held) + ? "promise" + : carriesArray(held) + ? "promises" + : null; + if (shape == null) continue; + if ( + callbackResultOutcome(call, analysis, arg, shape).fate === "dropped" + ) { flag(arg); } } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index c4762163e..04ba00e6c 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -13,6 +13,14 @@ const arrayHelperMap = `inboxes.map((inbox) => ${arrayHelperDelivery})`; for (const [producer, definition] of [ ["map", `const deliverAll = () => ${arrayHelperMap};`], + [ + "inline flatMap array", + `const deliverAll = () => inboxes.flatMap(() => [${arrayHelperDelivery}]);`, + ], + [ + "named flatMap array", + `const deliverOne = () => [${arrayHelperDelivery}]; const deliverAll = () => inboxes.flatMap(deliverOne);`, + ], [ "async map callback", `const deliverAll = () => inboxes.map(async () => { await ${arrayHelperDelivery}; });`, @@ -187,6 +195,56 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const [scenario, definition, consumer, dropped] of [ + ["named array forEach", "", "inboxes.forEach(deliverAll);", true], + ["named array flatMap dropped", "", "inboxes.flatMap(deliverAll);", true], + [ + "named array flatMap aggregated", + "", + "await Promise.all(inboxes.flatMap(deliverAll));", + false, + ], + [ + "named array map nested", + "", + "await Promise.all(inboxes.map(deliverAll));", + false, + ], + [ + "named array forEach thisArg", + "", + "inboxes.forEach(() => {}, deliverAll);", + false, + ], + [ + "named array flatMap thisArg", + "", + "await inboxes.flatMap(() => [], deliverAll);", + false, + ], + [ + "inline array flatMap thisArg", + "", + "await inboxes.flatMap(() => [], () => [ctx.sendActivity(sender, inbox, activity)]);", + false, + ], + [ + "inline array forEach", + "", + "inboxes.forEach(() => [ctx.sendActivity(sender, inbox, activity)]);", + true, + ], + [ + "inline array map nested", + "", + "await Promise.all(inboxes.map(() => [ctx.sendActivity(sender, inbox, activity)]));", + false, + ], + [ + "async array flatMap", + "", + "await inboxes.flatMap(async () => [ctx.sendActivity(sender, inbox, activity)]);", + false, + ], [ "async array and returned completion bindings", `let deliver = async () => []; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, From fe25d5307fe388f58c8d34396dfeb890da3bc76e Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 17:59:16 +0900 Subject: [PATCH 05/13] Preserve delivery evidence across returned arrays Classify synchronous array IIFE calls using the same return summaries as named helpers. Mixed and async array returns remain unclassified. Propagate named callback outcomes even after aggregation turns an array into a completion promise, so dropped enclosing calls are reported. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596886542 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596886551 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 9 ++-- ...tbox-listener-delivery-not-awaited.test.ts | 47 +++++++++++++++++++ 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index c68783f9f..c00fd9687 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -624,7 +624,7 @@ function helperReturnShapes( const helpersOf = (node: Node, scope: UsedScope): FunctionLikeNode[] => { const callee = unwrap(asNode(get(node, "callee")) ?? node); - return helpersAt(callee, scope); + return isFunctionLikeNode(callee) ? [callee] : helpersAt(callee, scope); }; // Keep array provenance even when a mixed or unsupported return has no // shape. Otherwise legacy promise propagation could revive that helper. @@ -802,8 +802,9 @@ function checkListener( ): Shape | null => { if (isDeliveryCall(call)) return "promise"; const callee = unwrap(call.callee as Node); - if (callee.type !== "Identifier") return null; - const helpers = helpersAt(callee, scope); + const helpers = isFunctionLikeNode(callee) + ? [callee] + : helpersAt(callee, scope); if (helpers.length === 0) return null; if (carriesCompletion(helpers)) return "promise"; if (carriesArray(helpers)) return "promises"; @@ -852,7 +853,7 @@ function checkListener( : null; if (shape == null) continue; const outcome = callbackResultOutcome(call, analysis, arg, shape); - if (outcome.shape === "promises" && noteCarrying(outcome)) { + if (noteCarrying(outcome)) { changed = true; } } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 04ba00e6c..ac8a51da6 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -13,6 +13,10 @@ const arrayHelperMap = `inboxes.map((inbox) => ${arrayHelperDelivery})`; for (const [producer, definition] of [ ["map", `const deliverAll = () => ${arrayHelperMap};`], + [ + "array IIFE", + `const deliverAll = () => (() => [${arrayHelperDelivery}])();`, + ], [ "inline flatMap array", `const deliverAll = () => inboxes.flatMap(() => [${arrayHelperDelivery}]);`, @@ -195,6 +199,49 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const [scenario, definition, consumer, dropped] of [ + [ + "named flatMap aggregate completion", + `const deliverOne = () => [${arrayHelperDelivery}]; const deliver = async () => { await Promise.all(inboxes.flatMap(deliverOne)); };`, + "deliver();", + true, + ], + [ + "named flatMap aggregate awaited", + `const deliverOne = () => [${arrayHelperDelivery}]; const deliver = async () => { await Promise.all(inboxes.flatMap(deliverOne)); };`, + "await deliver();", + false, + ], + [ + "named flatMap aggregate returned", + `const deliverOne = () => [${arrayHelperDelivery}]; const deliver = () => Promise.all(inboxes.flatMap(deliverOne));`, + "deliver();", + true, + ], + [ + "array IIFE directly awaited", + "", + `await (() => [${arrayHelperDelivery}])();`, + true, + ], + [ + "array IIFE aggregated", + "", + `await Promise.all((() => [${arrayHelperDelivery}])());`, + false, + ], + ["array IIFE bare", "", `(() => [${arrayHelperDelivery}])();`, true], + [ + "async array IIFE", + "", + `await (async () => [${arrayHelperDelivery}])();`, + false, + ], + [ + "mixed array IIFE", + "", + `await (() => condition ? [${arrayHelperDelivery}] : ${arrayHelperDelivery})();`, + false, + ], ["named array forEach", "", "inboxes.forEach(deliverAll);", true], ["named array flatMap dropped", "", "inboxes.flatMap(deliverAll);", true], [ From 826dbe7c4a518f7658da0c47879f0e2f90a76383 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 18:04:07 +0900 Subject: [PATCH 06/13] Suppress helper inference across shadow bindings Reject merged outer helper candidates when an intervening lexical binding declares the same name. Identifier aliases and destructured, loop, parameter, and catch bindings must not inherit an unrelated helper's array return shape. Keep shared reachability unchanged. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596968776 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 66 ++++++++++++++++++- ...tbox-listener-delivery-not-awaited.test.ts | 30 +++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index c00fd9687..b5c069bdc 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -156,6 +156,67 @@ function enclosingFunction(node: Node): FunctionLikeNode | null { return null; } +/** Checks binding patterns without treating property keys as bindings. */ +function bindsName(pattern: Node | null, name: string): boolean { + if (pattern == null) return false; + switch (pattern.type) { + case "Identifier": + return pattern.name === name; + case "RestElement": + return bindsName(asNode(get(pattern, "argument")), name); + case "AssignmentPattern": + return bindsName(asNode(get(pattern, "left")), name); + case "ArrayPattern": + return (get(pattern, "elements") as (Node | null)[]).some((item) => + bindsName(item, name), + ); + case "ObjectPattern": + return (get(pattern, "properties") as Node[]).some((prop) => + bindsName( + asNode(get(prop, prop.type === "RestElement" ? "argument" : "value")), + name, + ), + ); + default: + return false; + } +} + +/** A nearer lexical declaration makes a merged outer candidate ambiguous. */ +function shadowsName(region: Node, name: string): boolean { + if (isFunctionLikeNode(region)) { + return ( + (get(region, "params") as Node[]).some((param) => + bindsName(param, name), + ) || bindsName(asNode(get(region, "id")), name) + ); + } + if (region.type === "CatchClause") { + return bindsName(asNode(get(region, "param")), name); + } + const declarations: Node[] = + region.type === "BlockStatement" + ? (get(region, "body") as Node[]) + : region.type === "SwitchStatement" + ? (get(region, "cases") as Node[]).flatMap( + (clause) => get(clause, "consequent") as Node[], + ) + : region.type === "ForStatement" + ? ([asNode(get(region, "init"))].filter(isNode) as Node[]) + : region.type === "ForInStatement" || region.type === "ForOfStatement" + ? ([asNode(get(region, "left"))].filter(isNode) as Node[]) + : []; + return declarations.some((declaration) => + declaration.type === "VariableDeclaration" + ? (get(declaration, "declarations") as Node[]).some((item) => + bindsName(asNode(get(item, "id")), name), + ) + : (declaration.type === "FunctionDeclaration" || + declaration.type === "ClassDeclaration") && + bindsName(asNode(get(declaration, "id")), name), + ); +} + /** * The shared reachability map merges block-local functions. Do not use a * candidate outside its lexical declaration region: another binding may be @@ -186,7 +247,10 @@ function helpersAt(node: Node, scope: UsedScope): FunctionLikeNode[] { : null; if (region == null) continue; let current: Node | null = node; - while (current != null && current !== region) current = parentOf(current); + while (current != null && current !== region) { + if (shadowsName(current, node.name)) return []; + current = parentOf(current); + } if (current == null) return []; } return helpers; diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index ac8a51da6..e5c338cec 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -467,6 +467,36 @@ federation.setOutboxListeners("/users/{identifier}/outbox") }), ); +for (const consumer of [ + "{ const deliverAll = finish; await deliverAll(); }", + "{ let deliverAll = finish; await deliverAll(); }", + "{ const { run: deliverAll } = { run: finish }; await deliverAll(); }", + "{ const [deliverAll] = [finish]; await deliverAll(); }", + "for (const deliverAll of [finish]) { await deliverAll(); }", + "for (let deliverAll = finish; condition;) { await deliverAll(); }", + "try { throw finish; } catch (deliverAll) { await deliverAll(); }", + "switch (condition) { case true: { const deliverAll = finish; await deliverAll(); } }", + "{ const deliverAll = finish; inboxes.forEach(deliverAll); }", +]) { + test( + `${ruleName}: shadow binding does not use outer array helper: ${consumer}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const deliverAll = () => [ctx.sendActivity(sender, inbox, activity)]; + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + await Promise.all(deliverAll()); + ${consumer} + }); +`, + rule, + ruleName, + }), + ); +} + test(`${ruleName}: array helper diagnostics identify only discarded call sites`, () => { const code = `import { Activity } from "@fedify/vocab"; federation.setOutboxListeners("/users/{identifier}/outbox") From 5a63705fcf5aedc0ab0d67b1bdbbcec95b537290 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 18:23:49 +0900 Subject: [PATCH 07/13] Report dropped async IIFEs only once Use the invocation node for callback-completion diagnostics on IIFEs, matching the call-site pass so node-based deduplication works. Add exact-count regressions for arrow, function, and wrapped callees. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4597472692 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 9 +++++- ...tbox-listener-delivery-not-awaited.test.ts | 30 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index b5c069bdc..358638b0d 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -958,7 +958,14 @@ function checkListener( kind === "awaited" && returnedOutcome(fn, analysis).fate === "dropped" ) { - flag(fn); + const parent = parentOf(fn); + // The call-site pass also follows IIFE completion. Use the same node + // here so an unawaited invocation produces only one diagnostic. + flag( + parent?.type === "CallExpression" && get(parent, "callee") === fn + ? parent + : fn, + ); } } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index e5c338cec..3c5e07276 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -497,6 +497,36 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const invocation of [ + "(async () => { await ctx.sendActivity(sender, inbox, activity); })()", + "(async function () { await ctx.sendActivity(sender, inbox, activity); })()", + "((async () => { await ctx.sendActivity(sender, inbox, activity); }) as () => Promise)()", +]) { + test(`${ruleName}: dropped async IIFE reports once: ${invocation}`, () => { + const code = `import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + ${invocation}; + });`; + const messages = new Linter().verify( + `${FEDERATION_SETUP}\n\n${code}`, + [ + { + files: ["**/*.ts"], + languageOptions: { parser: tsParser }, + plugins: { fedify: { rules: { [ruleName]: rule.eslint } } }, + rules: { [`fedify/${ruleName}`]: "error" }, + }, + ], + "listener.ts", + ); + deepStrictEqual( + messages.map(({ ruleId, line }) => [ruleId, line]), + [[`fedify/${ruleName}`, 4 + FEDERATION_SETUP.split("\n").length + 1]], + ); + }); +} + test(`${ruleName}: array helper diagnostics identify only discarded call sites`, () => { const code = `import { Activity } from "@fedify/vocab"; federation.setOutboxListeners("/users/{identifier}/outbox") From 269f34eb5970be58a7242be5fca55cdac07571af Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 18:26:58 +0900 Subject: [PATCH 08/13] Invalidate helper inference on unknown writes Identifier-valued assignments are not included in the shared helper candidate map. Conservatively suppress inference for helper names with unclassified writes so a replacement completion promise is not treated as the original delivery array. Include destructuring and closure writes without extending alias data flow or changing shared reachability. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4597562390 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 65 +++++++++++++++++-- ...tbox-listener-delivery-not-awaited.test.ts | 27 ++++++++ 2 files changed, 85 insertions(+), 7 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 358638b0d..d13cbc16c 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -224,8 +224,12 @@ function shadowsName(region: Node, name: string): boolean { * Ambiguous merged candidates remain unclassified rather than filtered down * to a possibly incomplete set. */ -function helpersAt(node: Node, scope: UsedScope): FunctionLikeNode[] { - if (node.type !== "Identifier") return []; +function helpersAt( + node: Node, + scope: UsedScope, + unknownWrites: ReadonlySet, +): FunctionLikeNode[] { + if (node.type !== "Identifier" || unknownWrites.has(node.name)) return []; const helpers = scope.functionsByName.get(node.name) ?? []; for (const fn of helpers) { let declaration: Node = fn; @@ -662,6 +666,7 @@ function exitsFunction(node: Node): boolean { function helperReturnShapes( scopes: readonly UsedScope[], isDeliveryCall: (call: CallExpression) => boolean, + unknownWrites: ReadonlySet, ): { shapes: ReadonlyMap; arrayInvolved: ReadonlySet; @@ -688,7 +693,9 @@ function helperReturnShapes( const helpersOf = (node: Node, scope: UsedScope): FunctionLikeNode[] => { const callee = unwrap(asNode(get(node, "callee")) ?? node); - return isFunctionLikeNode(callee) ? [callee] : helpersAt(callee, scope); + return isFunctionLikeNode(callee) + ? [callee] + : helpersAt(callee, scope, unknownWrites); }; // Keep array provenance even when a mixed or unsupported return has no // shape. Otherwise legacy promise propagation could revive that helper. @@ -819,6 +826,46 @@ function checkListener( const scopes: UsedScope[] = []; walkUsedScopes(listener.body as Node, (scope) => scopes.push(scope)); + // Shared reachability collects function-valued assignments, but not aliases + // or unknown replacement values. Without ordered binding data flow, any + // such write makes a same-named helper unsafe to infer, including in a + // closure. Name-wide invalidation is deliberately conservative. + const helperNames = new Set( + scopes.flatMap((scope) => [...scope.functionsByName.keys()]), + ); + const unknownWrites = new Set(); + for (const scope of scopes) { + for (const statement of scope.statements) { + visitAll( + statement, + (node) => { + if ( + node.type !== "AssignmentExpression" && + node.type !== "UpdateExpression" + ) + return; + const target = asNode( + get( + node, + node.type === "AssignmentExpression" ? "left" : "argument", + ), + ); + const value = asNode(get(node, "right")); + if ( + get(node, "operator") === "=" && + value != null && + isFunctionLikeNode(unwrap(value)) + ) + return; + for (const name of helperNames) { + if (bindsName(target, name)) unknownWrites.add(name); + } + }, + false, + ); + } + } + const targets = findDeliveryTargets(listener, scopes); if (targets.contextName == null && targets.aliases.size === 0) return; @@ -838,7 +885,11 @@ function checkListener( const mentioned = new Set(); collectReferencedNames(listener.body, mentioned, true); const analysis: Analysis = { listener, mentioned }; - const { shapes, arrayInvolved } = helperReturnShapes(scopes, isDeliveryCall); + const { shapes, arrayInvolved } = helperReturnShapes( + scopes, + isDeliveryCall, + unknownWrites, + ); const callsByScope = scopes.map((scope) => { const calls: CallExpression[] = []; @@ -868,7 +919,7 @@ function checkListener( const callee = unwrap(call.callee as Node); const helpers = isFunctionLikeNode(callee) ? [callee] - : helpersAt(callee, scope); + : helpersAt(callee, scope, unknownWrites); if (helpers.length === 0) return null; if (carriesCompletion(helpers)) return "promise"; if (carriesArray(helpers)) return "promises"; @@ -909,7 +960,7 @@ function checkListener( } for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; - const helpers = helpersAt(arg, scope); + const helpers = helpersAt(arg, scope, unknownWrites); const shape = carriesCompletion(helpers) ? "promise" : carriesArray(helpers) @@ -975,7 +1026,7 @@ function checkListener( for (const call of callsByScope[index]) { for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; - const held = helpersAt(arg, scope); + const held = helpersAt(arg, scope, unknownWrites); const shape = carriesCompletion(held) ? "promise" : carriesArray(held) diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 3c5e07276..b43991853 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -497,6 +497,33 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const replacement of [ + "deliverAll = finish;", + "deliverAll = chooseHelper();", + "({ run: deliverAll } = { run: finish });", + "[deliverAll] = [finish];", + "const replace = () => { deliverAll = finish; }; replace();", +]) { + test( + `${ruleName}: unclassified reassignment invalidates array inference: ${replacement}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + let deliverAll = () => [ctx.sendActivity(sender, inbox, activity)]; + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + await Promise.all(deliverAll()); + ${replacement} + await deliverAll(); + }); +`, + rule, + ruleName, + }), + ); +} + for (const invocation of [ "(async () => { await ctx.sendActivity(sender, inbox, activity); })()", "(async function () { await ctx.sendActivity(sender, inbox, activity); })()", From fa38c13558dc7e202fdb5165909c92282b1386c5 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 21:01:36 +0900 Subject: [PATCH 09/13] Invalidate array helpers on loop target writes Reachability emits for-in and for-of iterable expressions rather than the loop statements themselves. Use their parent loops to invalidate existing helper bindings assigned by each iteration, including patterns. Loop variable declarations do not assign the outer helper binding. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4597732174 Assisted-by: OpenCode:gpt-6.1-sol --- .../rules/outbox-listener-delivery-not-awaited.ts | 15 +++++++++++++++ .../outbox-listener-delivery-not-awaited.test.ts | 5 +++++ 2 files changed, 20 insertions(+) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index d13cbc16c..fcb6de6ed 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -836,6 +836,21 @@ function checkListener( const unknownWrites = new Set(); for (const scope of scopes) { for (const statement of scope.statements) { + // Reachability emits the iterable expression, not the loop statement. + // Its left-hand target writes an existing binding on each iteration. + const parent = parentOf(statement); + if ( + (parent?.type === "ForOfStatement" || + parent?.type === "ForInStatement") && + get(parent, "right") === statement + ) { + const target = asNode(get(parent, "left")); + if (target?.type !== "VariableDeclaration") { + for (const name of helperNames) { + if (bindsName(target, name)) unknownWrites.add(name); + } + } + } visitAll( statement, (node) => { diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index b43991853..c72a28e49 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -503,6 +503,11 @@ for (const replacement of [ "({ run: deliverAll } = { run: finish });", "[deliverAll] = [finish];", "const replace = () => { deliverAll = finish; }; replace();", + "for (deliverAll of [finish]) {}", + "for ({ run: deliverAll } of [{ run: finish }]) {}", + "for ([deliverAll] of [[finish]]) {}", + "for (deliverAll in {}) {} deliverAll = finish;", + "for (deliverAll in {}) {}", ]) { test( `${ruleName}: unclassified reassignment invalidates array inference: ${replacement}`, From 19dd69f08969051472a2854108a9cc32ca5a20c2 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 21:04:32 +0900 Subject: [PATCH 10/13] Require directly held helper bindings Do not certify a named callable using an unrelated function buried in an aggregate initializer. Keep destructured and aggregate candidates unclassified rather than selecting a function from another property. Establish the enclosing function body for var and assignment-derived candidates so nearer lexical bindings still prevent wrong inference. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4597753996 https://github.com/fedify-dev/fedify/pull/1446#pullrequestreview-5936047270 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 17 ++++++- ...tbox-listener-delivery-not-awaited.test.ts | 51 +++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index fcb6de6ed..c83e144f8 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -240,6 +240,19 @@ function helpersAt( declaration = parentOf(declaration)!; } const declarator = parentOf(declaration); + // A function buried in an aggregate initializer may belong to a different + // property or tuple element than the identifier being invoked. Only a + // directly held callable certifies a named helper here. + if (fn.type !== "FunctionDeclaration") { + const target = + declarator?.type === "VariableDeclarator" + ? asNode(get(declarator, "id")) + : declarator?.type === "AssignmentExpression" && + get(declarator, "operator") === "=" + ? asNode(get(declarator, "left")) + : null; + if (target?.type !== "Identifier" || target.name !== node.name) return []; + } const variable = declarator?.type === "VariableDeclarator" ? parentOf(declarator) : null; const region = @@ -248,8 +261,8 @@ function helpersAt( : variable?.type === "VariableDeclaration" && get(variable, "kind") !== "var" ? parentOf(variable) - : null; - if (region == null) continue; + : asNode(get(enclosingFunction(fn), "body")); + if (region == null) return []; let current: Node | null = node; while (current != null && current !== region) { if (shadowsName(current, node.name)) return []; diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index c72a28e49..38848bcd6 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -497,6 +497,57 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const declaration of [ + "const { run } = { run: finish, other: () => [ctx.sendActivity(sender, inbox, activity)] };", + "const [run] = [finish, () => [ctx.sendActivity(sender, inbox, activity)]];", + "const { run = finish } = { other: () => [ctx.sendActivity(sender, inbox, activity)] };", +]) { + test( + `${ruleName}: aggregate binding does not select an unrelated helper: ${declaration}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + ${declaration} + await run(); + }); +`, + rule, + ruleName, + }), + ); +} + +for (const declaration of [ + "var deliverAll = () => [ctx.sendActivity(sender, inbox, activity)];", + "let deliverAll; deliverAll = () => [ctx.sendActivity(sender, inbox, activity)];", +]) { + for (const shadowed of [true, false]) { + test( + `${ruleName}: var or assignment helper respects shadowing (${shadowed}): ${declaration}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + ${declaration} + await Promise.all(deliverAll()); + { + ${shadowed ? "const deliverAll = external;" : ""} + await deliverAll(); + } + }); +`, + rule, + ruleName, + ...(shadowed ? {} : { expectedError: "Delivery is not awaited" }), + }), + ); + } +} + for (const replacement of [ "deliverAll = finish;", "deliverAll = chooseHelper();", From 51f8024f9c28687e0335635ae868d6e61a178750 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 23:08:47 +0900 Subject: [PATCH 11/13] Respect helper binding regions and var writes Find the nearest lexical declaration region for assignment-initialized helpers so block-local candidates cannot classify unrelated outer calls. Treat unknown var initializers and function-scoped loop targets as writes, including redeclarations and destructured loop targets, rather than retaining an earlier array shape for a replacement callable. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4599433504 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4599433523 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 47 +++++++++++++++-- ...tbox-listener-delivery-not-awaited.test.ts | 51 +++++++++++++++++++ 2 files changed, 94 insertions(+), 4 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index c83e144f8..b6e54a25e 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -183,7 +183,7 @@ function bindsName(pattern: Node | null, name: string): boolean { } /** A nearer lexical declaration makes a merged outer candidate ambiguous. */ -function shadowsName(region: Node, name: string): boolean { +function shadowsName(region: Node, name: string, lexicalOnly = false): boolean { if (isFunctionLikeNode(region)) { return ( (get(region, "params") as Node[]).some((param) => @@ -208,7 +208,8 @@ function shadowsName(region: Node, name: string): boolean { : []; return declarations.some((declaration) => declaration.type === "VariableDeclaration" - ? (get(declaration, "declarations") as Node[]).some((item) => + ? (!lexicalOnly || get(declaration, "kind") !== "var") && + (get(declaration, "declarations") as Node[]).some((item) => bindsName(asNode(get(item, "id")), name), ) : (declaration.type === "FunctionDeclaration" || @@ -217,6 +218,19 @@ function shadowsName(region: Node, name: string): boolean { ); } +/** Finds the nearest lexical binding, with function scope as a fallback. */ +function assignmentRegion(assignment: Node, name: string): Node | null { + for ( + let current = parentOf(assignment); + current != null; + current = parentOf(current) + ) { + if (isFunctionLikeNode(current)) return asNode(get(current, "body")); + if (shadowsName(current, name, true)) return current; + } + return null; +} + /** * The shared reachability map merges block-local functions. Do not use a * candidate outside its lexical declaration region: another binding may be @@ -261,7 +275,9 @@ function helpersAt( : variable?.type === "VariableDeclaration" && get(variable, "kind") !== "var" ? parentOf(variable) - : asNode(get(enclosingFunction(fn), "body")); + : declarator?.type === "AssignmentExpression" + ? assignmentRegion(declarator, node.name) + : asNode(get(enclosingFunction(fn), "body")); if (region == null) return []; let current: Node | null = node; while (current != null && current !== region) { @@ -858,7 +874,17 @@ function checkListener( get(parent, "right") === statement ) { const target = asNode(get(parent, "left")); - if (target?.type !== "VariableDeclaration") { + if ( + target?.type === "VariableDeclaration" && + get(target, "kind") === "var" + ) { + for (const item of get(target, "declarations") as Node[]) { + for (const name of helperNames) { + if (bindsName(asNode(get(item, "id")), name)) + unknownWrites.add(name); + } + } + } else if (target?.type !== "VariableDeclaration") { for (const name of helperNames) { if (bindsName(target, name)) unknownWrites.add(name); } @@ -867,6 +893,19 @@ function checkListener( visitAll( statement, (node) => { + if ( + node.type === "VariableDeclarator" && + get(parentOf(node), "kind") === "var" + ) { + const value = asNode(get(node, "init")); + if (value != null && !isFunctionLikeNode(unwrap(value))) { + for (const name of helperNames) { + if (bindsName(asNode(get(node, "id")), name)) + unknownWrites.add(name); + } + } + return; + } if ( node.type !== "AssignmentExpression" && node.type !== "UpdateExpression" diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 38848bcd6..604dcf8ad 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -422,6 +422,57 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const replacement of [ + "var run = finish;", + "{ var run = finish; }", + "for (var run of [finish]) {}", + "for (var { run } of [{ run: finish }]) {}", + "for (var run in {}) {}", +]) { + test( + `${ruleName}: initialized var replacement invalidates array inference: ${replacement}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + var run = () => [ctx.sendActivity(sender, inbox, activity)]; + await Promise.all(run()); + ${replacement} + await run(); + }); +`, + rule, + ruleName, + }), + ); +} + +for (const local of [ + "{ let run; run = () => [ctx.sendActivity(sender, inbox, activity)]; await Promise.all(run()); }", + "{ let run; { run = () => [ctx.sendActivity(sender, inbox, activity)]; } await Promise.all(run()); }", + "for (let run of [null]) { run = () => [ctx.sendActivity(sender, inbox, activity)]; await Promise.all(run()); }", +]) { + test( + `${ruleName}: assignment helper does not escape its binding region: ${local}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + const run = finish; + ${local} + await run(); + }); +`, + rule, + ruleName, + }), + ); +} + for (const declaration of [ "const deliverAll = () => [ctx.sendActivity(sender, inbox, activity)];", "function deliverAll() { return [ctx.sendActivity(sender, inbox, activity)]; }", From c626972737b80d02532478195297916e139a827c Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Wed, 18 Nov 2026 03:02:03 +0900 Subject: [PATCH 12/13] Preserve block-initialized var helper inference A var declaration in the candidate's own function scope initializes the same binding even when it appears inside a block or loop head. Ignore those declarations during shadow checks while retaining lexical and cross-function shadow checks, restoring dropped-delivery diagnostics. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4600901567 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 12 ++++- ...tbox-listener-delivery-not-awaited.test.ts | 49 +++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index b6e54a25e..5241bab2b 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -279,9 +279,19 @@ function helpersAt( ? assignmentRegion(declarator, node.name) : asNode(get(enclosingFunction(fn), "body")); if (region == null) return []; + const functionScope = enclosingFunction(fn); let current: Node | null = node; while (current != null && current !== region) { - if (shadowsName(current, node.name)) return []; + // A var declaration in this function initializes the same binding, + // even inside a block or loop head. In another function it can shadow. + if ( + shadowsName( + current, + node.name, + enclosingFunction(current) === functionScope, + ) + ) + return []; current = parentOf(current); } if (current == null) return []; diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 604dcf8ad..8d7c39c8b 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -422,6 +422,55 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const definition of [ + "{ var deliver = () => ctx.sendActivity(sender, inbox, activity); CONSUMER }", + "for (var deliver = () => ctx.sendActivity(sender, inbox, activity); condition;) { CONSUMER }", + "{ var deliver = async () => { await ctx.sendActivity(sender, inbox, activity); }; CONSUMER }", + "{ var deliver = () => [ctx.sendActivity(sender, inbox, activity)]; CONSUMER }", +]) { + for (const shadowed of [false, true]) { + const consumer = shadowed + ? "{ const deliver = external; await deliver(); }" + : "deliver();"; + test( + `${ruleName}: function-scoped var helper retains inference (${shadowed}): ${definition}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + ${definition.replace("CONSUMER", consumer)} + }); +`, + rule, + ruleName, + ...(shadowed ? {} : { expectedError: "Delivery is not awaited" }), + }), + ); + } +} + +test( + `${ruleName}: nested function var still shadows an outer helper`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + var deliver = () => [ctx.sendActivity(sender, inbox, activity)]; + await Promise.all(deliver()); + async function inner() { + var deliver = external; + await deliver(); + } + await inner(); + }); +`, + rule, + ruleName, + }), +); + for (const replacement of [ "var run = finish;", "{ var run = finish; }", From 80326a891ab0793b972d479a6b83008f66a95007 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Wed, 18 Nov 2026 08:48:59 +0900 Subject: [PATCH 13/13] Invalidate helper shapes across nested writes Function-literal assignments in used nested functions do not update the enclosing caller's helper map. Invalidate those enclosing bindings while retaining inference for local assignments. Scan parameter defaults of used functions too, since their writes can replace the same helpers without appearing in the reachable body statements. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4603848638 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4603848648 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 42 ++++++++++++++- ...tbox-listener-delivery-not-awaited.test.ts | 51 +++++++++++++++++++ 2 files changed, 91 insertions(+), 2 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 5241bab2b..49de6aae2 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -874,7 +874,35 @@ function checkListener( ); const unknownWrites = new Set(); for (const scope of scopes) { - for (const statement of scope.statements) { + const localFunctionNames = new Set(); + if (scope.fn != null) { + for (const name of helperNames) { + if (shadowsName(scope.fn, name)) localFunctionNames.add(name); + } + // var bindings belong to the whole function, including nested blocks. + for (const statement of scope.statements) { + visitAll( + statement, + (node) => { + if ( + node.type !== "VariableDeclarator" || + get(parentOf(node), "kind") !== "var" + ) + return; + for (const name of helperNames) { + if (bindsName(asNode(get(node, "id")), name)) + localFunctionNames.add(name); + } + }, + false, + ); + } + } + const expressions = [ + ...scope.statements, + ...(scope.fn == null ? [] : (get(scope.fn, "params") as Node[])), + ]; + for (const statement of expressions) { // Reachability emits the iterable expression, not the loop statement. // Its left-hand target writes an existing binding on each iteration. const parent = parentOf(statement); @@ -931,7 +959,17 @@ function checkListener( if ( get(node, "operator") === "=" && value != null && - isFunctionLikeNode(unwrap(value)) + isFunctionLikeNode(unwrap(value)) && + // Nested scope maps do not update the enclosing caller's map. + // Exempt a literal write only when its target is local. + (scope.fn == null || + (target?.type === "Identifier" && + (localFunctionNames.has(target.name) || + shadowsName( + assignmentRegion(node, target.name) ?? node, + target.name, + true, + )))) ) return; for (const name of helperNames) { diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 8d7c39c8b..f8702188a 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -422,6 +422,57 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const replace of [ + "const replace = () => { run = () => ctx.sendActivity(sender, inbox, activity); }; replace();", + "const replace = () => { run = async () => { await ctx.sendActivity(sender, inbox, activity); }; }; replace();", + "const replace = () => { const inner = () => { run = () => ctx.sendActivity(sender, inbox, activity); }; inner(); }; replace();", + "const replace = (value = (run = finish)) => value; replace();", + "const replace = ({ value = (run = finish) } = {}) => value; replace();", + "const replace = (value = (run = () => ctx.sendActivity(sender, inbox, activity))) => value; replace();", +]) { + test( + `${ruleName}: used helper writes invalidate enclosing array inference: ${replace}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + let run = () => [ctx.sendActivity(sender, inbox, activity)]; + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + await Promise.all(run()); + ${replace} + await run(); + }); +`, + rule, + ruleName, + }), + ); +} + +for (const declaration of ["let deliver;", "var deliver;"]) { + test( + `${ruleName}: local literal assignments in used helpers retain inference: ${declaration}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const outer = () => { + ${declaration} + deliver = () => ctx.sendActivity(sender, inbox, activity); + deliver(); + }; + outer(); + }); +`, + rule, + ruleName, + expectedError: "Delivery is not awaited", + }), + ); +} + for (const definition of [ "{ var deliver = () => ctx.sendActivity(sender, inbox, activity); CONSUMER }", "for (var deliver = () => ctx.sendActivity(sender, inbox, activity); condition;) { CONSUMER }",